text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import css from "css";
import { Resources, CachedFile } from "./resource";
import { decodeEUCJP } from "./euc_jp";
import { defaultCLUT } from "./default_clut";
import { readCLUT } from "./clut";
import { transpileCSS } from "./transpile_css";
import { Buffer } from "buffer";
import { BML } from "./interface/DOM";
import { bmlToXHTMLFXP } from "./bml_to_xhtml";
import { NPTReference, ResponseMessage } from "../server/ws_api";
import { EventDispatcher, EventQueue } from "./event_queue";
import { Interpreter } from "./interpreter/interpreter";
import { BMLBrowserEventTarget, Indicator, InputApplication } from "./bml_browser";
import { convertJPEG } from "./arib_jpeg";
export enum AribKeyCode {
Up = 1,
Down = 2,
Left = 3,
Right = 4,
Digit0 = 5,
Digit1 = 6,
Digit2 = 7,
Digit3 = 8,
Digit4 = 9,
Digit5 = 10,
Digit6 = 11,
Digit7 = 12,
Digit8 = 13,
Digit9 = 14,
Digit10 = 15,
Digit11 = 16,
Digit12 = 17,
Enter = 18,
Back = 19, // X
DataButton = 20,
BlueButton = 21, // B
RedButton = 22, // R
GreenButton = 23, // G
YellowButton = 24, // Y
DataButton1 = 25, // E
DataButton2 = 26, // F
Bookmark = 100,
}
type KeyGroup = "basic" | "data-button" | "numeric-tuning" | "other-tuning";
// TR-B14 第二分冊 5.3.1 表5-5参照
const keyCodeToKeyGroup = new Map<AribKeyCode, KeyGroup>([
[AribKeyCode.Up, "basic"],
[AribKeyCode.Down, "basic"],
[AribKeyCode.Left, "basic"],
[AribKeyCode.Right, "basic"],
[AribKeyCode.Enter, "basic"],
[AribKeyCode.Back, "basic"],
[AribKeyCode.BlueButton, "data-button"],
[AribKeyCode.RedButton, "data-button"],
[AribKeyCode.GreenButton, "data-button"],
[AribKeyCode.YellowButton, "data-button"],
[AribKeyCode.Bookmark, "data-button"],
[AribKeyCode.Digit0, "numeric-tuning"],
[AribKeyCode.Digit1, "numeric-tuning"],
[AribKeyCode.Digit2, "numeric-tuning"],
[AribKeyCode.Digit3, "numeric-tuning"],
[AribKeyCode.Digit4, "numeric-tuning"],
[AribKeyCode.Digit5, "numeric-tuning"],
[AribKeyCode.Digit6, "numeric-tuning"],
[AribKeyCode.Digit7, "numeric-tuning"],
[AribKeyCode.Digit8, "numeric-tuning"],
[AribKeyCode.Digit9, "numeric-tuning"],
[AribKeyCode.Digit10, "numeric-tuning"],
[AribKeyCode.Digit11, "numeric-tuning"],
[AribKeyCode.Digit12, "numeric-tuning"],
]);
const keyCodeToAccessKey = new Map<AribKeyCode, string>([
[AribKeyCode.Back, "X"],
[AribKeyCode.BlueButton, "B"],
[AribKeyCode.RedButton, "R"],
[AribKeyCode.GreenButton, "G"],
[AribKeyCode.YellowButton, "Y"],
[AribKeyCode.DataButton1, "E"],
[AribKeyCode.DataButton2, "F"],
]);
export function keyCodeToAribKey(keyCode: string): AribKeyCode | -1 {
// STD B-24 第二分冊(2/2) 第二編 A2 Table 5-9
switch (keyCode) {
case "ArrowUp":
return AribKeyCode.Up;
case "ArrowDown":
return AribKeyCode.Down;
case "ArrowLeft":
return AribKeyCode.Left;
case "ArrowRight":
return AribKeyCode.Right;
case "0":
return AribKeyCode.Digit0;
case "1":
return AribKeyCode.Digit1;
case "2":
return AribKeyCode.Digit2;
case "3":
return AribKeyCode.Digit3;
case "4":
return AribKeyCode.Digit4;
case "5":
return AribKeyCode.Digit5;
case "6":
return AribKeyCode.Digit6;
case "7":
return AribKeyCode.Digit7;
case "8":
return AribKeyCode.Digit8;
case "9":
return AribKeyCode.Digit9;
case "Enter":
case "Space":
return AribKeyCode.Enter;
case "Backspace":
case "X":
case "x":
return AribKeyCode.Back;
case "D":
case "d":
return AribKeyCode.DataButton;
case "B":
case "b":
return AribKeyCode.BlueButton;
case "R":
case "r":
return AribKeyCode.RedButton;
case "G":
case "g":
return AribKeyCode.GreenButton;
case "Y":
case "y":
return AribKeyCode.YellowButton;
case "E":
case "e":
return AribKeyCode.DataButton1;
case "F":
case "f":
return AribKeyCode.DataButton2;
default:
return -1;
}
}
type KeyProcessStatus = {
keyCode: AribKeyCode,
isAccessKey: boolean,
};
function requestAnimationFrameAsync(): Promise<void> {
return new Promise<void>((resolve, _) => {
requestAnimationFrame((_time) => resolve());
});
}
type NPT = {
nptReference: number,
stcReference: number,
scaleDenominator: number,
scaleNumerator: number,
};
export class Content {
private documentElement: HTMLElement;
private resources: Resources;
private eventQueue: EventQueue;
private eventDispatcher: EventDispatcher;
private interpreter: Interpreter;
public readonly bmlDocument: BML.BMLDocument;
private videoContainer: HTMLElement;
private bmlEventTarget: BMLBrowserEventTarget;
private indicator?: Indicator;
private fonts: FontFace[] = [];
private readonly videoPlaneModeEnabled: boolean;
private loaded = false;
// trueであれば厳密なテキストのレンダリングを有効にする
// letter-spacingなどの挙動の差異をどうにかする
private strictTextRenderingEnabled = true;
private readonly inputApplication?: InputApplication;
private npt?: NPT;
public constructor(
bmlDocument: BML.BMLDocument,
documentElement: HTMLElement,
resources: Resources,
eventQueue: EventQueue,
eventDispatcher: EventDispatcher,
interpreter: Interpreter,
videoContainer: HTMLElement,
bmlEventTarget: BMLBrowserEventTarget,
indicator: Indicator | undefined,
videoPlaneModeEnabled: boolean,
inputApplication: InputApplication | undefined,
) {
this.bmlDocument = bmlDocument;
this.documentElement = documentElement;
this.resources = resources;
this.eventQueue = eventQueue;
this.eventDispatcher = eventDispatcher;
this.interpreter = interpreter;
this.videoContainer = videoContainer;
this.bmlEventTarget = bmlEventTarget;
this.indicator = indicator;
this.videoPlaneModeEnabled = videoPlaneModeEnabled;
this.inputApplication = inputApplication;
this.documentElement.addEventListener("keydown", (event) => {
if (event.altKey || event.ctrlKey || event.metaKey) {
return;
}
const k = keyCodeToAribKey(event.key);
if (k == -1) {
return;
}
event.preventDefault();
this.processKeyDown(k);
});
this.documentElement.addEventListener("keyup", (event) => {
if (event.altKey || event.ctrlKey || event.metaKey) {
return;
}
const k = keyCodeToAribKey(event.key);
if (k == -1) {
return;
}
event.preventDefault();
this.processKeyUp(k);
});
this.resources.addEventListener("dataeventchanged", async (event) => {
const { component, returnToEntryFlag } = event.detail;
console.log("DataEventChanged", event.detail);
const { moduleId, componentId } = this.resources.parseURLEx(this.resources.activeDocument);
if (moduleId == null || componentId == null) {
return;
}
// 現在視聴中のコンポーネントまたはエントリコンポーネント(固定)かつ引き戻しフラグであればスタートアップ文書を起動
const returnToEntry = (component.componentId === resources.startupComponentId && returnToEntryFlag);
if (!returnToEntry && component.componentId !== componentId) {
return;
}
this.eventQueue.queueGlobalAsyncEvent(async () => {
if (component.componentId === componentId) {
// Exは運用されない
const moduleLocked = this.documentElement.querySelectorAll("beitem[type=\"DataEventChanged\"]");
for (const elem of Array.from(moduleLocked)) {
const beitem = BML.nodeToBMLNode(elem, this.bmlDocument) as BML.BMLBeitemElement;
if (!beitem.subscribe) {
continue;
}
const onoccur = elem.getAttribute("onoccur");
if (onoccur == null) {
continue;
}
this.eventDispatcher.setCurrentBeventEvent({
type: "DataEventChanged",
target: elem as HTMLElement,
status: component.modules.size === 0 ? 1 : 0,
});
if (await this.eventQueue.executeEventHandler(onoccur)) {
return true;
}
this.eventDispatcher.resetCurrentEvent();
}
// 提示中のコンポーネントでのデータイベントの更新があった場合lockModuleOnMemoryとlockModuleOnMemoryExでロックしたモジュールのロックが解除される TR-B14 第二分冊 表5-11
this.resources.unlockModules();
};
if (component.componentId === componentId || returnToEntry) {
if (returnToEntry) {
// 引き戻しフラグによるエントリコンポーネントへの遷移の場合lockModuleOnMemoryでロックしたモジュールのロックが解除される TR-B14 第二分冊 表5-11
this.resources.unlockModules("lockModuleOnMemory");
}
console.error("launch startup (DataEventChanged)");
this.launchStartup();
return true;
}
return false;
});
this.eventQueue.processEventQueue();
});
this.resources.addEventListener("moduleupdated", (event) => {
const { componentId, moduleId } = event.detail;
if (this.resources.activeDocument == null) {
if (componentId === this.resources.startupComponentId && moduleId === this.resources.startupModuleId) {
if (!this.loaded) {
this.loaded = true;
this.resources.getProgramInfoAsync().then(_ => this.launchStartup());
}
}
}
});
this.resources.addEventListener("componentupdated", (event) => {
const { component } = event.detail;
for (const beitem of this.documentElement.querySelectorAll("beitem[type=\"ModuleUpdated\"][subscribe=\"subscribe\"]")) {
const bmlBeitem = BML.nodeToBMLNode(beitem, this.bmlDocument) as BML.BMLBeitemElement;
bmlBeitem.internalDIIUpdated(component.componentId, component.modules, component.dataEventId);
}
});
// TR-B14 第二分冊 2.1.10.3 PMT更新時の受信機動作
this.resources.addEventListener("pmtupdated", (event) => {
const { components, prevComponents } = event.detail;
const { componentId: currentComponentId } = this.resources.parseURLEx(this.resources.activeDocument);
for (const beitem of this.documentElement.querySelectorAll("beitem[type=\"ModuleUpdated\"][subscribe=\"subscribe\"]")) {
const bmlBeitem = BML.nodeToBMLNode(beitem, this.bmlDocument) as BML.BMLBeitemElement;
bmlBeitem.internalPMTUpdated(new Set(components.keys()));
}
if (currentComponentId == null) {
return;
}
// 視聴中のコンポーネントが消滅
if (currentComponentId != null && !components.has(currentComponentId)) {
this.eventQueue.queueGlobalAsyncEvent(async () => {
this.resources.unlockModules();
this.launchStartup();
return true;
});
this.eventQueue.processEventQueue();
return;
}
const prevPID = prevComponents.get(currentComponentId)?.pid;
const currentPID = components.get(currentComponentId)?.pid;
const prevEntryPID = prevComponents.get(this.resources.startupComponentId)?.pid;
const currentEntryPID = components.get(this.resources.startupComponentId)?.pid;
// 視聴中のコンポーネントのPIDが変化
if ((prevPID != null && prevPID !== currentPID) ||
// 引き戻しフラグ監視中のデータカルーセルを伝送するコンポーネントのPIDが変化
(prevEntryPID != null && prevEntryPID !== currentEntryPID)) {
// エントリコンポーネントが消滅
if (currentEntryPID == null) {
this.quitDocument();
return;
}
console.error("PID changed", prevPID, currentPID, prevEntryPID, currentEntryPID);
this.eventQueue.queueGlobalAsyncEvent(async () => {
this.resources.unlockModules();
this.resources.clearCache();
this.launchStartup();
return true;
});
this.eventQueue.processEventQueue();
}
});
}
private _currentDateMode: number = 0;
public set currentDateMode(timeMode: number) {
this._currentDateMode = timeMode;
}
public get currentDateMode(): number {
return this._currentDateMode;
}
private getBody() {
return this.documentElement.querySelector("body");
}
private clipVideoPlane(videoElement: Element | null) {
const body = this.getBody()!;
body.style.background = "transparent";
body.style.setProperty("background", "transparent", "important");
const aribBG = document.createElement("arib-bg");
body.insertAdjacentElement("afterbegin", aribBG);
type Rect = { left: number, right: number, top: number, bottom: number };
function getRect(baseElement: HTMLElement, elem: HTMLElement): Rect {
let left = 0;
let top = 0;
let element: HTMLElement | null = elem;
while (element != null && element !== baseElement) {
left += element.offsetLeft;
top += element.offsetTop;
element = element.parentElement;
}
return { left, top, right: left + elem.clientWidth, bottom: top + elem.clientHeight };
}
function intersectRect(rect1: Rect, rect2: Rect): Rect | null {
if (rect1.left < rect2.right && rect2.left < rect1.right && rect1.top < rect2.bottom && rect2.top < rect1.bottom) {
const left = Math.max(rect1.left, rect2.left);
const right = Math.min(rect1.right, rect2.right);
const top = Math.max(rect1.top, rect2.top);
const bottom = Math.min(rect1.bottom, rect2.bottom);
return { left, top, right, bottom };
} else {
return null;
}
}
if (videoElement != null) {
const bgJpegs: HTMLElement[] = Array.from(body.querySelectorAll("object[arib-type=\"image/jpeg\"]")).filter(x => {
return (x.compareDocumentPosition(videoElement) & Node.DOCUMENT_POSITION_FOLLOWING) === Node.DOCUMENT_POSITION_FOLLOWING;
}) as HTMLElement[];
const changed = () => {
// transformの影響を受けないbodyからの相対座標を算出
const body = this.getBody()!;
const videoRect = getRect(body, videoElement as HTMLElement);
const clipPath = `polygon(0% 0%, 0% 100%, ${videoRect.left}px 100%, ${videoRect.left}px ${videoRect.top}px, ${videoRect.right}px ${videoRect.top}px, ${videoRect.right}px ${videoRect.bottom}px, ${videoRect.left}px ${videoRect.bottom}px, ${videoRect.left}px 100%, 100% 100%, 100% 0%)`;
aribBG.style.clipPath = clipPath;
for (const bgJpeg of bgJpegs) {
const jpegRect = getRect(body, bgJpeg);
const intersect = intersectRect(videoRect, jpegRect);
if (intersect != null) {
intersect.left -= jpegRect.left;
intersect.right -= jpegRect.left;
intersect.top -= jpegRect.top;
intersect.bottom -= jpegRect.top;
bgJpeg.style.clipPath = `polygon(0% 0%, 0% 100%, ${intersect.left}px 100%, ${intersect.left}px ${intersect.top}px, ${intersect.right}px ${intersect.top}px, ${intersect.right}px ${intersect.bottom}px, ${intersect.left}px ${intersect.bottom}px, ${intersect.left}px 100%, 100% 100%, 100% 0%)`;
} else {
bgJpeg.style.clipPath = "";
}
}
this.bmlEventTarget.dispatchEvent<"videochanged">(new CustomEvent("videochanged", { detail: { boundingRect: videoElement.getBoundingClientRect(), clientRect: videoRect } }));
};
const observer = new MutationObserver(changed);
observer.observe(videoElement, { attributes: true });
for (const bgJpeg of bgJpegs) {
observer.observe(bgJpeg, { attributes: true });
}
changed();
}
}
private replaceTextCDATA(element: Node, result: Element[]) {
element.childNodes.forEach(e => {
if (e.nodeType === Node.COMMENT_NODE) {
return;
}
if (e.nodeType === Node.TEXT_NODE || e.nodeType === Node.CDATA_SECTION_NODE) {
result.push(e as Element);
} else {
if (e.nodeName.toLowerCase() !== "object") {
this.replaceTextCDATA(e, result);
}
}
});
}
private async loadDocumentToDOM(data: string): Promise<void> {
const xhtmlDocument = new DOMParser().parseFromString(`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"></html>`, "application/xhtml+xml");
const documentElement = xhtmlDocument.createElement("html");
documentElement.innerHTML = bmlToXHTMLFXP(data);
const p = Array.from(this.documentElement.childNodes).filter(x => x.nodeName.toLowerCase() === "body" || x.nodeName.toLowerCase() === "head");
const videoElementNew = documentElement.querySelector("[arib-type=\"video/X-arib-mpeg2\"]");
const prevBody = this.getBody();
const newBody = documentElement.querySelector("body")!;
prevBody?.setAttribute("arib-loading", "arib-loading");
newBody.setAttribute("arib-loading", "arib-loading");
for (const style of Array.from(documentElement.querySelectorAll("arib-style, arib-link"))) {
if (style.nodeName.toLowerCase() === "arib-link") {
const href = style.getAttribute("href");
if (href != null) {
const newStyle = document.createElement("style");
const res = await this.resources.fetchResourceAsync(href);
if (res != null) {
newStyle.textContent = await transpileCSS(decodeEUCJP(res.data), { inline: false, clutReader: this.getCLUT.bind(this), convertUrl: this.convertCSSUrl.bind(this) });
style.parentElement?.appendChild(newStyle);
}
}
} else if (style.textContent) {
const newStyle = document.createElement("style");
newStyle.textContent = await transpileCSS(style.textContent, { inline: false, clutReader: this.getCLUT.bind(this), convertUrl: this.convertCSSUrl.bind(this) });
style.parentElement?.appendChild(newStyle);
}
}
for (const style of Array.from(documentElement.querySelectorAll("[style]"))) {
const styleAttribute = style.getAttribute("style");
if (!styleAttribute) {
continue;
}
style.setAttribute("style", await transpileCSS(styleAttribute, { inline: true, clutReader: this.getCLUT.bind(this), convertUrl: this.convertCSSUrl.bind(this) }));
}
this.documentElement.append(...Array.from(documentElement.children));
if (videoElementNew != null) {
videoElementNew.appendChild(this.videoContainer);
}
if (this.strictTextRenderingEnabled) {
const t: Element[] = [];
this.replaceTextCDATA(newBody, t);
for (const e of t) {
const elem = document.createElement(e.nodeType === Node.TEXT_NODE ? "arib-text" : "arib-cdata");
elem.textContent = e.textContent;
e.replaceWith(elem);
}
}
newBody.removeAttribute("arib-loading");
for (const n of p) {
n.remove();
}
if (this.strictTextRenderingEnabled) {
newBody.querySelectorAll("arib-text, arib-cdata").forEach(elem => {
const cd = BML.nodeToBMLNode(elem, this.bmlDocument) as unknown as BML.CharacterData;
cd.internalReflow();
});
const observer = new MutationObserver((recs) => {
for (const rec of recs) {
(rec.target as Element).querySelectorAll("arib-text, arib-cdata").forEach(elem => {
const cd = BML.nodeToBMLNode(elem, this.bmlDocument) as unknown as BML.CharacterData;
cd.internalReflow();
});
}
});
observer.observe(newBody, {
attributeFilter: ["style"],
attributes: true,
subtree: true,
});
}
if (this.videoPlaneModeEnabled) {
this.clipVideoPlane(videoElementNew);
}
}
private focusHelper(element?: HTMLElement | null) {
if (element == null) {
return;
}
const felem = BML.htmlElementToBMLHTMLElement(element, this.bmlDocument);
if (felem && (felem as any).focus) {
(felem as any).focus();
}
}
public unloadAllDRCS() {
for (const font of this.fonts) {
document.fonts.delete(font);
}
this.fonts.length = 0;
}
private _context: any = {};
public get context() {
return this._context;
}
private async unloadDocument() {
// スクリプトが呼ばれているときにさらにスクリプトが呼ばれることはないがonunloadだけ例外
this.interpreter.resetStack();
const onunload = this.getBody()?.getAttribute("arib-onunload");
if (onunload != null) {
this.eventDispatcher.setCurrentEvent({
target: null,
type: "unload",
});
if (await this.eventQueue.executeEventHandler(onunload)) {
// readPersistentArray writePersistentArray unlockModuleOnMemoryEx unlockAllModulesOnMemoryしか呼び出せないので終了したらおかしい
console.error("onunload");
return true;
}
this.eventDispatcher.resetCurrentEvent();
}
this.inputApplication?.cancel("unload");
this.interpreter.reset();
this.currentDateMode = 0;
this.keyProcessStatus = undefined;
this.npt = undefined;
}
public async quitDocument() {
await this.unloadDocument();
this.eventQueue.reset();
this.unloadAllDRCS();
this.resources.unlockModules();
this._context = { from: this.resources.activeDocument, to: null };
this.resources.activeDocument = null;
this.bmlEventTarget.dispatchEvent<"invisible">(new CustomEvent("invisible", { detail: true }));
const p = Array.from(this.documentElement.childNodes).filter(x => x.nodeName.toLowerCase() === "body" || x.nodeName.toLowerCase() === "head");
for (const n of p) {
n.remove();
}
this.loaded = false;
}
private async loadDocument(file: CachedFile, documentName: string): Promise<boolean> {
await this.unloadDocument();
this._context = { from: this.resources.activeDocument, to: documentName };
this.bmlDocument._currentFocus = null;
// 提示中の文書と同一サービス内の別コンポーネントへの遷移の場合lockModuleOnMemoryでロックしたモジュールのロックは解除される TR-B14 第二分冊 表5-11
const { componentId: nextComponent } = this.resources.parseURLEx(documentName);
const { componentId: prevComponent } = this.resources.parseURLEx(this.resources.activeDocument);
if (prevComponent !== nextComponent) {
this.resources.unlockModules("lockModuleOnMemory");
}
this.resources.activeDocument = documentName;
await requestAnimationFrameAsync();
await this.loadDocumentToDOM(decodeEUCJP(file.data));
this.loadObjects();
this.eventQueue.reset();
this.unloadAllDRCS();
let width: number = 960;
let height: number = 540;
const body = this.getBody()!;
const bmlBody = BML.nodeToBMLNode(body, this.bmlDocument) as BML.BMLBodyElement;
const bodyStyle = window.getComputedStyle(body);
const resolution = bodyStyle.getPropertyValue("--resolution").trim();
const displayAspectRatio = bodyStyle.getPropertyValue("--display-aspect-ratio").trim();
let aspectNum = 16;
let aspectDen = 9;
if (resolution === "720x480") {
if (displayAspectRatio === "4v3") {
[width, height] = [720, 480];
aspectNum = 4;
aspectDen = 3;
} else {
[width, height] = [720, 480];
}
}
this.bmlEventTarget.dispatchEvent<"load">(new CustomEvent("load", { detail: { resolution: { width, height }, displayAspectRatio: { numerator: aspectNum, denominator: aspectDen } } }));
body.style.maxWidth = width + "px";
body.style.minWidth = width + "px";
body.style.maxHeight = height + "px";
body.style.minHeight = height + "px";
bmlBody.invisible = bmlBody.invisible;
const usedKeyList = bodyStyle.getPropertyValue("--used-key-list");
this.bmlEventTarget.dispatchEvent<"usedkeylistchanged">(new CustomEvent("usedkeylistchanged", {
detail: {
usedKeyList: new Set(usedKeyList.split(" ").filter((x): x is "basic" | "numeric-tuning" | "data-button" => {
return x === "basic" || x === "numeric-tuning" || x === "data-button";
}))
}
}));
// フォーカスはonloadの前に当たるがonloadが実行されるまではイベントは実行されない
// STD-B24 第二分冊(2/2) 第二編 付属1 5.1.3参照
this.eventQueue.lockSyncEventQueue();
let exit = false;
let scriptCount = 0;
try {
this.focusHelper(this.findNavIndex(0));
for (const x of Array.from(this.documentElement.querySelectorAll("arib-script"))) {
const src = x.getAttribute("src");
if (src) {
const res = await this.resources.fetchResourceAsync(src);
if (res !== null) {
if (exit = await this.interpreter.addScript(decodeEUCJP(res.data), src)) {
return true;
}
}
} else if (x.textContent != null) {
scriptCount++;
if (exit = await this.interpreter.addScript(x.textContent, `${this.resources.activeDocument ?? ""}[${scriptCount}]`)) {
return true;
}
}
}
const onload = this.getBody()?.getAttribute("arib-onload");
if (onload != null) {
console.debug("START ONLOAD");
this.eventDispatcher.setCurrentEvent({
target: null,
type: "load",
});
if (exit = await this.eventQueue.executeEventHandler(onload)) {
return true;
}
this.eventDispatcher.resetCurrentEvent();
console.debug("END ONLOAD");
}
for (const beitem of this.documentElement.querySelectorAll("beitem[subscribe=\"subscribe\"]")) {
const bmlBeitem = BML.nodeToBMLNode(beitem, this.bmlDocument) as BML.BMLBeitemElement;
bmlBeitem.subscribe = bmlBeitem.subscribe;
}
}
finally {
if (!exit) {
this.eventQueue.unlockSyncEventQueue();
}
}
console.debug("START PROC EVQ");
if (await this.eventQueue.processEventQueue()) {
return true;
}
console.debug("END PROC EVQ");
this.indicator?.setUrl(this.resources.activeDocument.replace(/(?<=^https?:\/\/)[^/]+/, "…"), false);
return false;
}
private processTimerEvent() {
const timerFired = this.documentElement.querySelectorAll("beitem[type=\"TimerFired\"]");
timerFired.forEach(elem => {
const beitem = BML.nodeToBMLNode(elem, this.bmlDocument) as BML.BMLBeitemElement;
if (!beitem.subscribe) {
return;
}
if (beitem.internalTimerFired) {
return;
}
const timeValue = beitem.timeValue;
if (beitem.timeMode === "absolute" || beitem.timeMode === "origAbsolute") {
if (timeValue.length !== 14) {
return;
}
const year = Number.parseInt(timeValue.substring(0, 4));
const month = Number.parseInt(timeValue.substring(4, 6));
const day = Number.parseInt(timeValue.substring(6, 8));
const hour = Number.parseInt(timeValue.substring(8, 10));
const minute = Number.parseInt(timeValue.substring(10, 12));
const second = Number.parseInt(timeValue.substring(12, 14));
const date = new Date(year, month - 1, day, hour, minute, second);
const time = date.getTime();
if (this.resources.currentTimeUnixMillis != null && time <= this.resources.currentTimeUnixMillis) {
beitem.internalTimerFired = true;
this.eventDispatcher.dispatchTimerFiredEvent(0, elem);
}
} else if (beitem.timeMode === "NPT") {
// NPTが不定の時にsubscribeされたときは微妙
const npt = Number.parseInt(timeValue);
if (Number.isNaN(npt) || this.npt == null) {
return;
}
const currentNPT = this.getNPT90kHz();
if (currentNPT == null) {
return;
}
if (npt <= currentNPT / 90) {
beitem.internalTimerFired = true;
this.eventDispatcher.dispatchTimerFiredEvent(0, elem);
}
}
});
}
public launchDocument(documentName: string) {
this.launchDocumentAsync(documentName);
return NaN;
}
private async launchStartup(): Promise<boolean> {
const module = `/${this.resources.startupComponentId.toString(16).padStart(2, "0")}/${this.resources.startupModuleId.toString(16).padStart(4, "0")}`;
await this.resources.fetchResourceAsync(module);
if (this.resources.fetchLockedResource(module + "/startup.bml")) {
await this.launchDocumentAsync(module + "/startup.bml");
return true;
} else if (this.resources.fetchLockedResource(module)) {
await this.launchDocumentAsync(module);
return true;
} else {
this.quitDocument();
}
return false;
}
private async launchDocumentAsync(documentName: string) {
console.log("%claunchDocument", "font-size: 4em", documentName);
this.eventQueue.discard();
const { component, module, filename } = this.resources.parseURL(documentName);
const componentId = Number.parseInt(component ?? "", 16);
const moduleId = Number.parseInt(module ?? "", 16);
let normalizedDocument: string;
if (!Number.isInteger(componentId) || !Number.isInteger(moduleId)) {
const isInternet = documentName.startsWith("http://") || documentName.startsWith("https://");
if (isInternet && !this.resources.isInternetContent) {
// 放送コンテンツ->通信コンテンツへの遷移
this.resources.setBaseURIDirectory(documentName);
normalizedDocument = documentName;
} else if (this.resources.activeDocument != null && this.resources.isInternetContent) {
// 通信コンテンツ->通信コンテンツへの遷移
if (!this.resources.checkBaseURIDirectory(documentName)) {
console.error("base URI directory violation");
await this.quitDocument();
return NaN;
}
normalizedDocument = new URL(documentName, this.resources.activeDocument).toString();
} else {
await this.quitDocument();
return NaN;
}
} else if (filename != null) {
normalizedDocument = `/${componentId.toString(16).padStart(2, "0")}/${moduleId.toString(16).padStart(4, "0")}/${filename}`;
} else {
normalizedDocument = `/${componentId.toString(16).padStart(2, "0")}/${moduleId.toString(16).padStart(4, "0")}`;
}
this.indicator?.setUrl(normalizedDocument.replace(/(?<=^https?:\/\/)[^/]+/, "…"), true);
const res = await this.resources.fetchResourceAsync(documentName);
if (res == null) {
console.error("NOT FOUND");
await this.quitDocument();
return NaN;
}
const ad = this.resources.activeDocument;
await this.loadDocument(res, normalizedDocument);
console.log("return ", ad, documentName);
return NaN;
}
private findNavIndex(navIndex: number): HTMLElement | undefined {
return Array.from(this.documentElement.querySelectorAll("*")).find(elem => {
return parseInt(window.getComputedStyle(elem).getPropertyValue("--nav-index")) == navIndex;
}) as (HTMLElement | undefined);
}
private keyProcessStatus?: KeyProcessStatus;
public processKeyDown(k: AribKeyCode) {
if (k === AribKeyCode.DataButton) {
// データボタンの場合DataButtonPressedのみが発生する
this.eventDispatcher.dispatchDataButtonPressedEvent();
return;
}
if (this.keyProcessStatus != null) {
return;
}
const keyProcessStatus: KeyProcessStatus = {
keyCode: k,
isAccessKey: false,
};
this.keyProcessStatus = keyProcessStatus;
let focusElement = this.bmlDocument.currentFocus && this.bmlDocument.currentFocus["node"];
if (!focusElement) {
return;
}
if (focusElement instanceof HTMLInputElement) {
const inputMode = focusElement.getAttribute("inputmode");
if (inputMode !== "direct" && inputMode !== "indirect") {
// FIXME: changeイベントをフォーカス移動の際に発生させる (STD-B24 第二分冊(2/2) 5.3.1.3)
if (k >= AribKeyCode.Digit0 && k <= AribKeyCode.Digit9) {
const num = (k - AribKeyCode.Digit0).toString();
if (focusElement.maxLength > focusElement.value.length) {
focusElement.value += num;
}
} else if (k === AribKeyCode.Back) {
if (focusElement.value.length >= 1) {
focusElement.value = focusElement.value.substring(0, focusElement.value.length - 1);
}
}
}
}
const computedStyle = window.getComputedStyle(this.getBody()!);
const usedKeyList = computedStyle.getPropertyValue("--used-key-list").split(" ").filter(x => x.length);
if (usedKeyList.length && usedKeyList[0] === "none") {
return;
}
const keyGroup = keyCodeToKeyGroup.get(k);
if (keyGroup == null) {
return;
}
if (usedKeyList.length === 0) {
if (keyGroup !== "basic" && keyGroup !== "data-button") {
return;
}
} else if (!usedKeyList.some(x => x === keyGroup)) {
return;
}
focusElement = this.bmlDocument.currentFocus && this.bmlDocument.currentFocus["node"];
if (!focusElement) {
return;
}
const onkeydown = focusElement.getAttribute("onkeydown");
this.eventQueue.queueAsyncEvent(async () => {
if (onkeydown) {
this.eventDispatcher.setCurrentIntrinsicEvent({
keyCode: k as number,
type: "keydown",
target: focusElement,
});
let exit = false;
try {
this.eventQueue.lockSyncEventQueue();
if (exit = await this.eventQueue.executeEventHandler(onkeydown)) {
return true;
}
} finally {
if (!exit) {
this.eventQueue.unlockSyncEventQueue();
}
}
this.eventDispatcher.resetCurrentEvent();
}
// STD-B24 第二分冊 (2/2) 第二編 付属1 5.4.2.3参照
const accessKey = keyCodeToAccessKey.get(k);
if (accessKey != null) {
const elem = this.documentElement.querySelector(`[accesskey="${accessKey}"]`) as HTMLElement;
if (elem != null && BML.isFocusable(elem)) {
this.focusHelper(elem);
console.warn("accesskey is half implemented.");
// [6] 疑似的にkeyup割り込み事象が発生 keyCode = アクセスキー
const onkeyup = elem.getAttribute("onkeyup");
if (onkeyup != null) {
this.eventDispatcher.setCurrentIntrinsicEvent({
keyCode: k as number,
type: "keyup",
target: elem,
});
let exit = false;
try {
this.eventQueue.lockSyncEventQueue();
if (exit = await this.eventQueue.executeEventHandler(onkeyup)) {
return true;
}
} finally {
if (!exit) {
this.eventQueue.unlockSyncEventQueue();
}
}
this.eventDispatcher.resetCurrentEvent();
}
// [6] 疑似的にkeydown割り込み事象が発生 keyCode = 決定キー
const onkeydown = elem.getAttribute("onkeydown");
k = AribKeyCode.Enter;
if (onkeydown != null) {
this.eventDispatcher.setCurrentIntrinsicEvent({
keyCode: k as number,
type: "keydown",
target: elem,
});
let exit = false;
try {
this.eventQueue.lockSyncEventQueue();
if (exit = await this.eventQueue.executeEventHandler(onkeydown)) {
return true;
}
} finally {
if (!exit) {
this.eventQueue.unlockSyncEventQueue();
}
}
this.eventDispatcher.resetCurrentEvent();
}
keyProcessStatus.isAccessKey = true;
}
}
focusElement = this.bmlDocument.currentFocus && this.bmlDocument.currentFocus["node"];
if (focusElement) {
// [4] A'に対してnavigation関連特性を適用
let nextFocus = "";
let nextFocusStyle = window.getComputedStyle(focusElement);
while (true) {
if (k == AribKeyCode.Left) {
nextFocus = nextFocusStyle.getPropertyValue("--nav-left");
} else if (k == AribKeyCode.Right) {
nextFocus = nextFocusStyle.getPropertyValue("--nav-right");
} else if (k == AribKeyCode.Up) {
nextFocus = nextFocusStyle.getPropertyValue("--nav-up");
} else if (k == AribKeyCode.Down) {
nextFocus = nextFocusStyle.getPropertyValue("--nav-down");
}
const nextFocusIndex = parseInt(nextFocus);
if (Number.isFinite(nextFocusIndex) && nextFocusIndex >= 0 && nextFocusIndex <= 32767) {
const next = this.findNavIndex(nextFocusIndex);
if (next != null) {
nextFocusStyle = window.getComputedStyle(next);
// 非表示要素であれば飛ばされる (STD-B24 第二分冊 (1/2 第二編) 5.4.13.3参照)
if (!BML.isFocusable(next)) {
continue;
}
this.focusHelper(next);
}
}
break;
}
}
focusElement = this.bmlDocument.currentFocus && this.bmlDocument.currentFocus["node"];
if (k == AribKeyCode.Enter && focusElement) {
focusElement.setAttribute("arib-active", "arib-active");
this.eventQueue.queueSyncEvent({ type: "click", target: focusElement });
if (this.bmlDocument.currentFocus instanceof BML.BMLInputElement) {
const inputMode = focusElement.getAttribute("inputmode");
if (inputMode === "indirect") {
this.bmlDocument.currentFocus.internalLaunchInputApplication();
}
}
}
// [11] accessKeyの場合focusElementに対し決定キーのkeyupを発生させる必要がある
return false;
});
this.eventQueue.processEventQueue();
}
public processKeyUp(k: AribKeyCode) {
if (k === AribKeyCode.DataButton) {
return;
}
this.eventQueue.queueAsyncEvent(async () => {
const keyProcessStatus = this.keyProcessStatus;
if (keyProcessStatus?.keyCode !== k) {
return false;
} else {
this.keyProcessStatus = undefined;
}
const focusElement = this.bmlDocument.currentFocus && this.bmlDocument.currentFocus["node"];
if (!focusElement) {
return false;
}
const keyCode = keyProcessStatus.isAccessKey ? AribKeyCode.Enter : k;
if (keyCode === AribKeyCode.Enter) {
focusElement.removeAttribute("arib-active");
}
const computedStyle = window.getComputedStyle(this.getBody()!);
const usedKeyList = computedStyle.getPropertyValue("--used-key-list").split(" ").filter(x => x.length);
if (usedKeyList.length && usedKeyList[0] === "none") {
return false;
}
const keyGroup = keyCodeToKeyGroup.get(keyCode);
if (keyGroup == null) {
return false;
}
if (usedKeyList.length === 0) {
if (keyGroup !== "basic" && keyGroup !== "data-button") {
return false;
}
} else if (!usedKeyList.some(x => x === keyGroup)) {
return false;
}
const onkeyup = focusElement.getAttribute("onkeyup");
if (onkeyup) {
this.eventDispatcher.setCurrentIntrinsicEvent({
keyCode,
type: "keyup",
target: focusElement,
});
let exit = false;
try {
this.eventQueue.lockSyncEventQueue();
if (exit = await this.eventQueue.executeEventHandler(onkeyup)) {
return true;
}
} finally {
if (!exit) {
this.eventQueue.unlockSyncEventQueue();
}
}
this.eventDispatcher.resetCurrentEvent();
}
return false;
});
this.eventQueue.processEventQueue();
}
private clutToDecls(table: number[][]): css.Declaration[] {
const ret = [];
let i = 0;
for (const t of table) {
const decl: css.Declaration = {
type: "declaration",
property: "--clut-color-" + i,
value: `rgba(${t[0]},${t[1]},${t[2]},${t[3] / 255})`,
};
ret.push(decl);
i++;
}
return ret;
}
private async getCLUT(clutUrl: string): Promise<css.Declaration[]> {
const res = await this.resources.fetchResourceAsync(clutUrl);
let clut = defaultCLUT;
if (res?.data) {
clut = readCLUT(Buffer.from(res.data));
}
return this.clutToDecls(clut);
}
private async convertCSSUrl(url: string): Promise<string> {
const res = await this.resources.fetchResourceAsync(url);
if (!res) {
return url;
}
// background-imageはJPEGのみ運用される (STD-B24 第二分冊(2/2) 付属2 4.4.6)
let bt709 = res.blobUrl.get("BT.709");
if (bt709 != null) {
return bt709.blobUrl;
}
const bt601 = this.resources.getCachedFileBlobUrl(res);
bt709 = await convertJPEG(bt601);
res.blobUrl.set("BT.709", bt709);
return bt709.blobUrl;
}
private loadObjects() {
this.documentElement.querySelectorAll("object").forEach(obj => {
const adata = obj.getAttribute("arib-data");
BML.nodeToBMLNode(obj, this.bmlDocument).data = adata!;
});
}
pcrBase?: number;
public getNPT90kHz(): number | null {
if (this.npt == null || this.pcrBase == null) {
return null;
}
// TR-B14 第二分冊 NPT値算出アルゴリズムを参照
const STCr = this.npt.stcReference;
const NPTr = this.npt.nptReference;
const STCc = this.pcrBase;
const Wpre = 3888000000;
const Wpost = 3888000000;
const STCmax = 0x1FFFFFFFF;
if ((STCc > STCr && STCc - STCr <= Wpost) || (STCc < STCr && STCc + STCmax - STCr <= Wpost)) {
if (this.npt.scaleDenominator === 1 && this.npt.scaleNumerator === 1) {
return (STCc + ((STCmax + NPTr - STCr) % STCmax)) % STCmax;
} else if (this.npt.scaleDenominator === 1 && this.npt.scaleNumerator === 0) {
return NPTr;
} else {
return null;
}
} else if ((STCc > STCr && STCr + STCmax - STCc <= Wpre) || (STCc < STCr && STCr - STCc <= Wpre)) {
if (this.npt.scaleDenominator === 1 && this.npt.scaleNumerator === 1) {
return NPTr;
} else if (this.npt.scaleDenominator === 1 && this.npt.scaleNumerator === 0) {
return (STCc + ((STCmax + NPTr - STCr) % STCmax)) % STCmax;
} else {
return null;
}
}
return null;
}
public onMessage(msg: ResponseMessage) {
if (msg.type === "pcr") {
this.pcrBase = msg.pcrBase;
this.processTimerEvent();
} else if (msg.type === "esEventUpdated") {
const activeComponentId = this.resources.currentComponentId;
if (activeComponentId == null) {
return;
}
let queued = false;
const nptReference = msg.events.find((x): x is NPTReference => x.type === "nptReference");
if (this.pcrBase != null && nptReference != null) {
if (this.npt != null || nptReference.STCReference <= this.pcrBase) {
const nptChanged = this.npt == null ||
this.npt.nptReference !== nptReference.NPTReference || this.npt.stcReference !== nptReference.STCReference ||
this.npt.scaleDenominator !== nptReference.scaleDenominator || this.npt.scaleNumerator !== nptReference.scaleNumerator;
if (nptChanged) {
this.npt = {
nptReference: nptReference.NPTReference,
stcReference: nptReference.STCReference,
scaleDenominator: nptReference.scaleDenominator,
scaleNumerator: nptReference.scaleNumerator,
};
console.log("NPTReferred", this.npt);
}
const nptReferred = this.documentElement.querySelectorAll("beitem[type=\"NPTReferred\"][subscribe=\"subscribe\"]");
for (const beitemNative of Array.from(nptReferred)) {
const beitem = BML.nodeToBMLNode(beitemNative, this.bmlDocument) as BML.BMLBeitemElement;
if (!beitem.subscribe) {
continue;
}
if (!nptChanged && beitem.internalNPTReferred) {
continue;
}
const es_ref = beitem.esRef;
// STD-B24的には未指定の時現在のコンポーネントだけど運用規定的には独立したコンポーネントで伝送される
let componentId = activeComponentId;
if (es_ref != null) {
const esRefComponentId = this.resources.parseURLEx(es_ref).componentId;
if (esRefComponentId != null) {
componentId = esRefComponentId;
}
}
if (componentId !== msg.componentId) {
continue;
}
beitem.internalNPTReferred = true;
const onoccur = beitemNative.getAttribute("onoccur");
if (!onoccur) {
continue;
}
this.eventQueue.queueAsyncEvent(async () => {
this.eventDispatcher.setCurrentBeventEvent({
type: "NPTReferred",
target: beitemNative as HTMLElement,
status: 0,
esRef: es_ref ?? ("/" + componentId.toString(16).padStart(2, "0")),
});
if (await this.eventQueue.executeEventHandler(onoccur)) {
return true;
}
this.eventDispatcher.resetCurrentEvent();
return false;
});
queued = true;
}
}
}
const eventMessageFired = this.documentElement.querySelectorAll("beitem[type=\"EventMessageFired\"][subscribe=\"subscribe\"]");
eventMessageFired.forEach((beitemNative) => {
const beitem = BML.nodeToBMLNode(beitemNative, this.bmlDocument) as BML.BMLBeitemElement;
if (!beitem.subscribe) {
return;
}
const es_ref = beitem.esRef;
// message_group_idは0,1のみ運用される
// 省略時は0
const message_group_id = beitem.messageGroupId;
const message_id = beitem.messageId;
const message_version = beitem.messageVersion;
const onoccur = beitemNative.getAttribute("onoccur");
if (!onoccur) {
return;
}
let componentId = activeComponentId;
if (es_ref != null) {
const esRefComponentId = this.resources.parseURLEx(es_ref).componentId;
if (esRefComponentId != null) {
componentId = esRefComponentId;
}
}
for (const event of msg.events) {
// 即時イベントのみ実装
if (event.type === "nptEvent") {
const currentNPT = this.getNPT90kHz();
if (currentNPT == null || event.eventMessageNPT > currentNPT) {
continue;
}
} else if (event.type !== "immediateEvent") {
continue;
}
if (event.eventMessageGroupId !== message_group_id) {
continue;
}
if (event.eventMessageGroupId === 0) {
if (this.resources.currentDataEventId !== msg.dataEventId) {
continue;
}
}
const eventMessageId = event.eventMessageId >> 8;
const eventMessageVersion = event.eventMessageId & 0xff;
if (message_id !== 255 && message_id !== eventMessageId) {
continue;
}
if (message_version !== 255 && message_version !== eventMessageVersion) {
continue;
}
if (beitem.internalMessageVersion == null) {
beitem.internalMessageVersion = new Map<number, number>();
}
if (beitem.internalMessageVersion.get(eventMessageId) === eventMessageVersion) {
continue;
}
beitem.internalMessageVersion.set(eventMessageId, eventMessageVersion);
const privateData = decodeEUCJP(Uint8Array.from(event.privateDataByte));
console.log("EventMessageFired", eventMessageId, eventMessageVersion, privateData);
this.eventQueue.queueAsyncEvent(async () => {
this.eventDispatcher.setCurrentBeventEvent({
type: "EventMessageFired",
target: beitemNative as HTMLElement,
status: 0,
privateData,
esRef: es_ref ?? ("/" + componentId.toString(16).padStart(2, "0")),
messageId: eventMessageId,
messageVersion: eventMessageVersion,
messageGroupId: event.eventMessageGroupId,
});
if (await this.eventQueue.executeEventHandler(onoccur)) {
return true;
}
this.eventDispatcher.resetCurrentEvent();
return false;
});
queued = true;
}
});
if (queued) {
this.eventQueue.processEventQueue();
}
}
}
public addDRCSFont(font: FontFace) {
this.fonts.push(font);
document.fonts.add(font);
}
public get invisible(): boolean | undefined {
const body = this.getBody();
if (body == null) {
return undefined;
}
return (BML.nodeToBMLNode(body, this.bmlDocument) as BML.BMLBodyElement).invisible;
}
} | the_stack |
export interface ThemeSyntaxPreviewContents {
name: string;
text: string;
mimeType: string;
}
export const ThemeSyntaxPreviewContents: ThemeSyntaxPreviewContents[] = [
{ name: "Plain Text", mimeType: "text/plain", text: `Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
` },
{ name: "Batch file", mimeType: "application/bat", text: `:: batch file highlighting in Ace!
@echo off
CALL set var1=%cd%
echo unhide everything in %var1%!
:: FOR loop in bat is super strange!
FOR /f "tokens=*" %%G IN ('dir /A:D /b') DO (
echo %var1%%%G
attrib -r -a -h -s "%var1%%%G" /D /S
)
pause
REM that's all
`},
{ name: "CSS", mimeType: "text/css", text: `.text-layer {
font: 12px Monaco, "Courier New", monospace;
font-size: 3vmin;
cursor: text;
}
.blinker {
animation: blink 1s linear infinite alternate;
}
@keyframes blink {
0%, 40% {
opacity: 0; /*
*/
opacity: 1
}
40.5%, 100% {
opacity: 1
}
}
@document url(http://c9.io/), url-prefix(http://ace.c9.io/build/),
domain(c9.io), regexp("https:.*") /**/
{
/**/
img[title]:before
{
content: attr(title) "\AImage \
retrieved from"
attr(src); /*
*/
white-space: pre;
display: block;
background: url(asdasd); "err
}
}
@viewport {
min-zoom: 1;
max-zoom: 200%;
user-zoom: fixed;
}
`},
{ name: "Diff", mimeType: "text/x-diff", text: `diff --git a/lib/ace/edit_session.js b/lib/ace/edit_session.js
index 23fc3fc..ed3b273 100644
--- a/lib/ace/edit_session.js
+++ b/lib/ace/edit_session.js
@@ -51,6 +51,7 @@ var TextMode = require("./mode/text").Mode;
var Range = require("./range").Range;
var Document = require("./document").Document;
var BackgroundTokenizer = require("./background_tokenizer").BackgroundTokenizer;
+var SearchHighlight = require("./search_highlight").SearchHighlight;
/**
* class EditSession
@@ -307,6 +308,13 @@ var EditSession = function(text, mode) {
return token;
};
+ this.highlight = function(re) {
+ if (!this.$searchHighlight) {
+ var highlight = new SearchHighlight(null, "ace_selected-word", "text");
+ this.$searchHighlight = this.addDynamicMarker(highlight);
+ }
+ this.$searchHighlight.setRegexp(re);
+ }
/**
* EditSession.setUndoManager(undoManager)
* - undoManager (UndoManager): The new undo manager
@@ -556,7 +564,8 @@ var EditSession = function(text, mode) {
type : type || "line",
renderer: typeof type == "function" ? type : null,
clazz : clazz,
- inFront: !!inFront
+ inFront: !!inFront,
+ id: id
}
if (inFront) {
diff --git a/lib/ace/editor.js b/lib/ace/editor.js
index 834e603..b27ec73 100644
--- a/lib/ace/editor.js
+++ b/lib/ace/editor.js
@@ -494,7 +494,7 @@ var Editor = function(renderer, session) {
* Emitted when a selection has changed.
**/
this.onSelectionChange = function(e) {
- var session = this.getSession();
+ var session = this.session;
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
@@ -509,12 +509,40 @@ var Editor = function(renderer, session) {
this.$updateHighlightActiveLine();
}
- var self = this;
- if (this.$highlightSelectedWord && !this.$wordHighlightTimer)
- this.$wordHighlightTimer = setTimeout(function() {
- self.session.$mode.highlightSelection(self);
- self.$wordHighlightTimer = null;
- }, 30, this);
+ var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp()
};
diff --git a/lib/ace/search_highlight.js b/lib/ace/search_highlight.js
new file mode 100644
index 0000000..b2df779
--- /dev/null
+++ b/lib/ace/search_highlight.js
@@ -0,0 +1,3 @@
+new
+empty file`},
{ name: "Dockerfile", mimeType: "text/x-dockerfile", text: `#
# example Dockerfile for http://docs.docker.io/en/latest/examples/postgresql_service/
#
FROM ubuntu
MAINTAINER SvenDowideit@docker.com
# Add the PostgreSQL PGP key to verify their Debian packages.
# It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
# Add PostgreSQL's repository. It contains the most recent stable release
# of PostgreSQL, \`\`9.3\`\`.
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
# Update the Ubuntu and PostgreSQL repository indexes
RUN apt-get update
# Install \`\`python-software-properties\`\`, \`\`software-properties-common\`\` and PostgreSQL 9.3
# There are some warnings (in red) that show up during the build. You can hide
# them by prefixing each apt-get statement with DEBIAN_FRONTEND=noninteractive
RUN apt-get -y -q install python-software-properties software-properties-common
RUN apt-get -y -q install postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3
# Note: The official Debian and Ubuntu images automatically \`\`apt-get clean\`\`
# after each \`\`apt-get\`\`
# Run the rest of the commands as the \`\`postgres\`\` user created by the \`\`postgres-9.3\`\` package when it was \`\`apt-get installed\`\`
USER postgres
# Create a PostgreSQL role named \`\`docker\`\` with \`\`docker\`\` as the password and
# then create a database \`docker\` owned by the \`\`docker\`\` role.
# Note: here we use \`\`&&\\\`\` to run commands one after the other - the \`\`\\\`\`
# allows the RUN command to span multiple lines.
RUN /etc/init.d/postgresql start &&\\
psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" &&\\
createdb -O docker docker
# Adjust PostgreSQL configuration so that remote connections to the
# database are possible.
RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf
# And add \`\`listen_addresses\`\` to \`\`/etc/postgresql/9.3/main/postgresql.conf\`\`
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf
# Expose the PostgreSQL port
EXPOSE 5432
# Add VOLUMEs to allow backup of config, logs and databases
VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
# Set the default command to run when starting the container
CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]`},
{ name: "HTML", mimeType: "text/html", text: `<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.text-layer {
font-family: Monaco, "Courier New", monospace;
font-size: 12px;
cursor: text;
}
</style>
</head>
<body>
<h1 style="color:red">Juhu Kinners</h1>
</body>
</html>`},
{ name: "PowerShell", mimeType: "application/x-powershell", text: `# This is a simple comment
function Hello($name) {
Write-host "Hello $name"
}
function add($left, $right=4) {
if ($right -ne 4) {
return $left
} elseif ($left -eq $null -and $right -eq 2) {
return 3
} else {
return 2
}
}
$number = 1 + 2;
$number += 3
Write-Host Hello -name "World"
$an_array = @(1, 2, 3)
$a_hash = @{"something" = "something else"}
& notepad .\\readme.md
`},
{ name: "SH", mimeType: "application/x-sh", text: `#!/bin/sh
# Script to open a browser to current branch
# Repo formats:
# ssh git@github.com:richo/gh_pr.git
# http https://richoH@github.com/richo/gh_pr.git
# git git://github.com/richo/gh_pr.git
username=\`git config --get github.user\`
get_repo() {
git remote -v | grep \${@:-$username} | while read remote; do
if repo=\`echo $remote | grep -E -o "git@github.com:[^ ]*"\`; then
echo $repo | sed -e "s/^git@github\\.com://" -e "s/\\.git$//"
exit 1
fi
if repo=\`echo $remote | grep -E -o "https?://([^@]*@)?github.com/[^ ]*\\.git"\`; then
echo $repo | sed -e "s|^https?://||" -e "s/^.*github\.com\\///" -e "s/\\.git$//"
exit 1
fi
if repo=\`echo $remote | grep -E -o "git://github.com/[^ ]*\\.git"\`; then
echo $repo | sed -e "s|^git://github.com/||" -e "s/\\.git$//"
exit 1
fi
done
if [ $? -eq 0 ]; then
echo "Couldn't find a valid remote" >&2
exit 1
fi
}
echo \${#x[@]}
if repo=\`get_repo $@\`; then
branch=\`git symbolic-ref HEAD 2>/dev/null\`
echo "http://github.com/$repo/pull/new/\${branch##refs/heads/}"
else
exit 1
fi
`},
{ name: "XML", mimeType: "text/xml", text:
`<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
yahoo:count="7" yahoo:created="2011-10-11T08:40:23Z" yahoo:lang="en-US">
<diagnostics>
<publiclyCallable>true</publiclyCallable>
<url execution-start-time="0" execution-stop-time="25" execution-time="25"><![CDATA[http://where.yahooapis.com/v1/continents;start=0;count=10]]></url>
<user-time>26</user-time>
<service-time>25</service-time>
<build-version>21978</build-version>
</diagnostics>
<results>
<place xmlns="http://where.yahooapis.com/v1/schema.rng"
xml:lang="en-US" yahoo:uri="http://where.yahooapis.com/v1/place/24865670">
<woeid>24865670</woeid>
<placeTypeName code="29">Continent</placeTypeName>
<name>Africa</name>
</place>
<place xmlns="http://where.yahooapis.com/v1/schema.rng"
xml:lang="en-US" yahoo:uri="http://where.yahooapis.com/v1/place/24865675">
<woeid>24865675</woeid>
<placeTypeName code="29">Continent</placeTypeName>
<name>Europe</name>
</place>
<place xmlns="http://where.yahooapis.com/v1/schema.rng"
xml:lang="en-US" yahoo:uri="http://where.yahooapis.com/v1/place/24865673">
<woeid>24865673</woeid>
<placeTypeName code="29">Continent</placeTypeName>
<name>South America</name>
</place>
<place xmlns="http://where.yahooapis.com/v1/schema.rng"
xml:lang="en-US" yahoo:uri="http://where.yahooapis.com/v1/place/28289421">
<woeid>28289421</woeid>
<placeTypeName code="29">Continent</placeTypeName>
<name>Antarctic</name>
</place>
<place xmlns="http://where.yahooapis.com/v1/schema.rng"
xml:lang="en-US" yahoo:uri="http://where.yahooapis.com/v1/place/24865671">
<woeid>24865671</woeid>
<placeTypeName code="29">Continent</placeTypeName>
<name>Asia</name>
</place>
<place xmlns="http://where.yahooapis.com/v1/schema.rng"
xml:lang="en-US" yahoo:uri="http://where.yahooapis.com/v1/place/24865672">
<woeid>24865672</woeid>
<placeTypeName code="29">Continent</placeTypeName>
<name>North America</name>
</place>
<place xmlns="http://where.yahooapis.com/v1/schema.rng"
xml:lang="en-US" yahoo:uri="http://where.yahooapis.com/v1/place/55949070">
<woeid>55949070</woeid>
<placeTypeName code="29">Continent</placeTypeName>
<name>Australia</name>
</place>
</results>
</query>
`},
{ name: "YAML", mimeType: "text/yaml", text: `# This sample document was taken from wikipedia:
# http://en.wikipedia.org/wiki/YAML#Sample_document
---
receipt: Oz-Ware Purchase Invoice
date: 2007-08-06
customer:
given: Dorothy
family: Gale
items:
- part_no: 'A4786'
descrip: Water Bucket (Filled)
price: 1.47
quantity: 4
- part_no: 'E1628'
descrip: High Heeled "Ruby" Slippers
size: 8
price: 100.27
quantity: 1
bill-to: &id001
street: |
123 Tornado Alley
Suite 16
city: East Centerville
state: KS
ship-to: *id001
specialDelivery: >
Follow the Yellow Brick
Road to the Emerald City.
Pay no attention to the
man behind the curtain.
`},
]; | the_stack |
import common from "./common";
const { DEFAULT_SCHEMA, YAMLException } = require("js-yaml");
const _toString = Object.prototype.toString;
const _hasOwnProperty = Object.prototype.hasOwnProperty;
const CHAR_BOM = 0xfeff;
const CHAR_TAB = 0x09; /* Tab */
const CHAR_LINE_FEED = 0x0a; /* LF */
const CHAR_CARRIAGE_RETURN = 0x0d; /* CR */
const CHAR_SPACE = 0x20; /* Space */
const CHAR_EXCLAMATION = 0x21; /* ! */
const CHAR_DOUBLE_QUOTE = 0x22; /* " */
const CHAR_SHARP = 0x23; /* # */
const CHAR_PERCENT = 0x25; /* % */
const CHAR_AMPERSAND = 0x26; /* & */
const CHAR_SINGLE_QUOTE = 0x27; /* ' */
const CHAR_ASTERISK = 0x2a; /* * */
const CHAR_COMMA = 0x2c; /* , */
const CHAR_MINUS = 0x2d; /* - */
const CHAR_COLON = 0x3a; /* : */
const CHAR_EQUALS = 0x3d; /* = */
const CHAR_GREATER_THAN = 0x3e; /* > */
const CHAR_QUESTION = 0x3f; /* ? */
const CHAR_COMMERCIAL_AT = 0x40; /* @ */
const CHAR_LEFT_SQUARE_BRACKET = 0x5b; /* [ */
const CHAR_RIGHT_SQUARE_BRACKET = 0x5d; /* ] */
const CHAR_GRAVE_ACCENT = 0x60; /* ` */
const CHAR_LEFT_CURLY_BRACKET = 0x7b; /* { */
const CHAR_VERTICAL_LINE = 0x7c; /* | */
const CHAR_RIGHT_CURLY_BRACKET = 0x7d; /* } */
const ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0x00] = "\\0";
ESCAPE_SEQUENCES[0x07] = "\\a";
ESCAPE_SEQUENCES[0x08] = "\\b";
ESCAPE_SEQUENCES[0x09] = "\\t";
ESCAPE_SEQUENCES[0x0a] = "\\n";
ESCAPE_SEQUENCES[0x0b] = "\\v";
ESCAPE_SEQUENCES[0x0c] = "\\f";
ESCAPE_SEQUENCES[0x0d] = "\\r";
ESCAPE_SEQUENCES[0x1b] = "\\e";
ESCAPE_SEQUENCES[0x22] = '\\"';
ESCAPE_SEQUENCES[0x5c] = "\\\\";
ESCAPE_SEQUENCES[0x85] = "\\N";
ESCAPE_SEQUENCES[0xa0] = "\\_";
ESCAPE_SEQUENCES[0x2028] = "\\L";
ESCAPE_SEQUENCES[0x2029] = "\\P";
const DEPRECATED_BOOLEANS_SYNTAX = [
"y",
"Y",
"yes",
"Yes",
"YES",
"on",
"On",
"ON",
"n",
"N",
"no",
"No",
"NO",
"off",
"Off",
"OFF",
];
const DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
function compileStyleMap(schema, map) {
let result, keys, index, length, tag, style, type;
if (map === null) return {};
result = {};
keys = Object.keys(map);
for (index = 0, length = keys.length; index < length; index += 1) {
tag = keys[index];
style = String(map[tag]);
if (tag.slice(0, 2) === "!!") {
tag = "tag:yaml.org,2002:" + tag.slice(2);
}
type = schema.compiledTypeMap["fallback"][tag];
if (type && _hasOwnProperty.call(type.styleAliases, style)) {
style = type.styleAliases[style];
}
result[tag] = style;
}
return result;
}
function encodeHex(character) {
let string, handle, length;
string = character.toString(16).toUpperCase();
if (character <= 0xff) {
handle = "x";
length = 2;
} else if (character <= 0xffff) {
handle = "u";
length = 4;
} else if (character <= 0xffffffff) {
handle = "U";
length = 8;
} else {
throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF");
}
return "\\" + handle + common.repeat("0", length - string.length) + string;
}
const QUOTING_TYPE_SINGLE = 1,
QUOTING_TYPE_DOUBLE = 2;
function State(options) {
this.schema = options["schema"] || DEFAULT_SCHEMA;
this.indent = Math.max(1, options["indent"] || 2);
this.noArrayIndent = options["noArrayIndent"] || false;
this.skipInvalid = options["skipInvalid"] || false;
this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
this.sortKeys = options["sortKeys"] || false;
this.lineWidth = options["lineWidth"] || 80;
this.noRefs = options["noRefs"] || false;
this.noCompatMode = options["noCompatMode"] || false;
this.condenseFlow = options["condenseFlow"] || false;
this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
this.forceQuotes = options["forceQuotes"] || false;
this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
this.tag = null;
this.result = "";
this.duplicates = [];
this.usedDuplicates = null;
}
// Indents every line in a string. Empty lines (\n only) are not indented.
function indentString(string, spaces) {
let ind = common.repeat(" ", spaces),
position = 0,
next = -1,
result = "",
line,
length = string.length;
while (position < length) {
next = string.indexOf("\n", position);
if (next === -1) {
line = string.slice(position);
position = length;
} else {
line = string.slice(position, next + 1);
position = next + 1;
}
if (line.length && line !== "\n") result += ind;
result += line;
}
return result;
}
function generateNextLine(state, level) {
return "\n" + common.repeat(" ", state.indent * level);
}
function testImplicitResolving(state, str) {
let index, length, type;
for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
type = state.implicitTypes[index];
if (type.resolve(str)) {
return true;
}
}
return false;
}
// [33] s-white ::= s-space | s-tab
function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
// Returns true if the character can be printed without escaping.
// From YAML 1.2: "any allowed characters known to be non-printable
// should also be escaped. [However,] This isn’t mandatory"
// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
function isPrintable(c) {
return (
(0x00020 <= c && c <= 0x00007e) ||
(0x000a1 <= c && c <= 0x00d7ff && c !== 0x2028 && c !== 0x2029) ||
(0x0e000 <= c && c <= 0x00fffd && c !== CHAR_BOM) ||
(0x10000 <= c && c <= 0x10ffff)
);
}
// [34] ns-char ::= nb-char - s-white
// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
// [26] b-char ::= b-line-feed | b-carriage-return
// Including s-white (for some reason, examples doesn't match specs in this aspect)
// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
function isNsCharOrWhitespace(c) {
return (
isPrintable(c) &&
c !== CHAR_BOM &&
// - b-char
c !== CHAR_CARRIAGE_RETURN &&
c !== CHAR_LINE_FEED
);
}
// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out
// c = flow-in ⇒ ns-plain-safe-in
// c = block-key ⇒ ns-plain-safe-out
// c = flow-key ⇒ ns-plain-safe-in
// [128] ns-plain-safe-out ::= ns-char
// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator
// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )
// | ( /* An ns-char preceding */ “#” )
// | ( “:” /* Followed by an ns-plain-safe(c) */ )
function isPlainSafe(c, prev, inblock) {
const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
return (
// ns-plain-safe
((inblock // c = flow-in
? cIsNsCharOrWhitespace
: cIsNsCharOrWhitespace &&
// - c-flow-indicator
c !== CHAR_COMMA &&
c !== CHAR_LEFT_SQUARE_BRACKET &&
c !== CHAR_RIGHT_SQUARE_BRACKET &&
c !== CHAR_LEFT_CURLY_BRACKET &&
c !== CHAR_RIGHT_CURLY_BRACKET) &&
// ns-plain-char
c !== CHAR_SHARP && // false on '#'
!(prev === CHAR_COLON && !cIsNsChar)) || // false on ': '
(isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#'
(prev === CHAR_COLON && cIsNsChar)
); // change to true on ':[^ ]'
}
// Simplified test for values allowed as the first character in plain style.
function isPlainSafeFirst(c) {
// Uses a subset of ns-char - c-indicator
// where ns-char = nb-char - s-white.
// No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
return (
isPrintable(c) &&
c !== CHAR_BOM &&
!isWhitespace(c) && // - s-white
// - (c-indicator ::=
// “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
c !== CHAR_MINUS &&
c !== CHAR_QUESTION &&
c !== CHAR_COLON &&
c !== CHAR_COMMA &&
c !== CHAR_LEFT_SQUARE_BRACKET &&
c !== CHAR_RIGHT_SQUARE_BRACKET &&
c !== CHAR_LEFT_CURLY_BRACKET &&
c !== CHAR_RIGHT_CURLY_BRACKET &&
// | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
c !== CHAR_SHARP &&
c !== CHAR_AMPERSAND &&
c !== CHAR_ASTERISK &&
c !== CHAR_EXCLAMATION &&
c !== CHAR_VERTICAL_LINE &&
c !== CHAR_EQUALS &&
c !== CHAR_GREATER_THAN &&
c !== CHAR_SINGLE_QUOTE &&
c !== CHAR_DOUBLE_QUOTE &&
// | “%” | “@” | “`”)
c !== CHAR_PERCENT &&
c !== CHAR_COMMERCIAL_AT &&
c !== CHAR_GRAVE_ACCENT
);
}
// Simplified test for values allowed as the last character in plain style.
function isPlainSafeLast(c) {
// just not whitespace or colon, it will be checked to be plain character later
return !isWhitespace(c) && c !== CHAR_COLON;
}
// Same as 'string'.codePointAt(pos), but works in older browsers.
function codePointAt(string, pos) {
let first = string.charCodeAt(pos),
second;
if (first >= 0xd800 && first <= 0xdbff && pos + 1 < string.length) {
second = string.charCodeAt(pos + 1);
if (second >= 0xdc00 && second <= 0xdfff) {
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000;
}
}
return first;
}
// Determines whether block indentation indicator is required.
function needIndentIndicator(string) {
const leadingSpaceRe = /^\n* /;
return leadingSpaceRe.test(string);
}
const STYLE_PLAIN = 1,
STYLE_SINGLE = 2,
STYLE_LITERAL = 3,
STYLE_FOLDED = 4,
STYLE_DOUBLE = 5;
// Determines which scalar styles are possible and returns the preferred style.
// lineWidth = -1 => no limit.
// Pre-conditions: str.length > 0.
// Post-conditions:
// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
function chooseScalarStyle(
string,
singleLineOnly,
indentPerLevel,
lineWidth,
testAmbiguousType,
quotingType,
forceQuotes,
inblock,
) {
let i;
let char = 0;
let prevChar = null;
let hasLineBreak = false;
let hasFoldableLine = false; // only checked if shouldTrackWidth
const shouldTrackWidth = lineWidth !== -1;
let previousLineBreak = -1; // count the first line correctly
let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
if (singleLineOnly || forceQuotes) {
// Case: no block styles.
// Check for disallowed characters to rule out plain and single.
for (i = 0; i < string.length; char >= 0x10000 ? (i += 2) : i++) {
char = codePointAt(string, i);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
} else {
// Case: block styles permitted.
for (i = 0; i < string.length; char >= 0x10000 ? (i += 2) : i++) {
char = codePointAt(string, i);
if (char === CHAR_LINE_FEED) {
hasLineBreak = true;
// Check if any line can be folded.
if (shouldTrackWidth) {
hasFoldableLine =
hasFoldableLine ||
// Foldable line = too long, and not more-indented.
(i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
previousLineBreak = i;
}
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
// in case the end is missing a \n
hasFoldableLine =
hasFoldableLine ||
(shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
}
// Although every style can represent \n without escaping, prefer block styles
// for multiline, since they're more readable and they don't add empty lines.
// Also prefer folding a super-long line.
if (!hasLineBreak && !hasFoldableLine) {
// Strings interpretable as another type have to be quoted;
// e.g. the string 'true' vs. the boolean true.
if (plain && !forceQuotes && !testAmbiguousType(string)) {
return STYLE_PLAIN;
}
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
}
// Edge case: block indentation indicator can only have one digit.
if (indentPerLevel > 9 && needIndentIndicator(string)) {
return STYLE_DOUBLE;
}
// At this point we know block styles are valid.
// Prefer literal style unless we want to fold.
if (!forceQuotes) {
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
}
// Note: line breaking/folding is implemented for only the folded style.
// NB. We drop the last trailing newline (if any) of a returned block scalar
// since the dumper adds its own newline. This always works:
// • No ending newline => unaffected; already using strip "-" chomping.
// • Ending newline => removed then restored.
// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
function writeScalar(state, string, level, iskey, inblock) {
state.dump = (function () {
if (string.length === 0) {
return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
}
if (!state.noCompatMode) {
if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
}
}
const indent = state.indent * Math.max(1, level); // no 0-indent scalars
// As indentation gets deeper, let the width decrease monotonically
// to the lower bound min(state.lineWidth, 40).
// Note that this implies
// state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
// state.lineWidth > 40 + state.indent: width decreases until the lower bound.
// This behaves better than a constant minimum width which disallows narrower options,
// or an indent threshold which causes the width to suddenly increase.
const lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
// Without knowing if keys are implicit/explicit, assume implicit for safety.
const singleLineOnly =
iskey ||
// No block styles in flow mode.
(state.flowLevel > -1 && level >= state.flowLevel);
function testAmbiguity(string) {
return testImplicitResolving(state, string);
}
switch (
chooseScalarStyle(
string,
singleLineOnly,
state.indent,
lineWidth,
testAmbiguity,
state.quotingType,
state.forceQuotes && !iskey,
inblock,
)
) {
case STYLE_PLAIN:
return string;
case STYLE_SINGLE:
return "'" + string.replace(/'/g, "''") + "'";
case STYLE_LITERAL:
return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
case STYLE_FOLDED:
return (
">" +
blockHeader(string, state.indent) +
dropEndingNewline(indentString(foldString(string, lineWidth), indent))
);
case STYLE_DOUBLE:
return '"' + escapeString(string, lineWidth) + '"';
default:
throw new YAMLException("impossible error: invalid scalar style");
}
})();
}
// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
function blockHeader(string, indentPerLevel) {
const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
// note the special case: the string '\n' counts as a "trailing" empty line.
const clip = string[string.length - 1] === "\n";
const keep = clip && (string[string.length - 2] === "\n" || string === "\n");
const chomp = keep ? "+" : clip ? "" : "-";
return indentIndicator + chomp + "\n";
}
// (See the note for writeScalar.)
function dropEndingNewline(string) {
return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
}
// Note: a long line without a suitable break point will exceed the width limit.
// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
function foldString(string, width) {
// In folded style, $k$ consecutive newlines output as $k+1$ newlines—
// unless they're before or after a more-indented line, or at the very
// beginning or end, in which case $k$ maps to $k$.
// Therefore, parse each chunk as newline(s) followed by a content line.
const lineRe = /(\n+)([^\n]*)/g;
// first line (possibly an empty line)
let result = (function () {
let nextLF = string.indexOf("\n");
nextLF = nextLF !== -1 ? nextLF : string.length;
lineRe.lastIndex = nextLF;
return foldLine(string.slice(0, nextLF), width);
})();
// If we haven't reached the first content line yet, don't add an extra \n.
let prevMoreIndented = string[0] === "\n" || string[0] === " ";
let moreIndented;
// rest of the lines
let match;
while ((match = lineRe.exec(string))) {
const prefix = match[1],
line = match[2];
moreIndented = line[0] === " ";
result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
prevMoreIndented = moreIndented;
}
return result;
}
// Greedy line breaking.
// Picks the longest line under the limit each time,
// otherwise settles for the shortest line over the limit.
// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
function foldLine(line, width) {
if (line === "" || line[0] === " ") return line;
// Since a more-indented line adds a \n, breaks can't be followed by a space.
const breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
let match;
// start is an inclusive index. end, curr, and next are exclusive.
let start = 0,
end,
curr = 0,
next = 0;
let result = "";
// Invariants: 0 <= start <= length-1.
// 0 <= curr <= next <= max(0, length-2). curr - start <= width.
// Inside the loop:
// A match implies length >= 2, so curr and next are <= length-2.
while ((match = breakRe.exec(line))) {
next = match.index;
// maintain invariant: curr - start <= width
if (next - start > width) {
end = curr > start ? curr : next; // derive end <= length-2
result += "\n" + line.slice(start, end);
// skip the space that was output as \n
start = end + 1; // derive start <= length-1
}
curr = next;
}
// By the invariants, start <= length-1, so there is something left over.
// It is either the whole string or a part starting from non-whitespace.
result += "\n";
// Insert a break if the remainder is too long and there is a break available.
if (line.length - start > width && curr > start) {
result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
} else {
result += line.slice(start);
}
return result.slice(1); // drop extra \n joiner
}
// Escapes a double-quoted string.
function escapeString(string) {
let result = "";
let char = 0;
let escapeSeq;
for (let i = 0; i < string.length; char >= 0x10000 ? (i += 2) : i++) {
char = codePointAt(string, i);
escapeSeq = ESCAPE_SEQUENCES[char];
if (!escapeSeq && isPrintable(char)) {
result += string[i];
if (char >= 0x10000) result += string[i + 1];
} else {
result += escapeSeq || encodeHex(char);
}
}
return result;
}
function writeFlowSequence(state, level, object) {
let _result = "",
_tag = state.tag,
index,
length,
value;
for (index = 0, length = object.length; index < length; index += 1) {
value = object[index];
if (state.replacer) {
value = state.replacer.call(object, String(index), value);
}
// Write only valid elements, put null instead of invalid elements.
if (
writeNode(state, level, value, false, false) ||
(typeof value === "undefined" && writeNode(state, level, null, false, false))
) {
if (_result !== "") _result += "," + (!state.condenseFlow ? " " : "");
_result += state.dump;
}
}
state.tag = _tag;
state.dump = "[" + _result + "]";
}
function writeBlockSequence(state, level, object, compact) {
let _result = "",
_tag = state.tag,
index,
length,
value;
for (index = 0, length = object.length; index < length; index += 1) {
value = object[index];
if (state.replacer) {
value = state.replacer.call(object, String(index), value);
}
// Write only valid elements, put null instead of invalid elements.
if (
writeNode(state, level + 1, value, true, true, false, true) ||
(typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true))
) {
if (!compact || _result !== "") {
_result += generateNextLine(state, level);
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
_result += "-";
} else {
_result += "- ";
}
_result += state.dump;
}
}
state.tag = _tag;
state.dump = _result || "[]"; // Empty sequence if no valid values.
}
function writeFlowMapping(state, level, object) {
let _result = "",
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
pairBuffer;
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = "";
if (_result !== "") pairBuffer += ", ";
if (state.condenseFlow) pairBuffer += '"';
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (state.replacer) {
objectValue = state.replacer.call(object, objectKey, objectValue);
}
if (!writeNode(state, level, objectKey, false, false)) {
continue; // Skip this pair because of invalid key;
}
if (state.dump.length > 1024) pairBuffer += "? ";
pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
if (!writeNode(state, level, objectValue, false, false)) {
continue; // Skip this pair because of invalid value.
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = "{" + _result + "}";
}
function writeBlockMapping(state, level, object, compact) {
let _result = "",
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
explicitPair,
pairBuffer;
// Allow sorting keys so that the output file is deterministic
if (state.sortKeys === true) {
// Default sorting
objectKeyList.sort();
} else if (typeof state.sortKeys === "function") {
// Custom sort function
objectKeyList.sort(state.sortKeys);
} else if (state.sortKeys) {
// Something is wrong
throw new YAMLException("sortKeys must be a boolean or a function");
}
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = "";
if (!compact || _result !== "") {
pairBuffer += generateNextLine(state, level);
}
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (state.replacer) {
objectValue = state.replacer.call(object, objectKey, objectValue);
}
if (!writeNode(state, level + 1, objectKey, true, true, true)) {
continue; // Skip this pair because of invalid key.
}
explicitPair = (state.tag !== null && state.tag !== "?") || (state.dump && state.dump.length > 1024);
if (explicitPair) {
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += "?";
} else {
pairBuffer += "? ";
}
}
pairBuffer += state.dump;
if (explicitPair) {
pairBuffer += generateNextLine(state, level);
}
if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
continue; // Skip this pair because of invalid value.
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += ":";
} else {
pairBuffer += ": ";
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = _result || "{}"; // Empty mapping if no valid pairs.
}
function detectType(state, object, explicit) {
let _result, typeList, index, length, type, style;
typeList = explicit ? state.explicitTypes : state.implicitTypes;
for (index = 0, length = typeList.length; index < length; index += 1) {
type = typeList[index];
if (
(type.instanceOf || type.predicate) &&
(!type.instanceOf || (typeof object === "object" && object instanceof type.instanceOf)) &&
(!type.predicate || type.predicate(object))
) {
if (explicit) {
if (type.multi && type.representName) {
state.tag = type.representName(object);
} else {
state.tag = type.tag;
}
} else {
state.tag = "?";
}
if (type.represent) {
style = state.styleMap[type.tag] || type.defaultStyle;
if (_toString.call(type.represent) === "[object Function]") {
_result = type.represent(object, style);
} else if (_hasOwnProperty.call(type.represent, style)) {
_result = type.represent[style](object, style);
} else {
throw new YAMLException("!<" + type.tag + '> tag resolver accepts not "' + style + '" style');
}
state.dump = _result;
}
return true;
}
}
return false;
}
// Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object.
//
function writeNode(state, level, object, block, compact, iskey, isblockseq) {
state.tag = null;
state.dump = object;
if (!detectType(state, object, false)) {
detectType(state, object, true);
}
const type = _toString.call(state.dump);
const inblock = block;
let tagStr;
if (block) {
block = state.flowLevel < 0 || state.flowLevel > level;
}
let objectOrArray = type === "[object Object]" || type === "[object Array]",
duplicateIndex,
duplicate;
if (objectOrArray) {
duplicateIndex = state.duplicates.indexOf(object);
duplicate = duplicateIndex !== -1;
}
if ((state.tag !== null && state.tag !== "?") || duplicate || (state.indent !== 2 && level > 0)) {
compact = false;
}
if (duplicate && state.usedDuplicates[duplicateIndex]) {
state.dump = "*ref_" + duplicateIndex;
} else {
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
state.usedDuplicates[duplicateIndex] = true;
}
if (type === "[object Object]") {
if (block && Object.keys(state.dump).length !== 0) {
writeBlockMapping(state, level, state.dump, compact);
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + state.dump;
}
} else {
writeFlowMapping(state, level, state.dump);
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + " " + state.dump;
}
}
} else if (type === "[object Array]") {
if (block && state.dump.length !== 0) {
if (state.noArrayIndent && !isblockseq && level > 0) {
writeBlockSequence(state, level - 1, state.dump, compact);
} else {
writeBlockSequence(state, level, state.dump, compact);
}
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + state.dump;
}
} else {
writeFlowSequence(state, level, state.dump);
if (duplicate) {
state.dump = "&ref_" + duplicateIndex + " " + state.dump;
}
}
} else if (type === "[object String]") {
if (state.tag !== "?") {
writeScalar(state, state.dump, level, iskey, inblock);
}
} else if (type === "[object Undefined]") {
return false;
} else {
if (state.skipInvalid) return false;
throw new YAMLException("unacceptable kind of an object to dump " + type);
}
if (state.tag !== null && state.tag !== "?") {
// Need to encode all characters except those allowed by the spec:
//
// [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */
// [36] ns-hex-digit ::= ns-dec-digit
// | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
// [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
// [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”
// [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
// | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
// | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
//
// Also need to encode '!' because it has special meaning (end of tag prefix).
//
tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21");
if (state.tag[0] === "!") {
tagStr = "!" + tagStr;
} else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
tagStr = "!!" + tagStr.slice(18);
} else {
tagStr = "!<" + tagStr + ">";
}
state.dump = tagStr + " " + state.dump;
}
}
return true;
}
function getDuplicateReferences(object, state) {
let objects = new Set(),
duplicatesIndexes = new Set(),
index,
length;
inspectNode(object, objects, duplicatesIndexes);
state.duplicates = [...duplicatesIndexes];
state.usedDuplicates = new Array(length);
}
function inspectNode(object, objects, duplicatesIndexes) {
let objectKeyList, index, length;
if (object !== null && typeof object === "object") {
if (objects.has(object)) {
if (!duplicatesIndexes.has(object)) {
duplicatesIndexes.add(object);
}
} else {
objects.add(object);
if (Array.isArray(object)) {
for (index = 0, length = object.length; index < length; index += 1) {
inspectNode(object[index], objects, duplicatesIndexes);
}
} else {
objectKeyList = Object.keys(object);
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
}
}
}
}
}
export function dump(input, options) {
options = options || {};
const state = new State(options);
if (!state.noRefs) getDuplicateReferences(input, state);
let value = input;
if (state.replacer) {
value = state.replacer.call({ "": value }, "", value);
}
if (writeNode(state, 0, value, true, true)) return state.dump + "\n";
return "";
} | the_stack |
import { Common } from "../../../../modules/components/common_components/common";
import { CONSTANTS } from "../../../../modules/components/common_components/statics";
import { SFDMU_RUN_ADDON_MESSAGES } from "../../../messages/sfdmuRunAddonMessages";
import { API_ENGINE, OPERATION } from "../../../../modules/components/common_components/enumerations";
import ContentVersion from "../../../../modules/models/sf_models/contentVersion";
import SfdmuRunAddonModule from "../../../components/sfdmu-run/sfdmuRunAddonModule";
import AddonResult from "../../../components/common/addonResult";
import IAddonContext from "../../../components/common/IAddonContext";
interface IOnExecuteArguments {
deleteOldData: boolean;
operation: OPERATION;
/**
* ContentVersion external id (Title by default)
*/
externalId: string;
/**
* Additional WHERE on the ContentVersion for the source records to define detaily, which files
* we want to export
* WHERE IsLatest = true AND [selectWhere].
*/
sourceWhere: string;
/**
* Additional WHERE on the ContentVersion for the target records to compare against
* the source records to find updates.
* WHERE IsLatest = true AND [selectWhere].
*/
targetWhere: string;
}
interface IDataToImport {
recIdToDocLinks: Map<string, Array<any>>;
docIds: Array<string>;
recordIds: Array<string>;
docIdToDocVersion: Map<string, any>;
}
interface ILinkedRecord {
Id: string;
sourceDocLink: any;
}
interface IDataToExport {
version: ContentVersion; // only once => to update
targetVersion: ContentVersion; // The target version if found
recordsToBeLinked: ILinkedRecord[];
isVersionChanged: boolean;
}
export default class ExportFiles extends SfdmuRunAddonModule {
async onExecute(context: IAddonContext, args: IOnExecuteArguments): Promise<AddonResult> {
let _self = this;
this.runtime.logAddonExecutionStarted(this);
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_Preparing);
if (this.runtime.getOrgInfo(false).isFile || this.runtime.getOrgInfo(true).isFile) {
// File target -> error
this.runtime.logFormattedWarning(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_TargetIsFileWarning);
this.runtime.logAddonExecutionFinished(this);
return;
}
// Get the relevant parent task
let task = this.runtime.pluginJob.tasks.find(task => task.sObjectName == context.objectName);
// Set default parameters
args.operation = !args.operation ? task.operation : OPERATION[args.operation.toString()];
args.externalId = args.externalId || 'Title';
if (!task) {
// No task -> error
this.runtime.logFormattedWarning(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_CouldNotFindObjectToProcessWarning);
this.runtime.logAddonExecutionFinished(this);
return;
}
if (args.operation == OPERATION.Readonly) {
// Readonly -> error
this.runtime.logFormattedWarning(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ReadonlyOperationWarning);
this.runtime.logAddonExecutionFinished(this);
return;
}
let source: IDataToImport = {
recIdToDocLinks: new Map<string, Array<any>>(),
docIds: [],
recordIds: [...task.sourceTaskData.idRecordsMap.keys()],
docIdToDocVersion: new Map<string, any>()
};
let target: IDataToImport = {
recIdToDocLinks: new Map<string, Array<any>>(),
docIds: [],
recordIds: [...task.targetTaskData.idRecordsMap.keys()],
docIdToDocVersion: new Map<string, any>()
};
// Map: [Source ContentVersion] => IDataToExport
let dataToExportMap = new Map<any, IDataToExport>();
// ------------------ Read Target ------------------------------
// -------------------------------------------------------------
// Read target ContentDocumentLinks
if (args.operation != OPERATION.Insert && target.recordIds.length > 0) {
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ReadTargetContentDocumentLinks);
let queries = this.runtime.createFieldInQueries(
['Id', 'LinkedEntityId', 'ContentDocumentId', 'ShareType', 'Visibility'],
'LinkedEntityId',
'ContentDocumentLink',
target.recordIds);
let data = await this.runtime.queryMultiAsync(false, queries);
target.recIdToDocLinks = Common.arrayToMapMulti(data, ['LinkedEntityId']);
target.docIds = Common.distinctStringArray(Common.arrayToPropsArray(data, ['ContentDocumentId']));
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_RetrievedRecords, String(data.length));
}
// Delete all old target files (if no targetWhere was defined)
let isDeleted = false;
if (!args.targetWhere) {
if (await ___deleteTargetFiles(target.docIds)) {
return;
}
}
// Read target ContentVersions
if (args.operation != OPERATION.Insert && target.docIds.length > 0) {
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ReadTargetContentVersions);
let fields = Common.distinctStringArray([
'Id', args.externalId, 'ContentDocumentId',
'ContentModifiedDate', 'Title',
'Checksum', 'ContentUrl'
]);
let queries = this.runtime.createFieldInQueries(
fields,
'ContentDocumentId',
'ContentVersion',
target.docIds,
'IsLatest = true');
if (args.targetWhere) {
queries = queries.map(query => query.replace('WHERE', 'WHERE (' + args.targetWhere + ') AND (') + ')')
}
let data = await this.runtime.queryMultiAsync(false, queries);
target.docIdToDocVersion = Common.arrayToMap(data, ['ContentDocumentId']);
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_RetrievedRecords, String(data.length));
}
// Delete selective old target files (if targetWhere was defined)
if (args.targetWhere) {
if (await ___deleteTargetFiles([...target.docIdToDocVersion.keys()])) {
return;
}
}
if (source.recordIds.length == 0) {
// No source records -> exit
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_NoSourceRecords);
return;
}
if (args.operation == OPERATION.Update && isDeleted) {
// Update + Delete => exit
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_NothingToUpdate);
return;
}
if (args.operation == OPERATION.Upsert && isDeleted) {
args.operation = OPERATION.Insert;
}
// -----------------------------------------------------------
// -----------------------------------------------------------
// ------ Read Source ----------------------------------------
// -----------------------------------------------------------
// Read source ContentDocumentLinks
{
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ReadSourceContentDocumentLinks);
let queries = this.runtime.createFieldInQueries(
['Id', 'LinkedEntityId', 'ContentDocumentId', 'ShareType', 'Visibility'],
'LinkedEntityId',
'ContentDocumentLink',
[...task.sourceTaskData.idRecordsMap.keys()]);
let data = await this.runtime.queryMultiAsync(true, queries);
source.recIdToDocLinks = Common.arrayToMapMulti(data, ['LinkedEntityId']);
source.docIds = Common.distinctStringArray(Common.arrayToPropsArray(data, ['ContentDocumentId']));
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_RetrievedRecords, String(data.length));
}
// Read source ContentVersions
if (source.docIds.length > 0) {
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ReadSourceContentVersions);
let fields = Common.distinctStringArray([
'Id', args.externalId, 'ContentDocumentId',
'Title', 'Description', 'PathOnClient', 'VersionData',
'ContentModifiedDate', 'ContentSize', 'Checksum',
'ContentUrl', 'ContentBodyId'
]);
let queries = this.runtime.createFieldInQueries(
fields,
'ContentDocumentId',
'ContentVersion',
source.docIds,
'IsLatest = true');
if (args.sourceWhere) {
queries = queries.map(query => query.replace('WHERE', 'WHERE (' + args.sourceWhere + ') AND (') + ')')
}
let data = await this.runtime.queryMultiAsync(true, queries);
source.docIdToDocVersion = Common.arrayToMap(data, ['ContentDocumentId']);
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_RetrievedRecords, String(data.length));
}
// ---------- Compare versions to detect changes -------------------
// ----------- which files need to download and upload--------------
// -----------------------------------------------------------------
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_Analysing);
source.recIdToDocLinks.forEach((sourceDocLinks, recordId) => {
sourceDocLinks.forEach(sourceDocLink => {
let sourceContentVersion = source.docIdToDocVersion.get(sourceDocLink["ContentDocumentId"]);
if (sourceContentVersion) {
let targetRecord = task.sourceToTargetRecordMap.get(task.sourceTaskData.idRecordsMap.get(recordId));
if (!dataToExportMap.has(sourceContentVersion)) {
dataToExportMap.set(sourceContentVersion, {
version: new ContentVersion(sourceContentVersion),
recordsToBeLinked: new Array<ILinkedRecord>(),
isVersionChanged: false,
targetVersion: null
});
}
let dataToExport = dataToExportMap.get(sourceContentVersion);
if (targetRecord) {
let targetDocLinks = target.recIdToDocLinks.get(targetRecord["Id"]);
let found = false;
// File exists => check for the modification ******
(targetDocLinks || []).forEach(targetDocLink => {
let targetContentVersion = dataToExport.targetVersion || new ContentVersion(target.docIdToDocVersion.get(targetDocLink["ContentDocumentId"]));
if (dataToExport.version[args.externalId] == targetContentVersion[args.externalId]) {
// The same version found in the Target
found = true;
dataToExport.targetVersion = targetContentVersion;
if (!dataToExport.version.targetContentDocumentId) {
dataToExport.version.targetContentDocumentId = String(targetContentVersion['ContentDocumentId']);
}
if (dataToExport.version.isNewer(targetContentVersion)) {
// The file was modified ****************
// Add this item to the export array ///////////
dataToExport.isVersionChanged = true;
}
}
});
if (!found && args.operation != OPERATION.Update) {
// File was not found in the Target => Create new file and attach it to the target
// Only for upsert / insert, excluded update
dataToExport.recordsToBeLinked.push({
Id: targetRecord["Id"],
sourceDocLink
});
}
}
}
});
});
dataToExportMap.forEach((dataToExport) => {
if (!dataToExport.targetVersion) {
dataToExport.isVersionChanged = true;
}
});
// -----------------------------------------------------------------
// -----------------------------------------------------------------
// ---------- Upload -----------------------------------------------
// -----------------------------------------------------------------
let versionsToProcess = [...dataToExportMap.values()].filter(exportItem => exportItem.isVersionChanged).map(exportItem => exportItem.version);
if (versionsToProcess.length > 0) {
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ExportingContentVersions);
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_RecordsToBeProcessed, String(versionsToProcess.length));
await this.runtime.transferContentVersions(this, versionsToProcess);
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ProcessedRecords,
String(versionsToProcess.length),
String(versionsToProcess.filter(item => item.isError).length));
}
// -----------------------------------------------------------------
// -----------------------------------------------------------------
// -----------Create missing ContentDocumentLinks ---------------------------
// -----------------------------------------------------------------
let dataToProcess = [...dataToExportMap.values()].filter(exportItem => exportItem.recordsToBeLinked.length > 0);
if (dataToProcess.length > 0) {
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ExportingContentDocumentLinks);
let docLinks = Common.flattenArrays(dataToProcess.map(data => data.recordsToBeLinked.map(record => {
return {
LinkedEntityID: record.Id,
ContentDocumentID: data.version.targetContentDocumentId,
ShareType: record.sourceDocLink.ShareType,
Visibility: record.sourceDocLink.Visibility
};
})));
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_RecordsToBeProcessed, String(docLinks.length));
let data = await this.runtime.updateTargetRecordsAsync('ContentDocumentLink',
OPERATION.Insert,
docLinks,
API_ENGINE.DEFAULT_ENGINE, true);
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ProcessedRecords,
String(data.length),
String(data.filter(item => !!item[CONSTANTS.ERRORS_FIELD_NAME]).length));
}
if (dataToProcess.length == 0 && versionsToProcess.length == 0) {
this.runtime.logFormattedInfo(this, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_NothingToProcess);
}
// ------------------------------------------------------------------
// -----------------------------------------------------------------
this.runtime.logAddonExecutionFinished(this);
// ---------------- Helper Functions --------------------------- //
async function ___deleteTargetFiles(docIdsToDelete: Array<string>): Promise<boolean> {
if (args.deleteOldData || args.operation == OPERATION.Delete) {
isDeleted = true;
// -------- //
if (docIdsToDelete.length > 0) {
_self.runtime.logFormattedInfo(_self, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_DeleteTargetContentDocuments);
let data = await _self.runtime.updateTargetRecordsAsync('ContentDocument',
OPERATION.Delete,
docIdsToDelete.map(item => {
return {
Id: item
};
}));
_self.runtime.logFormattedInfo(_self, SFDMU_RUN_ADDON_MESSAGES.ExportFiles_ProcessedRecords,
String(data.length),
String(data.filter(item => !!item[CONSTANTS.ERRORS_FIELD_NAME]).length));
}
// ------- //
if (args.operation == OPERATION.Delete) {
// Only delete -> exit
return true;
}
}
return false;
}
return null;
}
} | the_stack |
'use strict';
(function(root: any, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
const v = factory(require, exports);
if (v !== undefined) module.exports = v;
} else if (typeof define === 'function' && define.amd) {
define(['require', 'exports'], factory);
} else {
// Browser globals (root is window)
let browserRequire = (name) => {
if (
(name == 'deep-freeze' || name == 'deep-freeze-strict') &&
root.deepFreeze
) {
return root.deepFreeze;
}
if (name == 'lodash' && root._) {
return root._;
}
if (name == 'immutable' && root.Immutable) {
return root.Immutable;
}
if (name == 'immer' && root.immer) {
return root.immer;
}
if (name.indexOf('iassign') > -1 && root.iassign) {
return root.iassign;
}
throw new Error('Unable to require: ' + name);
};
factory(browserRequire, {});
}
})(this, function(require, exports) {
const iassign: IIassign = require('../src/iassign');
var noDeepFreeze = false;
try {
var deepFreeze: DeepFreeze.DeepFreezeInterface = require('deep-freeze-strict');
} catch (ex) {
deepFreeze = <any>function() {};
noDeepFreeze = true;
console.warn(
'Cannot load deep-freeze module.',
ex && ex.message ? ex.message : ex
);
}
let willThrowWhenUpdateFrozenArray = false;
try {
const o = { b: [] };
deepFreeze(o);
o.b.push(1);
console.warn('Not throw when update frozen array.');
} catch (ex) {
willThrowWhenUpdateFrozenArray = true;
}
const _: _.LoDashStatic = require('lodash');
// const immer = require('immer').default;
// const immutable = require("immutable");
describe('Test', function() {
beforeEach(function() {});
it('Access array item', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
deepFreeze(o1);
const o2 = iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
ci.d++;
return ci;
}
);
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
});
// expect o2 inner property has been updated.
expect(o2.a.b.c[0][0].d).toBe(12);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][0].d).not.toBe(o1.a.b.c[0][0].d);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2.a2).toBe(o1.a2);
expect(o2.a.b2).toBe(o1.a.b2);
expect(o2.a.b.c2).toBe(o1.a.b.c2);
expect(o2.a.b.c[0][0].e).toBe(o1.a.b.c[0][0].e);
expect(o2.a.b.c[1][0]).toBe(o1.a.b.c[1][0]);
expect(o2.a.b.c[2][0]).toBe(o1.a.b.c[2][0]);
});
it('Access array item, need to detect change but the setProp is setting the inner property.', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
expect(() => {
iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
ci.d++;
return ci;
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
}).toThrowError(
TypeError,
/Cannot|Can't|writable|doesn't|support|readonly|not|read-only/i
);
});
it('Access array item, need to detect change and no change', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
deepFreeze(o1);
const o2 = iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
return ci;
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
});
// expect o2 === o1, because no change in the setProp().
expect(o2).toBe(o1);
});
it('Access array item, need to detect change but the setProp is setting the inner property, use setOption()', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
iassign.setOption({
ignoreIfNoChange: true,
freeze: true
});
expect(() => {
iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
ci.d++;
return ci;
}
);
}).toThrowError(
TypeError,
/Cannot|Can't|writable|doesn't|support|readonly|not|read-only/i
);
iassign.setOption({
ignoreIfNoChange: false,
freeze: false
});
});
it('Access array item, need to detect change and no change, use setOption()', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
iassign.setOption({
ignoreIfNoChange: true,
freeze: true
});
const o2 = iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
return ci;
}
);
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
});
// expect o2 === o1, because no change in the setProp().
expect(o2).toBe(o1);
iassign.setOption({
ignoreIfNoChange: false,
freeze: false
});
});
it('Access array item, need to detect change and ensure setProp() is called once', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
// No change to the root object
let count = 0;
let o2: any = iassign(
o1,
(o) => {
count++;
return o;
},
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).toBe(o1);
// Has change to the root object
count = 0;
o2 = iassign(
o1,
(o) => {
count++;
return <any>{};
},
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).not.toBe(o1);
// No change to the object properties
count = 0;
o2 = iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
count++;
return ci;
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).toBe(o1);
// Has change to the object properties
count = 0;
o2 = iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
count++;
return <any>{};
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).not.toBe(o1);
// No change to the root object, used getProp()
count = 0;
o2 = iassign(
o1,
(o) => o,
(o) => {
count++;
return o;
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).toBe(o1);
// Has change to the root object, used getProp()
count = 0;
o2 = iassign(
o1,
(o) => o,
(o) => {
count++;
return <any>{};
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).not.toBe(o1);
});
it('Access array item, need to detect change and has change', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
deepFreeze(o1);
const o2 = iassign(
o1,
(o) => o.a.b.c[0][0],
(ci) => {
ci.d++;
return ci;
},
{
ignoreIfNoChange: true,
freeze: true
}
);
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
});
// expect o2 inner property has been updated.
expect(o2.a.b.c[0][0].d).toBe(12);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][0].d).not.toBe(o1.a.b.c[0][0].d);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2.a2).toBe(o1.a2);
expect(o2.a.b2).toBe(o1.a.b2);
expect(o2.a.b.c2).toBe(o1.a.b.c2);
expect(o2.a.b.c[0][0].e).toBe(o1.a.b.c[0][0].e);
expect(o2.a.b.c[1][0]).toBe(o1.a.b.c[1][0]);
expect(o2.a.b.c[2][0]).toBe(o1.a.b.c[2][0]);
});
it('Access array 1', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
deepFreeze(o1);
const o2 = iassign(
o1,
(o) => o.a.b.c[1],
(c) => {
c.push(<any>101);
return c;
}
);
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
});
// expect o2 inner property has been updated.
expect(o2.a.b.c[1][1]).toBe(101);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[1]).not.toBe(o1.a.b.c[1]);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2.a2).toBe(o1.a2);
expect(o2.a.b2).toBe(o1.a.b2);
expect(o2.a.b.c2).toBe(o1.a.b.c2);
expect(o2.a.b.c[0]).toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[1][0]).toBe(o1.a.b.c[1][0]);
expect(o2.a.b.c[2]).toBe(o1.a.b.c[2]);
expect(o2.a.b.c[2][0]).toBe(o1.a.b.c[2][0]);
});
it('Access array 2', function() {
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]] }
}
};
deepFreeze(o1);
const o2 = iassign(
o1,
function(o) {
return o.a.b.c;
},
function(c) {
c.pop();
return c;
}
);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).toBe(o1.a.b.c[0]);
expect(o2.a.b.c[1]).toBe(o1.a.b.c[1]);
expect(o2.a.b.c[2]).toBe(undefined);
});
it('Access object', function() {
const o1 = { a: { b: { c: { d: 11, e: 12 } } } };
deepFreeze(o1);
let o2 = iassign(
o1,
(o) => o.a.b.c,
(c) => {
c.d++;
return c;
}
);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c.d).not.toBe(o1.a.b.c.d);
expect(o2.a.b.c.d).toBe(12);
});
it('Access primitive', function() {
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]] }
}
};
deepFreeze(o1);
let o2 = iassign(
o1,
(o) => o.a.b.c[0][0].d,
(d) => {
return d + 1;
}
);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][0].d).not.toBe(o1.a.b.c[0][0].d);
expect(o2.a.b.c[0][0].d).toBe(12);
});
it('Access date', function() {
const o1 = { a: { b: { c: { d: 11, e: 12, f: new Date() } } } };
deepFreeze(o1);
let o2 = iassign(
o1,
(o) => o.a.b.c.f,
(f) => {
return new Date(2016, 1, 1);
}
);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c.f).not.toBe(o1.a.b.c.f);
expect(o2.a.b.c.f).toEqual(new Date(2016, 1, 1));
});
it('Access array item using string', function() {
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]] }
}
};
deepFreeze(o1);
let o2 = iassign(
o1,
(o) => o.a.b.c['1']['0'].d,
(d) => {
return d + 1;
}
);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[1]).not.toBe(o1.a.b.c[1]);
expect(o2.a.b.c[1][0]).not.toBe(o1.a.b.c[1][0]);
expect(o2.a.b.c[1][0].d).not.toBe(o1.a.b.c[1][0].d);
expect(o2.a.b.c[1][0].d).toBe(22);
});
it('Access object property using string', function() {
const o1 = {
a: {
propB: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]]
}
}
};
deepFreeze(o1);
let o2 = iassign(
o1,
(o) => o.a['propB'].c['1'][0].d,
(d) => {
return d + 1;
}
);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.propB).not.toBe(o1.a.propB);
expect(o2.a.propB.c).not.toBe(o1.a.propB.c);
expect(o2.a.propB.c[1]).not.toBe(o1.a.propB.c[1]);
expect(o2.a.propB.c[1][0]).not.toBe(o1.a.propB.c[1][0]);
expect(o2.a.propB.c[1][0].d).not.toBe(o1.a.propB.c[1][0].d);
expect(o2.a.propB.c[1][0].d).toBe(22);
});
it('Access object property using string 2', function() {
let propBName = "p\\r\"o.p t[] e.s't'B";
let propCName = "h\\e'llo w'or\"ld";
const o1 = {
a: {
[propBName]: {
[propCName]: [
[{ d: 11, e: 12 }],
[{ d: 21, e: 22 }],
[{ d: 31, e: 32 }]
]
}
}
};
deepFreeze(o1);
let o2 = iassign(
o1,
(o) => o.a["p\\r\"o.p t[] e.s't'B"]["h\\e'llo w'or\"ld"]['1'][0].d,
(d) => {
return d + 1;
}
);
expect(o2.a[propBName][propCName][1][0].d).toBe(22);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a[propBName]).not.toBe(o1.a[propBName]);
expect(o2.a[propBName][propCName]).not.toBe(o1.a[propBName][propCName]);
expect(o2.a[propBName][propCName][1]).not.toBe(
o1.a[propBName][propCName][1]
);
expect(o2.a[propBName][propCName][1][0]).not.toBe(
o1.a[propBName][propCName][1][0]
);
expect(o2.a[propBName][propCName][1][0].d).not.toBe(
o1.a[propBName][propCName][1][0].d
);
});
it('Access object property using string 3', function() {
let propBName = 'p\\ro.p t[] e.stB';
let propCName = "h\\e'llo w'or\"ld";
let propDName = 'h\\e"llo w"or\'ld';
let propEName = 'p\\ro.p t[] e.stB';
const o1 = {
a: {
[propBName]: {
[propCName]: {
[propDName]: {
[propEName]: [
[{ d: 11, e: 12 }],
[{ d: 21, e: 22 }],
[{ d: 31, e: 32 }]
]
}
}
}
}
};
deepFreeze(o1);
let o2 = iassign(
o1,
(o) =>
o.a['p\\ro.p t[] e.stB']["h\\e'llo w'or\"ld"]['h\\e"llo w"or\'ld'][
'p\\ro.p t[] e.stB'
]['1'][0].d,
(d) => {
return d + 1;
}
);
expect(o2.a[propBName][propCName][propDName][propEName][1][0].d).toBe(22);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a[propBName]).not.toBe(o1.a[propBName]);
expect(o2.a[propBName][propCName]).not.toBe(o1.a[propBName][propCName]);
expect(o2.a[propBName][propCName][propDName]).not.toBe(
o1.a[propBName][propCName][propDName]
);
expect(o2.a[propBName][propCName][propDName][propEName]).not.toBe(
o1.a[propBName][propCName][propDName][propEName]
);
expect(o2.a[propBName][propCName][propDName][propEName][1]).not.toBe(
o1.a[propBName][propCName][propDName][propEName][1]
);
expect(o2.a[propBName][propCName][propDName][propEName][1][0]).not.toBe(
o1.a[propBName][propCName][propDName][propEName][1][0]
);
expect(o2.a[propBName][propCName][propDName][propEName][1][0].d).not.toBe(
o1.a[propBName][propCName][propDName][propEName][1][0].d
);
});
it('Access object property using string 4', function() {
let propBName = "p\\r\"o.p t[] e.s't'B";
let propCName = "h\\e'llo w'or\"ld";
let propDName = 'h\\e"llo w"or\'ld';
let propEName = 'p\\r\'o.p t[] e.s"t"B';
const o1 = {
a: {
[propBName]: {
[propCName]: {
[propDName]: {
[propEName]: [
[{ d: 11, e: 12 }],
[{ d: 21, e: 22 }],
[{ d: 31, e: 32 }]
]
}
}
}
}
};
deepFreeze(o1);
let o2 = iassign(
o1,
(o) =>
o.a["p\\r\"o.p t[] e.s't'B"]["h\\e'llo w'or\"ld"][
'h\\e"llo w"or\'ld'
]['p\\r\'o.p t[] e.s"t"B']['1'][0].d,
(d) => {
return d + 1;
}
);
expect(o2.a[propBName][propCName][propDName][propEName][1][0].d).toBe(22);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a[propBName]).not.toBe(o1.a[propBName]);
expect(o2.a[propBName][propCName]).not.toBe(o1.a[propBName][propCName]);
expect(o2.a[propBName][propCName][propDName]).not.toBe(
o1.a[propBName][propCName][propDName]
);
expect(o2.a[propBName][propCName][propDName][propEName]).not.toBe(
o1.a[propBName][propCName][propDName][propEName]
);
expect(o2.a[propBName][propCName][propDName][propEName][1]).not.toBe(
o1.a[propBName][propCName][propDName][propEName][1]
);
expect(o2.a[propBName][propCName][propDName][propEName][1][0]).not.toBe(
o1.a[propBName][propCName][propDName][propEName][1][0]
);
expect(o2.a[propBName][propCName][propDName][propEName][1][0].d).not.toBe(
o1.a[propBName][propCName][propDName][propEName][1][0].d
);
});
it('Access array using context parameter', function() {
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]] }
}
};
deepFreeze(o1);
const p1 = { a: 0 };
const o2 = iassign(
o1,
function(o, ctx) {
return o.a.b.c[ctx.p1.a][0];
},
function(ci) {
ci.d++;
return ci;
},
{ p1 }
);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][0].d).not.toBe(o1.a.b.c[0][0].d);
expect(o2.a.b.c[0][0].d).toBe(12);
});
it('Try to modify freezed object should throw error.', function() {
if (noDeepFreeze) return;
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]] }
}
};
deepFreeze(o1);
if (willThrowWhenUpdateFrozenArray) {
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c;
},
function(ci) {
ci[0].push(<any>3);
return ci;
}
);
}).toThrowError(
TypeError,
/Cannot|Can't|writable|doesn't|support|readonly|not/i
);
}
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c[0];
},
function(ci) {
ci[0].d++;
return ci;
}
);
}).toThrowError(
TypeError,
/Invalid|Cannot|read only|read-only|extensible|readonly/i
);
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c[0];
},
function(ci) {
(<any>ci[0]).g = 1;
return ci;
}
);
}).toThrowError(TypeError, /Invalid|add|extensible|readonly/i);
if (willThrowWhenUpdateFrozenArray) {
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c;
},
function(ci) {
ci[0].pop();
return ci;
}
);
}).toThrowError(TypeError, /extensible|Cannot|can't|support|unable/i);
}
});
it('Update array using lodash', function() {
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }, { d: 13, e: 14 }], [{ d: 21, e: 22 }]] }
},
a2: {}
};
deepFreeze(o1); // Ensure o1 is not changed, for testing only
//
// Calling iassign() and _.map() to increment to d in c[0] array
//
let o2 = iassign(
o1,
(o) => o.a.b.c[0],
(c) => {
return _.map(c, (item) => {
return iassign(item, (o) => o.d, (d) => d + 1);
});
}
);
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: { c: [[{ d: 11, e: 12 }, { d: 13, e: 14 }], [{ d: 21, e: 22 }]] }
},
a2: {}
});
expect(o2).toEqual({
a: {
b: { c: [[{ d: 12, e: 12 }, { d: 14, e: 14 }], [{ d: 21, e: 22 }]] }
},
a2: {}
});
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][1]).not.toBe(o1.a.b.c[0][1]);
expect(o2.a.b.c[1][0]).toBe(o1.a.b.c[1][0]);
});
it('Update array using lodash 2', function() {
const o1 = { a: { b: { c: [1, 2, 3] } } };
deepFreeze(o1); // Ensure o1 is not changed, for testing only
//
// Calling iassign() and _.map() to increment to every item in "c" array
//
let o2 = iassign(
o1,
(o) => o.a.b.c,
(c) => {
return _.map(c, (i) => i + 1);
}
);
// expect o1 has not been changed
expect(o1).toEqual({ a: { b: { c: [1, 2, 3] } } });
// expect o2.a.b.c has been updated.
expect(o2.a.b.c).toEqual([2, 3, 4]);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
});
it('Test root object is an array', function() {
const o1 = [[{ d: 11, e: 12 }, { d: 13, e: 14 }, { d: 21, e: 22 }]];
deepFreeze(o1); // Ensure o1 is not changed, for testing only
//
// Calling iassign() and _.map() to increment to every item in "c" array
//
let o2 = iassign(
o1,
(o) => o[0],
(o) => {
return _.map(o, (item, index) => {
if (index < 2) {
item = _.cloneDeep(item);
item.d++;
}
return item;
});
}
);
// expect o1 has not been changed
expect(o1).toEqual([
[{ d: 11, e: 12 }, { d: 13, e: 14 }, { d: 21, e: 22 }]
]);
// expect o2.a.b.c has been updated.
expect(o2).toEqual([
[{ d: 12, e: 12 }, { d: 14, e: 14 }, { d: 21, e: 22 }]
]);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2[0]).not.toBe(o1[0]);
expect(o2[0][0]).not.toBe(o1[0][0]);
expect(o2[0][1]).not.toBe(o1[0][1]);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2[0][2]).toBe(o1[0][2]);
});
it('Test root is an array, and try to update root array', function() {
const o1 = [{ d: 11, e: 12 }, { d: 13, e: 14 }, { d: 21, e: 22 }];
deepFreeze(o1); // Ensure o1 is not changed, for testing only
//
// Calling iassign() and _.map() to increment to every item in "c" array
//
let o2 = iassign(
o1,
(o) => o,
(o) => {
return _.map(o, (item, index) => {
if (index < 2) {
item = _.cloneDeep(item);
item.d++;
}
return item;
});
}
);
// expect o1 has not been changed
expect(o1).toEqual([
{ d: 11, e: 12 },
{ d: 13, e: 14 },
{ d: 21, e: 22 }
]);
// expect o2.a.b.c has been updated.
expect(o2).toEqual([
{ d: 12, e: 12 },
{ d: 14, e: 14 },
{ d: 21, e: 22 }
]);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2[0]).not.toBe(o1[0]);
expect(o2[1]).not.toBe(o1[1]);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2[2]).toBe(o1[2]);
});
it('Test root is an object, and try to update root object', function() {
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }]], c2: {} },
b2: {}
},
a2: {}
};
deepFreeze(o1);
const o2 = iassign(
o1,
(o) => o,
(o) => {
o.a = <any>{ b: 1 };
return o;
}
);
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }]], c2: {} },
b2: {}
},
a2: {}
});
// expect o2 inner property has been updated.
expect(o2).toEqual({ a: { b: 1 }, a2: {} });
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2.a2).toBe(o1.a2);
});
it('Use built-in deep freeze to protect input', function() {
if (noDeepFreeze) return;
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]] }
}
};
iassign.freezeInput = true;
if (willThrowWhenUpdateFrozenArray) {
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c;
},
function(ci) {
ci[0].push(<any>3);
return ci;
}
);
}).toThrowError(
TypeError,
/Cannot|Can't|writable|doesn't|support|readonly|not/i
);
}
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c[0];
},
function(ci) {
ci[0].d++;
return ci;
}
);
}).toThrowError(
TypeError,
/Invalid|Cannot|read only|read-only|extensible|readonly/i
);
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c[0];
},
function(ci) {
(<any>ci[0]).g = 1;
return ci;
}
);
}).toThrowError(TypeError, /Invalid|add|extensible|readonly/i);
if (willThrowWhenUpdateFrozenArray) {
expect(() => {
iassign(
o1,
function(o) {
return o.a.b.c;
},
function(ci) {
ci[0].pop();
return ci;
}
);
}).toThrowError(TypeError, /extensible|Cannot|can't|support|unable/i);
}
iassign.freezeInput = undefined;
});
it('Use built-in deep freeze to protect output', function() {
if (noDeepFreeze) return;
const o1 = {
a: {
b: { c: [[{ d: 11, e: 12 }, { d: 13, e: 14 }, { d: 21, e: 22 }]] }
}
};
iassign.freezeOutput = true;
let o2 = iassign(
o1,
(o) => o.a.b.c[0],
(c) => {
return _.map(c, (item) => {
return iassign(item, (o) => o.d, (d) => d + 1);
});
}
);
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: { c: [[{ d: 11, e: 12 }, { d: 13, e: 14 }, { d: 21, e: 22 }]] }
}
});
expect(o2.a.b.c[0][0].d).toBe(12);
expect(o2.a.b.c[0][1].d).toBe(14);
expect(o2.a.b.c[0][2].d).toBe(22);
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][1]).not.toBe(o1.a.b.c[0][1]);
expect(o2.a.b.c[0][2]).not.toBe(o1.a.b.c[0][2]);
if (willThrowWhenUpdateFrozenArray) {
expect(() => {
o2.a.b.c[0].push(<any>3);
}).toThrowError(
TypeError,
/Cannot|Can't|writable|doesn't|support|readonly|not/i
);
}
expect(() => {
o2.a.b.c[0][0].d++;
}).toThrowError(
TypeError,
/Invalid|Cannot|read only|read-only|extensible|readonly/i
);
expect(() => {
(<any>o2.a.b.c[0][0]).g = 1;
}).toThrowError(TypeError, /Invalid|add|extensible|readonly/i);
if (willThrowWhenUpdateFrozenArray) {
expect(() => {
o2.a.b.c[0].pop();
}).toThrowError(TypeError, /extensible|Cannot|can't|support|unable/i);
}
iassign.freezeOutput = undefined;
});
it('Example 1: update object', function() {
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const map1 = { a: 1, b: 2, c: 3 };
// 1: Calling iassign() to update map1.b
const map2 = iassign(map1, (m) => {
m.b = 50;
return m;
});
expect(map1).toEqual({ a: 1, b: 2, c: 3 });
expect(map2).toEqual({ a: 1, b: 50, c: 3 });
expect(map2).not.toBe(map1);
});
it('Example 1b: update object with option', function() {
if (noDeepFreeze) return;
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const map1 = { a: 1, b: 2, c: 3 };
// 1: Calling iassign() to update map1.b
const map2 = iassign(map1, (m) => {
m.b = 50;
return m;
});
expect(map1).toEqual({ a: 1, b: 2, c: 3 });
expect(map2).toEqual({ a: 1, b: 50, c: 3 });
expect(map2).not.toBe(map1);
expect(() => {
map2.a = 3;
}).toThrow();
const map3 = iassign(
map2,
(m) => {
m.c = 60;
return m;
},
{ freeze: false }
);
expect(map2).toEqual({ a: 1, b: 50, c: 3 });
expect(map3).toEqual({ a: 1, b: 50, c: 60 });
expect(map3).not.toBe(map2);
expect(() => {
map3.a = 3;
}).not.toThrow();
});
it('Example 1c: update object that pass undefined to getProp()', function() {
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.setOption({ freeze: true });
const map1 = { a: 1, b: 2, c: 3 };
// 1c: Calling iassign() to update map1.b
const map2 = iassign<any, { b: number }, any>(map1, undefined, (m) => {
m.b = 50;
return m;
});
expect(map1).toEqual({ a: 1, b: 2, c: 3 });
expect(map2).toEqual({ a: 1, b: 50, c: 3 });
expect(map2).not.toBe(map1);
});
it('Example 1d: update object with option that pass undefined to getProp()', function() {
if (noDeepFreeze) return;
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const map1 = { a: 1, b: 2, c: 3 };
// 1: Calling iassign() to update map1.b
const map2 = iassign<any, { b: number }, any>(map1, undefined, (m) => {
m.b = 50;
return m;
});
expect(map1).toEqual({ a: 1, b: 2, c: 3 });
expect(map2).toEqual({ a: 1, b: 50, c: 3 });
expect(map2).not.toBe(map1);
expect(() => {
map2.a = 3;
}).toThrow();
const map3 = iassign<any, { c: number }, any>(
map2,
undefined,
(m) => {
m.c = 60;
return m;
},
undefined,
{ freeze: false }
);
expect(map2).toEqual({ a: 1, b: 50, c: 3 });
expect(map3).toEqual({ a: 1, b: 50, c: 60 });
expect(map3).not.toBe(map2);
expect(() => {
map3.a = 3;
}).not.toThrow();
});
it('Example 2: update list/array', function() {
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const list1 = [1, 2];
// 2.1: Calling iassign() to push items to list1
const list2 = iassign(list1, function(l) {
l.push(3, 4, 5);
return l;
});
expect(list1).toEqual([1, 2]);
expect(list2).toEqual([1, 2, 3, 4, 5]);
expect(list2).not.toBe(list1);
// 2.2: Calling iassign() to unshift item to list2
const list3 = iassign(list2, function(l) {
l.unshift(0);
return l;
});
expect(list2).toEqual([1, 2, 3, 4, 5]);
expect(list3).toEqual([0, 1, 2, 3, 4, 5]);
expect(list3).not.toBe(list2);
// 2.3, Calling iassign() to concat list1, list2 and list3
const list4 = iassign(list1, function(l) {
return l.concat(list2, list3);
});
expect(list1).toEqual([1, 2]);
expect(list2).toEqual([1, 2, 3, 4, 5]);
expect(list3).toEqual([0, 1, 2, 3, 4, 5]);
expect(list4).toEqual([1, 2, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]);
expect(list4).not.toBe(list1);
expect(list4).not.toBe(list2);
expect(list4).not.toBe(list3);
// 2.4, Calling iassign() to concat sort list4
const list5 = iassign(list4, function(l) {
return l.sort();
});
expect(list4).toEqual([1, 2, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]);
expect(list5).toEqual([0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]);
expect(list5).not.toBe(list4);
});
it('Example 2b: update list/array that pass undefined to getProp()', function() {
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const list1 = [1, 2];
// 2.1: Calling iassign() to push items to list1
const list2 = iassign<any, number[], any>(list1, undefined, function(l) {
l.push(3, 4, 5);
return l;
});
expect(list1).toEqual([1, 2]);
expect(list2).toEqual([1, 2, 3, 4, 5]);
expect(list2).not.toBe(list1);
// 2.2: Calling iassign() to unshift item to list2
const list3 = iassign<any, number[], any>(list2, undefined, function(l) {
l.unshift(0);
return l;
});
expect(list2).toEqual([1, 2, 3, 4, 5]);
expect(list3).toEqual([0, 1, 2, 3, 4, 5]);
expect(list3).not.toBe(list2);
// 2.3, Calling iassign() to concat list1, list2 and list3
const list4 = iassign<any, number[], any>(list1, undefined, function(l) {
return l.concat(list2, list3);
});
expect(list1).toEqual([1, 2]);
expect(list2).toEqual([1, 2, 3, 4, 5]);
expect(list3).toEqual([0, 1, 2, 3, 4, 5]);
expect(list4).toEqual([1, 2, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]);
expect(list4).not.toBe(list1);
expect(list4).not.toBe(list2);
expect(list4).not.toBe(list3);
// 2.4, Calling iassign() to concat sort list4
const list5 = iassign<any, number[], any>(list4, undefined, function(l) {
return l.sort();
});
expect(list4).toEqual([1, 2, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]);
expect(list5).toEqual([0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]);
expect(list5).not.toBe(list4);
});
it('Example 3: update nested structures', function() {
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const nested1 = { a: { b: { c: [3, 4, 5] } } };
// 3.1: Calling iassign() to assign d to nested1.a.b
const nested2 = iassign(
nested1,
function(n) {
return n.a.b;
},
function(b: any) {
b.d = 6;
return b;
}
);
expect(nested1).toEqual({ a: { b: { c: [3, 4, 5] } } });
expect(nested2).toEqual({ a: { b: { c: [3, 4, 5], d: 6 } } });
expect(nested2).not.toBe(nested1);
// 3.2: Calling iassign() to increment nested2.a.b.d
const nested3 = iassign(
nested2,
function(n) {
return (<any>n.a.b).d;
},
function(d) {
return d + 1;
}
);
expect(nested2).toEqual({ a: { b: { c: [3, 4, 5], d: 6 } } });
expect(nested3).toEqual({ a: { b: { c: [3, 4, 5], d: 7 } } });
expect(nested3).not.toBe(nested2);
// 3.3: Calling iassign() to push item to nested3.a.b.c
const nested4 = iassign(
nested3,
function(n) {
return n.a.b.c;
},
function(c) {
c.push(6);
return c;
}
);
expect(nested3).toEqual({ a: { b: { c: [3, 4, 5], d: 7 } } });
expect(nested4).toEqual({ a: { b: { c: [3, 4, 5, 6], d: 7 } } });
expect(nested4).not.toBe(nested3);
});
it('Issue 3: nicer api', function() {
iassign.freeze = true;
const mutate = (getter, setter, context?) => (state) =>
iassign(state, getter, setter, context, { freeze: true });
const nested1 = { a: { b: { c: [3, 4, 5] } } };
// 3.1: Calling iassign() to assign d to nested1.a.b
let nested2 = mutate(
(n) => n.a.b,
(b) => {
b.d = 6;
return b;
}
)(nested1);
expect(nested1).toEqual({ a: { b: { c: [3, 4, 5] } } });
expect(nested2).toEqual({ a: { b: { c: [3, 4, 5], d: 6 } } });
expect(nested2).not.toBe(nested1);
});
it('Issue 4: Support classes', function() {
iassign.freeze = true;
const option: IIassignOption = {
useConstructor: true
};
class Klass {
prop: number = 11;
func() {
return 'Klass' + this.prop;
}
}
class ChildKlass extends Klass {
prop: number = 101;
func2() {
return 'ChildKlass' + this.prop;
}
}
const s = {
arr: [1],
obj: {
prop: 1,
func: function() {
return 'Klass' + this.prop;
}
},
inst: new Klass(),
inst2: new ChildKlass()
};
const t1 = iassign(
s,
(x) => x.arr,
(arr) => {
arr.push(2);
return arr;
},
null,
option
);
expect(s.arr.length).toEqual(1);
expect(t1.arr.length).toEqual(2);
const t2 = iassign(s, (x) => x.obj.prop, (y) => y + 1, null, option);
expect(s.obj.prop).toEqual(1);
expect(t2.obj.prop).toEqual(2);
expect(t2.obj.func()).toEqual('Klass2');
const t3 = iassign(s, (x) => x.inst.prop, (v) => v + 1, null, option);
expect(s.inst.prop).toEqual(11);
expect(t3.inst.prop).toEqual(12);
expect(t3.inst.func()).toEqual('Klass12');
const t4 = iassign(s, (x) => x.inst2.prop, (v) => v + 1, null, option);
expect(s.inst2.prop).toEqual(101);
expect(t4.inst2.prop).toEqual(102);
expect(t4.inst2.func()).toEqual('Klass102');
expect(t4.inst2.func2()).toEqual('ChildKlass102');
expect(t4.inst2 instanceof Klass).toEqual(true);
expect(t4.inst2 instanceof ChildKlass).toEqual(true);
expect(
(<any>t4.inst2.constructor).name == undefined ||
(<any>t4.inst2.constructor).name == 'ChildKlass'
).toEqual(true);
});
it('Issue 4b: Support classes', function() {
debugger;
iassign.freeze = true;
const option: IIassignOption = {
useConstructor: true
};
class Klass {
prop: number = 11;
func() {
return 'Klass' + this.prop;
}
}
class ChildKlass extends Klass {
prop: number = 101;
func2() {
return 'ChildKlass' + this.prop;
}
}
const s = {
arr: [1],
obj: {
prop: 1,
func: function() {
return 'Klass' + this.prop;
}
},
inst: {
k: new Klass()
},
inst2: {
ck: new ChildKlass()
}
};
const t1 = iassign(
s,
(x) => x.arr,
(arr) => {
arr.push(2);
return arr;
},
null,
option
);
expect(s.arr.length).toEqual(1);
expect(t1.arr.length).toEqual(2);
const t2 = iassign(s, (x) => x.obj.prop, (y) => y + 1, null, option);
expect(s.obj.prop).toEqual(1);
expect(t2.obj.prop).toEqual(2);
expect(t2.obj.func()).toEqual('Klass2');
const t3 = iassign(s, (x) => x.inst.k.prop, (v) => v + 1, null, option);
expect(s.inst.k.prop).toEqual(11);
expect(t3.inst.k.prop).toEqual(12);
expect(t3.inst.k.func()).toEqual('Klass12');
const t4 = iassign(s, (x) => x.inst2.ck.prop, (v) => v + 1, null, option);
expect(s.inst2.ck.prop).toEqual(101);
expect(t4.inst2.ck.prop).toEqual(102);
expect(t4.inst2.ck.func()).toEqual('Klass102');
expect(t4.inst2.ck.func2()).toEqual('ChildKlass102');
expect(t4.inst2.ck instanceof Klass).toEqual(true);
expect(t4.inst2.ck instanceof ChildKlass).toEqual(true);
expect(
(<any>t4.inst2.ck.constructor).name == undefined ||
(<any>t4.inst2.ck.constructor).name == 'ChildKlass'
).toEqual(true);
});
it('iassign.fp', function() {
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const nested1 = { a: { b: { c: [3, 4, 5] } } };
// 3.1: Calling iassign() to assign d to nested1.a.b
const nested2 = iassign.fp(
undefined,
function(n) {
return n.a.b;
},
function(b: any) {
b.d = 6;
return b;
},
undefined,
nested1
);
expect(nested1).toEqual({ a: { b: { c: [3, 4, 5] } } });
expect(nested2).toEqual({ a: { b: { c: [3, 4, 5], d: 6 } } });
expect(nested2).not.toBe(nested1);
// 3.2: Calling iassign() to increment nested2.a.b.d
const nested3 = iassign.fp(
undefined,
function(n) {
return (<any>n.a.b).d;
},
function(d) {
return d + 1;
},
undefined,
nested2
);
expect(nested2).toEqual({ a: { b: { c: [3, 4, 5], d: 6 } } });
expect(nested3).toEqual({ a: { b: { c: [3, 4, 5], d: 7 } } });
expect(nested3).not.toBe(nested2);
// 3.3: Calling iassign() to push item to nested3.a.b.c
const nested4 = iassign.fp(
undefined,
function(n) {
return n.a.b.c;
},
function(c) {
c.push(6);
return c;
},
undefined,
nested3
);
expect(nested3).toEqual({ a: { b: { c: [3, 4, 5], d: 7 } } });
expect(nested4).toEqual({ a: { b: { c: [3, 4, 5, 6], d: 7 } } });
expect(nested4).not.toBe(nested3);
});
it('iassign.fp 2: test Date', function() {
//const iassign = require("immutable-assign");
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const nested1 = { a: { b: { c: [3, 4, 5] } } };
// 3.1: Calling iassign() to assign d to nested1.a.b
const now1 = new Date();
const nested2 = iassign.fp(
undefined,
function(n) {
return n.a.b;
},
function(b: any) {
b.d = now1;
return b;
},
undefined,
nested1
);
expect(nested1).toEqual({ a: { b: { c: [3, 4, 5] } } });
expect(nested2).toEqual({ a: { b: { c: [3, 4, 5], d: now1 } } });
expect(nested2).not.toBe(nested1);
// 3.2: Calling iassign() to increment nested2.a.b.d
const now2 = new Date();
const nested3 = iassign.fp(
undefined,
function(n) {
return (<any>n.a.b).d;
},
function(d) {
return now2;
},
undefined,
nested2
);
expect(nested2).toEqual({ a: { b: { c: [3, 4, 5], d: now1 } } });
expect(nested3).toEqual({ a: { b: { c: [3, 4, 5], d: now2 } } });
expect(nested3).not.toBe(nested2);
});
it('undefined property', function() {
// Deep freeze both input and output, can be used in development to make sure they don't change.
iassign.freeze = true;
const obj1 = {
a: undefined,
b: {
c: undefined,
c2: {}
}
};
const obj2 = iassign(
obj1,
(o) => o.a,
(a) => {
return 'test a';
}
);
expect(obj1).toEqual({ a: undefined, b: { c: undefined, c2: {} } });
expect(obj2).toEqual({ a: 'test a', b: { c: undefined, c2: {} } });
const obj3 = iassign(
obj1,
(o) => (<any>o).d,
(d) => {
return 'test d';
}
);
expect(obj1).toEqual({ a: undefined, b: { c: undefined, c2: {} } });
expect(obj3).toEqual({
a: undefined,
b: { c: undefined, c2: {} },
d: 'test d'
});
const obj4 = iassign(
obj1,
(o) => (<any>o).b.e,
(e) => {
return 'test e';
}
);
expect(obj1).toEqual({ a: undefined, b: { c: undefined, c2: {} } });
expect(obj4).toEqual({
a: undefined,
b: { c: undefined, c2: {}, e: 'test e' }
});
const obj5 = iassign(
obj1,
(o, ctx) => (<any>o)[ctx.prop].f,
(f) => {
return 'test f';
},
{
prop: 'b'
}
);
expect(obj1).toEqual({ a: undefined, b: { c: undefined, c2: {} } });
expect(obj5).toEqual({
a: undefined,
b: { c: undefined, c2: {}, f: 'test f' }
});
expect(() => {
iassign(
obj1,
(o, ctx) => (<any>o)[ctx.prop].g,
(f) => {
return 'test g';
},
{
prop: 'notExists'
}
);
}).toThrowError(TypeError, /undefined/i);
const obj6 = iassign(
obj1,
(o, ctx) => (<any>o).b[ctx.prop].h,
(h) => {
return 'test h';
},
{
prop: 'c2'
}
);
expect(obj1).toEqual({ a: undefined, b: { c: undefined, c2: {} } });
expect(obj6).toEqual({
a: undefined,
b: { c: undefined, c2: { h: 'test h' } }
});
if (typeof Proxy === 'undefined') {
expect(() => {
iassign(
obj1,
(o, ctx) => (<any>o).b.c2[ctx.prop],
(h) => {
return 'test i';
},
{
prop: 'i'
}
);
}).toThrowError(/Cannot handle ctx\.prop/i);
}
});
// it('undefined property using immer', function() {
// // Deep freeze both input and output, can be used in development to make sure they don't change.
// iassign.freeze = true;
// let obj1 = {
// a: undefined,
// b: {
// c: undefined
// }
// };
// let obj2 = immer(obj1, (o) => {
// o.a = 'test a';
// });
// expect(obj1).toEqual({ a: undefined, b: { c: undefined } });
// expect(obj2).toEqual({ a: 'test a', b: { c: undefined } });
// let obj3 = immer(obj1, (o) => {
// o.d = 'test d';
// });
// expect(obj1).toEqual({ a: undefined, b: { c: undefined } });
// expect(obj3).toEqual({ a: undefined, b: { c: undefined }, d: 'test d' });
// });
it('test exposed deepFreeze should freeze', function() {
const nested1 = { a: { b: { c: [3, 4, 5] } } };
if (willThrowWhenUpdateFrozenArray) {
iassign.freeze = true;
iassign.deepFreeze(nested1);
expect(() => {
nested1.a.b.c.push(6);
}).toThrowError(
TypeError,
/Invalid|add|extensible|readonly|doesn't support|non-writable|Cannot assign/i
);
}
});
it('test exposed deepFreeze should not freeze', function() {
const nested1 = { a: { b: { c: [3, 4, 5] } } };
iassign.setOption({ freeze: false });
iassign.deepFreeze(nested1);
nested1.a.b.c.push(6);
expect(nested1).toEqual({ a: { b: { c: [3, 4, 5, 6] } } });
iassign.setOption({ freeze: false });
});
it('Access root array item using propPaths', function() {
const o1 = [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]];
deepFreeze(o1);
const o2 = iassign(o1, [1, 0], (ci: any) => {
ci.d++;
return ci;
});
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual([
[{ d: 11, e: 12 }],
[{ d: 21, e: 22 }],
[{ d: 31, e: 32 }]
]);
// expect o2 inner property has been updated.
expect(o2[1][0].d).toBe(22);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2[1]).not.toBe(o1[1]);
expect(o2[1][0]).not.toBe(o1[1][0]);
expect(o2[1][0].d).not.toBe(o1[1][0].d);
// // expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2[1][0].e).toBe(o1[1][0].e);
expect(o2[0][0]).toBe(o1[0][0]);
expect(o2[2][0]).toBe(o1[2][0]);
});
it('Access array item using propPaths', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
deepFreeze(o1);
const o2 = iassign(o1, ['a', 'b', 'c', 0, '0'], (ci: any) => {
ci.d++;
return ci;
});
// o2 != o1
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
});
// expect o2 inner property has been updated.
expect(o2.a.b.c[0][0].d).toBe(12);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][0].d).not.toBe(o1.a.b.c[0][0].d);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2.a2).toBe(o1.a2);
expect(o2.a.b2).toBe(o1.a.b2);
expect(o2.a.b.c2).toBe(o1.a.b.c2);
expect(o2.a.b.c[0][0].e).toBe(o1.a.b.c[0][0].e);
expect(o2.a.b.c[1][0]).toBe(o1.a.b.c[1][0]);
expect(o2.a.b.c[2][0]).toBe(o1.a.b.c[2][0]);
});
it('Access array item using propPaths, need to detect change and ensure setProp() is called once', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
// No change to the root object
let count = 0;
let o2: any = iassign(
o1,
[],
(o) => {
count++;
return o;
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).toBe(o1);
// Has change to the root object
count = 0;
o2 = iassign(
o1,
[],
(o) => {
count++;
return <any>{};
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).not.toBe(o1);
// No change to the object properties
count = 0;
o2 = iassign(
o1,
['a', 'b', 'c', '0', 0],
(ci) => {
count++;
return ci;
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).toBe(o1);
// Has change to the object properties
count = 0;
o2 = iassign(
o1,
['a', 'b', 'c', 0, 0],
(ci) => {
count++;
return <any>{};
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).not.toBe(o1);
// No change to the root object, used getProp()
count = 0;
o2 = iassign(
o1,
[],
(o) => {
count++;
return o;
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).toBe(o1);
// Has change to the root object, used getProp()
count = 0;
o2 = iassign(
o1,
[],
(o) => {
count++;
return <any>{};
},
undefined,
{
ignoreIfNoChange: true,
freeze: true
}
);
expect(count).toBe(1);
expect(o2).not.toBe(o1);
});
it('Access array item using propPaths, need to detect change and has change', function() {
const o1 = {
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
};
deepFreeze(o1);
const o2 = iassign(
o1,
['a', 'b', 'c', 0, 0],
(ci: any) => {
ci.d++;
return ci;
},
{
ignoreIfNoChange: true,
freeze: true
}
);
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual({
a: {
b: {
c: [[{ d: 11, e: 12 }], [{ d: 21, e: 22 }], [{ d: 31, e: 32 }]],
c2: {}
},
b2: {}
},
a2: {}
});
// expect o2 inner property has been updated.
expect(o2.a.b.c[0][0].d).toBe(12);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2.a).not.toBe(o1.a);
expect(o2.a.b).not.toBe(o1.a.b);
expect(o2.a.b.c).not.toBe(o1.a.b.c);
expect(o2.a.b.c[0]).not.toBe(o1.a.b.c[0]);
expect(o2.a.b.c[0][0]).not.toBe(o1.a.b.c[0][0]);
expect(o2.a.b.c[0][0].d).not.toBe(o1.a.b.c[0][0].d);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(o2.a2).toBe(o1.a2);
expect(o2.a.b2).toBe(o1.a.b2);
expect(o2.a.b.c2).toBe(o1.a.b.c2);
expect(o2.a.b.c[0][0].e).toBe(o1.a.b.c[0][0].e);
expect(o2.a.b.c[1][0]).toBe(o1.a.b.c[1][0]);
expect(o2.a.b.c[2][0]).toBe(o1.a.b.c[2][0]);
});
it('Issue 23: Feature request: Allow specifying the path of property to update by an array', function() {
const o1 = {
'/computer-sciences/': {
title: 'Computer sciences',
opened: false,
children: {
'artificial-intelligence/': {
title: 'Artificial intelligence',
opened: false,
children: {
'machine-learning/': {
title: 'Machine learning',
opened: false,
children: {
'introduction/': {
title: 'Introduction'
},
'common-models/': {
title: 'Common Models'
},
'common-training-methods/': {
title: 'Common training methods'
},
'ensemble-techniques/': {
title: 'Ensemble techniques'
}
}
}
}
}
}
}
};
deepFreeze(o1);
const o2 = iassign(
o1,
[
'/computer-sciences/',
'children',
'artificial-intelligence/',
'opened'
],
(opened) => !opened
);
//
// Jasmine Tests
//
// expect o1 has not been changed
expect(o1).toEqual({
'/computer-sciences/': {
title: 'Computer sciences',
opened: false,
children: {
'artificial-intelligence/': {
title: 'Artificial intelligence',
opened: false,
children: {
'machine-learning/': {
title: 'Machine learning',
opened: false,
children: {
'introduction/': {
title: 'Introduction'
},
'common-models/': {
title: 'Common Models'
},
'common-training-methods/': {
title: 'Common training methods'
},
'ensemble-techniques/': {
title: 'Ensemble techniques'
}
}
}
}
}
}
}
});
// expect o2 inner property has been updated.
expect(
o2['/computer-sciences/']['children']['artificial-intelligence/'][
'opened'
]
).toBe(true);
// expect object graph for changed property in o2 is now different from (!==) o1.
expect(o2).not.toBe(o1);
expect(o2['/computer-sciences/']).not.toBe(o1['/computer-sciences/']);
expect(o2['/computer-sciences/']['children']).not.toBe(
o1['/computer-sciences/']['children']
);
expect(
o2['/computer-sciences/']['children']['artificial-intelligence/']
).not.toBe(
o1['/computer-sciences/']['children']['artificial-intelligence/']
);
expect(
o2['/computer-sciences/']['children']['artificial-intelligence/'][
'opened'
]
).not.toBe(
o1['/computer-sciences/']['children']['artificial-intelligence/'][
'opened'
]
);
// expect object graph for unchanged property in o2 is still equal to (===) o1.
expect(
o2['/computer-sciences/']['children']['artificial-intelligence/'][
'children'
]
).toBe(
o1['/computer-sciences/']['children']['artificial-intelligence/'][
'children'
]
);
});
});
}); | the_stack |
import { Action } from 'redux/interfaces';
import { getType } from 'typesafe-actions';
import * as actions from 'redux/actions';
import {
DataEntityLineage,
DataEntityLineageEdge,
DataEntityLineageNode,
} from 'generated-sources';
import uniqWith from 'lodash/uniqWith';
import isEqual from 'lodash/isEqual';
import { DataEntityLineageState } from '../interfaces';
import {
DataEntityLineageStreamById,
FilterEdges,
GroupedDataEntityLineageNode,
GroupingNodes,
LocalState,
} from '../interfaces/dataentityLineage';
const localState: LocalState = {
allNodes: [],
nodeIds: new Set<number>(),
allEdges: [],
allGroups: [],
groupIds: new Set<number>(),
excludedIds: new Set<number>(),
};
export const initialState: DataEntityLineageState = {};
export const dataEntityLineageInitialState = {
edgesById: {},
nodesById: {},
};
enum DataEntityLineageStreamTypeEnum {
UPSTREAM = 'upstream',
DOWNSTREAM = 'downstream',
}
const startId = 2 ** 30;
let increment = 0;
// eslint-disable-next-line no-plusplus
const generateNumberId = () => startId + increment++;
const setDataByType = (
type: DataEntityLineageStreamTypeEnum,
firstData: any,
secondData: any
) => (type === 'downstream' ? firstData : secondData);
const getOrCalculate = (
type: DataEntityLineageStreamTypeEnum,
calculateType: DataEntityLineageStreamTypeEnum,
data: any,
consumer: () => any
) => (type === calculateType ? consumer() : data);
const groupingNodes = (
groupIdsBySourceId: Map<number, number[]>,
sourceIdByDepth: Map<number, number[]>,
minGroupSize: number,
keepInBiggestGroup: boolean,
excludedIds: Set<number>
): GroupingNodes[] => {
const groupedNodes: GroupingNodes[] = [];
Array.from(sourceIdByDepth.keys()).forEach(depth => {
const sourceIds = sourceIdByDepth
.get(depth)
?.filter(s => !excludedIds.has(s));
// groupId -> sourceId[]
const depthGroups = sourceIds!.reduce((map, sourceId) => {
const groupIds = groupIdsBySourceId.get(sourceId);
if (groupIds !== undefined) {
groupIds.forEach(groupId => {
if (!map.has(groupId)) {
map.set(groupId, [sourceId]);
} else {
map.get(groupId)?.push(sourceId);
}
});
}
return map;
}, new Map<number, number[]>());
const groupIdsBySourceIdByDepth = new Map<number, number[]>();
Array.from(groupIdsBySourceId.keys())
.filter(s => sourceIds?.includes(s))
.forEach(s =>
groupIdsBySourceIdByDepth.set(s, groupIdsBySourceId.get(s)!)
);
const resultSourceIdsByGroupId = new Map<number, number[]>();
const generatedGroupIdByGroupId = new Map<number, number>();
Array.from(groupIdsBySourceIdByDepth.keys()).forEach(sourceId => {
const groupIds = groupIdsBySourceIdByDepth.get(sourceId);
if (groupIds !== undefined && groupIds.length >= 1) {
const maxGroup = groupIds.reduce(
({ groupId, size }, currentGroupId) => {
const groupSize = depthGroups.get(currentGroupId)?.length;
if (groupSize && groupSize > size && keepInBiggestGroup) {
return { groupId: currentGroupId, size: groupSize };
}
if (groupSize && groupSize < size && !keepInBiggestGroup) {
return { groupId: currentGroupId, size: groupSize };
}
return { groupId, size };
},
{ groupId: 0, size: 0 }
);
// fill resultSourceIdsByGroupId Map with maxGroup.groupIds -> array of source ids
if (!resultSourceIdsByGroupId.has(maxGroup.groupId)) {
resultSourceIdsByGroupId.set(maxGroup.groupId, [sourceId]);
} else {
resultSourceIdsByGroupId.get(maxGroup.groupId)?.push(sourceId);
}
}
});
Array.from(resultSourceIdsByGroupId.keys()).forEach(groupId => {
if (resultSourceIdsByGroupId.get(groupId)!.length < minGroupSize) {
resultSourceIdsByGroupId.delete(groupId);
}
});
// fill generatedGroupIdByGroupId Map with groupId -> generated groupId
Array.from(resultSourceIdsByGroupId.keys()).forEach(groupId =>
generatedGroupIdByGroupId.set(groupId, generateNumberId())
);
Array.from(resultSourceIdsByGroupId.keys()).forEach(groupId =>
groupedNodes.push({
groupId,
depthGroupId: generatedGroupIdByGroupId.get(groupId)!,
depth,
sourceIds: resultSourceIdsByGroupId.get(groupId)!,
})
);
});
return groupedNodes;
};
const filterEdges = (
rootNodeId: number,
edges: DataEntityLineageEdge[],
lineageType: DataEntityLineageStreamTypeEnum
): FilterEdges => {
const edgeType: keyof DataEntityLineageEdge = setDataByType(
lineageType,
'sourceId',
'targetId'
);
const oppositeEdgeType: keyof DataEntityLineageEdge = setDataByType(
lineageType,
'targetId',
'sourceId'
);
type Queue = Array<{ sourceId: number; depth: number }>;
const sourceIdMapByDepth = new Map<number, number[]>();
const queue: Queue = [{ sourceId: rootNodeId, depth: 0 }];
const filteredEdges = new Array<DataEntityLineageEdge>();
const crossEdges = new Array<DataEntityLineageEdge>();
const allAddedIds = new Set<number>([rootNodeId]);
const edgesMap = edges.reduce((map, edge) => {
if (!map.has(edge[edgeType])) {
return map.set(edge[edgeType], [edge[oppositeEdgeType]]);
}
map.get(edge[edgeType])?.push(edge[oppositeEdgeType]);
return map;
}, new Map<number, number[]>());
while (queue.length > 0) {
const { sourceId, depth } = queue.shift()!;
const lineageDepth = depth + 1;
const targetIds = edgesMap.get(sourceId);
if (
targetIds !== undefined &&
targetIds !== null &&
targetIds.length > 0
) {
const nonAddedIds = targetIds.filter(id => !allAddedIds.has(id));
filteredEdges.push(
...nonAddedIds.map(id =>
lineageType === 'downstream'
? {
sourceId,
targetId: id,
}
: {
sourceId: id,
targetId: sourceId,
}
)
);
const addedIds = targetIds.filter(id => allAddedIds.has(id));
crossEdges.push(
...addedIds.map(id =>
lineageType === 'downstream'
? {
sourceId,
targetId: id,
}
: {
sourceId: id,
targetId: sourceId,
}
)
);
nonAddedIds.forEach(id => allAddedIds.add(id));
if (!sourceIdMapByDepth.has(lineageDepth)) {
sourceIdMapByDepth.set(lineageDepth, []);
}
const depthSourceIds: number[] = sourceIdMapByDepth.get(
lineageDepth
)!;
depthSourceIds.push(...nonAddedIds);
nonAddedIds.forEach(id =>
queue.push({ sourceId: id, depth: lineageDepth })
);
}
}
return { filteredEdges, sourceIdMapByDepth, crossEdges };
};
const updateDataEntityLineage = (
state: DataEntityLineageState,
entityId: number,
lineage: DataEntityLineage,
rootNodeId: number,
lineageType: DataEntityLineageStreamTypeEnum
): DataEntityLineageState => {
const getStreamDataFromState = (type: DataEntityLineageStreamTypeEnum) =>
state[rootNodeId]?.[type] || dataEntityLineageInitialState;
lineage[lineageType].nodes.forEach(node => {
if (!localState.nodeIds.has(node.id)) {
localState.allNodes.push(node);
localState.nodeIds.add(node.id);
}
});
localState.allEdges.push(...lineage[lineageType].edges);
lineage[lineageType].groups.forEach(group => {
if (!localState.groupIds.has(group.id)) {
localState.allGroups.push(group);
localState.groupIds.add(group.id);
}
});
localState.excludedIds.add(lineage.root.id);
const setRootNode = (rootNode: DataEntityLineageNode) =>
rootNodeId !== entityId ? state[rootNodeId].root : rootNode;
const edgeType: keyof DataEntityLineageEdge = setDataByType(
lineageType,
'sourceId',
'targetId'
);
const createStreamData = (): DataEntityLineageStreamById => {
const groupIdsBySourceId = Array.from(localState.allNodes).reduce(
(map, node) => {
if (
node.groupIdList &&
node.groupIdList?.length > 0 &&
!map.has(node.id)
) {
map.set(node.id, [...node.groupIdList]);
} else if (node.groupIdList && node.groupIdList?.length > 0) {
map.get(node.id)?.push(...node.groupIdList);
}
return map;
},
new Map<number, number[]>()
);
const { filteredEdges, sourceIdMapByDepth, crossEdges } = filterEdges(
rootNodeId,
Array.from(localState.allEdges),
lineageType
);
const groupedNodes = groupingNodes(
groupIdsBySourceId,
sourceIdMapByDepth,
2,
true,
localState.excludedIds
);
const depthGroupIdBySourceId = new Map<number, number>();
groupedNodes.forEach(node => {
node.sourceIds.forEach(sourceId =>
depthGroupIdBySourceId.set(sourceId, node.depthGroupId)
);
});
const replacedEdges = filteredEdges.map(edge => ({
sourceId: depthGroupIdBySourceId.has(edge.sourceId)
? depthGroupIdBySourceId.get(edge.sourceId)!
: edge.sourceId,
targetId: depthGroupIdBySourceId.has(edge.targetId)
? depthGroupIdBySourceId.get(edge.targetId)!
: edge.targetId,
}));
const resultEdges: DataEntityLineageEdge[] = uniqWith(
replacedEdges,
isEqual
);
const replacedCrossEdges = crossEdges.map(edge => ({
sourceId: depthGroupIdBySourceId.has(edge.sourceId)
? depthGroupIdBySourceId.get(edge.sourceId)!
: edge.sourceId,
targetId: depthGroupIdBySourceId.has(edge.targetId)
? depthGroupIdBySourceId.get(edge.targetId)!
: edge.targetId,
}));
const resultCrossEdges: DataEntityLineageEdge[] = uniqWith(
replacedCrossEdges,
isEqual
);
const resultNodes: GroupedDataEntityLineageNode[] = groupedNodes
.map(groupNode => {
const group = localState.allGroups.find(
g => g.id === groupNode.groupId
);
const resultNode: GroupedDataEntityLineageNode = {
...group,
id: groupNode.depthGroupId,
nodesRelatedWithDEG: localState.allNodes.filter(n =>
groupNode.sourceIds.includes(n.id)
),
originalGroupId: group?.id,
};
return resultNode;
})
.concat(localState.allNodes);
return {
edgesById: resultEdges.reduce<
DataEntityLineageStreamById['edgesById']
>(
(memo, edge) => ({
...memo,
[edge[edgeType]]: memo[edge[edgeType]]
? [...memo[edge[edgeType]], edge]
: [edge],
}),
{}
),
nodesById: resultNodes.reduce<
DataEntityLineageStreamById['nodesById']
>(
(memo, node) => ({
...memo,
[node.id]: node,
}),
{}
),
crossEdges: [...resultCrossEdges],
};
};
return {
...state,
[rootNodeId || entityId]: {
downstream: getOrCalculate(
lineageType,
DataEntityLineageStreamTypeEnum.DOWNSTREAM,
getStreamDataFromState(DataEntityLineageStreamTypeEnum.DOWNSTREAM),
createStreamData
),
root: setRootNode(lineage.root),
upstream: getOrCalculate(
lineageType,
DataEntityLineageStreamTypeEnum.UPSTREAM,
getStreamDataFromState(DataEntityLineageStreamTypeEnum.UPSTREAM),
createStreamData
),
},
};
};
const reducer = (
state = initialState,
action: Action
): DataEntityLineageState => {
const downstreamActionType = getType(
actions.fetchDataEntityDownstreamLineageAction.success
);
const upstreamActionType = getType(
actions.fetchDataEntityUpstreamLineageAction.success
);
if (
action.type === (downstreamActionType || upstreamActionType) &&
action.payload.entityId === action.payload.value.rootNodeId
) {
localState.allNodes = [];
localState.allGroups = [];
localState.allEdges = [];
localState.excludedIds = new Set();
localState.groupIds = new Set();
localState.nodeIds = new Set();
}
switch (action.type) {
case getType(actions.fetchDataEntityDownstreamLineageAction.success):
return updateDataEntityLineage(
state,
action.payload.entityId,
action.payload.value.dataEntityLineage,
action.payload.value.rootNodeId,
DataEntityLineageStreamTypeEnum.DOWNSTREAM
);
case getType(actions.fetchDataEntityUpstreamLineageAction.success):
return updateDataEntityLineage(
state,
action.payload.entityId,
action.payload.value.dataEntityLineage,
action.payload.value.rootNodeId,
DataEntityLineageStreamTypeEnum.UPSTREAM
);
default:
return state;
}
};
export default reducer; | the_stack |
import { dasherize } from '@angular-devkit/core/src/utils/strings';
import {
chain,
ExecutionOptions,
noop,
Rule,
SchematicContext,
SchematicsException,
TaskId,
Tree,
} from '@angular-devkit/schematics';
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
import {
addPackageJsonDependency,
NodeDependency,
NodeDependencyType,
} from '@schematics/angular/utility/dependencies';
import {
CMS_CONFIG,
I18N_CONFIG,
PROVIDE_CONFIG_FUNCTION,
UTF_8,
} from '../constants';
import {
SPARTACUS_CONFIGURATION_MODULE,
SPARTACUS_CORE,
SPARTACUS_FEATURES_MODULE,
SPARTACUS_FEATURES_NG_MODULE,
SPARTACUS_SETUP,
} from '../libs-constants';
import { getB2bConfiguration } from './config-utils';
import {
AdditionalFeatureConfiguration,
AdditionalProviders,
findFeatureModule,
getSpartacusFeaturesModule,
} from './feature-utils';
import {
crossFeatureInstallationOrder,
crossLibraryInstallationOrder,
} from './graph-utils';
import { createImports } from './import-utils';
import {
debugLogRule,
formatFeatureComplete,
formatFeatureStart,
} from './logger-utils';
import {
addModuleImport,
addModuleProvider,
ensureModuleExists,
Import,
} from './new-module-utils';
import {
createDependencies,
createSpartacusDependencies,
getPrefixedSpartacusSchematicsVersion,
readPackageJson,
} from './package-utils';
import { createProgram, saveAndFormat } from './program';
import { getProjectTsConfigPaths } from './project-tsconfig-paths';
import {
getDefaultProjectNameFromWorkspace,
getSourceRoot,
getWorkspace,
scaffoldStructure,
} from './workspace-utils';
export interface LibraryOptions extends Partial<ExecutionOptions> {
project: string;
lazy?: boolean;
features?: string[];
/**
* When enabled, prints the additional logs.
*/
debug?: boolean;
/**
* Internal options.
* Should not be set by the user.
*/
internal?: {
/**
* If Spartacus is already installed in the app.
*/
existingSpartacusApplication?: boolean;
};
/**
* Meta.
* Populated when programmatically invoking
* Spartacus installation schematics in order
* to install them as dependencies.
*/
options?: LibraryOptions;
}
/**
* Configuration describing the feature schematics.
*/
export interface SchematicConfig {
/**
* Library options
*/
library: {
/**
* The feature name, e.g. CHECKOUT_BASE_FEATURE.
* Corresponds to the CLI's name defined in file:
* `projects/schematics/src/add-spartacus/schema.json`
*/
featureName: string;
/**
* Spartacus library scope, e.g. `@spartacus/checkout`
*/
mainScope: string;
/**
* E.g. `@spartacus/checkout/base/b2b`
*/
featureScope?: string;
/**
* If the feature is a b2b feature, it will provide the b2b configuration.
*/
b2b?: boolean;
};
/**
* The folder in which we will generate the feature module. E.g. app/spartacus/features/__organization__ (__NOTE__: just the `organization` part should be provided.).
*/
folderName: string;
/**
* Used as the generated feature module's file name.
* Also, used as the lazy loading's feature name if the `lazyLoadingChunk` config is not provided.
*/
moduleName: string;
/**
* The feature module configuration.
* E.g. `CheckoutB2BModule` from `@spartacus/checkout/b2b`.
*/
featureModule: Module | Module[];
/**
* The root module configuration.
* E.g. `CheckoutB2BRootModule` from `@spartacus/checkout/b2b/root`.
*/
rootModule?: Module;
/**
* The lazy loading chunk's name.
* It's usually a constant imported from a library.
*/
lazyLoadingChunk?: Import;
/**
* Translation chunk configuration
*/
i18n?: I18NConfig;
/**
* Styling configuration
*/
styles?: StylingConfig;
/**
* Assets configuration
*/
assets?: AssetsConfig;
/**
* A function returning the custom configuration.
*/
customConfig?: <OPTIONS extends LibraryOptions>(
options: OPTIONS
) => AdditionalFeatureConfiguration;
/**
* A list of feature dependencies which will be configured
* during the new Spartacus installation.
*/
dependencyFeatures?: string[];
/**
* Configuration for generating the wrapper modules.
*/
importAfter?: {
/**
* The "marker" module name is a module name for which to search for.
*/
markerModuleName: string;
/**
* The feature module name will be imported after the "marker" module.
*/
featureModuleName: string;
}[];
}
export interface Module {
/** Module name */
name: string;
/** Module import path */
importPath: string;
/**
* The content to specify in ng-module's imports,
* e.g. `AuthModule.forRoot()`. If not specified,
* the `name` is used.
*/
content?: string;
}
export interface I18NConfig {
resources: string;
chunks: string;
importPath: string;
}
export interface StylingConfig {
scssFileName: string;
importStyle: string;
}
export interface AssetsConfig {
input: string;
output?: string;
glob: string;
}
export function shouldAddFeature(
feature: string,
features: string[] = []
): boolean {
return features.includes(feature);
}
export function addLibraryFeature<T extends LibraryOptions>(
options: T,
config: SchematicConfig
): Rule {
return (tree: Tree, context: SchematicContext) => {
const spartacusFeatureModuleExistsInApp = checkAppStructure(
tree,
options.project
);
if (!spartacusFeatureModuleExistsInApp) {
context.logger.info('Scaffolding the new app structure...');
context.logger.warn(
'Please migrate manually the rest of your feature modules to the new app structure: https://sap.github.io/spartacus-docs/reference-app-structure/'
);
}
return chain([
debugLogRule(
formatFeatureStart(config.library.featureName, `adding...`),
options.debug
),
spartacusFeatureModuleExistsInApp ? noop() : scaffoldStructure(options),
handleFeature(options, config),
config.styles ? addLibraryStyles(config.styles, options) : noop(),
config.assets ? addLibraryAssets(config.assets, options) : noop(),
debugLogRule(
formatFeatureComplete(config.library.featureName, `added.`),
options.debug
),
]);
};
}
export function checkAppStructure(tree: Tree, project: string): boolean {
const { buildPaths } = getProjectTsConfigPaths(tree, project);
if (!buildPaths.length) {
throw new SchematicsException(
`Could not find any tsconfig file. Can't find ${SPARTACUS_FEATURES_NG_MODULE}.`
);
}
const basePath = process.cwd();
for (const tsconfigPath of buildPaths) {
if (getSpartacusFeaturesModule(tree, basePath, tsconfigPath)) {
return true;
}
}
return false;
}
function handleFeature<T extends LibraryOptions>(
options: T,
config: SchematicConfig
): Rule {
return (tree: Tree, _context: SchematicContext) => {
const rules: Rule[] = [];
rules.push(
ensureModuleExists({
name: createSpartacusFeatureFileName(config.moduleName),
path: createSpartacusFeatureFolderPath(config.folderName),
module: SPARTACUS_FEATURES_MODULE,
project: options.project,
})
);
rules.push(addRootModule(options, config));
rules.push(addFeatureModule(options, config));
rules.push(addFeatureTranslations(options, config));
rules.push(addCustomConfig(options, config));
if (config.library.b2b) {
rules.push(configureB2bFeatures(options, readPackageJson(tree)));
}
return chain(rules);
};
}
export function createSpartacusFeatureFolderPath(folderName: string): string {
return `app/spartacus/features/${dasherize(folderName)}`;
}
export function createSpartacusFeatureFileName(name: string): string {
return `${dasherize(name)}-feature`;
}
export function createSpartacusWrapperModuleFileName(name: string): string {
const normalizedName = name.replace('module', '').replace('Module', '');
return `${dasherize(normalizedName)}-wrapper`;
}
function addRootModule<T extends LibraryOptions>(
options: T,
config: SchematicConfig
): Rule {
return (tree: Tree): Tree => {
if (!config.rootModule) {
return tree;
}
const basePath = process.cwd();
const moduleFileName = createModuleFileName(config);
const { buildPaths } = getProjectTsConfigPaths(tree, options.project);
for (const tsconfigPath of buildPaths) {
const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath);
for (const sourceFile of appSourceFiles) {
if (!sourceFile.getFilePath().endsWith('/' + moduleFileName)) {
continue;
}
addModuleImport(sourceFile, {
import: {
moduleSpecifier: config.rootModule.importPath,
namedImports: [config.rootModule.name],
},
content: config.rootModule.content || config.rootModule.name,
});
saveAndFormat(sourceFile);
break;
}
}
return tree;
};
}
function addFeatureModule<T extends LibraryOptions>(
options: T,
config: SchematicConfig
): Rule {
return (tree: Tree) => {
const basePath = process.cwd();
const moduleFileName = createModuleFileName(config);
const { buildPaths } = getProjectTsConfigPaths(tree, options.project);
for (const tsconfigPath of buildPaths) {
const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath);
for (const sourceFile of appSourceFiles) {
if (!sourceFile.getFilePath().endsWith('/' + moduleFileName)) {
continue;
}
const configFeatures = ([] as Module[]).concat(config.featureModule);
for (let i = 0; i < configFeatures.length; i++) {
const featureModule = configFeatures[i];
// if it's already in a wrapper module
if (findFeatureModule(featureModule, appSourceFiles)) {
break;
}
let content = `${PROVIDE_CONFIG_FUNCTION}(<${CMS_CONFIG}>{
featureModules: {`;
if (options.lazy) {
let lazyLoadingChunkName = config.moduleName;
if (config.lazyLoadingChunk) {
const namedImportsContent =
config.lazyLoadingChunk.namedImports[i];
lazyLoadingChunkName = `[${namedImportsContent}]`;
createImports(sourceFile, config.lazyLoadingChunk);
}
content =
content +
`${lazyLoadingChunkName}: {
module: () =>
import('${featureModule.importPath}').then((m) => m.${featureModule.name}),
},`;
addModuleProvider(sourceFile, {
import: [
{
moduleSpecifier: SPARTACUS_CORE,
namedImports: [PROVIDE_CONFIG_FUNCTION, CMS_CONFIG],
},
],
content: content + `}})`,
});
} else {
addModuleImport(sourceFile, {
import: {
moduleSpecifier: featureModule.importPath,
namedImports: [featureModule.name],
},
content: featureModule.content || featureModule.name,
});
}
}
saveAndFormat(sourceFile);
break;
}
}
return tree;
};
}
export function addFeatureTranslations<T extends LibraryOptions>(
options: T,
config: SchematicConfig
): Rule {
return (tree: Tree): Tree => {
if (!config.i18n) {
return tree;
}
const basePath = process.cwd();
const moduleFileName = createModuleFileName(config);
const { buildPaths } = getProjectTsConfigPaths(tree, options.project);
for (const tsconfigPath of buildPaths) {
const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath);
for (const sourceFile of appSourceFiles) {
if (!sourceFile.getFilePath().endsWith('/' + moduleFileName)) {
continue;
}
addModuleProvider(sourceFile, {
import: [
{
moduleSpecifier: SPARTACUS_CORE,
namedImports: [PROVIDE_CONFIG_FUNCTION, I18N_CONFIG],
},
{
moduleSpecifier: config.i18n.importPath,
namedImports: [config.i18n.chunks, config.i18n.resources],
},
],
content: `${PROVIDE_CONFIG_FUNCTION}(<${I18N_CONFIG}>{
i18n: {
resources: ${config.i18n.resources},
chunks: ${config.i18n.chunks},
},
})`,
});
saveAndFormat(sourceFile);
break;
}
}
return tree;
};
}
function addCustomConfig<T extends LibraryOptions>(
options: T,
config: SchematicConfig
): Rule {
return (tree: Tree): Tree => {
if (!config.customConfig) {
return tree;
}
const basePath = process.cwd();
const moduleFileName = createModuleFileName(config);
const { buildPaths } = getProjectTsConfigPaths(tree, options.project);
for (const tsconfigPath of buildPaths) {
const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath);
for (const sourceFile of appSourceFiles) {
if (!sourceFile.getFilePath().endsWith('/' + moduleFileName)) {
continue;
}
const customConfigs = ([] as AdditionalProviders[]).concat(
config.customConfig(options).providers ?? []
);
customConfigs.forEach((customConfig) => {
addModuleProvider(sourceFile, {
import: [
{
moduleSpecifier: SPARTACUS_CORE,
namedImports: [PROVIDE_CONFIG_FUNCTION],
},
...customConfig.import,
],
content: `${PROVIDE_CONFIG_FUNCTION}(${customConfig.content})`,
});
});
saveAndFormat(sourceFile);
break;
}
}
return tree;
};
}
function addLibraryAssets(
assetsConfig: AssetsConfig,
options: LibraryOptions
): Rule {
return (tree: Tree) => {
const { path, workspace: angularJson } = getWorkspace(tree);
const defaultProject = getDefaultProjectNameFromWorkspace(tree);
const project = options.project || defaultProject;
const architect = angularJson.projects[project].architect;
// `build` architect section
const architectBuild = architect?.build;
const buildAssets = createAssetsArray(
assetsConfig,
(architectBuild?.options as any)?.assets
);
const buildOptions = {
...architectBuild?.options,
assets: buildAssets,
};
// `test` architect section
const architectTest = architect?.test;
const testAssets = createAssetsArray(
assetsConfig,
(architectTest?.options as any)?.assets
);
const testOptions = {
...architectTest?.options,
assets: testAssets,
};
const updatedAngularJson = {
...angularJson,
projects: {
...angularJson.projects,
[project]: {
...angularJson.projects[project],
architect: {
...architect,
build: {
...architectBuild,
options: buildOptions,
},
test: {
...architectTest,
options: testOptions,
},
},
},
},
};
const initialContent = tree.read(path)?.toString(UTF_8) ?? '';
const toUpdate = JSON.stringify(updatedAngularJson, null, 2);
// prevent the unnecessary Angular logs about the files being updated
if (initialContent !== toUpdate) {
tree.overwrite(path, toUpdate);
}
};
}
function createAssetsArray(
assetsConfig: AssetsConfig,
angularJsonAssets: any[] = []
): unknown[] {
for (const asset of angularJsonAssets) {
if (typeof asset === 'object') {
if (
asset.glob === assetsConfig.glob &&
asset.input === `./node_modules/@spartacus/${assetsConfig.input}` &&
asset.output === (assetsConfig.output || 'assets/')
) {
return angularJsonAssets;
}
}
}
angularJsonAssets = [
...angularJsonAssets,
{
glob: assetsConfig.glob,
input: `./node_modules/@spartacus/${assetsConfig.input}`,
output: assetsConfig.output || 'assets/',
},
];
return angularJsonAssets;
}
export function addLibraryStyles(
stylingConfig: StylingConfig,
options: LibraryOptions
): Rule {
return (tree: Tree, _context: SchematicContext) => {
const defaultProject = getDefaultProjectNameFromWorkspace(tree);
const project = options.project || defaultProject;
const libraryScssPath = `${getSourceRoot(tree, {
project: project,
})}/styles/spartacus/${stylingConfig.scssFileName}`;
const toAdd = `@import "${stylingConfig.importStyle}";`;
if (tree.exists(libraryScssPath)) {
const initialContent = tree.read(libraryScssPath)?.toString(UTF_8) ?? '';
let content = initialContent;
if (!content.includes(toAdd)) {
content += `\n${toAdd}`;
}
// prevent the unnecessary Angular logs about the files being updated
if (initialContent !== content) {
tree.overwrite(libraryScssPath, content);
}
return tree;
}
tree.create(libraryScssPath, toAdd);
const { path, workspace: angularJson } = getWorkspace(tree);
const architect = angularJson.projects[project].architect;
// `build` architect section
const architectBuild = architect?.build;
const buildOptions = {
...architectBuild?.options,
styles: [
...((architectBuild?.options as any)?.styles
? (architectBuild?.options as any)?.styles
: []),
libraryScssPath,
],
};
// `test` architect section
const architectTest = architect?.test;
const testOptions = {
...architectTest?.options,
styles: [
...(architectTest?.options?.styles
? architectTest?.options?.styles
: []),
libraryScssPath,
],
};
const updatedAngularJson = {
...angularJson,
projects: {
...angularJson.projects,
[project]: {
...angularJson.projects[project],
architect: {
...architect,
build: {
...architectBuild,
options: buildOptions,
},
test: {
...architectTest,
options: testOptions,
},
},
},
},
};
tree.overwrite(path, JSON.stringify(updatedAngularJson, null, 2));
};
}
export function createNodePackageInstallationTask(
context: SchematicContext
): TaskId {
return context.addTask(new NodePackageInstallTask());
}
export function installPackageJsonDependencies(): Rule {
return (tree: Tree, context: SchematicContext) => {
createNodePackageInstallationTask(context);
return tree;
};
}
export function addPackageJsonDependencies(
dependencies: NodeDependency[],
packageJson: any
): Rule {
return (tree: Tree, context: SchematicContext): Tree => {
for (const dependency of dependencies) {
if (!dependencyExists(dependency, packageJson)) {
addPackageJsonDependency(tree, dependency);
context.logger.info(
`✅️ Added '${dependency.name}' into ${dependency.type}`
);
}
}
return tree;
};
}
/**
* Adds libraries dependencies to package.json
*/
export function addPackageJsonDependenciesForLibrary<
OPTIONS extends LibraryOptions
>(dependencies: Record<string, string>, _options: OPTIONS): Rule {
return (tree: Tree, _context: SchematicContext): Rule => {
const packageJson = readPackageJson(tree);
const spartacusLibraries = createSpartacusDependencies(dependencies);
const thirdPartyLibraries = createDependencies(dependencies);
const libraries = spartacusLibraries.concat(thirdPartyLibraries);
return chain([
addPackageJsonDependencies(libraries, packageJson),
installPackageJsonDependencies(),
]);
};
}
export function dependencyExists(
dependency: NodeDependency,
packageJson: any
): boolean {
return packageJson[dependency.type]?.hasOwnProperty(dependency.name);
}
export function configureB2bFeatures<T extends LibraryOptions>(
options: T,
packageJson: any
): Rule {
return (_tree: Tree, _context: SchematicContext): Rule => {
const spartacusVersion = getPrefixedSpartacusSchematicsVersion();
return chain([
addB2bProviders(options),
addPackageJsonDependencies(
[
{
type: NodeDependencyType.Default,
version: spartacusVersion,
name: SPARTACUS_SETUP,
},
],
packageJson
),
]);
};
}
function addB2bProviders<T extends LibraryOptions>(options: T): Rule {
return (tree: Tree, _context: SchematicContext): Tree => {
const { buildPaths } = getProjectTsConfigPaths(tree, options.project);
if (!buildPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot configure SpartacusConfigurationModule.'
);
}
const basePath = process.cwd();
for (const tsconfigPath of buildPaths) {
const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath);
for (const sourceFile of appSourceFiles) {
if (
!sourceFile
.getFilePath()
.includes(`${SPARTACUS_CONFIGURATION_MODULE}.module.ts`)
) {
continue;
}
getB2bConfiguration().forEach((provider) =>
addModuleProvider(sourceFile, provider)
);
saveAndFormat(sourceFile);
break;
}
}
return tree;
};
}
function createModuleFileName(config: SchematicConfig): string {
return `${dasherize(config.moduleName)}-feature.module.ts`;
}
/**
* Used a comparator function when sorting features.
*/
export function calculateCrossFeatureSort(
featureA: string,
featureB: string
): number {
return calculateSortInternal(
featureA,
featureB,
crossFeatureInstallationOrder
);
}
/**
* Used a comparator function when sorting libraries.
*/
export function calculateCrossLibrarySort(
libraryA: string,
libraryB: string
): number {
return calculateSortInternal(
libraryA,
libraryB,
crossLibraryInstallationOrder
);
}
/**
* Used to sort libraries or features in the correct order.
*/
function calculateSortInternal(
libOrFeatureA: string,
libOrFeatureB: string,
order: string[]
): number {
const indexA = order.indexOf(libOrFeatureA);
const indexB = order.indexOf(libOrFeatureB);
/**
* In case a feature module is _not_ found in the `order`,
* we want to sort it at the end of the list.
*/
return (indexA > -1 ? indexA : Infinity) - (indexB > -1 ? indexB : Infinity);
}
/**
* Performs the final steps of the installation,
* before Angular schematics mechanism takes over.
*/
export function finalizeInstallation<OPTIONS extends LibraryOptions>(
options: OPTIONS,
features: string[]
): Rule {
return (_tree: Tree, context: SchematicContext) => {
if (options.internal?.existingSpartacusApplication) {
let message = `🚨 Detected Spartacus installation. Please make sure the following `;
message += `features are installed, configured and sorted in the correct order:\n`;
message += features.join(', ');
context.logger.warn(message);
}
};
} | the_stack |
import {
MAGNETIC_MODULE_TYPE,
MAGNETIC_MODULE_V2,
TEMPERATURE_MODULE_TYPE,
TEMPERATURE_MODULE_V2,
THERMOCYCLER_MODULE_TYPE,
THERMOCYCLER_MODULE_V1,
} from '@opentrons/shared-data'
import { fixtureP10Single } from '@opentrons/shared-data/pipette/fixtures/name'
import fixture_tiprack_10_ul from '@opentrons/shared-data/labware/fixtures/2/fixture_tiprack_10_ul.json'
import { getStateAndContextTempTCModules } from '@opentrons/step-generation'
import {
DEFAULT_DELAY_SECONDS,
DEFAULT_MM_FROM_BOTTOM_DISPENSE,
} from '../../constants'
import {
createPresavedStepForm,
CreatePresavedStepFormArgs,
} from '../utils/createPresavedStepForm'
const stepId = 'stepId123'
const EXAMPLE_ENGAGE_HEIGHT = '18'
let defaultArgs: any
beforeEach(() => {
const { robotState } = getStateAndContextTempTCModules({
temperatureModuleId: 'someTemperatureModuleId',
thermocyclerId: 'someThermocyclerModuleId',
})
const leftPipette = {
name: 'p10_single',
id: 'leftPipetteId',
spec: fixtureP10Single,
tiprackLabwareDef: fixture_tiprack_10_ul,
}
const labwareOnMagModule = {
id: 'labwareOnMagModule',
def: {
parameters: {
magneticModuleEngageHeight: EXAMPLE_ENGAGE_HEIGHT,
},
},
}
defaultArgs = {
stepId,
pipetteEntities: {
leftPipetteId: { ...leftPipette },
},
labwareEntities: {
labwareOnMagModule: {
labwareOnMagModule,
},
},
savedStepForms: {},
orderedStepIds: [],
initialDeckSetup: {
labware: {
labwareOnMagModule: {
...labwareOnMagModule,
slot: 'someMagneticModuleId',
},
},
modules: {
someMagneticModuleId: {
id: 'someMagneticModuleId',
type: MAGNETIC_MODULE_TYPE,
model: MAGNETIC_MODULE_V2,
slot: '1',
},
someTemperatureModuleId: {
id: 'someTemperatureModuleId',
type: TEMPERATURE_MODULE_TYPE,
model: TEMPERATURE_MODULE_V2,
slot: '3',
},
someThermocyclerModuleId: {
id: 'someTemperatureModuleId',
type: THERMOCYCLER_MODULE_TYPE,
model: THERMOCYCLER_MODULE_V1,
slot: '3',
},
},
pipettes: {
leftPipetteId: { ...leftPipette, mount: 'left' },
},
},
robotStateTimeline: {
timeline: [
{
commands: [],
robotState,
},
],
},
}
})
afterEach(() => {
jest.resetAllMocks()
})
describe('createPresavedStepForm', () => {
;[true, false].forEach(hasTempModule => {
it(`should populate initial values for a new pause step (with ${
hasTempModule ? '' : 'NO'
} temp module)`, () => {
const args: CreatePresavedStepFormArgs = {
...defaultArgs,
stepType: 'pause',
initialDeckSetup: hasTempModule
? defaultArgs.initialDeckSetup
: { ...defaultArgs.initialDeckSetup, modules: {} },
}
expect(createPresavedStepForm(args)).toEqual({
id: stepId,
stepType: 'pause',
moduleId: hasTempModule ? 'someTemperatureModuleId' : null,
pauseAction: null,
pauseHour: null,
pauseMessage: '',
pauseMinute: null,
pauseSecond: null,
pauseTemperature: null,
stepDetails: '',
stepName: 'pause',
})
})
})
it(`should call handleFormChange with a default pipette for "moveLiquid" step`, () => {
const args = { ...defaultArgs, stepType: 'moveLiquid' }
expect(createPresavedStepForm(args)).toEqual({
id: stepId,
pipette: 'leftPipetteId',
stepType: 'moveLiquid',
// default fields
aspirate_airGap_checkbox: false,
aspirate_airGap_volume: '1',
aspirate_delay_checkbox: false,
aspirate_delay_mmFromBottom: null,
aspirate_delay_seconds: '1',
dispense_delay_checkbox: false,
dispense_delay_seconds: '1',
dispense_delay_mmFromBottom: null,
aspirate_flowRate: null,
aspirate_labware: null,
aspirate_mix_checkbox: false,
aspirate_mix_times: null,
aspirate_mix_volume: null,
aspirate_mmFromBottom: null,
aspirate_touchTip_checkbox: false,
aspirate_touchTip_mmFromBottom: null,
aspirate_wellOrder_first: 't2b',
aspirate_wellOrder_second: 'l2r',
aspirate_wells: [],
aspirate_wells_grouped: false,
blowout_checkbox: false,
blowout_location: 'trashId',
changeTip: 'always',
dispense_airGap_checkbox: false,
dispense_airGap_volume: '1',
dispense_flowRate: null,
dispense_labware: null,
dispense_mix_checkbox: false,
dispense_mix_times: null,
dispense_mix_volume: null,
dispense_mmFromBottom: null,
dispense_touchTip_checkbox: false,
dispense_touchTip_mmFromBottom: null,
dispense_wellOrder_first: 't2b',
dispense_wellOrder_second: 'l2r',
dispense_wells: [],
disposalVolume_checkbox: true,
disposalVolume_volume: '1',
path: 'single',
preWetTip: false,
stepDetails: '',
stepName: 'transfer',
volume: null,
})
})
describe('mix step', () => {
it('should call handleFormChange with a default pipette for mix step', () => {
const args = { ...defaultArgs, stepType: 'mix' }
expect(createPresavedStepForm(args)).toEqual({
id: stepId,
pipette: 'leftPipetteId',
stepType: 'mix',
// default fields
labware: null,
wells: [],
aspirate_delay_checkbox: false,
aspirate_delay_seconds: `${DEFAULT_DELAY_SECONDS}`,
dispense_delay_checkbox: false,
dispense_delay_seconds: `${DEFAULT_DELAY_SECONDS}`,
mix_mmFromBottom: DEFAULT_MM_FROM_BOTTOM_DISPENSE,
mix_touchTip_mmFromBottom: null,
mix_wellOrder_first: 't2b',
mix_wellOrder_second: 'l2r',
blowout_checkbox: false,
blowout_location: 'trashId',
changeTip: 'always',
stepDetails: '',
stepName: 'mix',
mix_touchTip_checkbox: false,
times: null,
volume: undefined,
aspirate_flowRate: null,
dispense_flowRate: null,
})
})
})
it('should set a default magnetic module for magnet step, and set engage height and magnetAction=engage, when it is the first magnet step in the timeline', () => {
const args = { ...defaultArgs, stepType: 'magnet' }
expect(createPresavedStepForm(args)).toEqual({
id: stepId,
stepType: 'magnet',
moduleId: 'someMagneticModuleId',
engageHeight: EXAMPLE_ENGAGE_HEIGHT,
magnetAction: 'engage',
// Default values
stepName: 'magnet',
stepDetails: '',
})
})
it('should set a default magnetic module for magnet step, and set magnetAction=disengage, when the previous magnet step is an engage', () => {
const args = {
...defaultArgs,
savedStepForms: {
prevStepId: {
id: 'prevStepId',
stepType: 'magnet',
moduleId: 'someMagneticModuleId',
engageHeight: EXAMPLE_ENGAGE_HEIGHT,
magnetAction: 'engage',
stepName: 'magnet',
stepDetails: '',
},
},
orderedStepIds: ['prevStepId'],
stepType: 'magnet',
}
expect(createPresavedStepForm(args)).toEqual({
id: stepId,
stepType: 'magnet',
moduleId: 'someMagneticModuleId',
engageHeight: EXAMPLE_ENGAGE_HEIGHT,
magnetAction: 'disengage',
stepName: 'magnet',
stepDetails: '',
})
})
it('should set a default magnetic module for magnet step, and set magnetAction=engage, when the previous magnet step is a disengage', () => {
const args = {
...defaultArgs,
savedStepForms: {
prevStepId: {
id: 'prevStepId',
stepType: 'magnet',
moduleId: 'someMagneticModuleId',
engageHeight: EXAMPLE_ENGAGE_HEIGHT,
magnetAction: 'disengage',
stepName: 'magnet',
stepDetails: '',
},
},
orderedStepIds: ['prevStepId'],
stepType: 'magnet',
}
expect(createPresavedStepForm(args)).toEqual({
id: stepId,
stepType: 'magnet',
moduleId: 'someMagneticModuleId',
engageHeight: EXAMPLE_ENGAGE_HEIGHT,
magnetAction: 'engage',
stepName: 'magnet',
stepDetails: '',
})
})
it('should set a default temperature module when a Temperature step is added', () => {
const args = { ...defaultArgs, stepType: 'temperature' }
expect(createPresavedStepForm(args)).toEqual({
id: stepId,
stepType: 'temperature',
moduleId: 'someTemperatureModuleId',
// Default fields
setTemperature: null,
targetTemperature: null,
stepName: 'temperature',
stepDetails: '',
})
})
;[true, false].forEach(timelineHasErrors => {
;[true, false].forEach(isFirstThermocyclerStep => {
const testName = `should set a default thermocycler module and set TC state defaults when ${
isFirstThermocyclerStep
? 'the first Thermocycler step is added'
: 'a following Thermocycler step is added'
}${timelineHasErrors ? ' and timeline has errors' : ''}`
it(testName, () => {
// mutate robot state in defaultArgs
if (timelineHasErrors) {
defaultArgs.robotStateTimeline = {
errors: ['OH NO!'],
timeline: [],
}
} else {
const thermocyclerModuleState =
defaultArgs.robotStateTimeline.timeline[0].robotState.modules
.someThermocyclerModuleId
thermocyclerModuleState.moduleState = {
...thermocyclerModuleState.moduleState,
blockTargetTemp: 42,
lidTargetTemp: 43,
lidOpen: true,
}
}
const args = { ...defaultArgs, stepType: 'thermocycler' }
if (isFirstThermocyclerStep) {
args.savedStepForms = {
prevStepId: {
stepType: 'thermocycler',
// TC Default fields (should all be ignored, robotState is used to populate the form)
stepName: 'thermocycler',
stepDetails: '',
thermocyclerFormType: 'thermocyclerState',
blockIsActive: false,
blockTargetTemp: null,
lidIsActive: false,
lidTargetTemp: null,
lidOpen: null,
profileVolume: null,
profileTargetLidTemp: null,
orderedProfileItems: [],
profileItemsById: {},
blockIsActiveHold: false,
blockTargetTempHold: null,
lidIsActiveHold: false,
lidTargetTempHold: null,
lidOpenHold: null,
},
}
args.orderedStepIds = ['prevStepId']
}
expect(createPresavedStepForm(args)).toEqual({
blockIsActive: !timelineHasErrors,
blockIsActiveHold: false,
blockTargetTemp: timelineHasErrors ? null : 42,
blockTargetTempHold: null,
id: stepId,
lidIsActive: !timelineHasErrors,
lidIsActiveHold: false,
lidOpen: !timelineHasErrors,
lidOpenHold: null,
lidTargetTemp: timelineHasErrors ? null : 43,
lidTargetTempHold: null,
moduleId: 'someThermocyclerModuleId',
orderedProfileItems: [],
profileItemsById: {},
profileTargetLidTemp: null,
profileVolume: null,
stepDetails: '',
stepName: 'thermocycler',
stepType: 'thermocycler',
thermocyclerFormType: null,
})
})
})
})
}) | the_stack |
import { SfdxCommandBuilder } from '@salesforce/salesforcedx-utils-vscode/out/src/cli';
import { RequestService } from '@salesforce/salesforcedx-utils-vscode/out/src/requestService';
import { expect } from 'chai';
import * as sinon from 'sinon';
import {
ApexBreakpointLocation,
LineBreakpointsInTyperef
} from '../../../src/breakpoints/lineBreakpoint';
import { BreakpointService } from '../../../src/core/breakpointService';
import childProcess = require('child_process');
describe('Debugger breakpoint service', () => {
let service: BreakpointService;
const mockSpawn = require('mock-spawn');
const lineNumberMapping: Map<string, LineBreakpointsInTyperef[]> = new Map();
const typerefMapping: Map<string, string> = new Map();
lineNumberMapping.set('file:///foo.cls', [
{ typeref: 'foo', lines: [1, 2] },
{ typeref: 'foo$inner', lines: [3, 4] }
]);
lineNumberMapping.set('file:///bar.cls', [{ typeref: 'bar', lines: [3, 4] }]);
typerefMapping.set('foo', 'file:///foo.cls');
typerefMapping.set('foo$inner', 'file:///foo.cls');
typerefMapping.set('bar', 'file:///bar.cls');
describe('Helpers', () => {
beforeEach(() => {
service = new BreakpointService(new RequestService());
});
it('Should detect an Apex Debugger breakpoint ID by key prefix', () => {
expect(service.isApexDebuggerBreakpointId('07bFAKE')).to.equal(true);
});
it('Should not detect an Apex Debugger breakpoint ID by key prefix', () => {
expect(service.isApexDebuggerBreakpointId('FAKE')).to.equal(false);
});
it('Should not have line number mapping', () => {
expect(service.hasLineNumberMapping()).to.equal(false);
});
it('Should get valid typeref', () => {
service.setValidLines(lineNumberMapping, typerefMapping);
const actualTyperef = service.getTyperefFor('file:///foo.cls', 3);
expect(actualTyperef).to.equal('foo$inner');
expect(service.hasLineNumberMapping()).to.equal(true);
});
it('Should not get typeref', () => {
service.setValidLines(lineNumberMapping, typerefMapping);
const actualTyperef = service.getTyperefFor('file:///xyz.cls', 3);
expect(actualTyperef).to.equal(undefined);
});
it('Should get valid uri from typeref', () => {
service.setValidLines(lineNumberMapping, typerefMapping);
const uri = service.getSourcePathFromTyperef('foo$inner');
expect(uri).to.equal('file:///foo.cls');
});
it('Should not get uri from typeref', () => {
service.setValidLines(lineNumberMapping, typerefMapping);
const uri = service.getSourcePathFromTyperef('xyz');
expect(uri).to.equal(undefined);
});
it('Should get valid uri from partial typeref', () => {
service.setValidLines(lineNumberMapping, typerefMapping);
const uri = service.getSourcePathFromPartialTyperef('inner');
expect(uri).to.equal('file:///foo.cls');
});
it('Should not get uri from partial typeref', () => {
service.setValidLines(lineNumberMapping, typerefMapping);
const uri = service.getSourcePathFromPartialTyperef('xyz');
expect(uri).to.equal(undefined);
});
it('Should cache breakpoint', () => {
const expectedCache: Map<string, ApexBreakpointLocation[]> = new Map();
expectedCache.set('file:///foo.cls', [
{ line: 1, breakpointId: '07bFAKE1' },
{ line: 2, breakpointId: '07bFAKE2' }
]);
expectedCache.set('file:///bar.cls', [
{ line: 3, breakpointId: '07bFAKE3' }
]);
service.cacheLineBreakpoint('file:///foo.cls', 1, '07bFAKE1');
service.cacheLineBreakpoint('file:///foo.cls', 2, '07bFAKE2');
service.cacheLineBreakpoint('file:///bar.cls', 3, '07bFAKE3');
expect(service.getLineBreakpointCache()).to.deep.equal(expectedCache);
});
it('Should clear cached breakpoints', () => {
service.cacheLineBreakpoint('file:///foo.cls', 1, '07bFAKE1');
service.getExceptionBreakpointCache().set('fooexception', '07bFAKE2');
service.clearSavedBreakpoints();
expect(service.getLineBreakpointCache().size).to.equal(0);
expect(service.getExceptionBreakpointCache().size).to.equal(0);
});
it('Should find existing breakpoints', () => {
service.cacheLineBreakpoint('file:///foo.cls', 1, '07bFAKE1');
service.cacheLineBreakpoint('file:///foo.cls', 2, '07bFAKE2');
service.cacheLineBreakpoint('file:///bar.cls', 3, '07bFAKE3');
const savedBreakpoints = service.getBreakpointsFor('file:///foo.cls');
expect(savedBreakpoints).to.have.all.keys([1, 2]);
});
it('Should not find existing breakpoints', () => {
service.cacheLineBreakpoint('file:///foo.cls', 1, '07bFAKE1');
service.cacheLineBreakpoint('file:///foo.cls', 2, '07bFAKE2');
const savedBreakpoints = service.getBreakpointsFor('file:///bar.cls');
expect(savedBreakpoints.size).to.equal(0);
});
});
describe('Create line breakpoint', () => {
let origSpawn: any;
let mySpawn: any;
let cmdWithArgSpy: sinon.SinonSpy;
let cmdWithFlagSpy: sinon.SinonSpy;
let cmdWithJsonSpy: sinon.SinonSpy;
let cmdBuildSpy: sinon.SinonSpy;
beforeEach(() => {
service = new BreakpointService(new RequestService());
origSpawn = childProcess.spawn;
mySpawn = mockSpawn();
childProcess.spawn = mySpawn;
cmdWithArgSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withArg');
cmdWithFlagSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withFlag');
cmdWithJsonSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withJson');
cmdBuildSpy = sinon.spy(SfdxCommandBuilder.prototype, 'build');
});
afterEach(() => {
childProcess.spawn = origSpawn;
cmdWithArgSpy.restore();
cmdWithFlagSpy.restore();
cmdWithJsonSpy.restore();
cmdBuildSpy.restore();
});
it('Should create successfully', async () => {
mySpawn.setDefault(mySpawn.simple(0, '{"result":{"id":"07bFAKE"}}'));
const cmdOutput = await service.createLineBreakpoint(
'someProjectPath',
'07aFAKE',
'foo$inner',
1
);
expect(cmdOutput).to.equal('07bFAKE');
expect(cmdWithArgSpy.getCall(0).args).to.have.same.members([
'force:data:record:create'
]);
expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([
'--sobjecttype',
'ApexDebuggerBreakpoint'
]);
expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([
'--values',
"SessionId='07aFAKE' FileName='foo$inner' Line=1 IsEnabled='true' Type='Line'"
]);
expect(cmdWithArgSpy.getCall(1).args).to.have.same.members([
'--usetoolingapi'
]);
expect(cmdWithJsonSpy.calledOnce).to.equal(true);
expect(cmdBuildSpy.calledOnce).to.equal(true);
});
it('Should not create breakpoint successfully with wrong ID', async () => {
mySpawn.setDefault(mySpawn.simple(0, '{"result":{"id":"FAKE"}}'));
try {
await service.createLineBreakpoint(
'someProjectPath',
'07aFAKE',
'foo$inner',
1
);
expect.fail('Should have failed');
} catch (error) {
expect(error).to.equal('{"result":{"id":"FAKE"}}');
}
});
it('Should not create breakpoint successfully with unexpected response format', async () => {
mySpawn.setDefault(mySpawn.simple(0, '{"result":{"notid":"FAKE"}}'));
try {
await service.createLineBreakpoint(
'someProjectPath',
'07aFAKE',
'foo$inner',
1
);
expect.fail('Should have failed');
} catch (error) {
expect(error).to.equal('{"result":{"notid":"FAKE"}}');
}
});
it('Should not create breakpoint successfully with error message & action', async () => {
mySpawn.setDefault(
mySpawn.simple(
1,
'',
'{"message":"There was an error", "action":"Try again"}'
)
);
try {
await service.createLineBreakpoint(
'someProjectPath',
'07aFAKE',
'foo$inner',
1
);
expect.fail('Should have failed');
} catch (error) {
expect(error).to.equal(
'{"message":"There was an error", "action":"Try again"}'
);
}
});
});
describe('Create exception breakpoint', () => {
let origSpawn: any;
let mySpawn: any;
let cmdWithArgSpy: sinon.SinonSpy;
let cmdWithFlagSpy: sinon.SinonSpy;
let cmdWithJsonSpy: sinon.SinonSpy;
let cmdBuildSpy: sinon.SinonSpy;
beforeEach(() => {
service = new BreakpointService(new RequestService());
origSpawn = childProcess.spawn;
mySpawn = mockSpawn();
childProcess.spawn = mySpawn;
cmdWithArgSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withArg');
cmdWithFlagSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withFlag');
cmdWithJsonSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withJson');
cmdBuildSpy = sinon.spy(SfdxCommandBuilder.prototype, 'build');
});
afterEach(() => {
childProcess.spawn = origSpawn;
cmdWithArgSpy.restore();
cmdWithFlagSpy.restore();
cmdWithJsonSpy.restore();
cmdBuildSpy.restore();
});
it('Should create successfully', async () => {
mySpawn.setDefault(mySpawn.simple(0, '{"result":{"id":"07bFAKE"}}'));
const cmdOutput = await service.createExceptionBreakpoint(
'someProjectPath',
'07aFAKE',
'fooexception'
);
expect(cmdOutput).to.equal('07bFAKE');
expect(cmdWithArgSpy.getCall(0).args).to.have.same.members([
'force:data:record:create'
]);
expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([
'--sobjecttype',
'ApexDebuggerBreakpoint'
]);
expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([
'--values',
"SessionId='07aFAKE' FileName='fooexception' IsEnabled='true' Type='Exception'"
]);
expect(cmdWithArgSpy.getCall(1).args).to.have.same.members([
'--usetoolingapi'
]);
expect(cmdWithJsonSpy.calledOnce).to.equal(true);
expect(cmdBuildSpy.calledOnce).to.equal(true);
});
});
describe('Delete breakpoint', () => {
let origSpawn: any;
let mySpawn: any;
let cmdWithArgSpy: sinon.SinonSpy;
let cmdWithFlagSpy: sinon.SinonSpy;
let cmdWithJsonSpy: sinon.SinonSpy;
let cmdBuildSpy: sinon.SinonSpy;
beforeEach(() => {
service = new BreakpointService(new RequestService());
origSpawn = childProcess.spawn;
mySpawn = mockSpawn();
childProcess.spawn = mySpawn;
cmdWithArgSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withArg');
cmdWithFlagSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withFlag');
cmdWithJsonSpy = sinon.spy(SfdxCommandBuilder.prototype, 'withJson');
cmdBuildSpy = sinon.spy(SfdxCommandBuilder.prototype, 'build');
});
afterEach(() => {
childProcess.spawn = origSpawn;
cmdWithArgSpy.restore();
cmdWithFlagSpy.restore();
cmdWithJsonSpy.restore();
cmdBuildSpy.restore();
});
it('Should delete successfully', async () => {
mySpawn.setDefault(mySpawn.simple(0, '{"result":{"id":"07bFAKE"}}'));
const cmdOutput = await service.deleteBreakpoint(
'someProjectPath',
'07bFAKE'
);
expect(cmdOutput).to.equal('07bFAKE');
expect(cmdWithArgSpy.getCall(0).args).to.have.same.members([
'force:data:record:delete'
]);
expect(cmdWithFlagSpy.getCall(0).args).to.have.same.members([
'--sobjecttype',
'ApexDebuggerBreakpoint'
]);
expect(cmdWithFlagSpy.getCall(1).args).to.have.same.members([
'--sobjectid',
'07bFAKE'
]);
expect(cmdWithArgSpy.getCall(1).args).to.have.same.members([
'--usetoolingapi'
]);
expect(cmdWithJsonSpy.calledOnce).to.equal(true);
expect(cmdBuildSpy.calledOnce).to.equal(true);
});
it('Should not delete breakpoint successfully with wrong ID', async () => {
mySpawn.setDefault(mySpawn.simple(0, '{"result":{"id":"FAKE"}}'));
try {
await service.deleteBreakpoint('someProjectPath', '07bFAKE');
expect.fail('Should have failed');
} catch (error) {
expect(error).to.equal('{"result":{"id":"FAKE"}}');
}
});
it('Should not delete breakpoint successfully with unexpected response format', async () => {
mySpawn.setDefault(mySpawn.simple(0, '{"result":{"notid":"FAKE"}}'));
try {
await service.deleteBreakpoint('someProjectPath', '07bFAKE');
expect.fail('Should have failed');
} catch (error) {
expect(error).to.equal('{"result":{"notid":"FAKE"}}');
}
});
it('Should not delete breakpoint successfully with error message & action', async () => {
mySpawn.setDefault(
mySpawn.simple(
1,
'',
'{"message":"There was an error", "action":"Try again"}'
)
);
try {
await service.deleteBreakpoint('someProjectPath', '07bFAKE');
expect.fail('Should have failed');
} catch (error) {
expect(error).to.equal(
'{"message":"There was an error", "action":"Try again"}'
);
}
});
});
describe('Reconcile', () => {
let addLineBreakpointSpy: sinon.SinonStub;
let addExceptionBreakpointSpy: sinon.SinonStub;
let deleteBreakpointSpy: sinon.SinonStub;
let getTyperefForSpy: sinon.SinonStub;
beforeEach(() => {
service = new BreakpointService(new RequestService());
service.cacheLineBreakpoint('file:///foo.cls', 3, '07bFAKE3');
service.cacheLineBreakpoint('file:///foo.cls', 4, '07bFAKE4');
service.cacheLineBreakpoint('file:///foo.cls', 5, '07bFAKE5');
service.cacheLineBreakpoint('file:///bar.cls', 1, '07bFAKE6');
service.getExceptionBreakpointCache().set('fooexception', '07bFAKE7');
});
afterEach(() => {
if (addLineBreakpointSpy) {
addLineBreakpointSpy.restore();
}
if (addExceptionBreakpointSpy) {
addExceptionBreakpointSpy.restore();
}
if (deleteBreakpointSpy) {
deleteBreakpointSpy.restore();
}
if (getTyperefForSpy) {
getTyperefForSpy.restore();
}
});
it('Should reconcile line breakpoints for client to create and server to delete', async () => {
getTyperefForSpy = sinon
.stub(BreakpointService.prototype, 'getTyperefFor')
.returns('foo');
addLineBreakpointSpy = sinon
.stub(BreakpointService.prototype, 'createLineBreakpoint')
.onFirstCall()
.returns(Promise.resolve('07bFAKE1'))
.onSecondCall()
.returns(Promise.resolve('07bFAKE2'));
deleteBreakpointSpy = sinon
.stub(BreakpointService.prototype, 'deleteBreakpoint')
.onFirstCall()
.returns(Promise.resolve('07bFAKE4'))
.onSecondCall()
.returns(Promise.resolve('07bFAKE5'));
const expectedCache: Map<string, ApexBreakpointLocation[]> = new Map();
expectedCache.set('file:///foo.cls', [
{ line: 3, breakpointId: '07bFAKE3' },
{ line: 1, breakpointId: '07bFAKE1' },
{ line: 2, breakpointId: '07bFAKE2' }
]);
expectedCache.set('file:///bar.cls', [
{ line: 1, breakpointId: '07bFAKE6' }
]);
const bpsToCreate = await service.reconcileLineBreakpoints(
'someProjectPath',
'file:///foo.cls',
'07aFAKE',
[1, 2, 3]
);
expect(bpsToCreate).to.have.all.keys([1, 2, 3]);
expect(addLineBreakpointSpy.calledTwice).to.equal(true);
expect(addLineBreakpointSpy.getCall(0).args).to.have.same.members([
'someProjectPath',
'07aFAKE',
'foo',
1
]);
expect(addLineBreakpointSpy.getCall(1).args).to.have.same.members([
'someProjectPath',
'07aFAKE',
'foo',
2
]);
expect(deleteBreakpointSpy.calledTwice).to.equal(true);
expect(deleteBreakpointSpy.getCall(0).args).to.have.same.members([
'someProjectPath',
'07bFAKE5'
]);
expect(deleteBreakpointSpy.getCall(1).args).to.have.same.members([
'someProjectPath',
'07bFAKE4'
]);
expect(service.getLineBreakpointCache()).to.deep.equal(expectedCache);
});
it('Should not create line breakpoints without known typeref', async () => {
getTyperefForSpy = sinon
.stub(BreakpointService.prototype, 'getTyperefFor')
.returns(undefined);
addLineBreakpointSpy = sinon.stub(
BreakpointService.prototype,
'createLineBreakpoint'
);
deleteBreakpointSpy = sinon
.stub(BreakpointService.prototype, 'deleteBreakpoint')
.onFirstCall()
.returns(Promise.resolve('07bFAKE4'))
.onSecondCall()
.returns(Promise.resolve('07bFAKE5'));
const expectedCache: Map<string, ApexBreakpointLocation[]> = new Map();
expectedCache.set('file:///foo.cls', [
{ line: 3, breakpointId: '07bFAKE3' }
]);
expectedCache.set('file:///bar.cls', [
{ line: 1, breakpointId: '07bFAKE6' }
]);
const bpsToCreate = await service.reconcileLineBreakpoints(
'someProjectPath',
'file:///foo.cls',
'07aFAKE',
[1, 2, 3]
);
expect(bpsToCreate).to.have.all.keys([3]);
expect(addLineBreakpointSpy.called).to.equal(false);
expect(deleteBreakpointSpy.calledTwice).to.equal(true);
expect(deleteBreakpointSpy.getCall(0).args).to.have.same.members([
'someProjectPath',
'07bFAKE5'
]);
expect(deleteBreakpointSpy.getCall(1).args).to.have.same.members([
'someProjectPath',
'07bFAKE4'
]);
expect(service.getLineBreakpointCache()).to.deep.equal(expectedCache);
});
it('Should create new exception breakpoint', async () => {
addExceptionBreakpointSpy = sinon
.stub(BreakpointService.prototype, 'createExceptionBreakpoint')
.returns('07bFAKE8');
await service.reconcileExceptionBreakpoints(
'someProjectPath',
'07aFAKE',
{
breakMode: 'always',
typeref: 'barexception',
label: 'barexception'
}
);
expect(addExceptionBreakpointSpy.calledOnce).to.equal(true);
expect(addExceptionBreakpointSpy.getCall(0).args).to.have.same.members([
'someProjectPath',
'07aFAKE',
'barexception'
]);
expect(
service.getExceptionBreakpointCache().has('barexception')
).to.equal(true);
});
it('Should not create existing exception breakpoint', async () => {
addExceptionBreakpointSpy = sinon
.stub(BreakpointService.prototype, 'createExceptionBreakpoint')
.returns('07bFAKE7');
await service.reconcileExceptionBreakpoints(
'someProjectPath',
'07aFAKE',
{
breakMode: 'always',
typeref: 'fooexception',
label: 'fooexception'
}
);
expect(addExceptionBreakpointSpy.called).to.equal(false);
expect(
service.getExceptionBreakpointCache().has('fooexception')
).to.equal(true);
});
it('Should delete existing exception breakpoint', async () => {
deleteBreakpointSpy = sinon
.stub(BreakpointService.prototype, 'deleteBreakpoint')
.returns(Promise.resolve('07bFAKE7'));
await service.reconcileExceptionBreakpoints(
'someProjectPath',
'07aFAKE',
{
breakMode: 'never',
typeref: 'fooexception',
label: 'fooexception'
}
);
expect(deleteBreakpointSpy.calledOnce).to.equal(true);
expect(deleteBreakpointSpy.getCall(0).args).to.have.same.members([
'someProjectPath',
'07bFAKE7'
]);
expect(
service.getExceptionBreakpointCache().has('fooexception')
).to.equal(false);
});
it('Should not delete unknown exception breakpoint', async () => {
deleteBreakpointSpy = sinon
.stub(BreakpointService.prototype, 'deleteBreakpoint')
.returns(Promise.resolve('07bFAKE8'));
await service.reconcileExceptionBreakpoints(
'someProjectPath',
'07aFAKE',
{
breakMode: 'never',
typeref: 'barexception',
label: 'barexception'
}
);
expect(deleteBreakpointSpy.called).to.equal(false);
expect(
service.getExceptionBreakpointCache().has('barexception')
).to.equal(false);
});
});
}); | the_stack |
import * as THREE from 'three';
import { LIQUID_TYPES } from './ground';
import { WORLD_SIZE, getPositions } from '../../../utils/lba';
import { BehaviourMode } from '../../loop/hero';
import { AnimType } from '../../data/animType';
import IslandLayout, { IslandSection } from './IslandLayout';
import Scene from '../../Scene';
import { Time } from '../../../datatypes';
import Actor from '../../Actor';
import Extra from '../../Extra';
import HeightMap from './physics/HeightMap';
import GroundInfo from './physics/GroundInfo';
const POSITION = new THREE.Vector3();
const P0 = new THREE.Vector3();
const P1 = new THREE.Vector3();
const FLAGS = {
hitObject: false
};
const DEFAULT_FLOOR_THRESHOLD = 0.001;
// Vertical height offsets for the jet/protopack.
const JETPACK_OFFSET = 0.5;
const PROTOPACK_OFFSET = 0.1;
// How fast we reach top vertical height when starting to jetpack.
const JETPACK_VERTICAL_SPEED = 7.5;
const GRID_SCALE = 32 / WORLD_SIZE;
const GRID_UNIT = 1 / 64;
const Y_THRESHOLD = WORLD_SIZE / 1600;
export default class IslandPhysics {
heightmap: HeightMap;
private sections: IslandSection[] = [];
private ground = new GroundInfo();
private ground2 = new GroundInfo();
constructor(layout: IslandLayout) {
for (const section of layout.groundSections) {
const { x, z } = section;
const sX = 16 - (x + 8);
const sZ = z + 8;
this.sections[sX * 16 + sZ] = section;
}
this.heightmap = new HeightMap(this.sections);
}
getNormal(
scene: Scene,
position: THREE.Vector3,
boundingBox: THREE.Box3,
result: THREE.Vector3
) {
POSITION.copy(position);
POSITION.add(scene.sceneNode.position);
this.heightmap.getGroundInfo(POSITION, this.ground);
if (this.ground.valid && position.y - this.ground.height < 0.1) {
const { points } = this.ground;
P0.copy(points[1]).sub(points[0]);
P1.copy(points[2]).sub(points[0]);
result.crossVectors(P0, P1).normalize();
return true;
}
if (!this.ground.section) {
return false;
}
ACTOR_BOX.copy(boundingBox);
ACTOR_BOX.translate(POSITION);
for (const obj of this.ground.section.objects) {
const bb = obj.boundingBox;
if (ACTOR_BOX.intersectsBox(bb)) {
INTERSECTION.copy(ACTOR_BOX);
INTERSECTION.intersect(bb);
INTERSECTION.getSize(ITRS_SIZE);
ACTOR_BOX.getCenter(CENTER1);
bb.getCenter(CENTER2);
const dir = CENTER1.sub(CENTER2);
if (ACTOR_BOX.min.y < bb.max.y - H_THRESHOLD) {
if (ITRS_SIZE.x < ITRS_SIZE.z) {
result.set(1 * Math.sign(dir.x), 0, 0);
} else {
result.set(0, 0, 1 * Math.sign(dir.z));
}
} else {
result.set(0, 1 * Math.sign(dir.y), 0);
}
return true;
}
}
return false;
}
processCollisions(scene: Scene, obj: Actor | Extra, time: Time) {
if (!obj.props.flags.hasCollisionBricks) {
return false;
}
POSITION.copy(obj.physics.position);
POSITION.add(scene.sceneNode.position);
const section = this.findSection(POSITION);
FLAGS.hitObject = false;
this.getGround(section, POSITION, this.ground);
let height = this.ground.height;
obj.state.distFromGround = Math.max(obj.physics.position.y - height, 0);
const distFromFloor = this.getDistFromFloor(scene, obj);
obj.state.distFromFloor = distFromFloor;
let isTouchingGround = true;
if (obj.physics.position.y > height) {
isTouchingGround = false;
}
const isUsingProtoOrJetpack = obj instanceof Actor &&
(obj.props.entityIndex === BehaviourMode.JETPACK ||
obj.props.entityIndex === BehaviourMode.PROTOPACK) &&
obj.props.animIndex === AnimType.FORWARD;
if (obj instanceof Actor)
obj.state.isUsingProtoOrJetpack = isUsingProtoOrJetpack;
if (isUsingProtoOrJetpack) {
let heightOffset = PROTOPACK_OFFSET;
if (obj instanceof Actor && obj.props.entityIndex === BehaviourMode.JETPACK) {
heightOffset = JETPACK_OFFSET;
}
const minFunc = (a, b) => a < b;
const floorHeight = this.getFloorHeight(scene, obj, minFunc, heightOffset);
// Only let Twinsen Jetpack over small objects.
if (floorHeight - obj.physics.position.y < heightOffset) {
height = floorHeight + heightOffset;
// Gradually converge on the desired value of height. This means we
// don't immediately jump to `height` but rather "fly" up to it.
const diff = height - obj.physics.position.y;
if (diff <= 0) {
obj.physics.position.y -= JETPACK_VERTICAL_SPEED * time.delta;
obj.physics.position.y = Math.max(height, obj.physics.position.y);
} else {
obj.physics.position.y += JETPACK_VERTICAL_SPEED * time.delta;
obj.physics.position.y = Math.min(height, obj.physics.position.y);
}
} else {
obj.physics.position.y = Math.max(height, obj.physics.position.y);
}
} else {
obj.physics.position.y = Math.max(height, obj.physics.position.y);
}
POSITION.y = obj.physics.position.y;
if (obj instanceof Actor) {
obj.state.floorSound = -1;
}
if (section) {
if (obj instanceof Actor) {
obj.state.floorSound = this.ground.sound;
}
isTouchingGround = processBoxIntersections(section, obj, POSITION, isTouchingGround);
if ((obj.state.isTouchingGround || isTouchingGround) && !FLAGS.hitObject) {
isTouchingGround = this.heightmap.processCollisions(
scene,
obj,
isTouchingGround,
time
);
}
}
obj.state.isTouchingGround = isTouchingGround;
obj.state.isTouchingFloor = distFromFloor < 0.001;
if (obj instanceof Actor && isTouchingGround && this.ground.liquid > 0) {
switch (this.ground.liquid) {
case LIQUID_TYPES.WATER:
obj.state.isDrowning = true;
break;
case LIQUID_TYPES.LAVA:
obj.state.isDrowningLava = true;
break;
default:
obj.state.isDrowning = true;
break;
}
}
return isTouchingGround;
}
processCameraCollisions(camPosition: THREE.Vector3, groundOffset = 0.15, objOffset = 0.2) {
const section = this.findSection(camPosition);
this.heightmap.getGroundInfo(camPosition, this.ground);
camPosition.y = Math.max(this.ground.height + groundOffset * WORLD_SIZE, camPosition.y);
if (section) {
for (const obj of section.objects) {
const bb = obj.boundingBox;
if (bb.containsPoint(camPosition)) {
camPosition.y = bb.max.y + objOffset * WORLD_SIZE;
}
}
}
}
// getDistFromFloor returns the distance Twinsen is from the "floor" where floor
// means any object which Twinsen could stand on between him and the ground, or
// the ground if none exist.
getDistFromFloor(scene: Scene, obj) {
if (!obj.model) {
return;
}
const originalPos = new THREE.Vector3();
originalPos.copy(obj.physics.position);
originalPos.add(scene.sceneNode.position);
const minFunc = (a, b) => a > b;
const floorHeight = this.getFloorHeight(scene, obj, minFunc, DEFAULT_FLOOR_THRESHOLD);
return originalPos.y - floorHeight;
}
private getGround(section: IslandSection, position: THREE.Vector3, result: GroundInfo) {
if (!section) {
result.setDefault();
return;
}
const { x, y, z } = position;
const yMinusThreshold = y - Y_THRESHOLD;
for (const obj of section.objects) {
const bb = obj.boundingBox;
if (x >= bb.min.x && x <= bb.max.x
&& z >= bb.min.z && z <= bb.max.z
&& y >= bb.min.y && yMinusThreshold < bb.max.y) {
FLAGS.hitObject = true;
result.setFromIslandObject(section, obj);
return;
}
}
this.heightmap.getGroundInfo(position, result);
}
// getFloorHeight returns the height of the floor below Twinsen. Note that this
// may be the height of the ground, or an object Twinsen is stood on. minFunc
// determines which of the 4 points of the base bounding box we should use and
// is intended to be either a < or > function of two arguments.
private getFloorHeight(scene: Scene, obj, minFunc, floorThreshold) {
const originalPos = new THREE.Vector3();
originalPos.copy(obj.physics.position);
originalPos.add(scene.sceneNode.position);
ACTOR_BOX.copy(obj.model.boundingBox);
ACTOR_BOX.translate(originalPos);
// It's not enough to just check for the exact position Twinsen is at.
// There are cases where we run over a gap in the geometry so we need
// to check all 4 points of Twinsens bounding box and take the max. I.e.
// if any point is touching the floor we consider Twinsen touching the
// floor.
let overallHeight = -1;
for (const pos of getPositions(ACTOR_BOX)) {
const section = this.findSection(pos);
this.getGround(section, pos, this.ground2);
if (minFunc(this.ground2.height, overallHeight) || overallHeight === -1) {
overallHeight = this.ground2.height;
}
}
// If Twinsen is touching the ground we don't need to check if any
// objects are under him.
if (originalPos.y - overallHeight <= floorThreshold) {
return overallHeight;
}
// Otherwise, check to see if there are any objects under Twinsen which
// would be considered the floor.
POSITION.copy(obj.physics.position);
POSITION.add(scene.sceneNode.position);
while (true) {
if (POSITION.y < 0) {
break;
}
ACTOR_BOX.copy(obj.model.boundingBox);
ACTOR_BOX.translate(POSITION);
const section = this.findSection(POSITION);
if (section) {
for (const iObj of section.objects) {
const bb = iObj.boundingBox;
if (ACTOR_BOX.intersectsBox(bb)) {
return bb.max.y;
}
}
}
POSITION.y -= 0.1;
}
// No objects were under Twinsen, return distance from the ground.
return overallHeight;
}
findSection(position): IslandSection {
const x = Math.floor(position.x * GRID_SCALE);
const z = Math.floor(position.z * GRID_SCALE);
const sX = Math.floor((x - 1) * GRID_UNIT);
const sZ = Math.floor(z * GRID_UNIT);
const iX = 16 - (sX + 8);
const iZ = sZ + 8;
return this.sections[iX * 16 + iZ];
}
}
const ACTOR_BOX = new THREE.Box3();
const INTERSECTION = new THREE.Box3();
const ITRS_SIZE = new THREE.Vector3();
const CENTER1 = new THREE.Vector3();
const CENTER2 = new THREE.Vector3();
const DIFF = new THREE.Vector3();
const H_THRESHOLD = 0.007 * WORLD_SIZE;
function processBoxIntersections(
section: IslandSection,
obj: Actor | Extra,
position: THREE.Vector3,
isTouchingGround: boolean
) {
const boundingBox = obj.model || obj instanceof Extra
? obj.model.boundingBox
: obj.sprite.boundingBox;
ACTOR_BOX.copy(boundingBox);
ACTOR_BOX.translate(position);
let collision = false;
for (const islandObj of section.objects) {
const bb = islandObj.boundingBox;
if (ACTOR_BOX.intersectsBox(bb)) {
collision = true;
isTouchingGround = true;
INTERSECTION.copy(ACTOR_BOX);
INTERSECTION.intersect(bb);
INTERSECTION.getSize(ITRS_SIZE);
ACTOR_BOX.getCenter(CENTER1);
bb.getCenter(CENTER2);
const dir = CENTER1.sub(CENTER2);
if (ACTOR_BOX.min.y < bb.max.y - H_THRESHOLD) {
if (ITRS_SIZE.x < ITRS_SIZE.z) {
DIFF.set(ITRS_SIZE.x * Math.sign(dir.x), 0, 0);
} else {
DIFF.set(0, 0, ITRS_SIZE.z * Math.sign(dir.z));
}
} else {
DIFF.set(0, ITRS_SIZE.y * Math.sign(dir.y), 0);
isTouchingGround = false;
}
obj.physics.position.add(DIFF);
position.add(DIFF);
ACTOR_BOX.translate(DIFF);
}
}
// don't let objects go to abysm
if (!isTouchingGround && obj.physics.position.y < 0) {
isTouchingGround = true;
}
obj.state.isColliding = collision;
return isTouchingGround;
} | the_stack |
import { nanoid } from "nanoid";
import {
BaseLiveComponent,
BaseLiveView,
html,
HtmlSafeString,
LiveComponentSocket,
LiveViewMeta,
LiveViewMountParams,
LiveViewSocket,
LiveViewTemplate,
} from "..";
import { PubSub, SingleProcessPubSub } from "../pubsub";
import { JsonSerDe } from "../adaptor/jsonSerDe";
import { LiveViewManager } from "./liveViewManager";
import {
PhxBlurPayload,
PhxClickPayload,
PhxFlash,
PhxFocusPayload,
PhxFormPayload,
PhxHeartbeatIncoming,
PhxHookPayload,
PhxIncomingMessage,
PhxJoinIncoming,
PhxKeyDownPayload,
PhxKeyUpPayload,
PhxLivePatchIncoming,
PhxLVClearFlashPayload,
} from "./types";
import { AnyLiveContext, AnyLiveEvent, AnyLiveInfo } from "../live";
import { SessionData } from "../session";
import { FlashAdaptor, SerDe, SessionFlashAdaptor, WsAdaptor } from "../adaptor";
describe("test liveview manager", () => {
let cmLiveView: LiveViewManager;
let cmLiveViewAndLiveComponent: LiveViewManager;
let liveViewConnectionId: string;
let liveViewAndLiveComponentConnectionId: string;
let pubSub: PubSub;
let flashAdaptor: FlashAdaptor;
let serDe: SerDe;
let ws: WsAdaptor;
beforeEach(() => {
pubSub = new SingleProcessPubSub();
flashAdaptor = new SessionFlashAdaptor();
serDe = new JsonSerDe();
liveViewConnectionId = nanoid();
liveViewAndLiveComponentConnectionId = nanoid();
ws = {
send: jest.fn(),
};
cmLiveView = new LiveViewManager(
new TestLiveViewComponent(),
liveViewConnectionId,
ws,
serDe,
pubSub,
flashAdaptor,
(sessionData, innerContent) => {
return html`<div>${innerContent}</div>`;
}
);
cmLiveViewAndLiveComponent = new LiveViewManager(
new TestLiveViewAndLiveComponent(),
liveViewAndLiveComponentConnectionId,
ws,
serDe,
pubSub,
flashAdaptor
);
});
afterEach(() => {
(cmLiveView as any).shutdown();
(cmLiveViewAndLiveComponent as any).shutdown();
});
it("handle join works for liveView", async () => {
const spyDefaultLiveViewMeta = jest.spyOn(cmLiveView as any, "defaultLiveViewMeta");
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
expect(ws.send).toHaveBeenCalledTimes(1);
expect(spyDefaultLiveViewMeta).toHaveBeenCalledTimes(1);
});
it("handle join works for liveViewAndLiveComponent", async () => {
const spyDefaultLiveViewMeta = jest.spyOn(cmLiveViewAndLiveComponent as any, "defaultLiveViewMeta");
await cmLiveViewAndLiveComponent.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
expect(ws.send).toHaveBeenCalledTimes(1);
expect(spyDefaultLiveViewMeta).toHaveBeenCalledTimes(1);
});
it("handle join with mismatching csrfTokens", () => {
cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", {
url: "http://localhost:4444/test",
paramCsrfOverride: "my other csrf token",
})
);
expect(ws.send).toHaveBeenCalledTimes(0);
});
it("handle join with jwt signing error", () => {
cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", {
url: "http://localhost:4444/test",
signingSecretOverride: "my other signing secret",
})
);
expect(ws.send).toHaveBeenCalledTimes(0);
});
it("fails join without valid redirect or url", () => {
cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", {
signingSecretOverride: "my other signing secret",
})
);
expect(ws.send).toHaveBeenCalledTimes(0);
});
it("handleSubscription unknown message fails", async () => {
const phx_unknown = [null, null, "unknown", "unknown", {}];
// @ts-ignore - ignore type error for test
await cmLiveView.handleSubscriptions({ type: "unknown", message: phx_unknown });
expect(ws.send).toHaveBeenCalledTimes(0);
});
it("handleHB sends reply", async () => {
const phx_hb: PhxHeartbeatIncoming = [null, "5", "phoenix", "heartbeat", {}];
await cmLiveView.handleSubscriptions({ type: "heartbeat", message: phx_hb });
await cmLiveView.onHeartbeat(phx_hb);
expect(ws.send).toHaveBeenCalledTimes(2);
});
it("send events to LiveComponent", async () => {
const spySendInternal = jest.spyOn(cmLiveViewAndLiveComponent as any, "sendInternal");
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
cid: 1,
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cmLiveViewAndLiveComponent.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveViewAndLiveComponent.handleSubscriptions({ type: "event", message: phx_click });
await cmLiveViewAndLiveComponent.onEvent(phx_click);
expect(ws.send).toHaveBeenCalledTimes(5); // join, subscription + sendInternal, event+sendInternal = 5
expect(spySendInternal).toHaveBeenCalledTimes(2); // subscription, event
await cmLiveViewAndLiveComponent.onEvent(phx_click);
expect(ws.send).toHaveBeenCalledTimes(7); // event + sendInternal = 2
});
it("multiple clicks for LiveComponent", async () => {
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
cid: 1,
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cmLiveViewAndLiveComponent.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveViewAndLiveComponent.handleSubscriptions({ type: "event", message: phx_click });
await cmLiveViewAndLiveComponent.onEvent(phx_click);
// join, subscription+sendInternal, event+sendInternal = 5
expect(ws.send).toHaveBeenCalledTimes(5);
});
it("find LiveComponent by cid that does not exist skips event", async () => {
const spySendInternal = jest.spyOn(cmLiveViewAndLiveComponent as any, "sendInternal");
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
cid: 10, // not found
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cmLiveViewAndLiveComponent.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveViewAndLiveComponent.handleSubscriptions({ type: "event", message: phx_click });
await cmLiveViewAndLiveComponent.onEvent(phx_click);
expect(ws.send).toHaveBeenCalledTimes(1); // join
expect(spySendInternal).toHaveBeenCalledTimes(0);
});
it("onEvent valid click event socket pageTitle", async () => {
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_click });
await cmLiveView.onEvent(phx_click);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent valid click event", async () => {
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_click });
await cmLiveView.onEvent(phx_click);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent valid form event", async () => {
const phx_form: PhxIncomingMessage<PhxFormPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "form",
event: "eventName",
value: { value: "eventValue" },
uploads: {},
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_form });
await cmLiveView.onEvent(phx_form);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent valid form event rejects mismatching csrf", async () => {
const phx_form: PhxIncomingMessage<PhxFormPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "form",
event: "eventName",
// @ts-ignore
value: { value: "eventValue", _csrf_token: "wrong" },
uploads: {},
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
// this call is rejected because mismatching csrf so send not called after join
await cmLiveView.handleSubscriptions({ type: "event", message: phx_form });
expect(ws.send).toHaveBeenCalledTimes(1);
});
it("onEvent valid keyup event", async () => {
const phx_keyup: PhxIncomingMessage<PhxKeyUpPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "keyup",
event: "eventName",
value: { key: "key", value: "eventValue" },
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_keyup });
await cmLiveView.onEvent(phx_keyup);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent valid keydown event", async () => {
const phx_keydown: PhxIncomingMessage<PhxKeyDownPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "keydown",
event: "eventName",
value: { key: "key", value: "eventValue" },
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_keydown });
await cmLiveView.onEvent(phx_keydown);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent valid blur event", async () => {
const phx_blur: PhxIncomingMessage<PhxBlurPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "blur",
event: "eventName",
value: { value: "eventValue" },
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_blur });
await cmLiveView.onEvent(phx_blur);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent valid focus event", async () => {
const phx_focus: PhxIncomingMessage<PhxFocusPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "focus",
event: "eventName",
value: { value: "eventValue" },
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_focus });
await cmLiveView.onEvent(phx_focus);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent valid hook event", async () => {
const phx_hook: PhxIncomingMessage<PhxHookPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "hook",
event: "eventName",
value: { blah: "something" },
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "event", message: phx_hook });
await cmLiveView.onEvent(phx_hook);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("onEvent unknown event type", async () => {
const phx_unknown: PhxIncomingMessage<unknown> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "unknown",
event: "eventName",
value: { value: "eventValue" },
},
];
// @ts-ignore -- skip type check for unknown
await cmLiveView.handleSubscriptions({ type: "event", message: phx_unknown });
// @ts-ignore -- skip type check for unknown
await cmLiveView.onEvent(phx_unknown);
expect(ws.send).toHaveBeenCalledTimes(0);
});
it("onLivePatch calls send", async () => {
const phxLivePatch: PhxLivePatchIncoming = [
"4",
"7",
"lv:phx-AAAAAAAA",
"live_patch",
{
url: "http://localhost:4444/test?id=1",
},
];
await cmLiveView.handleJoin(
newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" })
);
await cmLiveView.handleSubscriptions({ type: "live_patch", message: phxLivePatch });
await cmLiveView.onLivePatch(phxLivePatch);
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("sendInternal with handleInfo", async () => {
const sic = new SendInternalTestLiveViewComponent();
const cm = new LiveViewManager(
sic,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
await cm.handleSubscriptions({ type: "event", message: phx_click });
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("sendInternal with handleInfo string info", async () => {
const sic = new SendInternalTestLiveViewComponent(true);
const cm = new LiveViewManager(
sic,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
await cm.handleSubscriptions({ type: "event", message: phx_click });
expect(ws.send).toHaveBeenCalledTimes(3);
});
it("send phxReply on unknown socket error", async () => {
const tc = new TestLiveViewComponent();
const ws: WsAdaptor = {
send(message: string, errorHandler?: (error?: Error) => void) {
if (errorHandler) {
errorHandler(new Error("unknown error"));
}
},
};
const cm = new LiveViewManager(
tc,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
});
it("a component that sets page title", async () => {
const c = new SetsPageTitleComponent();
const cm = new LiveViewManager(
c,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
const spyMaybeAddPageTitleToParts = jest.spyOn(cm as any, "maybeAddPageTitleToParts");
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
expect(ws.send).toHaveBeenCalledTimes(1);
expect(spyMaybeAddPageTitleToParts).toHaveBeenCalledTimes(1);
expect(spyMaybeAddPageTitleToParts).toReturnWith({ s: ["<div>test</div>"], t: "new page title" });
});
it("liveview that repeats", async () => {
jest.useFakeTimers();
jest.spyOn(global, "setTimeout");
jest.spyOn(global, "setInterval");
const c = new Repeat50msTestLiveViewComponent();
const spyHandleInfo = jest.spyOn(c, "handleInfo");
const cm = new LiveViewManager(
c,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
jest.advanceTimersToNextTimer();
expect((cm["socket"] as LiveViewSocket).context).toHaveProperty("count", 1);
// TODO - something is wrong...
// expect((cm["socket"] as LiveViewSocket).context).toHaveProperty("ignores", 1);
// console.log("spySendInternal", spyHandleInfo.mock.calls);
// TODO should be 2
expect(spyHandleInfo).toHaveBeenCalledTimes(1);
jest.advanceTimersToNextTimer();
expect((cm["socket"] as LiveViewSocket).context).toHaveProperty("count", 2);
// TODO - something is wrong...
// expect((cm["socket"] as LiveViewSocket).context).toHaveProperty("ignores", 2);
// TODO should be 4
expect(spyHandleInfo).toHaveBeenCalledTimes(2);
(cm as any).shutdown();
});
it("component that subscribes and received message", async () => {
const c = new SubscribeTestLiveViewComponent();
const pubSub = new SingleProcessPubSub();
const cm = new LiveViewManager(c, liveViewConnectionId, ws, new JsonSerDe(), pubSub, new SessionFlashAdaptor());
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
await pubSub.broadcast("testTopic", { test: "test" });
expect((cm["socket"] as LiveViewSocket).context).toHaveProperty("testReceived", 1);
(cm as any).shutdown();
});
it("component that pushPatches", async () => {
const c = new PushPatchingTestComponent();
const cm = new LiveViewManager(
c,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
const spyCm = jest.spyOn(cm as any, "onPushPatch");
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.onEvent(phx_click);
await cm.onEvent(phx_click);
await cm.onEvent(phx_click);
expect(spyCm).toHaveBeenCalledTimes(3);
(cm as any).shutdown();
});
it("component that pushRedirects", async () => {
const c = new PushRedirectingTestComponent();
const cm = new LiveViewManager(
c,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
const spyCm = jest.spyOn(cm as any, "onPushRedirect");
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.onEvent(phx_click);
await cm.onEvent(phx_click);
await cm.onEvent(phx_click);
expect(spyCm).toHaveBeenCalledTimes(3);
(cm as any).shutdown();
});
it("component that pushEvents", async () => {
const c = new PushEventTestComponent();
const cm = new LiveViewManager(
c,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
const spyCm = jest.spyOn(cm as any, "onPushEvent");
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.onEvent(phx_click);
expect(spyCm).toHaveBeenCalledTimes(1);
(cm as any).shutdown();
});
it("component that puts and clears flash", async () => {
let lastMessage: string;
const wsa: WsAdaptor = {
send(msg: string) {
lastMessage = msg;
},
};
const c = new PutFlashComponent();
const cm = new LiveViewManager(
c,
liveViewConnectionId,
wsa,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor(),
async (session, innerContent) => {
const flashAdaptor = new SessionFlashAdaptor();
const _ = await flashAdaptor.peekFlash(session, "info");
const infoFlash = (await flashAdaptor.popFlash(session, "info")) || "";
return html`
<p class="alert alert-info" role="alert" phx-click="lv:clear-flash" phx-value-key="info">${infoFlash}</p>
<div>${innerContent}</div>
`;
}
);
const spyPutFlash = jest.spyOn(cm as any, "putFlash");
const spyClearFlash = jest.spyOn(cm as any, "clearFlash");
// initial join
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
expect(spyPutFlash).toHaveBeenCalledTimes(0);
expect(spyClearFlash).toHaveBeenCalledTimes(0);
expect(lastMessage!).toMatchInlineSnapshot(
`"[\\"4\\",\\"4\\",\\"lv:phx-AAAAAAAA\\",\\"phx_reply\\",{\\"response\\":{\\"rendered\\":{\\"0\\":\\"\\",\\"1\\":{\\"s\\":[\\"<div>test</div>\\"]},\\"s\\":[\\"\\\\n <p class=\\\\\\"alert alert-info\\\\\\" role=\\\\\\"alert\\\\\\" phx-click=\\\\\\"lv:clear-flash\\\\\\" phx-value-key=\\\\\\"info\\\\\\">\\",\\"</p>\\\\n <div>\\",\\"</div>\\\\n \\"]}},\\"status\\":\\"ok\\"}]"`
);
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.onEvent(phx_click);
expect(spyPutFlash).toHaveBeenCalledTimes(1);
expect(spyClearFlash).toHaveBeenCalledTimes(0);
// has flash of "flash test"
expect(lastMessage!).toMatchInlineSnapshot(
`"[\\"4\\",\\"6\\",\\"lv:phx-AAAAAAAA\\",\\"phx_reply\\",{\\"response\\":{\\"diff\\":{\\"0\\":\\"flash test\\"}},\\"status\\":\\"ok\\"}]"`
);
// clear flash by sending "lv:clear-flash" event
const phx_clear_flash: PhxIncomingMessage<PhxLVClearFlashPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "lv:clear-flash",
value: { key: "info" },
},
];
await cm.onEvent(phx_clear_flash);
expect(spyPutFlash).toHaveBeenCalledTimes(1);
expect(spyClearFlash).toHaveBeenCalledTimes(1);
// flash should be cleared again
expect(lastMessage!).toMatchInlineSnapshot(
`"[\\"4\\",\\"6\\",\\"lv:phx-AAAAAAAA\\",\\"phx_reply\\",{\\"response\\":{\\"diff\\":{\\"0\\":\\"\\"}},\\"status\\":\\"ok\\"}]"`
);
(cm as any).shutdown();
});
it("default live view meta", async () => {
const c = new PushPatchingTestComponent();
const spyHandleParams = jest.spyOn(c as any, "handleParams");
const cm = new LiveViewManager(
c,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
const phx_click: PhxIncomingMessage<PhxClickPayload> = [
"4",
"6",
"lv:phx-AAAAAAAA",
"event",
{
type: "click",
event: "eventName",
value: { value: "eventValue" },
},
];
await cm.onEvent(phx_click);
expect(spyHandleParams).toHaveBeenCalledTimes(2);
expect((cm["socket"] as LiveViewSocket).context).toHaveProperty("pushed", 2);
(cm as any).shutdown();
});
it("test liveViewRootTemplate", async () => {
const c = new TestLiveViewComponent();
const liveViewRootTemplate = (session: SessionData, inner_content: HtmlSafeString) =>
html`<div>${session.csrfToken} ${inner_content}</div>`;
const cm = new LiveViewManager(
c,
liveViewConnectionId,
ws,
new JsonSerDe(),
new SingleProcessPubSub(),
new SessionFlashAdaptor()
);
await cm.handleJoin(newPhxJoin("my csrf token", "my signing secret", { url: "http://localhost:4444/test" }));
// use inline shapshot to see liveViewRootTemplate rendered
expect(ws.send).toMatchInlineSnapshot(`
[MockFunction] {
"calls": Array [
Array [
"[\\"4\\",\\"4\\",\\"lv:phx-AAAAAAAA\\",\\"phx_reply\\",{\\"response\\":{\\"rendered\\":{\\"s\\":[\\"<div>test</div>\\"]}},\\"status\\":\\"ok\\"}]",
[Function],
],
],
"results": Array [
Object {
"type": "return",
"value": undefined,
},
],
}
`);
(cm as any).shutdown();
});
});
class TestLiveViewComponent extends BaseLiveView {
private newPageTitle?: string;
constructor(newPageTitle?: string) {
super();
this.newPageTitle = newPageTitle;
}
handleEvent(event: AnyLiveEvent, socket: LiveViewSocket<AnyLiveContext>) {
if (this.newPageTitle) {
socket.pageTitle(this.newPageTitle);
}
}
render() {
return html`<div>test</div>`;
}
}
interface SendInternalContext {
handleEventCount: number;
handleInfoCount: number;
}
type SendInternalInfo = { type: "internal" };
class SendInternalTestLiveViewComponent extends BaseLiveView<SendInternalContext, AnyLiveEvent, SendInternalInfo> {
useStringInfo: boolean = false;
constructor(useStringInfo: boolean = false) {
super();
this.useStringInfo = useStringInfo;
}
mount(socket: LiveViewSocket<SendInternalContext>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.assign({
handleEventCount: 0,
handleInfoCount: 0,
});
}
handleEvent(event: AnyLiveEvent, socket: LiveViewSocket<SendInternalContext>) {
this.useStringInfo ? socket.sendInfo("internal") : socket.sendInfo({ type: "internal" });
socket.assign({
handleEventCount: socket.context.handleEventCount + 1,
handleInfoCount: socket.context.handleInfoCount,
});
}
handleInfo(info: SendInternalInfo, socket: LiveViewSocket<SendInternalContext>) {
socket.assign({
handleEventCount: socket.context.handleEventCount,
handleInfoCount: socket.context.handleInfoCount + 1,
});
}
render(context: SendInternalContext) {
const { handleEventCount, handleInfoCount } = context;
return html`<div>${handleEventCount},${handleInfoCount}</div>`;
}
}
interface RepeatCtx {
count: number;
ignores: number;
}
type RepeatInfo = { type: "add" };
class Repeat50msTestLiveViewComponent extends BaseLiveView<RepeatCtx, AnyLiveEvent, RepeatInfo> {
mount(socket: LiveViewSocket<RepeatCtx>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.assign({ count: 0, ignores: 0 });
socket.repeat(() => {
socket.sendInfo({ type: "add" });
socket.sendInfo({ type: "ignore" });
}, 50);
}
handleInfo(info: RepeatInfo, socket: LiveViewSocket<RepeatCtx>) {
console.log("info", info, socket.context);
if (info.type === "add") {
socket.assign({ count: socket.context.count + 1 });
} else if (info.type === "ignore") {
socket.assign({ ignores: socket.context.ignores + 1 });
}
}
render(context: RepeatCtx, meta: LiveViewMeta) {
return html`<div>test:${context.count}</div>`;
}
}
interface SubscribeCtx {
testReceived: number;
}
type SubscribeInfo = { type: "testTopicReceived" };
class SubscribeTestLiveViewComponent extends BaseLiveView<SubscribeCtx> {
mount(socket: LiveViewSocket<SubscribeCtx>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.subscribe("testTopic");
socket.assign({
testReceived: 0,
});
}
handleInfo(info: SubscribeInfo, socket: LiveViewSocket<SubscribeCtx>) {
socket.assign({
testReceived: socket.context.testReceived + 1,
});
}
render() {
return html`<div>test</div>`;
}
}
interface PushPatchCtx {
pushed: number;
}
class PushPatchingTestComponent extends BaseLiveView<PushPatchCtx> {
mount(socket: LiveViewSocket<PushPatchCtx>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.assign({
pushed: 0,
});
}
handleParams(url: URL, socket: LiveViewSocket<PushPatchCtx>) {
let pushed = Number(socket.context.pushed);
socket.assign({
pushed: pushed + 1,
});
}
handleEvent(event: AnyLiveEvent, socket: LiveViewSocket<PushPatchCtx>) {
if (socket.context.pushed === 0) {
socket.pushPatch("pushed");
} else if (socket.context.pushed === 1) {
socket.pushPatch("pushed", new URLSearchParams({ go: "dog" }));
} else {
socket.pushPatch("pushed", new URLSearchParams({ go: "dog" }), true);
}
}
render() {
return html`<div>test</div>`;
}
}
interface PushRedirectCtx {
pushed: number;
}
class PushRedirectingTestComponent extends BaseLiveView<PushRedirectCtx> {
mount(socket: LiveViewSocket<PushRedirectCtx>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.assign({
pushed: 0,
});
}
handleParams(url: URL, socket: LiveViewSocket<PushRedirectCtx>) {
let pushed = Number(socket.context.pushed);
socket.assign({
pushed: pushed + 1,
});
}
handleEvent(event: AnyLiveEvent, socket: LiveViewSocket<PushRedirectCtx>) {
if (socket.context.pushed === 0) {
socket.pushRedirect("pushed");
} else if (socket.context.pushed === 1) {
socket.pushRedirect("pushed", new URLSearchParams({ go: "dog" }));
} else {
socket.pushRedirect("pushed", new URLSearchParams({ go: "dog" }), true);
}
}
render() {
return html`<div>test</div>`;
}
}
interface PushEventCtx {
pushed: number;
}
class PushEventTestComponent extends BaseLiveView<PushEventCtx> {
mount(socket: LiveViewSocket<PushEventCtx>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.assign({
pushed: 0,
});
}
handleParams(url: URL, socket: LiveViewSocket<PushEventCtx>) {
let pushed = Number(socket.context.pushed);
if (url.searchParams.get("go") === "dog") {
// only increment if passed params.go is dog
pushed += 1;
socket.assign({
pushed,
});
}
}
handleEvent(event: AnyLiveEvent, socket: LiveViewSocket<PushEventCtx>) {
socket.pushEvent({ type: "pushed", go: "dog" });
}
render() {
return html`<div>test</div>`;
}
}
interface PutFlashContext {
called: number;
}
class PutFlashComponent extends BaseLiveView<PutFlashContext> {
mount(socket: LiveViewSocket<PutFlashContext>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.assign({
called: 0,
});
}
handleEvent(event: AnyLiveEvent, socket: LiveViewSocket<PutFlashContext>) {
socket.putFlash("info", "flash test");
socket.assign({ called: socket.context.called + 1 });
}
render() {
return html`<div>test</div>`;
}
}
interface NewPhxJoinOptions {
url?: string;
redirect?: string;
flash?: PhxFlash | null;
paramCsrfOverride?: string;
signingSecretOverride?: string;
}
const newPhxJoin = (csrfToken: string, signingSecret: string, options: NewPhxJoinOptions): PhxJoinIncoming => {
const session: Partial<SessionData> = {
_csrf_token: csrfToken,
};
const params: LiveViewMountParams = {
_csrf_token: options.paramCsrfOverride ?? csrfToken,
_mounts: 0,
};
const url = options.url ?? options.redirect;
const jwtSession = JSON.stringify(session);
return [
"4",
"4",
"lv:phx-AAAAAAAA",
"phx_join",
{
url,
params,
session: jwtSession,
static: "",
},
];
};
class SetsPageTitleComponent extends BaseLiveView {
mount(socket: LiveViewSocket<{}>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.pageTitle("new page title");
}
render(): HtmlSafeString {
return html`<div>test</div>`;
}
}
interface TestLVAndLCContext {
called: number;
}
class TestLiveViewAndLiveComponent extends BaseLiveView<TestLVAndLCContext> {
mount(socket: LiveViewSocket<TestLVAndLCContext>, session: Partial<SessionData>, params: LiveViewMountParams) {
socket.assign({ called: 0 });
}
async render(ctx: TestLVAndLCContext, meta: LiveViewMeta): Promise<LiveViewTemplate> {
const { called } = ctx;
const { live_component } = meta;
return html`
<div>${await live_component(new TestLiveComponent(), { id: 1, foo: "called" })}</div>
<div>${await live_component(new TestLiveComponent(), { foo: "bar" })}</div>
`;
}
handleInfo(info: AnyLiveInfo, socket: LiveViewSocket<TestLVAndLCContext>) {
socket.assign({ called: socket.context.called + 1 });
}
}
interface TestLVContext {
foo: string;
}
class TestLiveComponent extends BaseLiveComponent<TestLVContext> {
render(ctx: TestLVContext) {
return html`<div>${ctx.foo}</div>`;
}
handleEvent(event: AnyLiveEvent, socket: LiveComponentSocket<TestLVContext>) {
socket.sendParentInfo({ type: "test" });
socket.pushEvent({ type: "test", foo: "bar" });
socket.assign({ foo: "bar" });
}
}
class TestWsAdaptor implements WsAdaptor {
constructor(private msgCb: (msg: string) => void, private errorCb?: (err: any) => void) {
this.msgCb = msgCb;
this.errorCb = errorCb;
}
send(message: string, errorHandler?: (err: any) => void): void {
this.msgCb(message);
if (errorHandler) {
}
}
} | the_stack |
import { assert } from "../../fixed_assert";
import { AzureRMAssets } from "../../language/expressions/AzureRMAssets";
import * as TLE from "../../language/expressions/TLE";
import * as Json from "../../language/json/JSON";
import { ContainsBehavior, Span } from "../../language/Span";
import * as Completion from "../../vscodeIntegration/Completion";
import { PositionContext } from "../positionContexts/PositionContext";
import { TemplatePositionContext } from "../positionContexts/TemplatePositionContext";
import { getResourcesInfo, IResourceInfo } from "./getResourcesInfo";
import { FunctionBehaviors } from "./IFunctionMetadata";
import { TemplateScope } from "./scopes/TemplateScope";
// Handle completions for resourceId and similar functions with the usesResourceIdCompletions behavior
export function getResourceIdCompletions(
pc: TemplatePositionContext,
funcCall: TLE.FunctionCallValue,
parentStringToken: Json.Token
): Completion.Item[] {
assert(parentStringToken.type === Json.TokenType.QuotedString, "parentStringToken should be a string token");
// Use scope at current position
const scope = pc.getScope();
if (!funcCall.isUserDefinedFunction && funcCall.name) {
const functionMetadata = AzureRMAssets.getFunctionMetadataFromName(funcCall.name);
if (functionMetadata?.hasBehavior(FunctionBehaviors.usesResourceIdCompletions)) {
// If the completion is for 'resourceId' or a related function, then in addition
// to the regular completions, also add special completions for resourceId
// What argument to the function call is the cursor in?
const argumentIndex = pc.getFunctionCallArgumentIndex(funcCall);
if (typeof argumentIndex === 'number' && argumentIndex >= 0) {
const segmentIndex = argumentIndex;
return getCompletions(pc, scope, funcCall, parentStringToken, segmentIndex, { maxOptionalParameters: 2 });
}
}
}
return [];
}
function getCompletions(
pc: TemplatePositionContext,
scope: TemplateScope,
funcCall: TLE.FunctionCallValue,
parentStringToken: Json.Token,
argIndexAtCursor: number,
resourceIdCompletions: { maxOptionalParameters: number }
): Completion.Item[] {
if (argIndexAtCursor === 0) {
// For the first argument, we always provide completions for the list of resource types,
// since we don't know if the user is adding optional args to the call
return getResourceTypeCompletions(funcCall, pc, scope, resourceIdCompletions, argIndexAtCursor, parentStringToken);
}
const allResources = getResourcesInfo({ scope, recognizeDecoupledChildren: false });
// Check previous arguments in the call to see if any of them matches a known resource type
let argWithResourceType = findFunctionCallArgumentWithResourceType(
allResources,
pc,
funcCall,
parentStringToken,
argIndexAtCursor - 1);
if (!argWithResourceType) {
// None of the previous arguments matched a known resource type, so the current argument might
// be intended to be a resource type.
return getResourceTypeCompletions(funcCall, pc, scope, resourceIdCompletions, argIndexAtCursor, parentStringToken);
}
// Only look at resources with that type
let filteredResources = filterResourceInfosByType(allResources, argWithResourceType.typeExpression);
// Previous parts of the name must also match what is currently specified in the function call
// argIndex = index of the argument where the cursor is (including any optional parameters), e.g.:
// resourceId('subscriptionId', 'resourceGroupName', 'Microsoft.Fake/resource', 'name1', 'name2')
// If the cursor is on 'name2', then argIndex = 4
let argIndex = argWithResourceType.argIndex + 1;
// nameSegmentIndex = index of the name's segment where the cursor is, e.g.:
// resourceId('subscriptionId', 'resourceGroupName', 'Microsoft.Fake/resource', 'name1', 'name2')
// If the cursor is on 'name2', then nameSegmentIndex = 1 (the 2nd segment of the name, which is after
// all optional args and after the resource type)
let nameSegmentIndex = 0;
// tslint:disable-next-line:no-constant-condition
while (true) {
assert(argIndex <= argIndexAtCursor);
if (argIndex === argIndexAtCursor) {
break;
}
let argExpression: string | undefined = getArgumentExpressionText(pc, funcCall, parentStringToken, argIndex);
if (!argExpression) {
return [];
}
filteredResources = filterResourceInfosByNameSegment(filteredResources, argExpression, nameSegmentIndex);
++argIndex;
++nameSegmentIndex;
}
// Add completions for all remaining resources, at the given name segment index
const results: Completion.Item[] = [];
for (let info of filteredResources) {
const insertText = info.nameSegmentExpressions[nameSegmentIndex];
if (insertText) {
const label = insertText;
let nameSegmentArgument = funcCall.argumentExpressions[argIndex];
let span = getReplacementSpan(pc, nameSegmentArgument, parentStringToken);
results.push(new Completion.Item({
label,
insertText,
span,
kind: Completion.CompletionKind.tleResourceIdResNameParameter,
priority: Completion.CompletionPriority.high,
// Force the first of the resourceId completions to be preselected, otherwise
// vscode tends to preselect one of the regular function completions based
// on recently-typed text
preselect: true,
commitCharacters: [')', ','],
telemetryProperties: {
segment: String(argIndex),
arg: String(argIndexAtCursor),
function: funcCall.fullName
}
}));
}
}
return Completion.Item.dedupeByLabel(results);
}
/**
* Finds the first argument in the function that matches a known type (could be
* an expression), or looks like a resource type as a string literal, e.g.
*
* resourceId(subscription().id, 'Microsoft.Network/vnet', 'vnet1')
* ->
* returns the second argument (index=0)
*/
function findFunctionCallArgumentWithResourceType(
resources: IResourceInfo[],
pc: TemplatePositionContext,
funcCall: TLE.FunctionCallValue,
parentStringToken: Json.Token,
maxIndex: number
): { argIndex: number; typeExpression: string } | undefined {
for (let argIndex = 0; argIndex <= maxIndex; ++argIndex) {
let argText: string | undefined = getArgumentExpressionText(pc, funcCall, parentStringToken, argIndex);
if (argText) {
if (looksLikeResourceTypeStringLiteral(argText)) {
return { argIndex, typeExpression: argText };
}
let argTextLC = argText?.toLowerCase();
if (argTextLC) {
for (let info of resources) {
if (info.getFullTypeExpression()?.toLowerCase() === argTextLC) {
return { argIndex, typeExpression: argText };
}
}
}
}
}
return undefined;
}
function filterResourceInfosByType(infos: IResourceInfo[], typeExpression: string): IResourceInfo[] {
if (!typeExpression) {
return [];
}
const typeExpressionLC = typeExpression.toLowerCase();
return infos.filter(info => info.getFullTypeExpression()?.toLowerCase() === typeExpressionLC);
}
function filterResourceInfosByNameSegment(infos: IResourceInfo[], segmentExpression: string, segmentIndex: number): IResourceInfo[] {
if (!segmentExpression) {
return [];
}
const segmentExpressionLC = lowerCaseAndNoWhitespace(segmentExpression);
return infos.filter(info => lowerCaseAndNoWhitespace(info.nameSegmentExpressions[segmentIndex]) === segmentExpressionLC);
}
function lowerCaseAndNoWhitespace(s: string | undefined): string | undefined {
return s?.toLowerCase().replace(/\s/g, '');
}
/**
* Get completions for all resource types available (all those used in the template)
* at the given document index
*/
function getResourceTypeCompletions(
funcCall: TLE.FunctionCallValue,
pc: TemplatePositionContext,
scope: TemplateScope,
resourceIdCompletions: { maxOptionalParameters: number },
argumentIndex: number,
parentStringToken: Json.Token
): Completion.Item[] {
if (argumentIndex > resourceIdCompletions.maxOptionalParameters) {
// The resource type must be the argument after the optional arguments.
// This argument is past that, so no resource type completions.
return [];
}
const results: Completion.Item[] = [];
const infos = getResourcesInfo({ scope, recognizeDecoupledChildren: false });
for (const info of infos) {
const insertText = info.getFullTypeExpression();
if (insertText) {
const label = insertText;
let typeArgument = funcCall.argumentExpressions[argumentIndex];
let span = getReplacementSpan(pc, typeArgument, parentStringToken);
const item = new Completion.Item({
label,
insertText,
span,
kind: Completion.CompletionKind.tleResourceIdResTypeParameter,
priority: Completion.CompletionPriority.high,
// Force the first of the resourceId completions to be preselected, otherwise
// vscode tends to preselect one of the regular function completions based
// on recently-typed text
preselect: true,
commitCharacters: [','],
telemetryProperties: {
segment: String(0),
arg: String(argumentIndex),
function: funcCall.fullName
}
});
if (item.span.contains(pc.documentCharacterIndex, ContainsBehavior.strict)) {
results.push(item);
} else {
// tslint:disable-next-line: no-suspicious-comment
// TODO: https://github.com/microsoft/vscode-azurearmtools/issues/1030
// assert(false, "Replacement span doesn't contain cursor");
}
}
}
return Completion.Item.dedupeByLabel(results);
}
function getReplacementSpan(pc: PositionContext, argument: TLE.Value | undefined, parentStringToken: Json.Token): Span {
let span = argument?.getSpan()?.translate(parentStringToken.span.startIndex)
?? pc.emptySpanAtDocumentCharacterIndex;
return span;
}
/**
* Retrieves the document text for the given function call argument
*/
function getArgumentExpressionText(
pc: TemplatePositionContext,
funcCall: TLE.FunctionCallValue,
parentStringToken: Json.Token,
argumentIndex: number
): string | undefined {
const argExpressionValue: TLE.Value | undefined = funcCall.argumentExpressions[argumentIndex];
if (argExpressionValue) {
return pc.document.getTextAtTleValue(argExpressionValue, parentStringToken)?.toLowerCase();
}
return undefined;
}
export function looksLikeResourceTypeStringLiteral(text: string): boolean {
// e.g. 'Microsoft.Compute/virtualMachines/extensions'
return !!text.match(/^'[^'.]+\.[^'.]+\/([^'.]+)(\.[^'.]+)*'$/);
} | the_stack |
import {AfterViewInit, Component, Injector, Input, OnInit, ViewChild} from "@angular/core";
import {StateService} from "@uirouter/angular";
import {DefineFeedService} from "../../services/define-feed.service";
import {AbstractLoadFeedComponent} from "../../shared/AbstractLoadFeedComponent";
import {FeedLoadingService} from "../../services/feed-loading-service";
import {FeedSideNavService} from "../../services/feed-side-nav.service";
import * as _ from "underscore";
import * as angular from 'angular';
import {HttpClient} from "@angular/common/http";
import {LINEAGE_LINK} from "../../model/feed-link-constants";
import {KyloIcons} from "../../../../../kylo-utils/kylo-icons";
import {KyloVisNetworkComponent} from "../../../../../common/kylo-vis-network/kylo-vis-network.component";
import {CloneUtil} from "../../../../../common/utils/clone-util";
@Component({
selector: "feed-lineage",
styleUrls: ["./feed-lineage.component.css"],
templateUrl: "./feed-lineage.component.html"
})
export class FeedLineageComponment extends AbstractLoadFeedComponent implements OnInit, AfterViewInit {
static LOADER = "FeedLineage.LOADER";
static LINK_NAME = LINEAGE_LINK;
restUrlService: any;
utils: any;
kyloStateService: any;
public kyloIcons_Links_lineage = KyloIcons.Links.lineage;
feedLineage: any = null;
nodes: any[];
edges: any[];
edgeKeys: any = {};
processedNodes: any = {};
loading: boolean = true;
options: any = null;
/**
*
* The default text of the node selector
* @type {{name: string, type: string, content: {displayProperties: null}}}
*/
SELECT_A_NODE: any = {name: 'Select a node', type: 'Feed Lineage', content: {displayProperties: null}};
/**
* The selected Node
* @type {{name: string, type: string, content: null}}
*/
selectedNode: any = this.SELECT_A_NODE;
graphModes: any = {SIMPLE: "SIMPLE", DETAILED: "DETAILED"};
graphMode: any = this.graphModes.DETAILED;
data: any = {nodes: null, edges: null};
@ViewChild("lineageGraph")
lineageGraph:KyloVisNetworkComponent
constructor(feedLoadingService: FeedLoadingService, stateService: StateService, defineFeedService: DefineFeedService, feedSideNavService: FeedSideNavService,
private $$angularInjector: Injector, private http: HttpClient) {
super(feedLoadingService, stateService, defineFeedService, feedSideNavService);
this.utils = $$angularInjector.get("Utils");
this.restUrlService = $$angularInjector.get("RestUrlService");
this.kyloStateService = $$angularInjector.get("StateService");
this.options = {
"height": "100%",
"width": "100%",
"edges": {
"arrowStrikethrough": false,
"smooth": {
"enabled": true,
"type": "cubicBezier",
"roundness": 0,
"forceDirection": "horizontal"
},
"font": {
"align": "horizontal"
}
},
"layout": {
"randomSeed":50,
"hierarchical": {
"direction": "LR",
"nodeSpacing": 300,
"sortMethod": "directed"
}
},
"nodes": {
"shape": "box",
"font": {
"align": "center"
}
},
"groups": {
"feed": {
"shape": "box",
"font": {
"align": "center"
}
},
"datasource": {
"shape": "box",
"font": {
"align": "center"
}
}
},
"interaction": {
"hover": true,
"navigationButtons": true,
"keyboard": true
},
"physics": {
"enabled": false,
"solver": "hierarchicalRepulsion"
}
}
}
getLinkName() {
return FeedLineageComponment.LINK_NAME;
}
navigateToFeed() {
if (this.selectedNode.type == 'FEED' && this.selectedNode.content) {
this.kyloStateService.FeedManager().Feed().navigateToFeedDetails(this.selectedNode.content.id, 2);
}
}
onHeightChange(height:number){
if(this.lineageGraph){
this.lineageGraph.setHeight(height);
}
}
/**
* Called when a Node is selected
* @param item
*/
changed = false;
panelOpenState = false;
onLoad(event:any) {
}
onSelect(item: any) {
if (item && item.nodes && item.nodes[0]) {
this.changed = true;
var firstItem = item.nodes[0];
var feed = this.feedLineage.feedMap[firstItem];
if (feed) {
this.selectedNode.name = feed.displayName;
this.selectedNode.type = 'FEED';
this.selectedNode.content = feed;
this.cleanProperties(feed);
feed.displayProperties = {};
//add in any properties of its own
angular.extend(feed.displayProperties, feed.properties);
this.selectedNode.content.displayProperties = feed.displayProperties
}
else {
var ds = this.feedLineage.datasourceMap[firstItem];
this.selectedNode.name = ds.name;
this.selectedNode.type = 'DATASOURCE';
this.selectedNode.content = ds;
}
}
else {
this.selectedNode = this.SELECT_A_NODE;
}
}
onStabilized(event:any){
let optionsUpdate = {
physics: {enabled: false, stabilization: false, "solver": "hierarchicalRepulsion"},
interaction: {dragNodes: true},
layout: {
hierarchical: {
enabled: false
}
}
}
let copy = CloneUtil.deepCopy(this.options);
let newOptions = _.extend(copy,optionsUpdate)
if (this.lineageGraph) {
this.lineageGraph.updateOptions(newOptions);
}
}
ngAfterViewInit(){
this._draw();
}
init() {
this.getFeedLineage();
}
getFeedLineage() {
this.http.get(this.restUrlService.FEED_LINEAGE_URL(this.feedId)).subscribe((response: any) => {
this.feedLineage = response;
this._draw();
this.loading = false;
});
}
onDrop(data: any) {
console.log('dropped', data);
}
networkView(value: string) {
this.graphMode = value;
if (!this.loading) {
this.redraw();
}
//this.options = {physics: {enabled: false, stabilization: true}};
}
redraw() {
if (this.isDetailedGraph()) {
this.onDetailedView();
}
else {
this.onSimpleView();
}
}
isDetailedGraph() {
return this.graphMode == this.graphModes.DETAILED;
}
onDetailedView() {
this.graphMode = this.graphModes.DETAILED;
this._draw();
}
onSimpleView() {
this.graphMode = this.graphModes.SIMPLE;
this._draw();
}
_draw() {
this.nodes = [];
this.edges = [];
this.edgeKeys = {};
this.processedNodes = {};
if(this.feedLineage && this.lineageGraph) {
//turn on physics for layout
this.options.physics.enabled = true;
this.options.physics.solver = "hierarchicalRepulsion";
this.options.physics.stabilization = true
//turn on physics for layout
this.buildVisJsGraph(this.feedLineage.feed);
this.setNodeData();
this.lineageGraph.drawNetwork();
}
}
setNodeData() {
this.data = {nodes: this.nodes, edges: this.edges};
}
buildVisJsGraph(feed: any) {
var node = this.processedNodes[feed.id] == undefined ? this.feedNode(feed) : this.processedNodes[feed.id];
if (this.processedNodes[node.id] == undefined) {
this.processedNodes[node.id] = node;
this.nodes.push(node);
this.buildDataSourceGraph(feed);
//walk the graph both ways (up and down)
if (feed.dependentFeedIds) {
_.each(feed.dependentFeedIds, (depFeedId: any) => {
//get it from the map
var depFeed = this.feedLineage.feedMap[depFeedId];
if (this.processedNodes[depFeed.id] == undefined) {
this.buildVisJsGraph(depFeed)
}
var edgeKey = depFeed.id + feed.id;
if (this.edgeKeys[edgeKey] == undefined) {
var edge = {from: depFeed.id, to: feed.id, arrows: 'from', label: 'depends on'};
this.edgeKeys[edgeKey] = edge;
this.edges.push(edge);
}
});
}
if (feed.usedByFeedIds) {
_.each(feed.usedByFeedIds, (usedByFeedId: string) => {
//get it from the map
var usedByFeed = this.feedLineage.feedMap[usedByFeedId];
if (this.processedNodes[usedByFeed.id] == undefined) {
this.buildVisJsGraph(usedByFeed);
}
var edgeKey = feed.id + usedByFeed.id;
});
}
}
}
feedNode(feed: any) {
var node = {id: feed.id, label: this.feedNodeLabel(feed), title: this.feedNodeLabel(feed), group: "feed"};
var style = this.feedLineage.styles['feed'];
this.setNodeStyle(node, style);
if (feed.id == this.feedId) {
var style = this.feedLineage.styles['currentFeed'];
this.setNodeStyle(node, style);
}
this.cleanProperties(feed);
feed.displayProperties = {};
//add in any properties of its own
angular.extend(feed.displayProperties, feed.properties);
return node;
}
feedNodeLabel(feed: any) {
var label = feed.displayName;
return label;
}
buildDataSourceGraph(feed: any) {
if (feed.sources) {
_.each(feed.sources, (src: any) => {
this.buildDatasource(feed, src.datasourceId, 'source');
});
}
if (feed.destinations) {
_.each(feed.destinations, (dest: any) => {
this.buildDatasource(feed, dest.datasourceId, 'destination');
})
}
}
assignDatasourceProperties(ds: any) {
var keysToOmit = ['@type', 'id', 'name', 'encrypted', 'compressed', 'destinationForFeeds', 'sourceForFeeds'];
var props = _.omit(ds, keysToOmit);
props = _.pick(props, (value: any, key: any) => {
return !_.isObject(value);
});
ds.displayProperties = props
this.cleanProperties(ds);
//add in any properties of its own
angular.extend(ds.displayProperties, ds.properties);
}
cleanProperties(item: any) {
if (item.properties) {
var updatedProps = _.omit(item.properties, (val: any, key: any) => {
return key.indexOf("jcr:") == 0 || key == "tba:properties" || key == 'tba:processGroupId';
});
item.properties = updatedProps
}
}
datasourceNodeLabel(ds: any) {
var label = "";
if (angular.isString(ds.datasourceType)) {
label = this.utils.endsWith(ds.datasourceType.toLowerCase(), "datasource") ? ds.datasourceType.substring(0, ds.datasourceType.toLowerCase().lastIndexOf("datasource")) : ds.datasourceType;
if(label && label.toLowerCase() == 'database'){
//attempt to find the name of the database in the properties
if(ds.properties && ds.properties['Database Connection']){
label = ds.properties['Database Connection'];
}
}
} else if (angular.isString(ds.type)) {
label = ds.type;
} else {
label = this.utils.endsWith(ds["@type"].toLowerCase(), "datasource") ? ds["@type"].substring(0, ds["@type"].toLowerCase().lastIndexOf("datasource")) : ds["@type"];
}
label += "\n" + ds.name;
return label;
}
buildDatasource(feed: any, dsId: any, type: any) {
if (dsId) {
var processedDatasource = this.processedNodes[dsId];
if (processedDatasource == undefined) {
var ds = this.feedLineage.datasourceMap[dsId];
//skip JdbcDatasource entries
if(ds['@type'] && ds['@type'] == 'JdbcDatasource'){
return;
}
this.assignDatasourceProperties(ds);
//console.log('building datasource',ds.name)
if (this.isDetailedGraph()) {
var node = {id: dsId, label: this.datasourceNodeLabel(ds), title: this.datasourceNodeLabel(ds), group: "datasource"};
this.nodes.push(node);
this.processedNodes[node.id] = node;
var style = this.feedLineage.styles[ds.datasourceType];
this.setNodeStyle(node, style);
}
//build subgraph of feed relationships
if (ds.sourceForFeeds) {
_.each(ds.sourceForFeeds, (feedItem: any) => {
var depFeed = this.feedLineage.feedMap[feedItem.id];
if (depFeed.id != feed.id) {
var edgeKey = dsId + depFeed.id;
var fromId = dsId;
var arrows = "to";
var label = 'source'
if (!this.isDetailedGraph()) {
label = '';
edgeKey = feed.id + depFeed.id;
var edgeKey2 = depFeed.id + feed.id;
fromId = feed.id;
var exists = this.edgeKeys[edgeKey];
var exists2 = this.edgeKeys[edgeKey2];
if (!exists && exists2) {
exists2.arrows = "to;from";
edgeKey = edgeKey2;
}
}
if (this.edgeKeys[edgeKey] == undefined) {
var edge = {from: fromId, to: depFeed.id, arrows: 'to', label: label};
this.edgeKeys[edgeKey] = edge;
this.edges.push(edge);
}
this.buildVisJsGraph(depFeed);
}
});
}
if (ds.destinationForFeeds) {
_.each(ds.destinationForFeeds, (feedItem: any) => {
var depFeed = this.feedLineage.feedMap[feedItem.id];
if (depFeed.id != feed.id) {
var edgeKey = dsId + depFeed.id;
var toId = dsId;
var label = 'destination'
if (!this.isDetailedGraph()) {
label = ''
edgeKey = depFeed.id + feed.id;
toId = feed.id;
var edgeKey2 = feed.id + depFeed.id;
var exists = this.edgeKeys[edgeKey];
var exists2 = this.edgeKeys[edgeKey2];
if (!exists && exists2) {
exists2.arrows = "to;from";
edgeKey = edgeKey2;
}
}
if (this.edgeKeys[edgeKey] == undefined) {
var edge = {from: depFeed.id, to: toId, arrows: 'to', label: label};
this.edgeKeys[edgeKey] = edge;
this.edges.push(edge);
}
this.buildVisJsGraph(depFeed);
}
});
}
}
if (this.isDetailedGraph()) {
if (type == 'source') {
var edgeKey = dsId + feed.id;
var fromId = dsId;
if (this.edgeKeys[edgeKey] == undefined) {
var edge = {from: fromId, to: feed.id, arrows: 'to', label: 'source'};
this.edgeKeys[edgeKey] = edge;
this.edges.push(edge);
}
}
else {
var edgeKey = dsId + feed.id;
var toId = dsId;
if (this.edgeKeys[edgeKey] == undefined) {
var edge = {from: feed.id, to: toId, arrows: 'to', label: 'destination'};
this.edgeKeys[edgeKey] = edge;
this.edges.push(edge);
}
}
}
}
}
setNodeStyle(node: any, style: any) {
if (style) {
if ((style.shape == 'icon' || !style.shape) && style.icon && style.icon.code) {
node.shape = 'icon';
if (angular.isObject(style.icon)) {
node.icon = style.icon;
}
}
else if (style.shape) {
node.shape = style.shape;
}
if (style.color) {
node.color = style.color;
}
if (style.size) {
node.size = style.size;
}
if (style.font) {
node.font = style.font;
}
if (!node.font) {
node.font = {}
}
node.font.background = '#ffffff'
}
}
} | the_stack |
import _Base = require('../../Core/_Base');
import _BaseUtils = require('../../Core/_BaseUtils');
import _Control = require('../../Utilities/_Control');
import _ElementUtilities = require('../../Utilities/_ElementUtilities');
import _ErrorFromName = require('../../Core/_ErrorFromName');
import _Events = require('../../Core/_Events');
import _Global = require('../../Core/_Global');
import _KeyboardBehavior = require('../../Utilities/_KeyboardBehavior');
import SplitViewTypeInfo = require('../SplitView/_SplitView'); // Only use for type information so we don't eagerly load the SplitView code
import _Hoverable = require('../../Utilities/_Hoverable');
_Hoverable.isHoverable; // Force dependency on the hoverable module
require(["require-style!less/styles-splitviewpanetoggle"]);
require(["require-style!less/colors-splitviewpanetoggle"]);
"use strict";
// This control has 2 modes depending on whether or not the app has provided a SplitView:
// - SplitView not provided
// SplitViewPaneToggle provides button visuals and fires the invoked event. The app
// intends to do everything else:
// - Handle the invoked event
// - Handle the SplitView opening and closing
// - Handle aria-expanded being mutated by UIA (i.e. screen readers)
// - Keep the aria-controls attribute, aria-expanded attribute, and SplitView in sync
// - SplitView is provided via splitView property
// SplitViewPaneToggle keeps the SplitView, the aria-controls attribute, and the
// aria-expands attribute in sync. In this use case, apps typically won't listen
// to the invoked event (but it's still fired).
var ClassNames = {
splitViewPaneToggle: "win-splitviewpanetoggle"
};
var EventNames = {
// Fires when the user invokes the button with mouse/keyboard/touch. Does not
// fire if the SplitViewPaneToggle's state changes due to UIA (i.e. aria-expanded
// being set) or due to the SplitView pane opening/closing.
invoked: "invoked"
};
var Strings = {
get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; },
get badButtonElement() { return "Invalid argument: The SplitViewPaneToggle's element must be a button element"; }
};
// The splitViewElement may not have a winControl associated with it yet in the case
// that the SplitViewPaneToggle was constructed before the SplitView. This may happen
// when WinJS.UI.processAll is used to construct the controls because the order of construction
// depends on the order in which the SplitView and SplitViewPaneToggle appear in the DOM.
function getSplitViewControl(splitViewElement: HTMLElement): SplitViewTypeInfo.SplitView {
return <SplitViewTypeInfo.SplitView>(splitViewElement && splitViewElement["winControl"]);
}
function getPaneOpened(splitViewElement: HTMLElement): boolean {
var splitViewControl = getSplitViewControl(splitViewElement);
return splitViewControl ? splitViewControl.paneOpened : false;
}
/// <field>
/// <summary locid="WinJS.UI.SplitViewPaneToggle">
/// Displays a button which is used for opening and closing a SplitView's pane.
/// </summary>
/// </field>
/// <icon src="ui_winjs.ui.splitviewpanetoggle.12x12.png" width="12" height="12" />
/// <icon src="ui_winjs.ui.splitviewpanetoggle.16x16.png" width="16" height="16" />
/// <htmlSnippet><![CDATA[<button data-win-control="WinJS.UI.SplitViewPaneToggle"></button>]]></htmlSnippet>
/// <part name="splitviewpanetoggle" class="win-splitviewpanetoggle" locid="WinJS.UI.SplitViewPaneToggle_part:splitviewpanetoggle">The SplitViewPaneToggle control itself.</part>
/// <resource type="javascript" src="//$(TARGET_DESTINATION)/js/WinJS.js" shared="true" />
/// <resource type="css" src="//$(TARGET_DESTINATION)/css/ui-dark.css" shared="true" />
export class SplitViewPaneToggle {
private static _ClassNames = ClassNames;
static supportedForProcessing: boolean = true;
private _onPaneStateSettledBound: EventListener;
private _opened: boolean; // Only used when a splitView is specified
private _ariaExpandedMutationObserver: _ElementUtilities.IMutationObserverShim;
private _initialized: boolean;
private _disposed: boolean;
private _dom: {
root: HTMLButtonElement;
};
constructor(element?: HTMLButtonElement, options: any = {}) {
/// <signature helpKeyword="WinJS.UI.SplitViewPaneToggle.SplitViewPaneToggle">
/// <summary locid="WinJS.UI.SplitViewPaneToggle.constructor">
/// Creates a new SplitViewPaneToggle control.
/// </summary>
/// <param name="element" type="HTMLElement" domElement="true" isOptional="true" locid="WinJS.UI.SplitViewPaneToggle.constructor_p:element">
/// The DOM element that hosts the SplitViewPaneToggle control.
/// </param>
/// <param name="options" type="Object" isOptional="true" locid="WinJS.UI.SplitViewPaneToggle.constructor_p:options">
/// An object that contains one or more property/value pairs to apply to the new control.
/// Each property of the options object corresponds to one of the control's properties or events.
/// Event names must begin with "on". For example, to provide a handler for the invoked event,
/// add a property named "oninvoked" to the options object and set its value to the event handler.
/// </param>
/// <returns type="WinJS.UI.SplitViewPaneToggle" locid="WinJS.UI.SplitViewPaneToggle.constructor_returnValue">
/// The new SplitViewPaneToggle.
/// </returns>
/// </signature>
// Check to make sure we weren't duplicated
if (element && element["winControl"]) {
throw new _ErrorFromName("WinJS.UI.SplitViewPaneToggle.DuplicateConstruction", Strings.duplicateConstruction);
}
this._onPaneStateSettledBound = this._onPaneStateSettled.bind(this);
this._ariaExpandedMutationObserver = new _ElementUtilities._MutationObserver(this._onAriaExpandedPropertyChanged.bind(this));
this._initializeDom(element || _Global.document.createElement("button"));
// Private state
this._disposed = false;
// Default values
this.splitView = null;
_Control.setOptions(this, options);
this._initialized = true;
this._updateDom();
}
/// <field type="HTMLElement" domElement="true" readonly="true" hidden="true" locid="WinJS.UI.SplitViewPaneToggle.element" helpKeyword="WinJS.UI.SplitViewPaneToggle.element">
/// Gets the DOM element that hosts the SplitViewPaneToggle control.
/// </field>
get element(): HTMLElement {
return this._dom.root;
}
private _splitView: HTMLElement;
/// <field type="HTMLElement" domElement="true" hidden="true" locid="WinJS.UI.SplitViewPaneToggle.splitView" helpKeyword="WinJS.UI.SplitViewPaneToggle.splitView">
/// Gets or sets the DOM element of the SplitView that is associated with the SplitViewPaneToggle control.
/// When the SplitViewPaneToggle is invoked, it'll toggle this SplitView's pane.
/// </field>
get splitView(): HTMLElement {
return this._splitView;
}
set splitView(splitView: HTMLElement) {
this._splitView = splitView;
if (splitView) {
this._opened = getPaneOpened(splitView);
}
this._updateDom();
}
dispose(): void {
/// <signature helpKeyword="WinJS.UI.SplitViewPaneToggle.dispose">
/// <summary locid="WinJS.UI.SplitViewPaneToggle.dispose">
/// Disposes this control.
/// </summary>
/// </signature>
if (this._disposed) {
return;
}
this._disposed = true;
this._splitView && this._removeListeners(this._splitView);
}
private _initializeDom(root: HTMLButtonElement): void {
if (root.tagName !== "BUTTON") {
throw new _ErrorFromName("WinJS.UI.SplitViewPaneToggle.BadButtonElement", Strings.badButtonElement);
}
root["winControl"] = this;
_ElementUtilities.addClass(root, ClassNames.splitViewPaneToggle);
_ElementUtilities.addClass(root, "win-disposable");
if (!root.hasAttribute("type")) {
root.type = "button";
}
new _KeyboardBehavior._WinKeyboard(root);
root.addEventListener("click", this._onClick.bind(this));
this._dom = {
root: root
};
}
// State private to _updateDom. No other method should make use of it.
//
// Nothing has been rendered yet so these are all initialized to undefined. Because
// they are undefined, the first time _updateDom is called, they will all be
// rendered.
private _updateDom_rendered = {
splitView: <HTMLElement>undefined
};
private _updateDom(): void {
if (!this._initialized || this._disposed) {
return;
}
var rendered = this._updateDom_rendered;
if (this._splitView !== rendered.splitView) {
if (rendered.splitView) {
this._dom.root.removeAttribute("aria-controls");
this._removeListeners(rendered.splitView);
}
if (this._splitView) {
_ElementUtilities._ensureId(this._splitView);
this._dom.root.setAttribute("aria-controls", this._splitView.id);
this._addListeners(this._splitView);
}
rendered.splitView = this._splitView;
}
// When no SplitView is provided, it's up to the app to manage aria-expanded.
if (this._splitView) {
// Always update aria-expanded and don't cache its most recently rendered value
// in _updateDom_rendered. The reason is that we're not the only ones that update
// aria-expanded. aria-expanded may be changed thru UIA APIs. Consequently, if we
// cached the last value we set in _updateDom_rendered, it may not reflect the current
// value in the DOM.
var expanded = this._opened ? "true" : "false";
_ElementUtilities._setAttribute(this._dom.root, "aria-expanded", expanded);
// The splitView element may not have a winControl associated with it yet in the case
// that the SplitViewPaneToggle was constructed before the SplitView. This may happen
// when WinJS.UI.processAll is used to construct the controls because the order of construction
// depends on the order in which the SplitView and SplitViewPaneToggle appear in the DOM.
var splitViewControl = getSplitViewControl(this._splitView);
if (splitViewControl) {
splitViewControl.paneOpened = this._opened;
}
}
}
private _addListeners(splitViewElement: HTMLElement) {
splitViewElement.addEventListener("_openCloseStateSettled", this._onPaneStateSettledBound);
this._ariaExpandedMutationObserver.observe(this._dom.root, {
attributes: true,
attributeFilter: ["aria-expanded"]
});
}
private _removeListeners(splitViewElement: HTMLElement) {
splitViewElement.removeEventListener("_openCloseStateSettled", this._onPaneStateSettledBound);
this._ariaExpandedMutationObserver.disconnect();
}
private _fireEvent(eventName: string) {
var eventObject = <CustomEvent>_Global.document.createEvent("CustomEvent");
eventObject.initCustomEvent(
eventName,
true, // bubbles
false, // cancelable
null // detail
);
return this._dom.root.dispatchEvent(eventObject);
}
// Inputs that change the SplitViewPaneToggle's state
//
private _onPaneStateSettled(eventObject: Event) {
if (eventObject.target === this._splitView) {
this._opened = getPaneOpened(this._splitView);
this._updateDom();
}
}
// Called by tests.
private _onAriaExpandedPropertyChanged(mutations: _ElementUtilities.IMutationRecordShim[]) {
var ariaExpanded = this._dom.root.getAttribute("aria-expanded") === "true";
this._opened = ariaExpanded;
this._updateDom();
}
private _onClick(eventObject: MouseEvent): void {
this._invoked();
}
// Called by tests.
private _invoked(): void {
if (this._disposed) {
return;
}
if (this._splitView) {
this._opened = !this._opened;
this._updateDom();
}
this._fireEvent(EventNames.invoked);
}
}
_Base.Class.mix(SplitViewPaneToggle, _Events.createEventProperties(
EventNames.invoked
));
_Base.Class.mix(SplitViewPaneToggle, _Control.DOMEventMixin); | the_stack |
import {
GraphQLResolveInfo,
GraphQLScalarType,
GraphQLScalarTypeConfig
} from "graphql";
import {
Author as AuthorEntity,
Avatar as AvatarEntity,
Book as BookEntity,
BookCopy as BookCopyEntity,
User as UserEntity,
Review as ReviewEntity
} from "~/infra/database/entity";
import { Context, AuthenticatedContext } from "~/interfaces/graphql/context";
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = {
[K in keyof T]: T[K];
};
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type RequireFields<T, K extends keyof T> = {
[X in Exclude<keyof T, K>]?: T[X];
} &
{ [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
ExternalID: string;
ISODateString: string;
};
export type RegistrationInput = {
readonly name: Scalars["String"];
readonly email: Scalars["String"];
readonly password: Scalars["String"];
};
export type RegistrationResult = ProtectedUser | ValidationErrors;
export type UpdateProfileInput = {
readonly name: Scalars["String"];
readonly email: Scalars["String"];
readonly info: Scalars["String"];
};
export type UpdateProfileResult = ProtectedUser | ValidationErrors;
export type Query = {
readonly __typename?: "Query";
/** Returns the currently logged in user. */
readonly currentUser?: Maybe<ProtectedUser>;
readonly authors: ReadonlyArray<Author>;
readonly author: AuthorResponse;
readonly booksCount: Scalars["Int"];
readonly books: ReadonlyArray<Book>;
readonly book: BookResult;
readonly randomBook?: Maybe<Book>;
readonly resources: ReadonlyArray<Resource>;
readonly resource: Resource;
/** @deprecated No longer supported. Use 'resource' instead */
readonly anything: Anything;
readonly users: ReadonlyArray<User>;
readonly user: UserResult;
};
export type QueryAuthorArgs = {
id: Scalars["ExternalID"];
};
export type QueryBooksArgs = {
offset?: Maybe<Scalars["Int"]>;
limit?: Maybe<Scalars["Int"]>;
};
export type QueryBookArgs = {
id: Scalars["ExternalID"];
};
export type QueryResourceArgs = {
id: Scalars["ID"];
};
export type QueryAnythingArgs = {
id: Scalars["ID"];
};
export type QueryUserArgs = {
id: Scalars["ExternalID"];
};
export type Mutation = {
readonly __typename?: "Mutation";
readonly register: RegistrationResult;
readonly updateProfile: UpdateProfileResult;
/** Authenticates a user with the given credentials. */
readonly login: LoginResult;
readonly logout: Scalars["Boolean"];
readonly addBookToFavourites: BookResult;
readonly removeBookFromFavourites: BookResult;
readonly borrowBookCopy: BorrowBookCopyResult;
readonly returnBookCopy: ReturnBookCopyResult;
readonly createReview: Review;
readonly createUser: CreateUserResult;
readonly updateUser: UpdateUserResult;
readonly deleteUser: DeleteUserResult;
};
export type MutationRegisterArgs = {
input: RegistrationInput;
};
export type MutationUpdateProfileArgs = {
input: UpdateProfileInput;
};
export type MutationLoginArgs = {
input: LoginInput;
};
export type MutationAddBookToFavouritesArgs = {
id: Scalars["ExternalID"];
};
export type MutationRemoveBookFromFavouritesArgs = {
id: Scalars["ExternalID"];
};
export type MutationBorrowBookCopyArgs = {
id: Scalars["ExternalID"];
};
export type MutationReturnBookCopyArgs = {
id: Scalars["ExternalID"];
};
export type MutationCreateReviewArgs = {
input: CreateReviewInput;
};
export type MutationCreateUserArgs = {
input: CreateUserInput;
};
export type MutationUpdateUserArgs = {
input: UpdateUserInput;
};
export type MutationDeleteUserArgs = {
id: Scalars["ExternalID"];
};
export enum Role {
Admin = "Admin",
User = "User"
}
export type LoginInput = {
readonly email: Scalars["String"];
readonly password: Scalars["String"];
};
export type LoginSuccess = {
readonly __typename?: "LoginSuccess";
readonly currentUser: ProtectedUser;
};
export type LoginFailure = {
readonly __typename?: "LoginFailure";
readonly validationErrors: ReadonlyArray<ValidationError>;
};
export type LoginResult = LoginSuccess | LoginFailure;
export type Author = Resource &
Timestampable & {
readonly __typename?: "Author";
readonly id: Scalars["ExternalID"];
readonly name: Scalars["String"];
readonly bio: Scalars["String"];
readonly photo: Image;
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
readonly books: ReadonlyArray<Book>;
};
export type Book = Resource &
Timestampable & {
readonly __typename?: "Book";
readonly author: Author;
readonly id: Scalars["ExternalID"];
readonly title: Scalars["String"];
readonly description: Scalars["String"];
readonly cover: Image;
readonly copies: ReadonlyArray<BookCopy>;
readonly isFavourite?: Maybe<Scalars["Boolean"]>;
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
readonly reviews: ReadonlyArray<Review>;
readonly reviewsCount: Scalars["Int"];
readonly averageRating?: Maybe<Scalars["Float"]>;
};
export type AuthorResponse = Author | ResourceNotFoundError;
export type BookCopy = Timestampable & {
readonly __typename?: "BookCopy";
readonly id: Scalars["ExternalID"];
readonly book: Book;
readonly borrowedAt?: Maybe<Scalars["ISODateString"]>;
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
readonly owner: User;
readonly borrower?: Maybe<User>;
};
export type User = {
readonly ownedBookCopies: ReadonlyArray<BookCopy>;
readonly id: Scalars["ExternalID"];
readonly name: Scalars["String"];
readonly info: Scalars["String"];
readonly avatar: AvatarResult;
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
};
export type PublicUser = User &
Resource &
Timestampable & {
readonly __typename?: "PublicUser";
readonly ownedBookCopies: ReadonlyArray<BookCopy>;
readonly id: Scalars["ExternalID"];
readonly name: Scalars["String"];
readonly info: Scalars["String"];
readonly avatar: AvatarResult;
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
};
export type ProtectedUser = User &
Resource &
Timestampable & {
readonly __typename?: "ProtectedUser";
readonly ownedBookCopies: ReadonlyArray<BookCopy>;
readonly borrowedBookCopies: ReadonlyArray<BookCopy>;
readonly favouriteBooks: ReadonlyArray<Book>;
readonly reviews: ReadonlyArray<Review>;
readonly id: Scalars["ExternalID"];
readonly name: Scalars["String"];
readonly info: Scalars["String"];
readonly avatar: AvatarResult;
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
readonly email: Scalars["String"];
readonly isAdmin: Scalars["Boolean"];
};
export type UpdateBookFavouriteResult = Book | MutationError;
export type BorrowBookCopyResult = BookCopy | MutationError;
export type ReturnBookCopyResult = BookCopy | MutationError;
export type BookResult = Book | ResourceNotFoundError;
export type Subscription = {
readonly __typename?: "Subscription";
readonly bookCopyUpdated: BookCopy;
};
export type SubscriptionBookCopyUpdatedArgs = {
id: Scalars["ExternalID"];
};
export type Timestampable = {
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
};
export type Image = {
readonly __typename?: "Image";
readonly path: Scalars["String"];
readonly url: Scalars["String"];
};
export type Error = {
readonly message: Scalars["String"];
};
export type MutationError = Error & {
readonly __typename?: "MutationError";
readonly message: Scalars["String"];
};
export type ValidationError = Error & {
readonly __typename?: "ValidationError";
readonly path: Scalars["String"];
readonly message: Scalars["String"];
};
export type ValidationErrors = {
readonly __typename?: "ValidationErrors";
readonly errors: ReadonlyArray<ValidationError>;
};
export type MutationResponse = {
/** A boolean that indicates whether the mutation was successful. */
readonly success: Scalars["Boolean"];
/** Human-readable string that describes the result of the mutation */
readonly message: Scalars["String"];
};
export type Resource = {
readonly id: Scalars["ExternalID"];
};
export type ResourceNotFoundError = Error & {
readonly __typename?: "ResourceNotFoundError";
readonly message: Scalars["String"];
};
export type Anything = PublicUser | ProtectedUser | Author | Book;
export type Review = Resource &
Timestampable & {
readonly __typename?: "Review";
readonly id: Scalars["ExternalID"];
readonly author: User;
readonly book: Book;
readonly text?: Maybe<Scalars["String"]>;
readonly rating?: Maybe<Scalars["Int"]>;
readonly createdAt: Scalars["ISODateString"];
readonly updatedAt: Scalars["ISODateString"];
};
export type CreateReviewInput = {
readonly bookId: Scalars["ExternalID"];
readonly text: Scalars["String"];
readonly rating: Scalars["Int"];
};
export type Avatar = {
readonly __typename?: "Avatar";
readonly image: Image;
readonly color: Scalars["String"];
};
export type FlaggedAvatarError = Error & {
readonly __typename?: "FlaggedAvatarError";
readonly message: Scalars["String"];
};
export type AvatarResult = Avatar | FlaggedAvatarError;
export type AvatarInput = {
readonly imagePath: Scalars["String"];
readonly color: Scalars["String"];
};
export type CreateUserInput = {
readonly name: Scalars["String"];
readonly info: Scalars["String"];
readonly email: Scalars["String"];
readonly password: Scalars["String"];
readonly avatar: AvatarInput;
};
export type UpdateUserInput = {
readonly id: Scalars["ExternalID"];
readonly name: Scalars["String"];
readonly email: Scalars["String"];
readonly info: Scalars["String"];
};
export type CreateUserResult = MutationResponse & {
readonly __typename?: "CreateUserResult";
readonly success: Scalars["Boolean"];
readonly message: Scalars["String"];
readonly user?: Maybe<User>;
};
export type DeleteUserResult = MutationResponse & {
readonly __typename?: "DeleteUserResult";
readonly success: Scalars["Boolean"];
readonly message: Scalars["String"];
};
export type UserResult = PublicUser | ProtectedUser | ResourceNotFoundError;
export type UpdateUserResult =
| ProtectedUser
| ResourceNotFoundError
| ValidationErrors;
export type ResolverTypeWrapper<T> = Promise<T> | T;
export type Resolver<
TResult,
TParent = {},
TContext = {},
TArgs = {}
> = ResolverFn<TResult, TParent, TContext, TArgs>;
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<
TResult,
TKey extends string,
TParent,
TContext,
TArgs
> {
subscribe: SubscriptionSubscribeFn<
{ [key in TKey]: TResult },
TParent,
TContext,
TArgs
>;
resolve?: SubscriptionResolveFn<
TResult,
{ [key in TKey]: TResult },
TContext,
TArgs
>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<
TResult,
TKey extends string,
TParent,
TContext,
TArgs
> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<
TResult,
TKey extends string,
TParent = {},
TContext = {},
TArgs = {}
> =
| ((
...args: any[]
) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
export type IsTypeOfResolverFn<T = {}, TContext = {}> = (
obj: T,
context: TContext,
info: GraphQLResolveInfo
) => boolean | Promise<boolean>;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<
TResult = {},
TParent = {},
TContext = {},
TArgs = {}
> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
RegistrationInput: RegistrationInput;
String: ResolverTypeWrapper<Scalars["String"]>;
RegistrationResult:
| ResolversTypes["ProtectedUser"]
| ResolversTypes["ValidationErrors"];
UpdateProfileInput: UpdateProfileInput;
UpdateProfileResult:
| ResolversTypes["ProtectedUser"]
| ResolversTypes["ValidationErrors"];
Query: ResolverTypeWrapper<{}>;
Int: ResolverTypeWrapper<Scalars["Int"]>;
ID: ResolverTypeWrapper<Scalars["ID"]>;
Mutation: ResolverTypeWrapper<{}>;
Boolean: ResolverTypeWrapper<Scalars["Boolean"]>;
Role: Role;
LoginInput: LoginInput;
LoginSuccess: ResolverTypeWrapper<
Omit<LoginSuccess, "currentUser"> & {
currentUser: ResolversTypes["ProtectedUser"];
}
>;
LoginFailure: ResolverTypeWrapper<LoginFailure>;
LoginResult: ResolversTypes["LoginSuccess"] | ResolversTypes["LoginFailure"];
Author: ResolverTypeWrapper<AuthorEntity>;
Book: ResolverTypeWrapper<BookEntity>;
Float: ResolverTypeWrapper<Scalars["Float"]>;
AuthorResponse:
| ResolversTypes["Author"]
| ResolversTypes["ResourceNotFoundError"];
BookCopy: ResolverTypeWrapper<BookCopyEntity>;
User: ResolversTypes["PublicUser"] | ResolversTypes["ProtectedUser"];
PublicUser: ResolverTypeWrapper<UserEntity>;
ProtectedUser: ResolverTypeWrapper<UserEntity>;
UpdateBookFavouriteResult:
| ResolversTypes["Book"]
| ResolversTypes["MutationError"];
BorrowBookCopyResult:
| ResolversTypes["BookCopy"]
| ResolversTypes["MutationError"];
ReturnBookCopyResult:
| ResolversTypes["BookCopy"]
| ResolversTypes["MutationError"];
BookResult: ResolversTypes["Book"] | ResolversTypes["ResourceNotFoundError"];
Subscription: ResolverTypeWrapper<{}>;
ExternalID: ResolverTypeWrapper<Scalars["ExternalID"]>;
ISODateString: ResolverTypeWrapper<Scalars["ISODateString"]>;
Timestampable:
| ResolversTypes["Author"]
| ResolversTypes["Book"]
| ResolversTypes["BookCopy"]
| ResolversTypes["PublicUser"]
| ResolversTypes["ProtectedUser"]
| ResolversTypes["Review"];
Image: ResolverTypeWrapper<Image>;
Error:
| ResolversTypes["MutationError"]
| ResolversTypes["ValidationError"]
| ResolversTypes["ResourceNotFoundError"]
| ResolversTypes["FlaggedAvatarError"];
MutationError: ResolverTypeWrapper<MutationError>;
ValidationError: ResolverTypeWrapper<ValidationError>;
ValidationErrors: ResolverTypeWrapper<ValidationErrors>;
MutationResponse:
| ResolversTypes["CreateUserResult"]
| ResolversTypes["DeleteUserResult"];
Resource:
| ResolversTypes["Author"]
| ResolversTypes["Book"]
| ResolversTypes["PublicUser"]
| ResolversTypes["ProtectedUser"]
| ResolversTypes["Review"];
ResourceNotFoundError: ResolverTypeWrapper<ResourceNotFoundError>;
Anything:
| ResolversTypes["PublicUser"]
| ResolversTypes["ProtectedUser"]
| ResolversTypes["Author"]
| ResolversTypes["Book"];
Review: ResolverTypeWrapper<ReviewEntity>;
CreateReviewInput: CreateReviewInput;
Avatar: ResolverTypeWrapper<AvatarEntity>;
FlaggedAvatarError: ResolverTypeWrapper<FlaggedAvatarError>;
AvatarResult: ResolversTypes["Avatar"] | ResolversTypes["FlaggedAvatarError"];
AvatarInput: AvatarInput;
CreateUserInput: CreateUserInput;
UpdateUserInput: UpdateUserInput;
CreateUserResult: ResolverTypeWrapper<
Omit<CreateUserResult, "user"> & { user?: Maybe<ResolversTypes["User"]> }
>;
DeleteUserResult: ResolverTypeWrapper<DeleteUserResult>;
UserResult:
| ResolversTypes["PublicUser"]
| ResolversTypes["ProtectedUser"]
| ResolversTypes["ResourceNotFoundError"];
UpdateUserResult:
| ResolversTypes["ProtectedUser"]
| ResolversTypes["ResourceNotFoundError"]
| ResolversTypes["ValidationErrors"];
};
/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
RegistrationInput: RegistrationInput;
String: Scalars["String"];
RegistrationResult:
| ResolversParentTypes["ProtectedUser"]
| ResolversParentTypes["ValidationErrors"];
UpdateProfileInput: UpdateProfileInput;
UpdateProfileResult:
| ResolversParentTypes["ProtectedUser"]
| ResolversParentTypes["ValidationErrors"];
Query: {};
Int: Scalars["Int"];
ID: Scalars["ID"];
Mutation: {};
Boolean: Scalars["Boolean"];
LoginInput: LoginInput;
LoginSuccess: Omit<LoginSuccess, "currentUser"> & {
currentUser: ResolversParentTypes["ProtectedUser"];
};
LoginFailure: LoginFailure;
LoginResult:
| ResolversParentTypes["LoginSuccess"]
| ResolversParentTypes["LoginFailure"];
Author: AuthorEntity;
Book: BookEntity;
Float: Scalars["Float"];
AuthorResponse:
| ResolversParentTypes["Author"]
| ResolversParentTypes["ResourceNotFoundError"];
BookCopy: BookCopyEntity;
User:
| ResolversParentTypes["PublicUser"]
| ResolversParentTypes["ProtectedUser"];
PublicUser: UserEntity;
ProtectedUser: UserEntity;
UpdateBookFavouriteResult:
| ResolversParentTypes["Book"]
| ResolversParentTypes["MutationError"];
BorrowBookCopyResult:
| ResolversParentTypes["BookCopy"]
| ResolversParentTypes["MutationError"];
ReturnBookCopyResult:
| ResolversParentTypes["BookCopy"]
| ResolversParentTypes["MutationError"];
BookResult:
| ResolversParentTypes["Book"]
| ResolversParentTypes["ResourceNotFoundError"];
Subscription: {};
ExternalID: Scalars["ExternalID"];
ISODateString: Scalars["ISODateString"];
Timestampable:
| ResolversParentTypes["Author"]
| ResolversParentTypes["Book"]
| ResolversParentTypes["BookCopy"]
| ResolversParentTypes["PublicUser"]
| ResolversParentTypes["ProtectedUser"]
| ResolversParentTypes["Review"];
Image: Image;
Error:
| ResolversParentTypes["MutationError"]
| ResolversParentTypes["ValidationError"]
| ResolversParentTypes["ResourceNotFoundError"]
| ResolversParentTypes["FlaggedAvatarError"];
MutationError: MutationError;
ValidationError: ValidationError;
ValidationErrors: ValidationErrors;
MutationResponse:
| ResolversParentTypes["CreateUserResult"]
| ResolversParentTypes["DeleteUserResult"];
Resource:
| ResolversParentTypes["Author"]
| ResolversParentTypes["Book"]
| ResolversParentTypes["PublicUser"]
| ResolversParentTypes["ProtectedUser"]
| ResolversParentTypes["Review"];
ResourceNotFoundError: ResourceNotFoundError;
Anything:
| ResolversParentTypes["PublicUser"]
| ResolversParentTypes["ProtectedUser"]
| ResolversParentTypes["Author"]
| ResolversParentTypes["Book"];
Review: ReviewEntity;
CreateReviewInput: CreateReviewInput;
Avatar: AvatarEntity;
FlaggedAvatarError: FlaggedAvatarError;
AvatarResult:
| ResolversParentTypes["Avatar"]
| ResolversParentTypes["FlaggedAvatarError"];
AvatarInput: AvatarInput;
CreateUserInput: CreateUserInput;
UpdateUserInput: UpdateUserInput;
CreateUserResult: Omit<CreateUserResult, "user"> & {
user?: Maybe<ResolversParentTypes["User"]>;
};
DeleteUserResult: DeleteUserResult;
UserResult:
| ResolversParentTypes["PublicUser"]
| ResolversParentTypes["ProtectedUser"]
| ResolversParentTypes["ResourceNotFoundError"];
UpdateUserResult:
| ResolversParentTypes["ProtectedUser"]
| ResolversParentTypes["ResourceNotFoundError"]
| ResolversParentTypes["ValidationErrors"];
};
export type RequireAuthorizationDirectiveArgs = { role?: Maybe<Role> };
export type RequireAuthorizationDirectiveResolver<
Result,
Parent,
ContextType = Context,
Args = RequireAuthorizationDirectiveArgs
> = DirectiveResolverFn<Result, Parent, ContextType, Args>;
export type RegistrationResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["RegistrationResult"] = ResolversParentTypes["RegistrationResult"]
> = {
__resolveType?: TypeResolveFn<
"ProtectedUser" | "ValidationErrors",
ParentType,
ContextType
>;
};
export type UpdateProfileResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["UpdateProfileResult"] = ResolversParentTypes["UpdateProfileResult"]
> = {
__resolveType?: TypeResolveFn<
"ProtectedUser" | "ValidationErrors",
ParentType,
ContextType
>;
};
export type QueryResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Query"] = ResolversParentTypes["Query"]
> = {
currentUser?: Resolver<
Maybe<ResolversTypes["ProtectedUser"]>,
ParentType,
ContextType
>;
authors?: Resolver<
ReadonlyArray<ResolversTypes["Author"]>,
ParentType,
ContextType
>;
author?: Resolver<
ResolversTypes["AuthorResponse"],
ParentType,
ContextType,
RequireFields<QueryAuthorArgs, "id">
>;
booksCount?: Resolver<ResolversTypes["Int"], ParentType, ContextType>;
books?: Resolver<
ReadonlyArray<ResolversTypes["Book"]>,
ParentType,
ContextType,
RequireFields<QueryBooksArgs, "offset" | "limit">
>;
book?: Resolver<
ResolversTypes["BookResult"],
ParentType,
ContextType,
RequireFields<QueryBookArgs, "id">
>;
randomBook?: Resolver<Maybe<ResolversTypes["Book"]>, ParentType, ContextType>;
resources?: Resolver<
ReadonlyArray<ResolversTypes["Resource"]>,
ParentType,
ContextType
>;
resource?: Resolver<
ResolversTypes["Resource"],
ParentType,
ContextType,
RequireFields<QueryResourceArgs, "id">
>;
anything?: Resolver<
ResolversTypes["Anything"],
ParentType,
ContextType,
RequireFields<QueryAnythingArgs, "id">
>;
users?: Resolver<
ReadonlyArray<ResolversTypes["User"]>,
ParentType,
ContextType
>;
user?: Resolver<
ResolversTypes["UserResult"],
ParentType,
ContextType,
RequireFields<QueryUserArgs, "id">
>;
};
export type MutationResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Mutation"] = ResolversParentTypes["Mutation"]
> = {
register?: Resolver<
ResolversTypes["RegistrationResult"],
ParentType,
ContextType,
RequireFields<MutationRegisterArgs, "input">
>;
updateProfile?: Resolver<
ResolversTypes["UpdateProfileResult"],
ParentType,
AuthenticatedContext,
RequireFields<MutationUpdateProfileArgs, "input">
>;
login?: Resolver<
ResolversTypes["LoginResult"],
ParentType,
ContextType,
RequireFields<MutationLoginArgs, "input">
>;
logout?: Resolver<ResolversTypes["Boolean"], ParentType, ContextType>;
addBookToFavourites?: Resolver<
ResolversTypes["BookResult"],
ParentType,
AuthenticatedContext,
RequireFields<MutationAddBookToFavouritesArgs, "id">
>;
removeBookFromFavourites?: Resolver<
ResolversTypes["BookResult"],
ParentType,
AuthenticatedContext,
RequireFields<MutationRemoveBookFromFavouritesArgs, "id">
>;
borrowBookCopy?: Resolver<
ResolversTypes["BorrowBookCopyResult"],
ParentType,
AuthenticatedContext,
RequireFields<MutationBorrowBookCopyArgs, "id">
>;
returnBookCopy?: Resolver<
ResolversTypes["ReturnBookCopyResult"],
ParentType,
AuthenticatedContext,
RequireFields<MutationReturnBookCopyArgs, "id">
>;
createReview?: Resolver<
ResolversTypes["Review"],
ParentType,
AuthenticatedContext,
RequireFields<MutationCreateReviewArgs, "input">
>;
createUser?: Resolver<
ResolversTypes["CreateUserResult"],
ParentType,
ContextType,
RequireFields<MutationCreateUserArgs, "input">
>;
updateUser?: Resolver<
ResolversTypes["UpdateUserResult"],
ParentType,
ContextType,
RequireFields<MutationUpdateUserArgs, "input">
>;
deleteUser?: Resolver<
ResolversTypes["DeleteUserResult"],
ParentType,
ContextType,
RequireFields<MutationDeleteUserArgs, "id">
>;
};
export type LoginSuccessResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["LoginSuccess"] = ResolversParentTypes["LoginSuccess"]
> = {
currentUser?: Resolver<
ResolversTypes["ProtectedUser"],
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type LoginFailureResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["LoginFailure"] = ResolversParentTypes["LoginFailure"]
> = {
validationErrors?: Resolver<
ReadonlyArray<ResolversTypes["ValidationError"]>,
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type LoginResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["LoginResult"] = ResolversParentTypes["LoginResult"]
> = {
__resolveType?: TypeResolveFn<
"LoginSuccess" | "LoginFailure",
ParentType,
ContextType
>;
};
export type AuthorResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Author"] = ResolversParentTypes["Author"]
> = {
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
name?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
bio?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
photo?: Resolver<ResolversTypes["Image"], ParentType, ContextType>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
books?: Resolver<
ReadonlyArray<ResolversTypes["Book"]>,
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type BookResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Book"] = ResolversParentTypes["Book"]
> = {
author?: Resolver<ResolversTypes["Author"], ParentType, ContextType>;
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
title?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
description?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
cover?: Resolver<ResolversTypes["Image"], ParentType, ContextType>;
copies?: Resolver<
ReadonlyArray<ResolversTypes["BookCopy"]>,
ParentType,
ContextType
>;
isFavourite?: Resolver<
Maybe<ResolversTypes["Boolean"]>,
ParentType,
ContextType
>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
reviews?: Resolver<
ReadonlyArray<ResolversTypes["Review"]>,
ParentType,
ContextType
>;
reviewsCount?: Resolver<ResolversTypes["Int"], ParentType, ContextType>;
averageRating?: Resolver<
Maybe<ResolversTypes["Float"]>,
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AuthorResponseResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["AuthorResponse"] = ResolversParentTypes["AuthorResponse"]
> = {
__resolveType?: TypeResolveFn<
"Author" | "ResourceNotFoundError",
ParentType,
ContextType
>;
};
export type BookCopyResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["BookCopy"] = ResolversParentTypes["BookCopy"]
> = {
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
book?: Resolver<ResolversTypes["Book"], ParentType, ContextType>;
borrowedAt?: Resolver<
Maybe<ResolversTypes["ISODateString"]>,
ParentType,
ContextType
>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
owner?: Resolver<ResolversTypes["User"], ParentType, ContextType>;
borrower?: Resolver<Maybe<ResolversTypes["User"]>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UserResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["User"] = ResolversParentTypes["User"]
> = {
__resolveType?: TypeResolveFn<
"PublicUser" | "ProtectedUser",
ParentType,
ContextType
>;
ownedBookCopies?: Resolver<
ReadonlyArray<ResolversTypes["BookCopy"]>,
ParentType,
ContextType
>;
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
name?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
info?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
avatar?: Resolver<ResolversTypes["AvatarResult"], ParentType, ContextType>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
};
export type PublicUserResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["PublicUser"] = ResolversParentTypes["PublicUser"]
> = {
ownedBookCopies?: Resolver<
ReadonlyArray<ResolversTypes["BookCopy"]>,
ParentType,
ContextType
>;
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
name?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
info?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
avatar?: Resolver<ResolversTypes["AvatarResult"], ParentType, ContextType>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type ProtectedUserResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["ProtectedUser"] = ResolversParentTypes["ProtectedUser"]
> = {
ownedBookCopies?: Resolver<
ReadonlyArray<ResolversTypes["BookCopy"]>,
ParentType,
ContextType
>;
borrowedBookCopies?: Resolver<
ReadonlyArray<ResolversTypes["BookCopy"]>,
ParentType,
ContextType
>;
favouriteBooks?: Resolver<
ReadonlyArray<ResolversTypes["Book"]>,
ParentType,
ContextType
>;
reviews?: Resolver<
ReadonlyArray<ResolversTypes["Review"]>,
ParentType,
ContextType
>;
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
name?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
info?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
avatar?: Resolver<ResolversTypes["AvatarResult"], ParentType, ContextType>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
email?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
isAdmin?: Resolver<ResolversTypes["Boolean"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UpdateBookFavouriteResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["UpdateBookFavouriteResult"] = ResolversParentTypes["UpdateBookFavouriteResult"]
> = {
__resolveType?: TypeResolveFn<
"Book" | "MutationError",
ParentType,
ContextType
>;
};
export type BorrowBookCopyResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["BorrowBookCopyResult"] = ResolversParentTypes["BorrowBookCopyResult"]
> = {
__resolveType?: TypeResolveFn<
"BookCopy" | "MutationError",
ParentType,
ContextType
>;
};
export type ReturnBookCopyResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["ReturnBookCopyResult"] = ResolversParentTypes["ReturnBookCopyResult"]
> = {
__resolveType?: TypeResolveFn<
"BookCopy" | "MutationError",
ParentType,
ContextType
>;
};
export type BookResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["BookResult"] = ResolversParentTypes["BookResult"]
> = {
__resolveType?: TypeResolveFn<
"Book" | "ResourceNotFoundError",
ParentType,
ContextType
>;
};
export type SubscriptionResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Subscription"] = ResolversParentTypes["Subscription"]
> = {
bookCopyUpdated?: SubscriptionResolver<
ResolversTypes["BookCopy"],
"bookCopyUpdated",
ParentType,
ContextType,
RequireFields<SubscriptionBookCopyUpdatedArgs, "id">
>;
};
export interface ExternalIdScalarConfig
extends GraphQLScalarTypeConfig<ResolversTypes["ExternalID"], any> {
name: "ExternalID";
}
export interface IsoDateStringScalarConfig
extends GraphQLScalarTypeConfig<ResolversTypes["ISODateString"], any> {
name: "ISODateString";
}
export type TimestampableResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Timestampable"] = ResolversParentTypes["Timestampable"]
> = {
__resolveType?: TypeResolveFn<
"Author" | "Book" | "BookCopy" | "PublicUser" | "ProtectedUser" | "Review",
ParentType,
ContextType
>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
};
export type ImageResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Image"] = ResolversParentTypes["Image"]
> = {
path?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
url?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type ErrorResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Error"] = ResolversParentTypes["Error"]
> = {
__resolveType?: TypeResolveFn<
| "MutationError"
| "ValidationError"
| "ResourceNotFoundError"
| "FlaggedAvatarError",
ParentType,
ContextType
>;
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
};
export type MutationErrorResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["MutationError"] = ResolversParentTypes["MutationError"]
> = {
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type ValidationErrorResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["ValidationError"] = ResolversParentTypes["ValidationError"]
> = {
path?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type ValidationErrorsResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["ValidationErrors"] = ResolversParentTypes["ValidationErrors"]
> = {
errors?: Resolver<
ReadonlyArray<ResolversTypes["ValidationError"]>,
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type MutationResponseResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["MutationResponse"] = ResolversParentTypes["MutationResponse"]
> = {
__resolveType?: TypeResolveFn<
"CreateUserResult" | "DeleteUserResult",
ParentType,
ContextType
>;
success?: Resolver<ResolversTypes["Boolean"], ParentType, ContextType>;
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
};
export type ResourceResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Resource"] = ResolversParentTypes["Resource"]
> = {
__resolveType?: TypeResolveFn<
"Author" | "Book" | "PublicUser" | "ProtectedUser" | "Review",
ParentType,
ContextType
>;
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
};
export type ResourceNotFoundErrorResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["ResourceNotFoundError"] = ResolversParentTypes["ResourceNotFoundError"]
> = {
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AnythingResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Anything"] = ResolversParentTypes["Anything"]
> = {
__resolveType?: TypeResolveFn<
"PublicUser" | "ProtectedUser" | "Author" | "Book",
ParentType,
ContextType
>;
};
export type ReviewResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Review"] = ResolversParentTypes["Review"]
> = {
id?: Resolver<ResolversTypes["ExternalID"], ParentType, ContextType>;
author?: Resolver<ResolversTypes["User"], ParentType, ContextType>;
book?: Resolver<ResolversTypes["Book"], ParentType, ContextType>;
text?: Resolver<Maybe<ResolversTypes["String"]>, ParentType, ContextType>;
rating?: Resolver<Maybe<ResolversTypes["Int"]>, ParentType, ContextType>;
createdAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
updatedAt?: Resolver<
ResolversTypes["ISODateString"],
ParentType,
ContextType
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AvatarResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["Avatar"] = ResolversParentTypes["Avatar"]
> = {
image?: Resolver<ResolversTypes["Image"], ParentType, ContextType>;
color?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type FlaggedAvatarErrorResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["FlaggedAvatarError"] = ResolversParentTypes["FlaggedAvatarError"]
> = {
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AvatarResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["AvatarResult"] = ResolversParentTypes["AvatarResult"]
> = {
__resolveType?: TypeResolveFn<
"Avatar" | "FlaggedAvatarError",
ParentType,
ContextType
>;
};
export type CreateUserResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["CreateUserResult"] = ResolversParentTypes["CreateUserResult"]
> = {
success?: Resolver<ResolversTypes["Boolean"], ParentType, ContextType>;
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes["User"]>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DeleteUserResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["DeleteUserResult"] = ResolversParentTypes["DeleteUserResult"]
> = {
success?: Resolver<ResolversTypes["Boolean"], ParentType, ContextType>;
message?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UserResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["UserResult"] = ResolversParentTypes["UserResult"]
> = {
__resolveType?: TypeResolveFn<
"PublicUser" | "ProtectedUser" | "ResourceNotFoundError",
ParentType,
ContextType
>;
};
export type UpdateUserResultResolvers<
ContextType = Context,
ParentType extends ResolversParentTypes["UpdateUserResult"] = ResolversParentTypes["UpdateUserResult"]
> = {
__resolveType?: TypeResolveFn<
"ProtectedUser" | "ResourceNotFoundError" | "ValidationErrors",
ParentType,
ContextType
>;
};
export type Resolvers<ContextType = Context> = {
RegistrationResult?: RegistrationResultResolvers<ContextType>;
UpdateProfileResult?: UpdateProfileResultResolvers<ContextType>;
Query?: QueryResolvers<ContextType>;
Mutation?: MutationResolvers<ContextType>;
LoginSuccess?: LoginSuccessResolvers<ContextType>;
LoginFailure?: LoginFailureResolvers<ContextType>;
LoginResult?: LoginResultResolvers<ContextType>;
Author?: AuthorResolvers<ContextType>;
Book?: BookResolvers<ContextType>;
AuthorResponse?: AuthorResponseResolvers<ContextType>;
BookCopy?: BookCopyResolvers<ContextType>;
User?: UserResolvers<ContextType>;
PublicUser?: PublicUserResolvers<ContextType>;
ProtectedUser?: ProtectedUserResolvers<ContextType>;
UpdateBookFavouriteResult?: UpdateBookFavouriteResultResolvers<ContextType>;
BorrowBookCopyResult?: BorrowBookCopyResultResolvers<ContextType>;
ReturnBookCopyResult?: ReturnBookCopyResultResolvers<ContextType>;
BookResult?: BookResultResolvers<ContextType>;
Subscription?: SubscriptionResolvers<ContextType>;
ExternalID?: GraphQLScalarType;
ISODateString?: GraphQLScalarType;
Timestampable?: TimestampableResolvers<ContextType>;
Image?: ImageResolvers<ContextType>;
Error?: ErrorResolvers<ContextType>;
MutationError?: MutationErrorResolvers<ContextType>;
ValidationError?: ValidationErrorResolvers<ContextType>;
ValidationErrors?: ValidationErrorsResolvers<ContextType>;
MutationResponse?: MutationResponseResolvers<ContextType>;
Resource?: ResourceResolvers<ContextType>;
ResourceNotFoundError?: ResourceNotFoundErrorResolvers<ContextType>;
Anything?: AnythingResolvers<ContextType>;
Review?: ReviewResolvers<ContextType>;
Avatar?: AvatarResolvers<ContextType>;
FlaggedAvatarError?: FlaggedAvatarErrorResolvers<ContextType>;
AvatarResult?: AvatarResultResolvers<ContextType>;
CreateUserResult?: CreateUserResultResolvers<ContextType>;
DeleteUserResult?: DeleteUserResultResolvers<ContextType>;
UserResult?: UserResultResolvers<ContextType>;
UpdateUserResult?: UpdateUserResultResolvers<ContextType>;
};
/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = Context> = Resolvers<ContextType>;
export type DirectiveResolvers<ContextType = Context> = {
requireAuthorization?: RequireAuthorizationDirectiveResolver<
any,
any,
ContextType
>;
};
/**
* @deprecated
* Use "DirectiveResolvers" root object instead. If you wish to get "IDirectiveResolvers", add "typesPrefix: I" to your config.
*/
export type IDirectiveResolvers<ContextType = Context> = DirectiveResolvers<
ContextType
>; | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the Project class.
* @constructor
* Azure Migrate Project.
*
* @member {string} [id] Path reference to this project
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}
* @member {string} [name] Name of the project.
* @member {string} [type] Type of the object = [Microsoft.Migrate/projects].
* @member {string} [eTag] For optimistic concurrency control.
* @member {string} [location] Azure location in which project is created.
* @member {object} [tags] Tags provided by Azure Tagging service.
* @member {date} [createdTimestamp] Time when this project was created.
* Date-Time represented in ISO-8601 format.
* @member {date} [updatedTimestamp] Time when this project was last updated.
* Date-Time represented in ISO-8601 format.
* @member {string} [discoveryStatus] Reports whether project is under
* discovery. Possible values include: 'Unknown', 'NotStarted', 'InProgress',
* 'Completed'
* @member {string} [customerWorkspaceId] ARM ID of the Service Map workspace
* created by user.
* @member {string} [customerWorkspaceLocation] Location of the Service Map
* workspace created by user.
* @member {date} [lastDiscoveryTimestamp] Time when this project was created.
* Date-Time represented in ISO-8601 format. This value will be null until
* discovery is complete.
* @member {string} [lastDiscoverySessionId] Session id of the last discovery.
* @member {number} [numberOfGroups] Number of groups created in the project.
* @member {number} [numberOfMachines] Number of machines in the project.
* @member {number} [numberOfAssessments] Number of assessments created in the
* project.
* @member {date} [lastAssessmentTimestamp] Time when last assessment was
* created. Date-Time represented in ISO-8601 format. This value will be null
* until assessment is created.
* @member {string} [provisioningState] Provisioning state of the project.
* Possible values include: 'Accepted', 'Creating', 'Deleting', 'Failed',
* 'Moving', 'Succeeded'
*/
export interface Project extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
eTag?: string;
location?: string;
tags?: any;
readonly createdTimestamp?: Date;
readonly updatedTimestamp?: Date;
readonly discoveryStatus?: string;
customerWorkspaceId?: string;
customerWorkspaceLocation?: string;
readonly lastDiscoveryTimestamp?: Date;
readonly lastDiscoverySessionId?: string;
readonly numberOfGroups?: number;
readonly numberOfMachines?: number;
readonly numberOfAssessments?: number;
readonly lastAssessmentTimestamp?: Date;
provisioningState?: string;
}
/**
* @class
* Initializes a new instance of the Group class.
* @constructor
* A group created in a Migration project.
*
* @member {string} [id] Path reference to this group.
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/groups/{groupName}
* @member {string} [name] Name of the group.
* @member {string} [eTag] For optimistic concurrency control.
* @member {string} [type] Type of the object =
* [Microsoft.Migrate/projects/groups].
* @member {array} machines List of machine names that are part of this group.
* @member {array} [assessments] List of References to Assessments created on
* this group.
* @member {date} [createdTimestamp] Time when this project was created.
* Date-Time represented in ISO-8601 format.
* @member {date} [updatedTimestamp] Time when this project was last updated.
* Date-Time represented in ISO-8601 format.
*/
export interface Group extends BaseResource {
readonly id?: string;
readonly name?: string;
eTag?: string;
readonly type?: string;
machines: string[];
readonly assessments?: string[];
readonly createdTimestamp?: Date;
readonly updatedTimestamp?: Date;
}
/**
* @class
* Initializes a new instance of the Assessment class.
* @constructor
* An assessment created for a group in the Migration project.
*
* @member {string} [id] Path reference to this assessment.
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/groups/{groupName}/assessment/{assessmentName}
* @member {string} [name] Unique name of an assessment.
* @member {string} [eTag] For optimistic concurrency control.
* @member {string} [type] Type of the object =
* [Microsoft.Migrate/projects/groups/assessments].
* @member {string} azureLocation Target Azure location for which the machines
* should be assessed. These enums are the same as used by Compute API.
* Possible values include: 'Unknown', 'EastAsia', 'SoutheastAsia',
* 'AustraliaEast', 'AustraliaSoutheast', 'BrazilSouth', 'CanadaCentral',
* 'CanadaEast', 'WestEurope', 'NorthEurope', 'CentralIndia', 'SouthIndia',
* 'WestIndia', 'JapanEast', 'JapanWest', 'KoreaCentral', 'KoreaSouth',
* 'UkWest', 'UkSouth', 'NorthCentralUs', 'EastUs', 'WestUs2',
* 'SouthCentralUs', 'CentralUs', 'EastUs2', 'WestUs', 'WestCentralUs',
* 'GermanyCentral', 'GermanyNortheast', 'ChinaNorth', 'ChinaEast'
* @member {string} azureOfferCode Offer code according to which cost
* estimation is done. Possible values include: 'Unknown', 'MSAZR0003P',
* 'MSAZR0044P', 'MSAZR0059P', 'MSAZR0060P', 'MSAZR0062P', 'MSAZR0063P',
* 'MSAZR0064P', 'MSAZR0029P', 'MSAZR0022P', 'MSAZR0023P', 'MSAZR0148P',
* 'MSAZR0025P', 'MSAZR0036P', 'MSAZR0120P', 'MSAZR0121P', 'MSAZR0122P',
* 'MSAZR0123P', 'MSAZR0124P', 'MSAZR0125P', 'MSAZR0126P', 'MSAZR0127P',
* 'MSAZR0128P', 'MSAZR0129P', 'MSAZR0130P', 'MSAZR0111P', 'MSAZR0144P',
* 'MSAZR0149P', 'MSMCAZR0044P', 'MSMCAZR0059P', 'MSMCAZR0060P',
* 'MSMCAZR0063P', 'MSMCAZR0120P', 'MSMCAZR0121P', 'MSMCAZR0125P',
* 'MSMCAZR0128P', 'MSAZRDE0003P', 'MSAZRDE0044P'
* @member {string} azurePricingTier Pricing tier for Size evaluation. Possible
* values include: 'Standard', 'Basic'
* @member {string} azureStorageRedundancy Storage Redundancy type offered by
* Azure. Possible values include: 'Unknown', 'LocallyRedundant',
* 'ZoneRedundant', 'GeoRedundant', 'ReadAccessGeoRedundant'
* @member {number} scalingFactor Scaling factor used over utilization data to
* add a performance buffer for new machines to be created in Azure. Min Value
* = 1.0, Max value = 1.9, Default = 1.3.
* @member {string} percentile Percentile of performance data used to recommend
* Azure size. Possible values include: 'Percentile50', 'Percentile90',
* 'Percentile95', 'Percentile99'
* @member {string} timeRange Time range of performance data used to recommend
* a size. Possible values include: 'Day', 'Week', 'Month'
* @member {string} stage User configurable setting that describes the status
* of the assessment. Possible values include: 'InProgress', 'UnderReview',
* 'Approved'
* @member {string} currency Currency to report prices in. Possible values
* include: 'Unknown', 'USD', 'DKK', 'CAD', 'IDR', 'JPY', 'KRW', 'NZD', 'NOK',
* 'RUB', 'SAR', 'ZAR', 'SEK', 'TRY', 'GBP', 'MXN', 'MYR', 'INR', 'HKD', 'BRL',
* 'TWD', 'EUR', 'CHF', 'ARS', 'AUD', 'CNY'
* @member {string} azureHybridUseBenefit AHUB discount on windows virtual
* machines. Possible values include: 'Unknown', 'Yes', 'No'
* @member {number} discountPercentage Custom discount percentage to be applied
* on final costs. Can be in the range [0, 100].
* @member {number} [confidenceRatingInPercentage] Confidence rating percentage
* for assessment. Can be in the range [0, 100].
* @member {string} sizingCriterion Assessment sizing criterion. Possible
* values include: 'PerformanceBased', 'AsOnPremises'
* @member {date} [pricesTimestamp] Time when the Azure Prices were queried.
* Date-Time represented in ISO-8601 format.
* @member {date} [createdTimestamp] Time when this project was created.
* Date-Time represented in ISO-8601 format.
* @member {date} [updatedTimestamp] Time when this project was last updated.
* Date-Time represented in ISO-8601 format.
* @member {number} [monthlyComputeCost] Monthly compute cost estimate for the
* machines that are part of this assessment as a group, for a 31-day month.
* @member {number} [monthlyBandwidthCost] Monthly network cost estimate for
* the machines that are part of this assessment as a group, for a 31-day
* month.
* @member {number} [monthlyStorageCost] Monthly storage cost estimate for the
* machines that are part of this assessment as a group, for a 31-day month.
* @member {string} [status] Wheter the assessment has been created and is
* valid. Possible values include: 'Created', 'Updated', 'Running',
* 'Completed', 'Invalid'
* @member {number} [numberOfMachines] Number of assessed machines part of this
* assessment.
*/
export interface Assessment extends BaseResource {
readonly id?: string;
readonly name?: string;
eTag?: string;
readonly type?: string;
azureLocation: string;
azureOfferCode: string;
azurePricingTier: string;
azureStorageRedundancy: string;
scalingFactor: number;
percentile: string;
timeRange: string;
stage: string;
currency: string;
azureHybridUseBenefit: string;
discountPercentage: number;
readonly confidenceRatingInPercentage?: number;
sizingCriterion: string;
readonly pricesTimestamp?: Date;
readonly createdTimestamp?: Date;
readonly updatedTimestamp?: Date;
readonly monthlyComputeCost?: number;
readonly monthlyBandwidthCost?: number;
readonly monthlyStorageCost?: number;
readonly status?: string;
readonly numberOfMachines?: number;
}
/**
* @class
* Initializes a new instance of the Disk class.
* @constructor
* A disk discovered on a machine.
*
* @member {number} [gigabytesAllocated] Gigabytes of storage provisioned for
* this disk.
* @member {number} [gigabytesConsumed] Gigabytes of storage consumed by this
* disk.
*/
export interface Disk {
readonly gigabytesAllocated?: number;
readonly gigabytesConsumed?: number;
}
/**
* @class
* Initializes a new instance of the NetworkAdapter class.
* @constructor
* A network adapter discovered on a machine.
*
* @member {string} [macAddress] MAC Address of the network adapter.
* @member {array} [ipAddresses] List of IP Addresses on the network adapter.
*/
export interface NetworkAdapter {
readonly macAddress?: string;
readonly ipAddresses?: string[];
}
/**
* @class
* Initializes a new instance of the Machine class.
* @constructor
* A machine in a migration project.
*
* @member {string} [id] Path reference to this machine.
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/machines/{machineName}
* @member {string} [name] Name of the machine. It is a GUID which is unique
* identifier of machine in private data center. For user-readable name, we
* have a displayName property on this machine.
* @member {string} [eTag] For optimistic concurrency control.
* @member {string} [type] Type of the object =
* [Microsoft.Migrate/projects/machines].
* @member {string} [bootType] Boot type of the machine. Possible values
* include: 'Unknown', 'EFI', 'BIOS'
* @member {string} [datacenterContainer] Container defined in the management
* solution that this machine is part of in the datacenter.
* @member {string} [datacenterManagementServer] Name of the server hosting the
* datacenter management solution.
* @member {string} [datacenterMachineId] ID of the machine as tracked by the
* datacenter management solution.
* @member {string} [datacenterManagementServerId] ID of the server hosting the
* datacenter management solution.
* @member {string} [description] Description of the machine
* @member {string} [displayName] User readable name of the machine as defined
* by the user in their private datacenter.
* @member {number} [megabytesOfMemory] Memory in Megabytes.
* @member {number} [numberOfCores] Processor count.
* @member {string} [operatingSystem] Operating System of the machine.
* @member {array} [groups] List of references to the groups that the machine
* is member of.
* @member {date} [createdTimestamp] Time when this machine was created.
* Date-Time represented in ISO-8601 format.
* @member {date} [updatedTimestamp] Time when this machine was last updated.
* Date-Time represented in ISO-8601 format.
* @member {date} [discoveredTimestamp] Time when this machine was discovered
* by Azure Migrate agent. Date-Time represented in ISO-8601 format.
* @member {object} [disks] Dictionary of disks attached to the machine. Key is
* ID of disk. Value is a disk object
* @member {object} [networkAdapters] Dictionary of network adapters attached
* to the machine. Key is ID of network adapter. Value is a network adapter
* object
*/
export interface Machine extends BaseResource {
readonly id?: string;
readonly name?: string;
eTag?: string;
readonly type?: string;
readonly bootType?: string;
readonly datacenterContainer?: string;
readonly datacenterManagementServer?: string;
readonly datacenterMachineId?: string;
readonly datacenterManagementServerId?: string;
readonly description?: string;
readonly displayName?: string;
readonly megabytesOfMemory?: number;
readonly numberOfCores?: number;
readonly operatingSystem?: string;
readonly groups?: string[];
readonly createdTimestamp?: Date;
readonly updatedTimestamp?: Date;
readonly discoveredTimestamp?: Date;
readonly disks?: { [propertyName: string]: Disk };
readonly networkAdapters?: { [propertyName: string]: NetworkAdapter };
}
/**
* @class
* Initializes a new instance of the AssessedDisk class.
* @constructor
* A disk assessed for an assessment.
*
* @member {string} [name] Name of the assessed disk.
* @member {number} [gigabytesProvisioned] Gigabytes of storage provisioned for
* this disk.
* @member {number} [gigabytesConsumed] Gigabytes of storage consumed by this
* disk.
* @member {number} [megabytesPerSecondOfRead] Disk throughput in MegaBytes per
* second.
* @member {number} [megabytesPerSecondOfReadDataPointsExpected] Expected data
* points for MegaBytes per second of read.
* @member {number} [megabytesPerSecondOfReadDataPointsReceived] Received data
* points for MegaBytes per second of read.
* @member {number} [megabytesPerSecondOfWrite] Disk throughput in MegaBytes
* per second.
* @member {number} [megabytesPerSecondOfWriteDataPointsExpected] Expected data
* points for MegaBytes per second of write.
* @member {number} [megabytesPerSecondOfWriteDataPointsReceived] Received data
* points for MegaBytes per second of write.
* @member {number} [numberOfReadOperationsPerSecond] Number of read operations
* per second for the disk.
* @member {number} [numberOfReadOperationsPerSecondDataPointsExpected]
* Expected number of data points for read operations per second.
* @member {number} [numberOfReadOperationsPerSecondDataPointsReceived]
* Received number of data points for read operations per second.
* @member {number} [numberOfWriteOperationsPerSecond] Number of read and write
* operations per second for the disk.
* @member {number} [numberOfWriteOperationsPerSecondDataPointsExpected]
* Expected number of data points for write operations per second.
* @member {number} [numberOfWriteOperationsPerSecondDataPointsReceived]
* Received number of data points for write operations per second.
* @member {number} [monthlyStorageCost] Estimated aggregate storage cost for a
* 31-day month for this disk.
* @member {string} [recommendedDiskType] Storage type selected for this disk.
* Possible values include: 'Unknown', 'Standard', 'Premium'
* @member {string} [recommendedDiskSize] Recommended Azure size for the disk,
* given utilization data and preferences set on Assessment. Possible values
* include: 'Unknown', 'Standard_S4', 'Standard_S6', 'Standard_S10',
* 'Standard_S20', 'Standard_S30', 'Standard_S40', 'Standard_S50',
* 'Premium_P4', 'Premium_P6', 'Premium_P10', 'Premium_P20', 'Premium_P30',
* 'Premium_P40', 'Premium_P50'
* @member {number} [gigabytesForRecommendedDiskSize] Gigabytes of storage
* provided by the recommended Azure disk size.
* @member {string} [suitability] Whether this disk is suitable for Azure.
* Possible values include: 'Unknown', 'NotSuitable', 'Suitable',
* 'ConditionallySuitable', 'ReadinessUnknown'
* @member {string} [suitabilityExplanation] If disk is suitable, this explains
* the reasons and mitigation steps. Possible values include: 'Unknown',
* 'NotApplicable', 'DiskSizeGreaterThanSupported',
* 'NoSuitableDiskSizeForIops', 'NoSuitableDiskSizeForThroughput',
* 'NoDiskSizeFoundInSelectedLocation', 'NoDiskSizeFoundForSelectedRedundancy',
* 'InternalErrorOccurredForDiskEvaluation'
*/
export interface AssessedDisk {
readonly name?: string;
readonly gigabytesProvisioned?: number;
readonly gigabytesConsumed?: number;
readonly megabytesPerSecondOfRead?: number;
readonly megabytesPerSecondOfReadDataPointsExpected?: number;
readonly megabytesPerSecondOfReadDataPointsReceived?: number;
readonly megabytesPerSecondOfWrite?: number;
readonly megabytesPerSecondOfWriteDataPointsExpected?: number;
readonly megabytesPerSecondOfWriteDataPointsReceived?: number;
readonly numberOfReadOperationsPerSecond?: number;
readonly numberOfReadOperationsPerSecondDataPointsExpected?: number;
readonly numberOfReadOperationsPerSecondDataPointsReceived?: number;
readonly numberOfWriteOperationsPerSecond?: number;
readonly numberOfWriteOperationsPerSecondDataPointsExpected?: number;
readonly numberOfWriteOperationsPerSecondDataPointsReceived?: number;
readonly monthlyStorageCost?: number;
readonly recommendedDiskType?: string;
readonly recommendedDiskSize?: string;
readonly gigabytesForRecommendedDiskSize?: number;
readonly suitability?: string;
readonly suitabilityExplanation?: string;
}
/**
* @class
* Initializes a new instance of the AssessedNetworkAdapter class.
* @constructor
* A network adapter assessed for an assessment.
*
* @member {string} [macAddress] MAC Address of the network adapter.
* @member {array} [ipAddresses] List of IP Addresses on the network adapter.
* @member {number} [monthlyBandwidthCosts] Monthly cost estimate for network
* bandwidth used by this network adapter.
* @member {number} [megabytesPerSecondReceived] Adapter throughput for
* incoming traffic in MegaBytes per second.
* @member {number} [megabytesPerSecondReceivedDataPointsExpected] Expected
* data points for incoming traffic in MegaBytes per second.
* @member {number} [megabytesPerSecondOfReadDataPointsReceived] Received data
* points for incoming traffic in MegaBytes per second.
* @member {number} [megabytesPerSecondTransmitted] Adapter throughput for
* outgoing traffic in MegaBytes per second.
* @member {number} [megabytesPerSecondTransmittedDataPointsExpected] Expected
* data points for outgoing traffic in MegaBytes per second.
* @member {number} [megabytesPerSecondTransmittedDataPointsReceived] Received
* data points for outgoing traffic in MegaBytes per second.
* @member {number} [netGigabytesTransmittedPerMonth] Gigabytes transmitted
* through this adapter each month.
* @member {string} [suitability] Whether this adapter is suitable for Azure.
* Possible values include: 'Unknown', 'NotSuitable', 'Suitable',
* 'ConditionallySuitable', 'ReadinessUnknown'
* @member {string} [suitabilityExplanation] If network adapter is suitable,
* this explains the reasons and mitigation steps. Possible values include:
* 'Unknown', 'NotApplicable', 'InternalErrorOccured'
*/
export interface AssessedNetworkAdapter {
readonly macAddress?: string;
readonly ipAddresses?: string[];
readonly monthlyBandwidthCosts?: number;
readonly megabytesPerSecondReceived?: number;
readonly megabytesPerSecondReceivedDataPointsExpected?: number;
readonly megabytesPerSecondOfReadDataPointsReceived?: number;
readonly megabytesPerSecondTransmitted?: number;
readonly megabytesPerSecondTransmittedDataPointsExpected?: number;
readonly megabytesPerSecondTransmittedDataPointsReceived?: number;
netGigabytesTransmittedPerMonth?: number;
readonly suitability?: string;
readonly suitabilityExplanation?: string;
}
/**
* @class
* Initializes a new instance of the AssessedMachine class.
* @constructor
* A machine evaluated as part of an assessment.
*
* @member {string} [id] Path reference to this assessed machine.
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/groups/{groupName}/assessments/{assessmentName}/assessedMachines/{assessedMachineName}
* @member {string} [name] Name of the machine.
* @member {string} [eTag] For optimistic concurrency control.
* @member {string} [type] Type of the object =
* [Microsoft.Migrate/projects/groups/assessments/assessedMachines].
* @member {array} [groups] List of references to the groups that the machine
* is member of.
* @member {date} [discoveredTimestamp] Time when this machine was discovered
* by Azure Migrate agent. Date-Time represented in ISO-8601 format.
* @member {string} [bootType] Boot type of the machine. Possible values
* include: 'Unknown', 'EFI', 'BIOS'
* @member {string} [datacenterContainer] Container defined in the management
* solution that this machine is part of in the datacenter.
* @member {string} [datacenterManagementServer] Name of the server hosting the
* datacenter management solution.
* @member {string} [datacenterMachineId] ID of the machine as tracked by the
* datacenter management solution.
* @member {string} [datacenterManagementServerId] ID of the server hosting the
* datacenter management solution.
* @member {string} [description] Description of the machine
* @member {string} [displayName] User readable name of the machine as defined
* by the user in their private datacenter.
* @member {number} [megabytesOfMemory] Memory in Megabytes.
* @member {number} [numberOfCores] Processor count.
* @member {string} [operatingSystem] Operating System of the machine.
* @member {number} [monthlyBandwidthCost] Monthly network cost estimate for
* the network adapters that are attached to this machine as a group, for a
* 31-day month.
* @member {number} [monthlyStorageCost] Monthly storage cost estimate for the
* disks that are attached to this machine as a group, for a 31-day month.
* @member {object} [disks] Dictionary of disks attached to the machine. Key is
* ID of disk. Value is a disk object.
* @member {object} [networkAdapters] Dictionary of network adapters attached
* to the machine. Key is name of the adapter. Value is a network adapter
* object.
* @member {string} [recommendedSize] Recommended Azure size for this machine.
* Possible values include: 'Unknown', 'Basic_A0', 'Basic_A1', 'Basic_A2',
* 'Basic_A3', 'Basic_A4', 'Standard_A0', 'Standard_A1', 'Standard_A2',
* 'Standard_A3', 'Standard_A4', 'Standard_A5', 'Standard_A6', 'Standard_A7',
* 'Standard_A8', 'Standard_A9', 'Standard_A10', 'Standard_A11',
* 'Standard_A1_v2', 'Standard_A2_v2', 'Standard_A4_v2', 'Standard_A8_v2',
* 'Standard_A2m_v2', 'Standard_A4m_v2', 'Standard_A8m_v2', 'Standard_D1',
* 'Standard_D2', 'Standard_D3', 'Standard_D4', 'Standard_D11', 'Standard_D12',
* 'Standard_D13', 'Standard_D14', 'Standard_D1_v2', 'Standard_D2_v2',
* 'Standard_D3_v2', 'Standard_D4_v2', 'Standard_D5_v2', 'Standard_D11_v2',
* 'Standard_D12_v2', 'Standard_D13_v2', 'Standard_D14_v2', 'Standard_D15_v2',
* 'Standard_DS1', 'Standard_DS2', 'Standard_DS3', 'Standard_DS4',
* 'Standard_DS11', 'Standard_DS12', 'Standard_DS13', 'Standard_DS14',
* 'Standard_DS1_v2', 'Standard_DS2_v2', 'Standard_DS3_v2', 'Standard_DS4_v2',
* 'Standard_DS5_v2', 'Standard_DS11_v2', 'Standard_DS12_v2',
* 'Standard_DS13_v2', 'Standard_DS14_v2', 'Standard_DS15_v2', 'Standard_F1',
* 'Standard_F2', 'Standard_F4', 'Standard_F8', 'Standard_F16', 'Standard_F1s',
* 'Standard_F2s', 'Standard_F4s', 'Standard_F8s', 'Standard_F16s',
* 'Standard_G1', 'Standard_G2', 'Standard_G3', 'Standard_G4', 'Standard_G5',
* 'Standard_GS1', 'Standard_GS2', 'Standard_GS3', 'Standard_GS4',
* 'Standard_GS5', 'Standard_H8', 'Standard_H16', 'Standard_H8m',
* 'Standard_H16m', 'Standard_H16r', 'Standard_H16mr', 'Standard_L4s',
* 'Standard_L8s', 'Standard_L16s', 'Standard_L32s'
* @member {number} [numberOfCoresForRecommendedSize] Number of CPU cores in
* the Recommended Azure VM Size.
* @member {number} [megabytesOfMemoryForRecommendedSize] Megabytes of memory
* in the Recommended Azure VM Size.
* @member {number} [monthlyComputeCostForRecommendedSize] Compute Cost for a
* 31-day month, if the machine is migrated to Azure with the Recommended Size.
* @member {number} [percentageCoresUtilization] Utilization percentage of the
* processor core as observed in the private data center, in the Time Range
* selected on Assessment, reported as the Percentile value based on the
* percentile number selected in assessment.
* @member {number} [percentageMemoryUtilization] Utilization percentage of the
* memory as observed in the private data center, in the Time Range selected on
* Assessment, reported as the Percentile value based on the percentile number
* selected in assessment.
* @member {number} [percentageCoresUtilizationDataPointsExpected] Expected
* data points for percentage of cores utilization.
* @member {number} [percentageCoresUtilizationDataPointsReceived] Received
* data points for percentage of cores utilization.
* @member {number} [percentageMemoryUtilizationDataPointsExpected] Expected
* data points for percentage of memory utilization.
* @member {number} [percentageMemoryUtilizationDataPointsReceived] Received
* data points for percentage of memory utilization.
* @member {string} [suitability] Whether machine is suitable for migration to
* Azure. Possible values include: 'Unknown', 'NotSuitable', 'Suitable',
* 'ConditionallySuitable', 'ReadinessUnknown'
* @member {string} [suitabilityExplanation] If machine is not ready to be
* migrated, this explains the reasons and mitigation steps. Possible values
* include: 'Unknown', 'NotApplicable',
* 'GuestOperatingSystemArchitectureNotSupported',
* 'GuestOperatingSystemNotSupported', 'BootTypeNotSupported',
* 'MoreDisksThanSupported', 'NoSuitableVmSizeFound',
* 'OneOrMoreDisksNotSuitable', 'OneOrMoreAdaptersNotSuitable',
* 'InternalErrorOccuredDuringComputeEvaluation',
* 'InternalErrorOccuredDuringStorageEvaluation',
* 'InternalErrorOccuredDuringNetworkEvaluation',
* 'NoVmSizeSupportsStoragePerformance', 'NoVmSizeSupportsNetworkPerformance',
* 'NoVmSizeForSelectedPricingTier', 'NoVmSizeForSelectedAzureLocation',
* 'CheckRedHatLinuxVersion', 'CheckOpenSuseLinuxVersion',
* 'CheckWindowsServer2008R2Version', 'CheckCentOsVersion',
* 'CheckDebianLinuxVersion', 'CheckSuseLinuxVersion',
* 'CheckOracleLinuxVersion', 'CheckUbuntuLinuxVersion',
* 'CheckCoreOsLinuxVersion', 'WindowsServerVersionConditionallySupported',
* 'NoGuestOperatingSystemConditionallySupported',
* 'WindowsClientVersionsConditionallySupported', 'BootTypeUnknown',
* 'GuestOperatingSystemUnknown', 'WindowsServerVersionsSupportedWithCaveat',
* 'WindowsOSNoLongerUnderMSSupport',
* 'EndorsedWithConditionsLinuxDistributions', 'UnendorsedLinuxDistributions',
* 'NoVmSizeForStandardPricingTier', 'NoVmSizeForBasicPricingTier'
* @member {date} [createdTimestamp] Time when this machine was created.
* Date-Time represented in ISO-8601 format.
* @member {date} [updatedTimestamp] Time when this machine was last updated.
* Date-Time represented in ISO-8601 format.
*/
export interface AssessedMachine extends BaseResource {
readonly id?: string;
readonly name?: string;
eTag?: string;
readonly type?: string;
readonly groups?: string[];
readonly discoveredTimestamp?: Date;
readonly bootType?: string;
readonly datacenterContainer?: string;
readonly datacenterManagementServer?: string;
readonly datacenterMachineId?: string;
readonly datacenterManagementServerId?: string;
readonly description?: string;
readonly displayName?: string;
readonly megabytesOfMemory?: number;
readonly numberOfCores?: number;
readonly operatingSystem?: string;
readonly monthlyBandwidthCost?: number;
readonly monthlyStorageCost?: number;
readonly disks?: { [propertyName: string]: AssessedDisk };
readonly networkAdapters?: { [propertyName: string]: AssessedNetworkAdapter };
readonly recommendedSize?: string;
readonly numberOfCoresForRecommendedSize?: number;
readonly megabytesOfMemoryForRecommendedSize?: number;
readonly monthlyComputeCostForRecommendedSize?: number;
readonly percentageCoresUtilization?: number;
readonly percentageMemoryUtilization?: number;
readonly percentageCoresUtilizationDataPointsExpected?: number;
readonly percentageCoresUtilizationDataPointsReceived?: number;
readonly percentageMemoryUtilizationDataPointsExpected?: number;
readonly percentageMemoryUtilizationDataPointsReceived?: number;
readonly suitability?: string;
readonly suitabilityExplanation?: string;
readonly createdTimestamp?: Date;
readonly updatedTimestamp?: Date;
}
/**
* @class
* Initializes a new instance of the ProjectKey class.
* @constructor
* ID and Key for Migration Project.
*
* @member {string} [workspaceId] ID of Migration Project.
* @member {string} [workspaceKey] Key of Migration Project.
*/
export interface ProjectKey extends BaseResource {
readonly workspaceId?: string;
readonly workspaceKey?: string;
}
/**
* @class
* Initializes a new instance of the OperationDisplay class.
* @constructor
* Displayable properties of the operation.
*
* @member {string} [provider] Provider of the operation.
* @member {string} [resource] Resource operated on by the operation.
* @member {string} [operation] Operation Type.
* @member {string} [description] Description of the operation.
*/
export interface OperationDisplay {
readonly provider?: string;
readonly resource?: string;
readonly operation?: string;
readonly description?: string;
}
/**
* @class
* Initializes a new instance of the Operation class.
* @constructor
* A REST API operation supported by the provider.
*
* @member {string} [name] Name of the operation.
* @member {object} [display] Displayable properties of the operation.
* @member {string} [display.provider] Provider of the operation.
* @member {string} [display.resource] Resource operated on by the operation.
* @member {string} [display.operation] Operation Type.
* @member {string} [display.description] Description of the operation.
* @member {string} [origin] Origin of the operation.
*/
export interface Operation {
readonly name?: string;
display?: OperationDisplay;
readonly origin?: string;
}
/**
* @class
* Initializes a new instance of the DownloadUrl class.
* @constructor
* Download URL for assessment report.
*
* @member {string} [assessmentReportUrl] Hyperlink to download report.
* @member {date} [expirationTime] Expiry date of download url.
*/
export interface DownloadUrl {
readonly assessmentReportUrl?: string;
readonly expirationTime?: Date;
}
/**
* @class
* Initializes a new instance of the ProjectResultList class.
* @constructor
* List of projects.
*
*/
export interface ProjectResultList extends Array<Project> {
}
/**
* @class
* Initializes a new instance of the MachineResultList class.
* @constructor
* List of machines.
*
*/
export interface MachineResultList extends Array<Machine> {
}
/**
* @class
* Initializes a new instance of the GroupResultList class.
* @constructor
* List of groups.
*
*/
export interface GroupResultList extends Array<Group> {
}
/**
* @class
* Initializes a new instance of the AssessmentResultList class.
* @constructor
* List of assessments.
*
*/
export interface AssessmentResultList extends Array<Assessment> {
}
/**
* @class
* Initializes a new instance of the AssessedMachineResultList class.
* @constructor
* List of assessed machines.
*
*/
export interface AssessedMachineResultList extends Array<AssessedMachine> {
}
/**
* @class
* Initializes a new instance of the OperationResultList class.
* @constructor
* List of API operations.
*
*/
export interface OperationResultList extends Array<Operation> {
} | the_stack |
import invariant from "invariant";
import {
getSelector,
PluralReaderSelector,
ReaderSelector,
SingularReaderSelector,
} from "relay-runtime";
import type { Disposable, IEnvironment, ReaderFragment } from "relay-runtime";
import recycleNodesInto from "relay-runtime/lib/util/recycleNodesInto";
import { Snapshot, KeyType } from "../types";
export type SingularOrPluralSnapshot<
TData,
TPlural extends boolean = boolean
> = TPlural extends true ? Snapshot<TData>[] : Snapshot<TData>;
export type FragmentResult<TData, TPlural extends boolean = boolean> = {
cacheKey: string;
data: null | (TPlural extends true ? TData[] : TData);
isMissingData: any;
snapshot: SingularOrPluralSnapshot<TData, TPlural> | null;
};
// TODO: Fix to not rely on LRU. If the number of active fragments exceeds this
// capacity, readSpec() will fail to find cached entries and break object
// identity even if data hasn't changed.{
const CACHE_CAPACITY = 1000000;
const createCache = () => {
const cache = {};
return {
get: (key) => cache[key],
set: (key, val) => {
cache[key] = val;
},
delete: (key) => {
delete cache[key];
},
};
};
export function isMissingData(snapshot: SingularOrPluralSnapshot<any>) {
if (Array.isArray(snapshot)) {
return snapshot.some((s) => s.isMissingData);
}
return snapshot.isMissingData;
}
function getFragmentResult<TData>(
cacheKey: string,
snapshot: SingularOrPluralSnapshot<TData>
): FragmentResult<TData> {
if (Array.isArray(snapshot)) {
return {
cacheKey,
snapshot,
data: snapshot.map((s) => s.data),
isMissingData: isMissingData(snapshot),
};
}
return {
cacheKey,
snapshot,
data: snapshot.data,
isMissingData: isMissingData(snapshot),
};
}
export class FragmentResource {
_environment: IEnvironment;
_cache: ReturnType<typeof createCache>;
constructor(environment: IEnvironment) {
this._environment = environment;
this._cache = createCache();
}
/**
* Like `read`, but with pre-computed fragmentIdentifier that should be
* equal to `getFragmentIdentifier(fragmentNode, fragmentRef)` from the
* arguments.
*/
readWithIdentifier<
TData,
TKey extends KeyType | KeyType[],
TPlural extends boolean = KeyType extends any[] ? true : false
>(
fragmentNode: ReaderFragment,
fragmentRef: TKey,
fragmentIdentifier: string,
fragmentKey?: string,
componentDisplayName?: string,
): FragmentResult<TData, TPlural> {
const environment = this._environment;
// If fragmentRef is null or undefined, pass it directly through.
// This is a convenience when consuming fragments via a HOC api, when the
// prop corresponding to the fragment ref might be passed as null.
if (fragmentRef == null) {
return {
cacheKey: fragmentIdentifier,
data: null,
snapshot: null,
isMissingData: true,
};
}
// If fragmentRef is plural, ensure that it is an array.
// If it's empty, return the empty array direclty before doing any more work.
if (fragmentNode?.metadata?.plural === true) {
invariant(
Array.isArray(fragmentRef),
"Relay: Expected fragment pointer%s for fragment `%s` to be " +
"an array, instead got `%s`. Remove `@relay(plural: true)` " +
"from fragment `%s` to allow the prop to be an object.",
fragmentKey != null ? ` for key \`${fragmentKey}\`` : "",
fragmentNode.name,
typeof fragmentRef,
fragmentNode.name
);
// if (fragmentRef.length === 0) {
// return { cacheKey: fragmentIdentifier, data: [], snapshot: [] };
// }
}
// Now we actually attempt to read the fragment:
// 1. Check if there's a cached value for this fragment
const cachedValue = this._cache.get(fragmentIdentifier);
if (cachedValue != null && cachedValue.snapshot) {
return cachedValue;
}
// 2. If not, try reading the fragment from the Relay store.
// If the snapshot has data, return it and save it in cache
const fragmentSelector = getSelector(fragmentNode, fragmentRef);
invariant(
fragmentSelector != null,
'Relay: Expected to receive an object where `...%s` was spread, ' +
'but the fragment reference was not found`. This is most ' +
'likely the result of:\n' +
"- Forgetting to spread `%s` in `%s`'s parent's fragment.\n" +
'- Conditionally fetching `%s` but unconditionally passing %s prop ' +
'to `%s`. If the parent fragment only fetches the fragment conditionally ' +
'- with e.g. `@include`, `@skip`, or inside a `... on SomeType { }` ' +
'spread - then the fragment reference will not exist. ' +
'In this case, pass `null` if the conditions for evaluating the ' +
'fragment are not met (e.g. if the `@include(if)` value is false.)',
fragmentNode.name,
fragmentNode.name,
componentDisplayName,
fragmentNode.name,
fragmentKey == null ? 'a fragment reference' : `the \`${fragmentKey}\``,
componentDisplayName,
);
const snapshot: SingularOrPluralSnapshot<TData> = (fragmentSelector.kind ===
"PluralReaderSelector"
? (fragmentSelector as PluralReaderSelector).selectors.map((s) =>
environment.lookup(s)
)
: environment.lookup(fragmentSelector as SingularReaderSelector)) as any;
const fragmentOwner =
fragmentSelector.kind === "PluralReaderSelector"
? (fragmentSelector as PluralReaderSelector).selectors[0].owner
: (fragmentSelector as SingularReaderSelector).owner;
const parentQueryName =
fragmentOwner?.node?.params?.name ?? "Unknown Parent Query";
if (!isMissingData(snapshot)) {
const fragmentResult = getFragmentResult<TData>(
fragmentIdentifier,
snapshot
);
this._cache.set(fragmentIdentifier, fragmentResult);
return fragmentResult;
}
return {
data: null,
isMissingData: true,
snapshot: null,
cacheKey: fragmentIdentifier,
};
}
// // 3. If we don't have data in the store, check if a request is in
// // flight for the fragment's parent query, or for another operation
// // that may affect the parent's query data, such as a mutation
// // or subscription. If a promise exists, cache the promise and use it
// // to suspend.
// const networkPromise = this._getAndSavePromiseForFragmentRequestInFlight(
// fragmentIdentifier,
// fragmentOwner,
// );
// if (networkPromise != null) {
// throw networkPromise;
// }
// // 5. If a cached value still isn't available, raise a warning.
// // This means that we're trying to read a fragment that isn't available
// // and isn't being fetched at all.
// warning(
// false,
// 'Relay: Tried reading fragment `%s` declared in ' +
// '`%s`, but it has missing data and its parent query `%s` is not ' +
// 'being fetched.\n' +
// 'This might be fixed by by re-running the Relay Compiler. ' +
// ' Otherwise, make sure of the following:\n' +
// '* You are correctly fetching `%s` if you are using a ' +
// '"store-only" `fetchPolicy`.\n' +
// "* Other queries aren't accidentally fetching and overwriting " +
// 'the data for this fragment.\n' +
// '* Any related mutations or subscriptions are fetching all of ' +
// 'the data for this fragment.\n' +
// "* Any related store updaters aren't accidentally deleting " +
// 'data for this fragment.',
// fragmentNode.name,
// componentDisplayName,
// parentQueryName,
// parentQueryName,
// );
// this._reportMissingRequiredFieldsInSnapshot(snapshot);
// return getFragmentResult(fragmentIdentifier, snapshot);
// }
// _reportMissingRequiredFieldsInSnapshot(snapshot: SingularOrPluralSnapshot) {
// if (Array.isArray(snapshot)) {
// snapshot.forEach(s => {
// if (s.missingRequiredFields != null) {
// reportMissingRequiredFields(
// this._environment,
// s.missingRequiredFields,
// );
// }
// });
// } else {
// if (snapshot.missingRequiredFields != null) {
// reportMissingRequiredFields(
// this._environment,
// snapshot.missingRequiredFields,
// );
// }
// }
// }
// readSpec(
// fragmentNodes: {[string]: ReaderFragment, ...},
// fragmentRefs: {[string]: mixed, ...},
// componentDisplayName: string,
// ): {[string]: FragmentResult, ...} {
// return mapObject(fragmentNodes, (fragmentNode, fragmentKey) => {
// const fragmentRef = fragmentRefs[fragmentKey];
// return this.read(
// fragmentNode,
// fragmentRef,
// componentDisplayName,
// fragmentKey,
// );
// });
// }
subscribe(
fragmentResult: FragmentResult<any>,
callback: () => void
): Disposable {
const environment = this._environment;
const { cacheKey } = fragmentResult;
const renderedSnapshot = fragmentResult.snapshot;
if (!renderedSnapshot) {
return { dispose: () => {} };
}
// 1. Check for any updates missed during render phase
// TODO(T44066760): More efficiently detect if we missed an update
const [didMissUpdates, currentSnapshot] = this.checkMissedUpdates(
fragmentResult
);
// 2. If an update was missed, notify the component so it updates with
// latest data.
if (didMissUpdates) {
callback();
}
// 3. Establish subscriptions on the snapshot(s)
const dataSubscriptions: Disposable[] = [];
if (Array.isArray(renderedSnapshot)) {
invariant(
Array.isArray(currentSnapshot),
"Relay: Expected snapshots to be plural. " +
"If you're seeing this, this is likely a bug in Relay."
);
(currentSnapshot as Snapshot<any>[]).forEach((snapshot, idx) => {
dataSubscriptions.push(
environment.subscribe(snapshot, (latestSnapshot) => {
this._updatePluralSnapshot(
cacheKey,
currentSnapshot as Snapshot<any>[],
latestSnapshot,
idx
);
callback();
})
);
});
} else {
invariant(
currentSnapshot != null && !Array.isArray(currentSnapshot),
"Relay: Expected snapshot to be singular. " +
"If you're seeing this, this is likely a bug in Relay."
);
dataSubscriptions.push(
environment.subscribe(
currentSnapshot as Snapshot<any>,
(latestSnapshot) => {
this._cache.set(
cacheKey,
getFragmentResult(cacheKey, latestSnapshot)
);
callback();
}
)
);
}
return {
dispose: () => {
dataSubscriptions.map((s) => s.dispose());
this._cache.delete(cacheKey);
},
};
}
checkMissedUpdates(
fragmentResult: FragmentResult<any>
): [boolean, SingularOrPluralSnapshot<any> | null] {
const environment = this._environment;
const { cacheKey } = fragmentResult;
const renderedSnapshot = fragmentResult.snapshot;
if (!renderedSnapshot) {
return [false, null];
}
let didMissUpdates = false;
if (Array.isArray(renderedSnapshot)) {
const currentSnapshots: Snapshot<any>[] = [];
renderedSnapshot.forEach((snapshot, idx) => {
let currentSnapshot = environment.lookup(snapshot.selector);
const renderData = snapshot.data;
const currentData = currentSnapshot.data;
const updatedData = recycleNodesInto(renderData, currentData);
if (updatedData !== renderData) {
currentSnapshot = { ...currentSnapshot, data: updatedData };
didMissUpdates = true;
}
currentSnapshots[idx] = currentSnapshot;
});
if (didMissUpdates) {
this._cache.set(
cacheKey,
getFragmentResult(cacheKey, currentSnapshots)
);
}
return [didMissUpdates, currentSnapshots];
}
let currentSnapshot = environment.lookup(renderedSnapshot.selector);
const renderData = renderedSnapshot.data;
const currentData = currentSnapshot.data;
const updatedData = recycleNodesInto(renderData, currentData);
currentSnapshot = {
data: updatedData,
isMissingData: currentSnapshot.isMissingData,
seenRecords: currentSnapshot.seenRecords,
selector: currentSnapshot.selector,
};
if (updatedData !== renderData) {
this._cache.set(cacheKey, getFragmentResult(cacheKey, currentSnapshot));
didMissUpdates = true;
}
return [didMissUpdates, currentSnapshot];
}
_updatePluralSnapshot(
cacheKey: string,
baseSnapshots: Snapshot<any>[],
latestSnapshot: Snapshot<any>,
idx: number
): void {
const currentFragmentResult = this._cache.get(cacheKey);
const currentSnapshot = currentFragmentResult?.snapshot;
if (currentSnapshot && !Array.isArray(currentSnapshot)) {
return;
}
const nextSnapshots = currentSnapshot
? [...currentSnapshot]
: [...baseSnapshots];
nextSnapshots[idx] = latestSnapshot;
this._cache.set(cacheKey, getFragmentResult(cacheKey, nextSnapshots));
}
} | the_stack |
import * as os from 'os'
import {
GraphQLTypeObject,
GraphQLTypeDefinition,
GraphQLTypeField,
getGraphQLEnumValues,
GraphQLInterfaceObject,
GraphQLUnionObject,
} from '../source-helper'
import { ModelMap, ContextDefinition, GenerateArgs, Model } from '../types'
import {
TypeDefinition,
FieldDefinition,
InterfaceDefinition,
AnonymousInterfaceAnnotation,
} from '../introspection/types'
import {
isFieldDefinitionEnumOrLiteral,
getEnumValues,
} from '../introspection/utils'
type SpecificGraphQLScalarType = 'boolean' | 'number' | 'string'
export interface InputTypesMap {
[inputTypeName: string]: GraphQLTypeObject
}
export interface TypeToInputTypeAssociation {
[objectTypeName: string]: string[]
}
export type InterfacesMap = Record<string, GraphQLTypeDefinition[]>
export const createInterfacesMap = (
interfaces: GraphQLInterfaceObject[],
): InterfacesMap =>
interfaces.reduce<InterfacesMap>((interfacesMap, inter) => {
interfacesMap[inter.name] = inter.implementors
return interfacesMap
}, {})
export type UnionsMap = Record<string, GraphQLTypeDefinition[]>
export const createUnionsMap = (unions: GraphQLUnionObject[]): UnionsMap =>
unions.reduce<UnionsMap>((unionsMap, union) => {
unionsMap[union.name] = union.types
return unionsMap
}, {})
export function fieldsFromModelDefinition(
modelDef: TypeDefinition,
): FieldDefinition[] {
// If model is of type `interface InterfaceName { ... }`
if (modelDef.kind === 'InterfaceDefinition') {
const interfaceDef = modelDef as InterfaceDefinition
return interfaceDef.fields
}
// If model is of type `type TypeName = { ... }`
if (
modelDef.kind === 'TypeAliasDefinition' &&
modelDef.getType() &&
modelDef.getType().kind === 'AnonymousInterfaceAnnotation'
) {
const interfaceDef = modelDef.getType() as AnonymousInterfaceAnnotation
return interfaceDef.fields
}
return []
}
export function renderDefaultResolvers(
graphQLTypeObject: GraphQLTypeObject,
args: GenerateArgs,
variableName: string,
): string {
const model = args.modelMap[graphQLTypeObject.name]
if (model === undefined) {
return `export const ${variableName} = {}`
}
const modelDef = model.definition
return `export const ${variableName} = {
${fieldsFromModelDefinition(modelDef)
.filter(modelField => {
const graphQLField = graphQLTypeObject.fields.find(
field => field.name === modelField.name,
)
return shouldRenderDefaultResolver(graphQLField, modelField, args)
})
.map(modelField =>
renderDefaultResolver(
modelField.name,
modelField.optional,
model.definition.name,
),
)
.join(os.EOL)}
}`
}
function renderDefaultResolver(
fieldName: string,
fieldOptional: boolean,
parentTypeName: string,
): string {
const field = `parent.${fieldName}`
const fieldGetter = renderFieldGetter(field, fieldOptional)
return `${fieldName}: (parent: ${parentTypeName}) => ${fieldGetter},`
}
function renderFieldGetter(
fieldGetter: string,
fieldOptional: boolean,
): string {
if (fieldOptional) {
return `${fieldGetter} === undefined ? null : ${fieldGetter}`
}
return fieldGetter
}
export function getContextName(context?: ContextDefinition) {
if (!context) {
return 'Context'
}
return context.interfaceName
}
export function getModelName(
type: GraphQLTypeDefinition,
modelMap: ModelMap,
emptyType: string = '{}',
): string {
const model = modelMap[type.name]
if (type.isEnum) {
return type.name
}
// NOTE if no model is found, return the empty type
// It's usually assumed that every GraphQL type has a model associated
// expect for the `Query`, `Mutation` and `Subscription` type
if (model === undefined) {
return emptyType
}
return model.definition.name
}
function isModelEnumSubsetOfGraphQLEnum(
graphQLEnumValues: string[],
modelEnumValues: string[],
) {
return modelEnumValues.every(enumValue =>
graphQLEnumValues.includes(enumValue),
)
}
function shouldRenderDefaultResolver(
graphQLField: GraphQLTypeField | undefined,
modelField: FieldDefinition | undefined,
args: GenerateArgs,
) {
if (graphQLField === undefined) {
return false
}
if (modelField === undefined) {
return false
}
const modelFieldType = modelField.getType()
if (modelFieldType === undefined) {
return false;
}
// If both types are enums, and model definition enum is a subset of the graphql enum
// Then render as defaultResolver
// eg: given GraphQLEnum = 'A' | 'B' | 'C'
// render when FieldDefinition = ('A') | ('A' | 'B') | ('A | 'B' | 'C')
if (
graphQLField.type.isEnum &&
isFieldDefinitionEnumOrLiteral(modelFieldType)
) {
return isModelEnumSubsetOfGraphQLEnum(
getGraphQLEnumValues(graphQLField, args.enums),
getEnumValues(modelFieldType),
)
}
return !(modelField.optional && graphQLField.type.isRequired)
}
export function shouldScaffoldFieldResolver(
graphQLField: GraphQLTypeField,
modelFields: FieldDefinition[],
args: GenerateArgs,
): boolean {
const modelField = modelFields.find(
modelField => modelField.name === graphQLField.name,
)
return !shouldRenderDefaultResolver(graphQLField, modelField, args)
}
const nullable = (type: string): string => {
return `${type} | null`
}
export const kv = (
key: string,
value: string,
isOptional: boolean = false,
): string => {
return `${key}${isOptional ? '?' : ''}: ${value}`
}
const array = (
innerType: string,
config: { innerUnion?: boolean } = {},
): string => {
return config.innerUnion ? `${innerType}[]` : `Array<${innerType}>`
}
export const union = (types: string[]): string => {
return types.join(' | ')
}
export const resolverReturnType = (returnType: string): string =>
union([returnType, `Promise<${returnType}>`])
type FieldPrintOptions = {
isReturn?: boolean
}
export const printFieldLikeType = (
field: GraphQLTypeField,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
options: FieldPrintOptions = {
isReturn: false,
},
): string => {
if (field.type.isInterface || field.type.isUnion) {
const typesMap = field.type.isInterface ? interfacesMap : unionsMap
const modelNames = typesMap[field.type.name].map(type =>
getModelName(type, modelMap),
)
let rendering = union(modelNames)
if (!field.type.isRequired) {
rendering = nullable(rendering)
}
if (field.type.isArray) {
rendering = array(rendering, { innerUnion: false })
if (!field.type.isArrayRequired) {
rendering = nullable(rendering)
}
}
// We do not have to handle defaults becuase graphql only
// supports defaults on field params but conversely
// interfaces and unions are only supported on output. Therefore
// these two features will never cross.
// No check for isReturn option because unions and interfaces
// cannot be used to type graphql field parameters which implies
// this branch will always be for a return case.
return rendering
}
const name = field.type.isScalar
? getTypeFromGraphQLType(field.type.name)
: field.type.isInput || field.type.isEnum
? field.type.name
: getModelName(field.type, modelMap)
/**
* Considerable difference between types in array versus not, such as what
* default value means, isRequired, ..., lead to forking the rendering paths.
*
* Regarding voidable, note how it can only show up in the k:v rendering e.g.:
*
* foo?: null | string
*
* but not for return style e.g.:
*
* undefined | null | string
*
* given footnote 1 below.
*
* 1. Return type doesn't permit void return since that would allow
* resolvers to e.g. forget to return anything and that be considered OK.
*/
if (field.type.isArray) {
const innerUnion = field.type.isRequired
// - Not voidable here because a void array member is not possible
// - For arrays default value does not apply to inner value
const valueInnerType = field.type.isRequired ? name : nullable(name)
const isArrayNullable =
!field.type.isArrayRequired &&
(field.defaultValue === undefined || field.defaultValue === null)
const isArrayVoidable = isArrayNullable && field.defaultValue === undefined
const valueType = isArrayNullable
? nullable(array(valueInnerType, { innerUnion })) // [1]
: array(valueInnerType, { innerUnion })
return options.isReturn
? valueType
: kv(field.name, valueType, isArrayVoidable)
} else {
const isNullable =
!field.type.isRequired &&
(field.defaultValue === undefined || field.defaultValue === null)
const isVoidable = isNullable && field.defaultValue === undefined
const valueType = isNullable ? nullable(name) : name // [1]
return options.isReturn ? valueType : kv(field.name, valueType, isVoidable)
}
}
export function getTypeFromGraphQLType(
type: string,
): SpecificGraphQLScalarType {
if (type === 'Int' || type === 'Float') {
return 'number'
}
if (type === 'Boolean') {
return 'boolean'
}
if (type === 'String' || type === 'ID' || type === 'DateTime') {
return 'string'
}
return 'string'
}
export const getDistinctInputTypes = (
type: GraphQLTypeObject,
typeToInputTypeAssociation: TypeToInputTypeAssociation,
inputTypesMap: InputTypesMap,
) => {
const inputTypes: GraphQLTypeObject[] = []
const seen: Record<string, boolean> = {}
const inputTypeNames: string[] = []
const see = (typeName: string): void => {
if (!seen[typeName]) {
seen[typeName] = true
inputTypes.push(inputTypesMap[typeName])
}
}
typeToInputTypeAssociation[type.name].forEach(see)
for (const inputType of inputTypes) {
inputTypeNames.push(inputType.type.name)
// Keep seeing (aka. traversing the tree) until we've seen everything.
for (const field of inputType.fields) {
if (field.type.isInput) {
see(field.type.name)
}
}
}
return inputTypeNames
}
export function renderEnums(args: GenerateArgs): string {
return args.enums
.map(enumObject => {
return `export type ${enumObject.name} = ${enumObject.values
.map(value => `'${value}'`)
.join(' | ')}`
})
.join(os.EOL)
}
export function isParentType(name: string) {
const parentTypes = ['Query', 'Mutation', 'Subscription']
return parentTypes.indexOf(name) > -1
}
export function groupModelsNameByImportPath(models: Model[]) {
return models.reduce<{ [importPath: string]: string[] }>((acc, model) => {
const fileModels = acc[model.importPathRelativeToOutput] || []
if (!fileModels.includes(model.definition.name)) {
fileModels.push(model.definition.name)
}
acc[model.importPathRelativeToOutput] = fileModels
return acc
}, {})
} | the_stack |
import { ParseTreeListener } from 'antlr4ts/tree/ParseTreeListener';
import { DocumentationContext } from './TomParser';
import { BodyContext } from './TomParser';
import { WhitespaceContext } from './TomParser';
import { AnnotationsContext } from './TomParser';
import { TagContext } from './TomParser';
import { TagNameContext } from './TomParser';
import { TagIDContext } from './TomParser';
import { OptionalTagIDContext } from './TomParser';
import { PropertyTagIDContext } from './TomParser';
import { OptionalTagOrIdentifierContext } from './TomParser';
import { TypeContext } from './TomParser';
import { UnaryTypeContext } from './TomParser';
import { TupleTypeContext } from './TomParser';
import { TupleTypeListContext } from './TomParser';
import { PrimaryTypeContext } from './TomParser';
import { IdentifierOrKeywordContext } from './TomParser';
import { ParenthesizedTypeContext } from './TomParser';
import { LambdaTypeContext } from './TomParser';
import { FormalParameterSequenceContext } from './TomParser';
import { ParameterContext } from './TomParser';
import { ArrayTypeContext } from './TomParser';
import { ObjectTypeContext } from './TomParser';
import { ObjectPairTypeListContext } from './TomParser';
import { ObjectPairTypeContext } from './TomParser';
import { OptionalTypeContext } from './TomParser';
import { PropertyTypeContext } from './TomParser';
import { OptionalTypeOrIdentiferContext } from './TomParser';
import { ValueContext } from './TomParser';
import { ExpressionContext } from './TomParser';
import { UnaryExpressionContext } from './TomParser';
import { ArrayExpressionContext } from './TomParser';
import { ObjectExpressionContext } from './TomParser';
import { ObjectPairExpressionListContext } from './TomParser';
import { ObjectPairExpressionContext } from './TomParser';
import { LambdaExpressionContext } from './TomParser';
import { LiteralContext } from './TomParser';
import { ParenthesizedExpressionContext } from './TomParser';
import { DescriptionContext } from './TomParser';
import { DescriptionLineContext } from './TomParser';
import { DescriptionLineStartContext } from './TomParser';
import { DescriptionTextContext } from './TomParser';
import { DescriptionLineElementContext } from './TomParser';
import { DescriptionLineTextContext } from './TomParser';
import { InlineTagContext } from './TomParser';
import { InlineTagNameContext } from './TomParser';
import { InlineTagBodyContext } from './TomParser';
import { BraceExpressionContext } from './TomParser';
import { BraceBodyContext } from './TomParser';
import { BraceTextContext } from './TomParser';
import { IdentifierContext } from './TomParser';
/**
* This interface defines a complete listener for a parse tree produced by
* `TomParser`.
*/
export interface TomParserListener extends ParseTreeListener {
/**
* Enter a parse tree produced by `TomParser.documentation`.
* @param ctx the parse tree
*/
enterDocumentation?: (ctx: DocumentationContext) => void;
/**
* Exit a parse tree produced by `TomParser.documentation`.
* @param ctx the parse tree
*/
exitDocumentation?: (ctx: DocumentationContext) => void;
/**
* Enter a parse tree produced by `TomParser.body`.
* @param ctx the parse tree
*/
enterBody?: (ctx: BodyContext) => void;
/**
* Exit a parse tree produced by `TomParser.body`.
* @param ctx the parse tree
*/
exitBody?: (ctx: BodyContext) => void;
/**
* Enter a parse tree produced by `TomParser.whitespace`.
* @param ctx the parse tree
*/
enterWhitespace?: (ctx: WhitespaceContext) => void;
/**
* Exit a parse tree produced by `TomParser.whitespace`.
* @param ctx the parse tree
*/
exitWhitespace?: (ctx: WhitespaceContext) => void;
/**
* Enter a parse tree produced by `TomParser.annotations`.
* @param ctx the parse tree
*/
enterAnnotations?: (ctx: AnnotationsContext) => void;
/**
* Exit a parse tree produced by `TomParser.annotations`.
* @param ctx the parse tree
*/
exitAnnotations?: (ctx: AnnotationsContext) => void;
/**
* Enter a parse tree produced by `TomParser.tag`.
* @param ctx the parse tree
*/
enterTag?: (ctx: TagContext) => void;
/**
* Exit a parse tree produced by `TomParser.tag`.
* @param ctx the parse tree
*/
exitTag?: (ctx: TagContext) => void;
/**
* Enter a parse tree produced by `TomParser.tagName`.
* @param ctx the parse tree
*/
enterTagName?: (ctx: TagNameContext) => void;
/**
* Exit a parse tree produced by `TomParser.tagName`.
* @param ctx the parse tree
*/
exitTagName?: (ctx: TagNameContext) => void;
/**
* Enter a parse tree produced by `TomParser.tagID`.
* @param ctx the parse tree
*/
enterTagID?: (ctx: TagIDContext) => void;
/**
* Exit a parse tree produced by `TomParser.tagID`.
* @param ctx the parse tree
*/
exitTagID?: (ctx: TagIDContext) => void;
/**
* Enter a parse tree produced by `TomParser.optionalTagID`.
* @param ctx the parse tree
*/
enterOptionalTagID?: (ctx: OptionalTagIDContext) => void;
/**
* Exit a parse tree produced by `TomParser.optionalTagID`.
* @param ctx the parse tree
*/
exitOptionalTagID?: (ctx: OptionalTagIDContext) => void;
/**
* Enter a parse tree produced by `TomParser.propertyTagID`.
* @param ctx the parse tree
*/
enterPropertyTagID?: (ctx: PropertyTagIDContext) => void;
/**
* Exit a parse tree produced by `TomParser.propertyTagID`.
* @param ctx the parse tree
*/
exitPropertyTagID?: (ctx: PropertyTagIDContext) => void;
/**
* Enter a parse tree produced by `TomParser.optionalTagOrIdentifier`.
* @param ctx the parse tree
*/
enterOptionalTagOrIdentifier?: (ctx: OptionalTagOrIdentifierContext) => void;
/**
* Exit a parse tree produced by `TomParser.optionalTagOrIdentifier`.
* @param ctx the parse tree
*/
exitOptionalTagOrIdentifier?: (ctx: OptionalTagOrIdentifierContext) => void;
/**
* Enter a parse tree produced by `TomParser.type`.
* @param ctx the parse tree
*/
enterType?: (ctx: TypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.type`.
* @param ctx the parse tree
*/
exitType?: (ctx: TypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.unaryType`.
* @param ctx the parse tree
*/
enterUnaryType?: (ctx: UnaryTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.unaryType`.
* @param ctx the parse tree
*/
exitUnaryType?: (ctx: UnaryTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.tupleType`.
* @param ctx the parse tree
*/
enterTupleType?: (ctx: TupleTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.tupleType`.
* @param ctx the parse tree
*/
exitTupleType?: (ctx: TupleTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.tupleTypeList`.
* @param ctx the parse tree
*/
enterTupleTypeList?: (ctx: TupleTypeListContext) => void;
/**
* Exit a parse tree produced by `TomParser.tupleTypeList`.
* @param ctx the parse tree
*/
exitTupleTypeList?: (ctx: TupleTypeListContext) => void;
/**
* Enter a parse tree produced by `TomParser.primaryType`.
* @param ctx the parse tree
*/
enterPrimaryType?: (ctx: PrimaryTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.primaryType`.
* @param ctx the parse tree
*/
exitPrimaryType?: (ctx: PrimaryTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.identifierOrKeyword`.
* @param ctx the parse tree
*/
enterIdentifierOrKeyword?: (ctx: IdentifierOrKeywordContext) => void;
/**
* Exit a parse tree produced by `TomParser.identifierOrKeyword`.
* @param ctx the parse tree
*/
exitIdentifierOrKeyword?: (ctx: IdentifierOrKeywordContext) => void;
/**
* Enter a parse tree produced by `TomParser.parenthesizedType`.
* @param ctx the parse tree
*/
enterParenthesizedType?: (ctx: ParenthesizedTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.parenthesizedType`.
* @param ctx the parse tree
*/
exitParenthesizedType?: (ctx: ParenthesizedTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.lambdaType`.
* @param ctx the parse tree
*/
enterLambdaType?: (ctx: LambdaTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.lambdaType`.
* @param ctx the parse tree
*/
exitLambdaType?: (ctx: LambdaTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.formalParameterSequence`.
* @param ctx the parse tree
*/
enterFormalParameterSequence?: (ctx: FormalParameterSequenceContext) => void;
/**
* Exit a parse tree produced by `TomParser.formalParameterSequence`.
* @param ctx the parse tree
*/
exitFormalParameterSequence?: (ctx: FormalParameterSequenceContext) => void;
/**
* Enter a parse tree produced by `TomParser.parameter`.
* @param ctx the parse tree
*/
enterParameter?: (ctx: ParameterContext) => void;
/**
* Exit a parse tree produced by `TomParser.parameter`.
* @param ctx the parse tree
*/
exitParameter?: (ctx: ParameterContext) => void;
/**
* Enter a parse tree produced by `TomParser.arrayType`.
* @param ctx the parse tree
*/
enterArrayType?: (ctx: ArrayTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.arrayType`.
* @param ctx the parse tree
*/
exitArrayType?: (ctx: ArrayTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.objectType`.
* @param ctx the parse tree
*/
enterObjectType?: (ctx: ObjectTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.objectType`.
* @param ctx the parse tree
*/
exitObjectType?: (ctx: ObjectTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.objectPairTypeList`.
* @param ctx the parse tree
*/
enterObjectPairTypeList?: (ctx: ObjectPairTypeListContext) => void;
/**
* Exit a parse tree produced by `TomParser.objectPairTypeList`.
* @param ctx the parse tree
*/
exitObjectPairTypeList?: (ctx: ObjectPairTypeListContext) => void;
/**
* Enter a parse tree produced by `TomParser.objectPairType`.
* @param ctx the parse tree
*/
enterObjectPairType?: (ctx: ObjectPairTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.objectPairType`.
* @param ctx the parse tree
*/
exitObjectPairType?: (ctx: ObjectPairTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.optionalType`.
* @param ctx the parse tree
*/
enterOptionalType?: (ctx: OptionalTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.optionalType`.
* @param ctx the parse tree
*/
exitOptionalType?: (ctx: OptionalTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.propertyType`.
* @param ctx the parse tree
*/
enterPropertyType?: (ctx: PropertyTypeContext) => void;
/**
* Exit a parse tree produced by `TomParser.propertyType`.
* @param ctx the parse tree
*/
exitPropertyType?: (ctx: PropertyTypeContext) => void;
/**
* Enter a parse tree produced by `TomParser.optionalTypeOrIdentifer`.
* @param ctx the parse tree
*/
enterOptionalTypeOrIdentifer?: (ctx: OptionalTypeOrIdentiferContext) => void;
/**
* Exit a parse tree produced by `TomParser.optionalTypeOrIdentifer`.
* @param ctx the parse tree
*/
exitOptionalTypeOrIdentifer?: (ctx: OptionalTypeOrIdentiferContext) => void;
/**
* Enter a parse tree produced by `TomParser.value`.
* @param ctx the parse tree
*/
enterValue?: (ctx: ValueContext) => void;
/**
* Exit a parse tree produced by `TomParser.value`.
* @param ctx the parse tree
*/
exitValue?: (ctx: ValueContext) => void;
/**
* Enter a parse tree produced by `TomParser.expression`.
* @param ctx the parse tree
*/
enterExpression?: (ctx: ExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.expression`.
* @param ctx the parse tree
*/
exitExpression?: (ctx: ExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.unaryExpression`.
* @param ctx the parse tree
*/
enterUnaryExpression?: (ctx: UnaryExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.unaryExpression`.
* @param ctx the parse tree
*/
exitUnaryExpression?: (ctx: UnaryExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.arrayExpression`.
* @param ctx the parse tree
*/
enterArrayExpression?: (ctx: ArrayExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.arrayExpression`.
* @param ctx the parse tree
*/
exitArrayExpression?: (ctx: ArrayExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.objectExpression`.
* @param ctx the parse tree
*/
enterObjectExpression?: (ctx: ObjectExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.objectExpression`.
* @param ctx the parse tree
*/
exitObjectExpression?: (ctx: ObjectExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.objectPairExpressionList`.
* @param ctx the parse tree
*/
enterObjectPairExpressionList?: (ctx: ObjectPairExpressionListContext) => void;
/**
* Exit a parse tree produced by `TomParser.objectPairExpressionList`.
* @param ctx the parse tree
*/
exitObjectPairExpressionList?: (ctx: ObjectPairExpressionListContext) => void;
/**
* Enter a parse tree produced by `TomParser.objectPairExpression`.
* @param ctx the parse tree
*/
enterObjectPairExpression?: (ctx: ObjectPairExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.objectPairExpression`.
* @param ctx the parse tree
*/
exitObjectPairExpression?: (ctx: ObjectPairExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.lambdaExpression`.
* @param ctx the parse tree
*/
enterLambdaExpression?: (ctx: LambdaExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.lambdaExpression`.
* @param ctx the parse tree
*/
exitLambdaExpression?: (ctx: LambdaExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.literal`.
* @param ctx the parse tree
*/
enterLiteral?: (ctx: LiteralContext) => void;
/**
* Exit a parse tree produced by `TomParser.literal`.
* @param ctx the parse tree
*/
exitLiteral?: (ctx: LiteralContext) => void;
/**
* Enter a parse tree produced by `TomParser.parenthesizedExpression`.
* @param ctx the parse tree
*/
enterParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.parenthesizedExpression`.
* @param ctx the parse tree
*/
exitParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.description`.
* @param ctx the parse tree
*/
enterDescription?: (ctx: DescriptionContext) => void;
/**
* Exit a parse tree produced by `TomParser.description`.
* @param ctx the parse tree
*/
exitDescription?: (ctx: DescriptionContext) => void;
/**
* Enter a parse tree produced by `TomParser.descriptionLine`.
* @param ctx the parse tree
*/
enterDescriptionLine?: (ctx: DescriptionLineContext) => void;
/**
* Exit a parse tree produced by `TomParser.descriptionLine`.
* @param ctx the parse tree
*/
exitDescriptionLine?: (ctx: DescriptionLineContext) => void;
/**
* Enter a parse tree produced by `TomParser.descriptionLineStart`.
* @param ctx the parse tree
*/
enterDescriptionLineStart?: (ctx: DescriptionLineStartContext) => void;
/**
* Exit a parse tree produced by `TomParser.descriptionLineStart`.
* @param ctx the parse tree
*/
exitDescriptionLineStart?: (ctx: DescriptionLineStartContext) => void;
/**
* Enter a parse tree produced by `TomParser.descriptionText`.
* @param ctx the parse tree
*/
enterDescriptionText?: (ctx: DescriptionTextContext) => void;
/**
* Exit a parse tree produced by `TomParser.descriptionText`.
* @param ctx the parse tree
*/
exitDescriptionText?: (ctx: DescriptionTextContext) => void;
/**
* Enter a parse tree produced by `TomParser.descriptionLineElement`.
* @param ctx the parse tree
*/
enterDescriptionLineElement?: (ctx: DescriptionLineElementContext) => void;
/**
* Exit a parse tree produced by `TomParser.descriptionLineElement`.
* @param ctx the parse tree
*/
exitDescriptionLineElement?: (ctx: DescriptionLineElementContext) => void;
/**
* Enter a parse tree produced by `TomParser.descriptionLineText`.
* @param ctx the parse tree
*/
enterDescriptionLineText?: (ctx: DescriptionLineTextContext) => void;
/**
* Exit a parse tree produced by `TomParser.descriptionLineText`.
* @param ctx the parse tree
*/
exitDescriptionLineText?: (ctx: DescriptionLineTextContext) => void;
/**
* Enter a parse tree produced by `TomParser.inlineTag`.
* @param ctx the parse tree
*/
enterInlineTag?: (ctx: InlineTagContext) => void;
/**
* Exit a parse tree produced by `TomParser.inlineTag`.
* @param ctx the parse tree
*/
exitInlineTag?: (ctx: InlineTagContext) => void;
/**
* Enter a parse tree produced by `TomParser.inlineTagName`.
* @param ctx the parse tree
*/
enterInlineTagName?: (ctx: InlineTagNameContext) => void;
/**
* Exit a parse tree produced by `TomParser.inlineTagName`.
* @param ctx the parse tree
*/
exitInlineTagName?: (ctx: InlineTagNameContext) => void;
/**
* Enter a parse tree produced by `TomParser.inlineTagBody`.
* @param ctx the parse tree
*/
enterInlineTagBody?: (ctx: InlineTagBodyContext) => void;
/**
* Exit a parse tree produced by `TomParser.inlineTagBody`.
* @param ctx the parse tree
*/
exitInlineTagBody?: (ctx: InlineTagBodyContext) => void;
/**
* Enter a parse tree produced by `TomParser.braceExpression`.
* @param ctx the parse tree
*/
enterBraceExpression?: (ctx: BraceExpressionContext) => void;
/**
* Exit a parse tree produced by `TomParser.braceExpression`.
* @param ctx the parse tree
*/
exitBraceExpression?: (ctx: BraceExpressionContext) => void;
/**
* Enter a parse tree produced by `TomParser.braceBody`.
* @param ctx the parse tree
*/
enterBraceBody?: (ctx: BraceBodyContext) => void;
/**
* Exit a parse tree produced by `TomParser.braceBody`.
* @param ctx the parse tree
*/
exitBraceBody?: (ctx: BraceBodyContext) => void;
/**
* Enter a parse tree produced by `TomParser.braceText`.
* @param ctx the parse tree
*/
enterBraceText?: (ctx: BraceTextContext) => void;
/**
* Exit a parse tree produced by `TomParser.braceText`.
* @param ctx the parse tree
*/
exitBraceText?: (ctx: BraceTextContext) => void;
/**
* Enter a parse tree produced by `TomParser.identifier`.
* @param ctx the parse tree
*/
enterIdentifier?: (ctx: IdentifierContext) => void;
/**
* Exit a parse tree produced by `TomParser.identifier`.
* @param ctx the parse tree
*/
exitIdentifier?: (ctx: IdentifierContext) => void;
} | the_stack |
import path from 'path'
import { exec } from '@monodeploy/io'
import {
cleanUp,
createFile,
getMonodeployConfig,
initGitRepository,
setupMonorepo,
} from '@monodeploy/test-utils'
import { YarnContext } from '@monodeploy/types'
import {
getCommitMessages,
gitAdd,
gitCommit,
gitDiffTree,
gitLastTaggedCommit,
gitLog,
gitPushTags,
gitResolveSha,
gitTag,
} from '.'
describe('@monodeploy/git', () => {
let context: YarnContext
let prevNodeEnv: string | undefined
beforeEach(async () => {
prevNodeEnv = process.env.NODE_ENV
context = await setupMonorepo({
'pkg-1': {},
'pkg-2': {},
'pkg-3': { dependencies: ['pkg-2'] },
'pkg-4': {},
'pkg-5': { private: true, dependencies: ['pkg-4'] },
'pkg-6': {
dependencies: ['pkg-3', 'pkg-7'],
},
'pkg-7': {},
})
const rootPath = context.project.cwd
await initGitRepository(rootPath, { allowScaffoldingCommits: false })
})
afterEach(async () => {
process.env.NODE_ENV = prevNodeEnv
jest.restoreAllMocks()
await cleanUp([context.project.cwd])
})
describe('gitDiffTree', () => {
it('returns list of modified files', async () => {
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await createFile({ filePath: path.join('testDir', 'test.txt'), cwd })
await exec('git add . && git commit -m "test: test file" -n', {
cwd,
})
const { stdout: headSha } = await exec('git rev-parse HEAD', {
cwd,
})
const diffTreeOutput = await gitDiffTree(headSha, { cwd, context })
expect(diffTreeOutput.trim()).toEqual(
expect.stringContaining(['test.txt', 'testDir/test.txt'].join('\n')),
)
})
})
describe('gitResolveSha', () => {
it('resolves HEAD properly', async () => {
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "test: test file" -n', {
cwd,
})
const { stdout: headSha } = await exec('git rev-parse HEAD', {
cwd,
})
const resolvedHead = await gitResolveSha('HEAD', { cwd, context })
expect(resolvedHead).toEqual(headSha.trim())
})
})
describe('gitCommitMessages', () => {
it('gets commit messages', async () => {
const cwd = context.project.cwd
// Create some files and commit them to have a diff.
await createFile({ filePath: 'test.txt', cwd })
await exec('git commit -m "test: base" --allow-empty -n', {
cwd,
})
await exec('git checkout -b test-branch', { cwd })
const commitMessage = 'test: test file'
await exec(`git add . && git commit -m "${commitMessage}" -n`, {
cwd,
})
const headSha = (
await exec('git rev-parse HEAD', {
cwd,
})
).stdout.trim()
const messages = await getCommitMessages(
await getMonodeployConfig({
cwd,
baseBranch: 'main',
commitSha: headSha,
}),
context,
)
expect(messages).toEqual([{ sha: headSha, body: `${commitMessage}\n\n` }])
})
it('includes all commits from parents of merge', async () => {
const cwd = context.project.cwd
const commit = (msg: string) => exec(`git commit -m "${msg}" --allow-empty -n`, { cwd })
// add some commits to "main"
await commit('initial')
await commit('1')
await commit('2')
// branch off to "feature", and add some commits to new branch
await exec('git checkout -b feature', { cwd })
// switch back to main, cause it to diverge immediately
await exec('git checkout main', { cwd })
await commit('3')
// add our first feature commit
await exec('git checkout feature', { cwd })
await commit('4')
// At this point, the common ancestor of feature and main is "commit 2"
// back to "main", and cause it to diverge
await exec('git checkout main', { cwd })
await commit('5')
// add another commit to "feature"
await exec('git checkout feature', { cwd })
const fromSha = (
await exec('git rev-parse HEAD', {
cwd,
})
).stdout.trim()
await commit('6')
// merge main into feature
await exec('git merge main --no-edit', { cwd })
await commit('7')
const messages = await getCommitMessages(
await getMonodeployConfig({
cwd,
baseBranch: fromSha,
commitSha: 'HEAD',
}),
context,
)
// We expect "6" and "7" that are on "feature", but also any commits
// from "main" that were only introduced to feature after the merge. This
// includes "3" (from right when we branched feature off main, and "5" from later on).
expect(
messages
.filter((m) => !m.body.includes('Merge branch'))
.map((c) => Number(c.body.trim()))
.sort(),
).toEqual([3, 5, 6, 7])
})
})
describe('gitTag', () => {
it('fails if invariant not respected', async () => {
const cwd = context.project.cwd
await exec('git commit -m "test: base" --allow-empty', {
cwd,
})
await expect(async () =>
gitTag('pkg@1.0.0', { cwd, context }),
).rejects.toMatchInlineSnapshot(
'[Error: Invariant Violation: Invalid environment test !== production.]',
)
})
it('creates an annotated tag', async () => {
process.env.NODE_ENV = 'production'
const { cwd } = context.project
await exec('git commit -m "test: base" --allow-empty', {
cwd,
})
await gitTag('pkg@1.0.0', { cwd, context })
const { stdout } = await exec('git describe --abbrev=0', { cwd })
expect(stdout).toEqual(expect.stringContaining('1.0.0'))
})
})
describe('gitPushTags', () => {
it('fails if invariant not respected', async () => {
const cwd = context.project.cwd
await exec('git commit -m "test: base" --allow-empty', {
cwd,
})
await expect(async () =>
gitPushTags({ cwd, context, remote: 'origin' }),
).rejects.toMatchInlineSnapshot(
'[Error: Invariant Violation: Invalid environment test !== production.]',
)
})
})
describe('gitLastTaggedCommit', () => {
it('defaults to HEAD if no tag exists', async () => {
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "chore: initial commit" -n', {
cwd,
})
await createFile({ filePath: 'test1.txt', cwd })
await exec('git add . && git commit -m "chore: second commit" -n', {
cwd,
})
const headSha = await gitResolveSha('HEAD', { cwd, context })
const commit = await gitLastTaggedCommit({ cwd, context })
expect(commit).toEqual(headSha)
})
it('defaults to HEAD if on initial commit', async () => {
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "chore: initial commit" -n', {
cwd,
})
const headSha = await gitResolveSha('HEAD', { cwd, context })
const commit = await gitLastTaggedCommit({ cwd, context })
expect(commit).toEqual(headSha)
})
it('gets the last tagged commit', async () => {
process.env.NODE_ENV = 'production'
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "chore: initial commit" -n', {
cwd,
})
const taggedSha = await gitResolveSha('HEAD', { cwd, context })
await gitTag('test-tag@0.0.1', { cwd, context })
await createFile({ filePath: 'test2.txt', cwd })
await exec('git add . && git commit -m "chore: non-tagged" -n', {
cwd,
})
expect(await gitLastTaggedCommit({ cwd, context })).toEqual(taggedSha)
})
it('skips prerelease tags if not in prerelease mode', async () => {
process.env.NODE_ENV = 'production'
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "chore: initial commit" -n', {
cwd,
})
const releaseTagSha = await gitResolveSha('HEAD', { cwd, context })
const nonPrereleaseTags = [
'test-tag@0.0.1',
'test-tag@v0.0.1',
'test-tag@pkg-name-dash.1', // only support semantic versions
'@scope-with-hyphen/name.with.dot-and-hyphen',
]
for (const tag of nonPrereleaseTags) {
await gitTag(tag, { cwd, context })
}
await createFile({ filePath: 'test1.txt', cwd })
await exec('git add . && git commit -m "chore: second commit" -n', {
cwd,
})
const prereleaseTagSha = await gitResolveSha('HEAD', {
cwd,
context,
})
await gitTag('test-tag@0.0.2-rc.1', { cwd, context })
await createFile({ filePath: 'test2.txt', cwd })
await exec('git add . && git commit -m "chore: non-tagged" -n', {
cwd,
})
const detectedCommit = await gitLastTaggedCommit({
cwd,
context,
prerelease: false,
})
expect(detectedCommit).not.toEqual(prereleaseTagSha)
expect(detectedCommit).toEqual(releaseTagSha)
})
it('includes prerelease tags when in prerelease mode', async () => {
process.env.NODE_ENV = 'production'
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "chore: initial commit" -n', {
cwd,
})
const releaseTagSha = await gitResolveSha('HEAD', { cwd, context })
await gitTag('test-tag@0.0.1', { cwd, context })
await createFile({ filePath: 'test1.txt', cwd })
await exec('git add . && git commit -m "chore: second commit" -n', {
cwd,
})
const prereleaseTagSha = await gitResolveSha('HEAD', {
cwd,
context,
})
await gitTag('test-tag@0.0.2-rc.1', { cwd, context })
await createFile({ filePath: 'test2.txt', cwd })
await exec('git add . && git commit -m "chore: non-tagged" -n', {
cwd,
})
const detectedCommit = await gitLastTaggedCommit({
cwd,
context,
prerelease: true,
})
expect(detectedCommit).toEqual(prereleaseTagSha)
expect(detectedCommit).not.toEqual(releaseTagSha)
})
})
describe('gitLog', () => {
it('returns an entry for commit between from and to refs', async () => {
process.env.NODE_ENV = 'production'
const DELIMITER = '===='
const cwd = context.project.cwd
await createFile({ filePath: 'other.txt', cwd })
await exec('git add . && git commit -m "chore: initial commit" -n', {
cwd,
})
const fromSha = await gitResolveSha('HEAD', { cwd, context })
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "chore: second commit" -n', {
cwd,
})
await createFile({ filePath: 'test1.txt', cwd })
await exec('git add . && git commit -m "chore: third commit" -n', {
cwd,
})
const toSha = await gitResolveSha('HEAD', { cwd, context })
// Note that gitLog excludes the "from" commit itself
const logEntries = (await gitLog(fromSha, toSha, { cwd, DELIMITER }))
.split(DELIMITER)
.filter((v) => Boolean(v.trim()))
expect(logEntries).toHaveLength(2)
expect(logEntries).toEqual(
expect.arrayContaining([
expect.stringContaining('chore: third commit'),
expect.stringContaining('chore: second commit'),
]),
)
})
it('returns a single commit entry if "from" ref is the same as "to" ref', async () => {
process.env.NODE_ENV = 'production'
const DELIMITER = '===='
const cwd = context.project.cwd
await createFile({ filePath: 'other.txt', cwd })
await exec('git add . && git commit -m "chore: initial commit" -n', {
cwd,
})
await createFile({ filePath: 'test.txt', cwd })
await exec('git add . && git commit -m "chore: second commit" -n', {
cwd,
})
const sha = await gitResolveSha('HEAD', { cwd, context })
const logEntries = (await gitLog(sha, sha, { cwd, DELIMITER }))
.split(DELIMITER)
.filter((v) => Boolean(v.trim()))
expect(logEntries).toHaveLength(1)
expect(logEntries[0]).toEqual(expect.stringContaining('chore: second commit'))
})
})
describe('gitAdd, gitCommit', () => {
it('adds files, commits changes', async () => {
process.env.NODE_ENV = 'production'
const cwd = context.project.cwd
await createFile({ filePath: 'test.txt', cwd })
await gitAdd(['test.txt'], { cwd, context })
// assert added
expect(
(
await exec('git ls-files --error-unmatch test.txt', {
cwd,
})
).stdout.toString(),
).toEqual(expect.stringContaining('test.txt'))
await gitCommit('chore: initial commit', { cwd, context })
// assert committed
expect(
(
await exec('git log -1 --format="%B"', {
cwd,
})
).stdout.toString(),
).toEqual(expect.stringContaining('chore: initial commit'))
})
})
}) | the_stack |
import * as vscode from 'vscode';
import * as xregexp from 'xregexp';
import CSymbol from './CSymbol';
import SubSymbol from './SubSymbol';
import { logger } from './extension';
export function masker(match: string): string { return ' '.repeat(match.length); }
const re_matchRecursiveError = /^Unbalanced (left|right) delimiter found in string at position (\d+)$/;
/**
* Performs a balanced mask of text between left and right, accounting for depth.
* Should only be used with single characters.
*/
function maskBalanced(text: string, left: string, right: string, keepEnclosingChars: boolean): string {
try {
xregexp.matchRecursive(text, left, right, 'gm', {
valueNames: ['outer', 'left', 'inner', 'right'],
escapeChar: '\\'
}).forEach(match => {
if (match.name === 'inner') {
if (keepEnclosingChars) {
text = text.substring(0, match.start) + masker(match.value) + text.substring(match.end);
} else {
text = text.substring(0, match.start - 1)
+ ' '.repeat(match.value.length + 2)
+ text.substring(match.end + 1);
}
}
});
} catch (error) {
if (error instanceof Error) {
const unbalancedIndexMatch = error.message.match(re_matchRecursiveError);
if (unbalancedIndexMatch !== null) {
const unbalancedIndex: number = +unbalancedIndexMatch[2];
if (unbalancedIndex < text.length) {
// There is an unbalanced delimiter, so we mask it and try again.
let maskedText = text.substring(0, unbalancedIndex) + ' ';
if (unbalancedIndex !== text.length - 1) {
maskedText += text.substring(unbalancedIndex + 1);
}
return maskBalanced(maskedText, left, right, keepEnclosingChars);
}
}
logger.alertError(`Unknown parsing error: ${error.message}`);
} else {
logger.alertError('Unknown parsing error');
}
throw error;
}
return text;
}
export function maskComments(text: string, keepEnclosingChars: boolean = true): string {
return replaceComments(text, keepEnclosingChars, masker);
}
export function removeComments(text: string): string {
return replaceComments(text, false, '');
}
function replaceComments(text: string, keepEnclosingChars: boolean = true, replacer: any): string {
if (keepEnclosingChars) {
text = text.replace(/(?<=\/\/).*/gm, replacer);
text = text.replace(/(?<=\/\*)(\*(?!\/)|[^*])*(?=\*\/)/gm, replacer);
} else {
text = text.replace(/\/\/.*/gm, replacer);
text = text.replace(/\/\*(\*(?!\/)|[^*])*\*\//gm, replacer);
}
return text;
}
export function maskRawStringLiterals(text: string, keepEnclosingChars: boolean = true): string {
if (keepEnclosingChars) {
return text.replace(/(?<=R")(?<delimiter>.*)\(.*\)\k<delimiter>(?=")/gs, masker);
}
return text.replace(/R"(?<delimiter>.*)\(.*\)\k<delimiter>"/gs, masker);
}
export function maskQuotes(text: string, keepEnclosingChars: boolean = true): string {
if (keepEnclosingChars) {
text = text.replace(/(?<=').*(?=')(?<!\\)/g, masker);
text = text.replace(/(?<=").*(?=")(?<!\\)/g, masker);
} else {
text = text.replace(/'.*'(?<!\\)/g, masker);
text = text.replace(/".*"(?<!\\)/g, masker);
}
return text;
}
export function maskAttributes(text: string, keepEnclosingChars: boolean = true): string {
return replaceAttributes(text, keepEnclosingChars, masker);
}
export function removeAttributes(text: string): string {
return replaceAttributes(text, false, '');
}
function replaceAttributes(text: string, keepEnclosingChars: boolean = true, replacer: any): string {
if (keepEnclosingChars) {
return text.replace(/(?<=\[\[).*(?=\]\])/g, replacer);
}
return text.replace(/\[\[.*\]\]/g, replacer);
}
export function maskNonSourceText(text: string, keepAttributeBrackets: boolean = true): string {
text = maskComments(text, false);
text = maskRawStringLiterals(text);
text = maskQuotes(text);
return maskAttributes(text, keepAttributeBrackets);
}
export function maskParentheses(text: string, keepEnclosingChars: boolean = true): string {
return maskBalanced(text, '\\(', '\\)', keepEnclosingChars);
}
export function maskBraces(text: string, keepEnclosingChars: boolean = true): string {
return maskBalanced(text, '{', '}', keepEnclosingChars);
}
export function maskBrackets(text: string, keepEnclosingChars: boolean = true): string {
return maskBalanced(text, '\\[', '\\]', keepEnclosingChars);
}
export function maskAngleBrackets(text: string, keepEnclosingChars: boolean = true): string {
return maskBalanced(text, '\\<', '\\>', keepEnclosingChars);
}
export function maskComparisonOperators(text: string): string {
return text.replace(/[^\w\d_\s]=(?!=)/g, masker);
}
/**
* Removes all whitespace except for whitespace that exists between 2 adjacent word boundaries,
* and normalizes that whitespace to be single spaces.
*/
export function normalizeWhitespace(text: string): string {
return text.replace(/\b\s+\B|\B\s+\b|\B\s+\B/g, '').replace(/\s+/g, ' ');
}
export function normalizeSourceText(sourceText: string): string {
sourceText = removeComments(sourceText);
sourceText = removeAttributes(sourceText);
return normalizeWhitespace(sourceText);
}
/**
* DocumentSymbol.range doesn't always include the final semi-colon, so this finds the end of the last semi-colon.
*/
export function getEndOfStatement(document: vscode.TextDocument, position: vscode.Position): vscode.Position {
const text = document.getText(new vscode.Range(position, document.lineAt(document.lineCount - 1).range.end));
const match = text.match(/^(\s*;)*/);
if (!match || match.length === 0 || !match[0]) {
return position;
}
return document.positionAt(document.offsetAt(position) + match[0].length);
}
export function getRangeOfSymbolName(symbol: CSymbol | SubSymbol): vscode.Range {
if (symbol.document.getText(symbol.selectionRange) === symbol.name
|| symbol.selectionRange.isEqual(symbol.range)) {
return symbol.selectionRange;
}
const operatorMatch = symbol.name.match(/(?<=^operator\s*)\S+/);
if (operatorMatch) {
const nameToEndText = symbol.document.getText(new vscode.Range(symbol.selectionRange.start, symbol.range.end));
const indexOfOperator = nameToEndText.indexOf(operatorMatch[0], 8);
if (indexOfOperator !== -1) {
const nameStartOffset = symbol.document.offsetAt(symbol.selectionRange.start);
const nameEndOffset = nameStartOffset + indexOfOperator + operatorMatch[0].length;
return symbol.document.rangeAt(nameStartOffset, nameEndOffset);
}
}
const nameEnd = symbol.selectionRange.start.translate(0, symbol.name.length);
return symbol.selectionRange.with(symbol.selectionRange.start, nameEnd);
}
export function getIndentationRegExp(symbol: CSymbol): RegExp {
const line = symbol.document.lineAt(symbol.trueStart);
const indentation = line.text.substring(0, line.firstNonWhitespaceCharacterIndex);
return new RegExp('^' + indentation, 'gm');
}
export function stripDefaultValues(parameters: string): string {
// Mask anything that might contain commas or equals-signs.
let maskedParameters = maskNonSourceText(parameters);
maskedParameters = maskParentheses(maskedParameters);
maskedParameters = maskAngleBrackets(maskedParameters);
maskedParameters = maskBraces(maskedParameters);
maskedParameters = maskBrackets(maskedParameters);
maskedParameters = maskComparisonOperators(maskedParameters);
const splitParameters = maskedParameters.split(',');
let strippedParameters = '';
let charPos = 0;
for (const parameter of splitParameters) {
if (parameter.includes('=')) {
strippedParameters += parameters.substring(charPos, charPos + parameter.indexOf('=')).trimEnd() + ',';
} else {
strippedParameters += parameters.substring(charPos, charPos + parameter.length) + ',';
}
charPos += parameter.length + 1;
}
return strippedParameters.slice(0, -1);
}
export function getParameterTypes(parameters: string): string[] {
parameters = maskNonSourceText(parameters, false);
// Mask anything that might contain commas or equals-signs.
let maskedParameters = maskParentheses(parameters);
maskedParameters = maskAngleBrackets(maskedParameters);
maskedParameters = maskBraces(maskedParameters);
maskedParameters = maskBrackets(maskedParameters);
maskedParameters = maskComparisonOperators(maskedParameters);
const parameterTypes: string[] = [];
for (const match of maskedParameters.matchAll(/(?<=^|,)[^=,]+(?==|,|$)/g)) {
if (match.index !== undefined && !/^\s*$/.test(match[0])) {
const maskedParameter = match[0].trimEnd();
const parameter = parameters.slice(match.index, match.index + maskedParameter.length);
const nameMatch = maskedParameter.match(/(?<=.+)(\b[\w_][\w\d_]*)(\s*\[\s*\])*$/s);
if (nameMatch) {
const parameterType = parameter.slice(0, -nameMatch[0].length).trimStart();
if (parameterType.length !== 0 && nameMatch[1] !== 'const' && nameMatch[1] !== 'volatile'
&& !/^(const|volatile)(\s+(const|volatile))?\s*$/.test(parameterType)) {
parameterTypes.push(parameterType + (nameMatch[2] ? parameter.slice(-nameMatch[2].length) : ''));
continue;
}
} else {
const nestedDeclaratorIndex = maskedParameter.search(/\(\s*\)(\s*\(\s*\)|(\s*\[\s*\])+)$/);
if (nestedDeclaratorIndex !== -1) {
const deepestRightParen = parameter.indexOf(')', nestedDeclaratorIndex);
if (deepestRightParen !== -1) {
const trimmedParameter = parameter.slice(0, deepestRightParen);
const parameterType = trimmedParameter.replace(/\b[\w_][\w\d_]*(?=\s*$)/, match => {
return (match !== 'const' && match !== 'volatile') ? '' : match;
}) + parameter.slice(deepestRightParen);
parameterTypes.push(parameterType.trimStart());
continue;
}
}
}
parameterTypes.push(parameter.trimStart());
}
}
return parameterTypes;
}
export function getLeadingReturnType(leadingText: string): string {
const maskedLeadingText = maskAngleBrackets(maskNonSourceText(leadingText));
const identifierMatches: RegExpMatchArray[] = [];
for (const match of maskedLeadingText.matchAll(/\b[\w_][\w\d_]*\b(\s*::\s*[\w_][\w\d_]*\b)*/g)) {
identifierMatches.push(match);
}
let startOfType: number | undefined;
for (let i = identifierMatches.length - 1; i >= 0; --i) {
if ((startOfType === undefined
&& identifierMatches[i][0] !== 'const' && identifierMatches[i][0] !== 'volatile')
|| (startOfType !== undefined
&& (identifierMatches[i][0] === 'const' || identifierMatches[i][0] === 'volatile'))) {
startOfType = identifierMatches[i].index;
}
}
return leadingText.slice(startOfType);
}
const re_trailingReturnTypeFragments =
/\b[\w_][\w\d_]*\b(\s*::\s*[\w_][\w\d_]*\b)*(\s*<\s*>)?(\s*\(\s*\)){0,2}|&{1,2}|\*{1,}/g;
const re_constVolatileRefPtr = /^(const|volatile|&{1,2}|\*{1,})$/;
export function getTrailingReturnType(trailingText: string): string {
const maskedTrailingText = maskAngleBrackets(maskParentheses(maskNonSourceText(trailingText)));
let endOfType: number | undefined;
for (const match of maskedTrailingText.matchAll(re_trailingReturnTypeFragments)) {
if ((endOfType === undefined && !re_constVolatileRefPtr.test(match[0]))
|| (endOfType !== undefined && re_constVolatileRefPtr.test(match[0]))) {
endOfType = match.index !== undefined ? match.index + match[0].length : undefined;
}
}
return trailingText.slice(0, endOfType);
}
const re_primitiveTypes =
/\b(void|bool|char|wchar_t|char8_t|char16_t|char32_t|int|short|long|signed|unsigned|float|double)\b/;
export function matchesPrimitiveType(text: string): boolean {
return !(text.includes('<') && text.includes('>')) && re_primitiveTypes.test(text);
} | the_stack |
import {
CONVENTION_FOR_ETH_ASSET_ID,
ProtocolParams,
ProtocolEventMessage,
IStoreService,
MethodNames,
MethodParams,
MethodResults,
EventNames,
} from "@connext/types";
import { delay, getAddressFromAssetId } from "@connext/utils";
import { BigNumber, constants, utils } from "ethers";
import { expect } from "../assertions";
import { CFCore } from "../../cfCore";
import { NULL_INITIAL_STATE_FOR_PROPOSAL, TOO_MANY_APPS_IN_CHANNEL } from "../../errors";
import { setup, SetupContext } from "../setup";
import {
assertInstallMessage,
assertProposeMessage,
collateralizeChannel,
constructAppProposalRpc,
createChannel,
getAppContext,
getBalances,
getContractAddresses,
getInstalledAppInstances,
getProposedAppInstances,
makeAndSendProposeCall,
makeInstallCall,
transferERC20Tokens,
} from "../utils";
import { MAX_CHANNEL_APPS } from "../../constants";
const { One } = constants;
const { isHexString } = utils;
describe("Node method follows spec - install", () => {
let multisigAddress: string;
let nodeA: CFCore;
let nodeB: CFCore;
let storeA: IStoreService;
let TicTacToeApp: string;
describe(
"Node A gets app install proposal, sends to node B, B approves it, installs it, " +
"sends acks back to A, A installs it, both nodes have the same app instance",
() => {
beforeEach(async () => {
const context: SetupContext = await setup(global);
nodeA = context["A"].node;
nodeB = context["B"].node;
storeA = context["A"].store;
multisigAddress = await createChannel(nodeA, nodeB);
expect(multisigAddress).to.be.ok;
expect(isHexString(multisigAddress)).to.be.ok;
TicTacToeApp = getContractAddresses().TicTacToeApp;
});
it("install app with ETH", async () => {
return new Promise(async (done) => {
await collateralizeChannel(multisigAddress, nodeA, nodeB);
const appDeposit = One;
let preInstallETHBalanceNodeA: BigNumber;
let postInstallETHBalanceNodeA: BigNumber;
let preInstallETHBalanceNodeB: BigNumber;
let postInstallETHBalanceNodeB: BigNumber;
// eslint-disable-next-line prefer-const
let proposeInstallParams: ProtocolParams.Propose;
nodeB.on(
"PROPOSE_INSTALL_EVENT",
async (msg: ProtocolEventMessage<"PROPOSE_INSTALL_EVENT">) => {
// Delay because propose event fires before params are set
await delay(1500);
[preInstallETHBalanceNodeA, preInstallETHBalanceNodeB] = await getBalances(
nodeA,
nodeB,
multisigAddress,
CONVENTION_FOR_ETH_ASSET_ID,
);
assertProposeMessage(nodeA.publicIdentifier, msg, proposeInstallParams);
await makeInstallCall(nodeB, msg.data.appInstanceId, multisigAddress);
},
);
nodeA.on("INSTALL_EVENT", async (msg: ProtocolEventMessage<"INSTALL_EVENT">) => {
const [appInstanceNodeA] = await getInstalledAppInstances(nodeA, multisigAddress);
const [appInstanceNodeB] = await getInstalledAppInstances(nodeB, multisigAddress);
expect(appInstanceNodeA).to.be.ok;
expect(appInstanceNodeA).to.deep.eq(appInstanceNodeB);
const proposedAppsA = await getProposedAppInstances(nodeA, multisigAddress);
expect(proposedAppsA.length).to.eq(0);
[postInstallETHBalanceNodeA, postInstallETHBalanceNodeB] = await getBalances(
nodeA,
nodeB,
multisigAddress,
CONVENTION_FOR_ETH_ASSET_ID,
);
expect(postInstallETHBalanceNodeA).to.eq(preInstallETHBalanceNodeA.sub(appDeposit));
expect(postInstallETHBalanceNodeB).to.eq(preInstallETHBalanceNodeB.sub(appDeposit));
// assert install message
assertInstallMessage(nodeB.publicIdentifier, msg, appInstanceNodeA.identityHash);
done();
});
const { params } = await makeAndSendProposeCall(
nodeA,
nodeB,
TicTacToeApp,
multisigAddress,
undefined,
appDeposit,
CONVENTION_FOR_ETH_ASSET_ID,
appDeposit,
CONVENTION_FOR_ETH_ASSET_ID,
);
proposeInstallParams = params;
});
});
it("install app with ERC20", async () => {
await transferERC20Tokens(nodeA.signerAddress);
await transferERC20Tokens(nodeB.signerAddress);
const erc20TokenAddress = getContractAddresses().DolphinCoin;
const assetId = getAddressFromAssetId(erc20TokenAddress);
await collateralizeChannel(multisigAddress, nodeA, nodeB, One, assetId);
let preInstallERC20BalanceNodeA: BigNumber;
let postInstallERC20BalanceNodeA: BigNumber;
let preInstallERC20BalanceNodeB: BigNumber;
let postInstallERC20BalanceNodeB: BigNumber;
// eslint-disable-next-line prefer-const
let proposedParams: ProtocolParams.Propose;
nodeB.on("PROPOSE_INSTALL_EVENT", async (msg) => {
// Delay because propose event fires before params are set
await delay(2000);
[preInstallERC20BalanceNodeA, preInstallERC20BalanceNodeB] = await getBalances(
nodeA,
nodeB,
multisigAddress,
assetId,
);
assertProposeMessage(nodeA.publicIdentifier, msg, proposedParams);
makeInstallCall(nodeB, msg.data.appInstanceId, multisigAddress);
});
nodeA.on("INSTALL_EVENT", async (msg) => {
const [appInstanceNodeA] = await getInstalledAppInstances(nodeA, multisigAddress);
const [appInstanceNodeB] = await getInstalledAppInstances(nodeB, multisigAddress);
expect(appInstanceNodeA).to.deep.eq(appInstanceNodeB);
[postInstallERC20BalanceNodeA, postInstallERC20BalanceNodeB] = await getBalances(
nodeA,
nodeB,
multisigAddress,
assetId,
);
expect(postInstallERC20BalanceNodeA).to.be.lt(preInstallERC20BalanceNodeA);
expect(postInstallERC20BalanceNodeB).to.be.lt(preInstallERC20BalanceNodeB);
assertInstallMessage(nodeB.publicIdentifier, msg, appInstanceNodeA.identityHash);
});
const { params } = await makeAndSendProposeCall(
nodeA,
nodeB,
TicTacToeApp,
multisigAddress,
undefined,
One,
assetId,
One,
assetId,
);
proposedParams = params;
});
it("sends proposal with null initial state", async () => {
const appContext = getAppContext(TicTacToeApp);
const AppInstanceJsonReq = constructAppProposalRpc(
multisigAddress,
nodeB.publicIdentifier,
appContext.appDefinition,
appContext.abiEncodings,
appContext.initialState,
);
AppInstanceJsonReq.parameters["initialState"] = undefined;
await expect(nodeA.rpcRouter.dispatch(AppInstanceJsonReq)).to.eventually.be.rejectedWith(
NULL_INITIAL_STATE_FOR_PROPOSAL,
);
});
it("should error on initiating node if there is an error for the responder", async () => {
return new Promise(async (done) => {
await collateralizeChannel(multisigAddress, nodeA, nodeB);
const appDeposit = One;
nodeB.on(
"PROPOSE_INSTALL_EVENT",
async (msg: ProtocolEventMessage<"PROPOSE_INSTALL_EVENT">) => {
// Delay because propose event fires before params are set
await delay(500);
// Delete the responders channel
await storeA.removeAppProposal(multisigAddress, msg.data.appInstanceId, {} as any);
await expect(
makeInstallCall(nodeB, msg.data.appInstanceId, multisigAddress),
).to.eventually.be.rejectedWith(
`No proposed AppInstance exists for the given appIdentityHash`,
);
done();
},
);
await makeAndSendProposeCall(
nodeA,
nodeB,
TicTacToeApp,
multisigAddress,
undefined,
appDeposit,
CONVENTION_FOR_ETH_ASSET_ID,
appDeposit,
CONVENTION_FOR_ETH_ASSET_ID,
);
});
});
it("cannot install more than the max number of apps", async () => {
const { TicTacToeApp } = getContractAddresses();
nodeB.on(EventNames.PROPOSE_INSTALL_EVENT, async (msg) => {
await makeInstallCall(nodeB, msg.data.appInstanceId, multisigAddress);
});
for (let i = 0; i < MAX_CHANNEL_APPS; i++) {
// eslint-disable-next-line no-loop-func
const installed = new Promise((res) => nodeA.once(EventNames.INSTALL_EVENT, res));
await makeAndSendProposeCall(
nodeA,
nodeB,
TicTacToeApp,
multisigAddress,
undefined,
constants.Zero,
CONVENTION_FOR_ETH_ASSET_ID,
constants.Zero,
CONVENTION_FOR_ETH_ASSET_ID,
);
await installed;
}
const {
result: {
result: { appInstances },
},
} = (await nodeA.rpcRouter.dispatch({
id: Date.now(),
methodName: MethodNames.chan_getAppInstances,
parameters: { multisigAddress } as MethodParams.GetAppInstances,
})) as { result: { result: MethodResults.GetAppInstances } };
expect(appInstances.length).to.be.eq(MAX_CHANNEL_APPS);
nodeB.off(EventNames.PROPOSE_INSTALL_EVENT);
const failed = new Promise((res) =>
nodeB.on(EventNames.PROPOSE_INSTALL_EVENT, async (msg) => {
// await makeInstallCall(nodeB, msg.data.appInstanceId, multisigAddress);
await expect(
makeInstallCall(nodeB, msg.data.appInstanceId, multisigAddress),
).to.be.rejectedWith(TOO_MANY_APPS_IN_CHANNEL);
res();
}),
);
makeAndSendProposeCall(
nodeA,
nodeB,
TicTacToeApp,
multisigAddress,
undefined,
constants.Zero,
CONVENTION_FOR_ETH_ASSET_ID,
constants.Zero,
CONVENTION_FOR_ETH_ASSET_ID,
);
await failed;
});
},
);
}); | the_stack |
import {
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
HostListener,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Output,
QueryList,
Renderer2,
TemplateRef,
ViewChild,
ViewEncapsulation,
Optional,
ViewChildren,
ViewContainerRef
} from '@angular/core';
import {
LyTheme2,
mixinBg,
mixinColor,
mixinDisabled,
mixinDisableRipple,
mixinElevation,
mixinOutlined,
mixinRaised,
mixinShadowColor,
mixinStyleUpdater,
ThemeVariables,
AlignAlias,
YPosition,
XPosition,
Dir,
LyRippleService,
LyFocusState,
scrollWithAnimation,
toBoolean,
lyl,
LY_COMMON_STYLES,
ThemeRef,
StyleCollection,
LyClasses,
StyleTemplate,
StyleRenderer,
Style
} from '@alyle/ui';
import { LyButton } from '@alyle/ui/button';
import { LyTabContent } from './tab-content.directive';
import { Subscription, Subject } from 'rxjs';
import { ViewportRuler } from '@angular/cdk/scrolling';
import { Platform } from '@angular/cdk/platform';
import { TemplatePortal } from '@angular/cdk/portal';
import { takeUntil, take, switchMapTo } from 'rxjs/operators';
export interface LyTabTheme {
/** Styles for Tab Component */
root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate);
}
export interface LyTabVariables {
tab?: LyTabTheme;
}
const DEFAULT_DISABLE_RIPPLE = false;
const STYLE_PRIORITY = -2;
const DEFAULT_BG = 'primary';
const DEFAULT_INDICATOR_COLOR = 'accent';
const DEFAULT_ELEVATION = 4;
const DEFAULT_HEADER_PLACEMENT = 'above';
export type AlignTabs = 'start' | 'center' | 'end' | 'stretch' | 'baseline';
export type LyTabsHeaderPlacement = 'before' | 'after' | 'above' | 'below';
export const STYLES = (theme: ThemeVariables & LyTabVariables, ref: ThemeRef) => {
const __ = ref.selectorsOf(STYLES);
return {
$name: LyTabs.и,
$priority: STYLE_PRIORITY,
root: () => lyl `{
display: flex
{
...${
(theme.tab
&& theme.tab.root
&& (theme.tab.root instanceof StyleCollection
? theme.tab.root.setTransformer(fn => fn(__)).css
: theme.tab.root(__))
)
}
}
}`,
tab: lyl `{
position: relative
display: inline-flex
}`,
/** Tab container */
contentContainer: lyl `{
display: flex
overflow: hidden
flex-grow: 1
width: 100%
position: relative
}`,
/** Tab header */
labels: lyl `{
display: flex
position: relative
height: 100%
}`,
labelsContainer: () => lyl `{
overflow: hidden
flex-shrink: 0
${__.scrollable} & {
@media (hover: none) {
overflow: auto
}
}
}`,
label: lyl `{
-webkit-tap-highlight-color: transparent
-webkit-appearance: none
background-color: transparent
user-select: none
border: 0
min-width: 72px
padding: 0 24px
cursor: pointer
height: 48px
display: inline-flex
justify-content: center
align-items: center
position: relative
overflow: hidden
font-family: ${theme.typography.fontFamily}
font-size: ${theme.pxToRem(theme.typography.fontSize)}
letter-spacing: 0.02857em
color: currentColor
outline: none
width: 100%
font-weight: 500
opacity: .7
@media ${theme.breakpoints['XSmall']} {
padding: 0 12px
}
}`,
labelActive: lyl `{
opacity: 1
}`,
contents: lyl `{
display: flex
width: 100%
}`,
content: lyl `{
...${LY_COMMON_STYLES.fill}
width: 100%
height: 100%
position: absolute
overflow: auto
}`,
contentActive: lyl `{
position: relative
z-index: 1
}`,
contentInner: null,
indicator: lyl `{
position: absolute
height: 2px
transition: 450ms cubic-bezier(.1, 1, 0.5, 1)
background: currentColor
}`,
indicatorForServer: lyl `{
position: absolute
background: currentColor
}`,
rippleContainer: lyl `{
...${LY_COMMON_STYLES.fill}
overflow: hidden
}`,
scrollable: null,
hiddenContent: () => lyl `{
visibility: hidden
}`,
column: null,
row: null
};
};
/** @docs-private */
export class LyTabsBase {
constructor(
public _theme: LyTheme2
) { }
}
/** @docs-private */
export const LyTabsMixinBase = mixinStyleUpdater(mixinBg(mixinElevation(mixinShadowColor(LyTabsBase))));
/** @docs-private */
export class LyTabLabelBase {
constructor(
public _theme: LyTheme2,
public _ngZone: NgZone,
public _platform: Platform
) { }
}
/** @docs-private */
export const LyTabLabelMixinBase = mixinStyleUpdater(
mixinBg(
mixinColor(
mixinRaised(
mixinDisabled(
mixinOutlined(
mixinElevation(
mixinShadowColor(
mixinDisableRipple(LyTabLabelBase)))))))));
/**
* @dynamic
*/
@Component({
selector: 'ly-tabs',
templateUrl: './tabs.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
exportAs: 'lyTabs',
inputs: [
'bg', 'elevation', 'shadowColor'
],
providers: [
StyleRenderer
]
})
export class LyTabs extends LyTabsMixinBase implements OnChanges, OnInit, AfterViewInit, AfterContentInit, OnDestroy {
/** @docs-private */
static и = 'LyTabs';
/** @docs-private */
$priority = STYLE_PRIORITY;
/** @docs-private */
readonly classes = this.sRenderer.renderSheet(STYLES, true);
_selectedIndex: number;
_selectedBeforeIndex: number;
_selectedTab: LyTab | null;
_selectedBeforeTab: LyTab | null;
_isViewInitLoaded: boolean;
private _tabsSubscription = Subscription.EMPTY;
private _headerPlacement: LyTabsHeaderPlacement;
private _headerPlacementClass: string;
private _alignTabs: AlignTabs;
private _alignTabsClass: string;
private _textColor: string;
private _textColorClass: string;
private _tabResizeSub: Subscription;
private _scrollable: boolean;
private _timeoutIds: { [index: number]: number } = {};
/** Emits whenever the component is destroyed. */
private readonly _destroy = new Subject<void>();
@ViewChild('tabs', { static: true }) tabsRef: ElementRef;
@ViewChild('tabContents', { static: true }) tabContents: ElementRef<HTMLDivElement>;
@ViewChild('tabsIndicator', { static: true, read: ElementRef }) tabsIndicator?: ElementRef;
@Input() selectedIndexOnChange: 'auto' | number = 'auto';
/**
* Keep the content.
* By default, when changing a tab, the previous one is created and deleted.
* With this, the content will only be hidden instead of deleting it.
*/
@Input()
set keepContent(val: boolean) {
const newVal = toBoolean(val);
this._keepContent = newVal;
}
get keepContent() {
return this._keepContent;
}
private _keepContent: boolean;
/** Animation duration in milliseconds */
@Input()
set animationDuration(val: number) {
this._animationDuration = val;
Promise.resolve().then(() => {
this.tabContents.nativeElement.style.transitionDuration = `${val}ms`;
});
}
get animationDuration() {
return this._animationDuration;
}
private _animationDuration: number;
/**
* Whether the tab group should grow to the size of the active tab.
*/
@Input()
set dynamicHeight(val: boolean) {
const newVal = toBoolean(val);
this._dynamicHeight = newVal;
}
get dynamicHeight() {
return this._dynamicHeight;
}
private _dynamicHeight: boolean;
@Input()
set scrollable(val: any) {
const newVal = toBoolean(val);
if (newVal) {
this.renderer.addClass(this.el.nativeElement, this.classes.scrollable);
} else if (this._scrollable != null) {
this.renderer.removeClass(this.el.nativeElement, this.classes.scrollable);
}
this._scrollable = newVal;
}
get scrollable() {
return this._scrollable;
}
@Input()
@Style<string | null>(
val => (theme, ref) => {
const __ = ref.selectorsOf(STYLES);
return lyl `{
${__.indicator} {
color:${theme.colorOf(val)}
}
}`;
}
) indicatorColor: string;
@Input()
set headerPlacement(val: LyTabsHeaderPlacement) {
if (val !== this.headerPlacement) {
this._headerPlacement = val;
this.sRenderer.toggleClass(this.classes.column, val === 'above' || val === 'below');
this.sRenderer.toggleClass(this.classes.row, val === 'before' || val === 'after');
this._headerPlacementClass = this.theme.addStyle(`lyTabs.headerPlacement:${val}`,
() => {
let flexDirectionContainer: string;
let flexDirection = this._getFlexDirection(val);
let position: string;
let height: string | null = null;
let width: string | null = null;
let heightServer: string | null = null;
let widthServer: string | null = null;
switch (val) {
case YPosition.above:
flexDirectionContainer = 'column';
position = YPosition.below;
height = '2px';
widthServer = '100%';
break;
case YPosition.below:
flexDirectionContainer = 'column-reverse';
position = YPosition.above;
height = '2px';
widthServer = '100%';
break;
case XPosition.before:
flexDirectionContainer = 'row';
position = XPosition.after;
width = '2px';
heightServer = '100%';
break;
case XPosition.after:
flexDirectionContainer = 'row-reverse';
position = XPosition.before;
width = '2px';
heightServer = '100%';
break;
default:
throw new Error(`LyTabs: value:${val} do not is valid for \`headerPlacement\``);
}
if (val === YPosition.above || val === YPosition.below) {
flexDirection = 'row';
} else {
flexDirection = 'column';
}
return {
[`&`]: {
flexDirection: flexDirectionContainer
},
[`& .${this.classes.indicator},& .${this.classes.indicatorForServer}`]: {
[position]: 0,
height,
width
},
[`.${this.classes.indicatorForServer}`]: {
width: widthServer,
height: heightServer
},
[`& .${this.classes.labels},& .${this.classes.contents}`]: { flexDirection },
[`.${this.classes.contents}`]: { flexDirection }
};
},
this.el.nativeElement,
this._headerPlacementClass,
STYLE_PRIORITY);
}
}
get headerPlacement() {
return this._headerPlacement;
}
@Input()
set alignTabs(val: AlignTabs) {
this._alignTabs = val;
this._alignTabsClass = this.theme.addStyle(`lyAlignTabs: ${val}`,
(
val === 'stretch' ? {
[`& .${this.classes.labels} .${this.classes.tab}`]: {
flexBasis: 0,
flexGrow: 1
}
} : {
[`& .${this.classes.labels}`]: {
justifyContent: val in AlignAlias ? AlignAlias[val] : val
}
}
),
this.el.nativeElement,
this._alignTabsClass,
STYLE_PRIORITY);
}
get alignTabs() {
return this._alignTabs;
}
@Input()
set textColor(val: string) {
this._textColor = val;
this._textColorClass = this.theme.addStyle(`lyTabs.textColor:${val}`,
(theme: ThemeVariables) => ({
[`& .${this.classes.labelActive}`]: {
color: theme.colorOf(val)
}
}),
this.el.nativeElement,
this._textColorClass,
STYLE_PRIORITY);
}
get textColor() {
return this._textColor;
}
@Input()
set selectedIndex(val: number) {
if (val !== this.selectedIndex) {
this._selectedBeforeIndex = this._selectedIndex as number;
this._selectedIndex = this._findIndex(val, 'auto');
this._selectedBeforeTab = this._selectedTab!;
if (this._isViewInitLoaded) {
this._updateTabs();
} else {
Promise.resolve(null).then(() => this._updateTabs());
}
this.selectedIndexChange.emit(this._selectedIndex);
this._markForCheck();
}
}
get selectedIndex() {
return this._selectedIndex;
}
@Output() selectedIndexChange: EventEmitter<any> = new EventEmitter();
@ContentChildren(forwardRef(() => LyTab)) tabsList: QueryList<LyTab>;
@ViewChildren('tabContent') tabContentList: QueryList<ElementRef<HTMLDivElement>>;
constructor(
private theme: LyTheme2,
private renderer: Renderer2,
private el: ElementRef,
private cd: ChangeDetectorRef,
private _viewportRuler: ViewportRuler,
readonly sRenderer: StyleRenderer,
private _platform: Platform,
private _ngZone: NgZone
) {
super(theme);
this.setAutoContrast();
this.animationDuration = 500;
}
ngOnChanges() {
if (this._isViewInitLoaded) {
this.updateStyle(this.tabsRef.nativeElement);
}
}
ngOnInit() {
if (this.selectedIndex == null) {
this.selectedIndex = 0;
}
this.renderer.addClass(this.el.nativeElement, this.classes.root);
const tabsIndicatorEl = this.tabsIndicator!.nativeElement;
this.renderer.addClass(tabsIndicatorEl, this.classes.indicator);
/** Set default Color */
if (!this.indicatorColor && !this.bg && !this.textColor && !this.elevation) {
this.indicatorColor = DEFAULT_INDICATOR_COLOR;
this.bg = DEFAULT_BG;
this.elevation = DEFAULT_ELEVATION;
}
if (!this.headerPlacement) {
this.headerPlacement = DEFAULT_HEADER_PLACEMENT;
}
}
ngAfterContentInit() {
this._tabsSubscription = this.tabsList.changes.subscribe(() => {
if (this._selectedIndex !== this.selectedIndexOnChange) {
this.selectedIndex = this._findIndex(this.selectedIndex, this.selectedIndexOnChange);
}
this.cd.markForCheck();
});
}
ngAfterViewInit() {
this._isViewInitLoaded = true;
this.tabsList.changes
.pipe(
switchMapTo(this._ngZone.onStable.asObservable().pipe(take(1))),
takeUntil(this._destroy)
)
.subscribe(() => {
this._updateTabs();
});
this._updateTabs();
this.updateStyle(this.tabsRef.nativeElement);
if (this._platform.isBrowser) {
this._tabResizeSub = this._viewportRuler.change().subscribe(() => {
if (this._selectedTab) {
this._updateIndicator(this._selectedTab);
this._selectedTab._tabLabel._updateTabScroll();
}
});
}
}
ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
this._tabsSubscription.unsubscribe();
if (this._tabResizeSub) {
this._tabResizeSub.unsubscribe();
}
this._clearTimeouts();
}
private _findIndex(selectedIndex: number, index: string | number) {
if (!this.tabsList) {
return selectedIndex;
}
const indexOfLastTab = this.tabsList.length - 1;
const currentIndex = typeof index === 'number' ? index : selectedIndex;
return currentIndex < 0 ? 0 : currentIndex > indexOfLastTab ? indexOfLastTab : currentIndex;
}
_updateIndicator(currentTab: LyTab, beforeTab?: LyTab): void {
if (currentTab) {
if (beforeTab) {
beforeTab._renderer.removeAttribute(beforeTab._tabIndicator.nativeElement, 'class');
}
const el = currentTab._el.nativeElement as HTMLElement;
const rects = el.getBoundingClientRect();
if (this.headerPlacement === XPosition.after || this.headerPlacement === XPosition.before) {
this.renderer.setStyle(this.tabsIndicator!.nativeElement, 'height', `${rects.height}px`);
this.renderer.setStyle(this.tabsIndicator!.nativeElement, 'top', `${el.offsetTop}px`);
this.renderer.removeStyle(this.tabsIndicator!.nativeElement, 'width');
this.renderer.removeStyle(this.tabsIndicator!.nativeElement, 'left');
} else {
this.renderer.setStyle(this.tabsIndicator!.nativeElement, 'width', `${rects.width}px`);
this.renderer.setStyle(this.tabsIndicator!.nativeElement, 'left', `${el.offsetLeft}px`);
this.renderer.removeStyle(this.tabsIndicator!.nativeElement, 'height');
this.renderer.removeStyle(this.tabsIndicator!.nativeElement, 'top');
}
}
}
_markForCheck() {
this.cd.markForCheck();
}
private _updateTabs() {
if (!this._isViewInitLoaded) {
return;
}
const tabsContents = this.tabContentList.toArray();
const tabsForUpdate: [LyTab, HTMLDivElement, number][] = [];
this.tabsList.forEach((tab, index) => {
const tabContent = tabsContents[index].nativeElement;
if (this.selectedIndex === index || this._selectedBeforeIndex === index) {
tab._activeContent = true;
tabsForUpdate.push([tab, tabContent, index]);
} else {
if (this.keepContent) {
this.renderer.addClass(tabContent, this.classes.hiddenContent);
}
}
});
this._ngZone.run(() => {
this._markForCheck();
});
this._ngZone.onStable.asObservable()
.pipe(
take(1),
takeUntil(this._destroy)
)
.subscribe(() =>
tabsForUpdate.forEach(parms =>
this._updateContentStyle(...parms)));
}
loadTemplate(tab: LyTab, index: number): TemplatePortal<any> | null {
tab.index = index;
if (this.selectedIndex === tab.index) {
// set 0 if is null
this._selectedTab = tab;
Promise.resolve(null).then(() => {
// this._updateDynamicHeight(tabContent, index);
if (this._platform.isBrowser) {
this._updateIndicator(tab);
} else {
// for server
const selectedBeforeTab = this._selectedBeforeTab;
if (selectedBeforeTab) {
this.renderer.removeClass(selectedBeforeTab._tabIndicator.nativeElement, this.classes.indicatorForServer);
}
this.renderer.addClass(this._selectedTab!._tabIndicator.nativeElement, this.classes.indicatorForServer);
}
});
} else if (this._selectedBeforeIndex === index) {
// Promise.resolve(null).then(() => this._updateDynamicHeight(tabContent, index));
}
tab._tabLabel._updateTabState();
if (this.keepContent) {
return tab.content;
}
if (tab._activeContent) {
return tab.content;
}
return null;
}
private _getFlexDirection(val: LyTabsHeaderPlacement) {
let flexDirection: string;
if (val === YPosition.above || val === YPosition.below) {
flexDirection = 'row';
} else {
flexDirection = 'column';
}
return flexDirection;
}
private _updateContentStyle(tab: LyTab, tabContent: HTMLDivElement, index: number) {
if (this.selectedIndex === index || this._selectedBeforeIndex === index) {
const prevIndex = this._selectedBeforeIndex;
const currentIndex = this.selectedIndex;
const dynamicHeight = this.dynamicHeight && this._platform.isBrowser && prevIndex != null;
const contentInner = tabContent.firstElementChild as HTMLDivElement;
const contentHeight = dynamicHeight ? contentInner.getBoundingClientRect().height : null;
const contentHeightPrev = dynamicHeight
? this.tabContentList.toArray()[prevIndex].nativeElement.firstElementChild!.getBoundingClientRect().height
: null;
if (currentIndex === index) {
this.renderer.addClass(tabContent, this.classes.contentActive);
if (this.keepContent) {
this.renderer.removeClass(tabContent, this.classes.hiddenContent);
}
} else {
this.renderer.removeClass(tabContent, this.classes.contentActive);
}
if (prevIndex == null || !this._platform.isBrowser || prevIndex === currentIndex) {
return;
}
this._clearTimeouts(index);
const { before } = this._theme.variables;
const isDirRow = this.headerPlacement === XPosition.after
|| this.headerPlacement === XPosition.before;
const x = before === 'left'
? 100
: isDirRow
? 100
: -100;
if (currentIndex === index) {
const sign = prevIndex < index ? 1 : -1;
const pos = isDirRow ? `0,${x * sign}%` : `${x * sign}%, 0`;
tabContent.style.overflow = 'hidden';
if (dynamicHeight) {
tabContent.style.height = `${contentHeightPrev}px`;
}
tabContent.style.transform = `translate3d(${pos}, 0)`;
enforceStyleRecalculation(tabContent);
tabContent.style.transition = `${this.animationDuration}ms cubic-bezier(0.35, 0, 0.25, 1)`;
tabContent.style.transform = `translate3d(0%, 0, 0)`;
if (dynamicHeight) {
tabContent.style.height = `${contentHeight}px`;
}
} else {
const sign = currentIndex < index ? 1 : -1;
const pos = isDirRow ? `0,${x * sign}%` : `${x * sign}%, 0`;
tabContent.style.overflow = 'hidden';
tabContent.style.transform = `translate3d(0%, 0, 0)`;
enforceStyleRecalculation(tabContent);
tabContent.style.transition = `${this.animationDuration}ms cubic-bezier(0.35, 0, 0.25, 1)`;
tabContent.style.transform = `translate3d(${pos}, 0)`;
}
this._runTimeoutOutsideZone(index, () => {
tabContent.style.transform = ``;
tabContent.style.transition = ``;
tabContent.style.overflow = ``;
if (dynamicHeight) {
tabContent.style.height = ``;
}
if (currentIndex !== index) {
if (this.keepContent) {
this.renderer.addClass(tabContent, this.classes.hiddenContent);
}
tab._activeContent = false;
this._ngZone.run(() => this._markForCheck());
}
}, this.animationDuration);
}
}
/** Runs a timeout outside of the Angular zone to avoid triggering the change detection. */
private _runTimeoutOutsideZone(index: number, fn: () => void, delay = 0) {
this._ngZone.runOutsideAngular(() => this._timeoutIds[`_${index}`] = window.setTimeout(fn, delay));
}
private _clearTimeouts(tabIndex?: number) {
if (tabIndex != null) {
const key = `_${tabIndex}`;
if (this._timeoutIds[key] != null) {
window.clearTimeout(this._timeoutIds[key]);
delete this._timeoutIds[key];
}
} else {
Object.keys(this._timeoutIds)
.forEach(key => window.clearTimeout(this._timeoutIds[`_${key}`]));
}
}
}
@Component({
selector: 'ly-tab',
templateUrl: './tab.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [
StyleRenderer
]
})
export class LyTab implements OnInit {
/** Current tab index */
index: number;
_isBrowser = this._platform.isBrowser;
@ContentChild(LyTabContent, { read: TemplateRef, static: true }) _templateRefLazy: TemplateRef<LyTabContent>;
@ViewChild('_templateNgContent', { static: true }) _templateRef: TemplateRef<any>;
@ViewChild('tabIndicator') _tabIndicator: ElementRef;
@ContentChild(forwardRef(() => LyTabLabel), { static: true }) _tabLabel: LyTabLabel & { };
/** Portal that will be the hosted content of the tab */
private _contentPortal: TemplatePortal | null = null;
/** @docs-private */
get content(): TemplatePortal | null {
return this._contentPortal;
}
_activeContent: boolean;
constructor(
private _tabs: LyTabs,
public _renderer: Renderer2,
public _el: ElementRef,
readonly sRenderer: StyleRenderer,
private _platform: Platform,
private _viewContainerRef: ViewContainerRef,
) { }
ngOnInit() {
this._renderer.addClass(this._el.nativeElement, this._tabs.classes.tab);
this._contentPortal = new TemplatePortal(
this._templateRefLazy || this._templateRef,
this._viewContainerRef
);
}
}
@Component({
selector: 'button[ly-tab-label], a[ly-tab-label]',
templateUrl: 'tab-label.html',
inputs: [
'bg',
'color',
'raised',
'disabled',
'outlined',
'elevation',
'shadowColor',
'disableRipple'
],
providers: [
StyleRenderer
]
})
export class LyTabLabel extends LyButton implements OnInit, AfterViewInit {
private _activeTabStyle: boolean;
private _active: boolean;
disableRipple: boolean;
_isBrowser = this._platform.isBrowser;
@Input()
get active() {
return this._active;
}
set active(val: boolean) {
const newVal = toBoolean(val);
if (newVal && val !== this.active) {
Promise.resolve(null).then(() => this._tabs.selectedIndex = this._tab.index);
}
}
@ViewChild('rippleContainer') _rippleContainer: ElementRef;
@HostListener('click') _onClickTab() {
if (!this.disabled) {
this._tabs.selectedIndex = this._tab.index;
}
}
constructor(
_el: ElementRef,
_renderer: Renderer2,
_theme: LyTheme2,
_ngZone: NgZone,
_rippleService: LyRippleService,
_focusState: LyFocusState,
readonly sRenderer: StyleRenderer,
@Optional() private _tab: LyTab,
@Optional() private _tabs: LyTabs,
platform: Platform
) {
super(_el, _renderer, _theme, _ngZone, _rippleService, _focusState, sRenderer, platform, null as any);
}
ngOnInit() {
this._renderer.addClass(this._el.nativeElement, this._tabs.classes.label);
// set default disable ripple
if (this.disableRipple == null) {
this.disableRipple = DEFAULT_DISABLE_RIPPLE;
}
}
_updateTabState() {
// update styles for active tab
if (this._tabs._selectedIndex === this._tab.index) {
if (!this._activeTabStyle) {
this._activeTabStyle = true;
this._renderer.addClass(this._el.nativeElement, this._tabs.classes.labelActive);
this._updateTabScroll();
}
} else if (this._activeTabStyle) {
this._activeTabStyle = false;
this._renderer.removeClass(this._el.nativeElement, this._tabs.classes.labelActive);
}
}
_updateTabScroll() {
if (this._platform.isBrowser && this._tabs.scrollable) {
const tab = this._tab._el.nativeElement as HTMLElement;
const tabContainer = this._tabs.tabsRef.nativeElement as HTMLElement;
if (tabContainer.scrollWidth !== tabContainer.offsetWidth) {
const dir = this._theme.variables.direction;
const max = tabContainer.scrollWidth - tabContainer.offsetWidth;
const offsetBefore = dir === Dir.rtl
? max + tab.offsetLeft
: tab.offsetLeft;
const l = offsetBefore + tab.offsetWidth / 2 - tabContainer.offsetWidth / 2;
const newVal = l >= max ? max : l <= 0 ? 0 : l;
scrollWithAnimation(this._tabs.tabsRef.nativeElement, newVal, 350, 'x');
}
}
}
ngAfterViewInit() { }
}
/** Enforces a style recalculation of a DOM element by computing its styles. */
function enforceStyleRecalculation(element: HTMLElement) {
window.getComputedStyle(element).getPropertyValue('opacity');
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_purchaseorderproduct_Information {
interface tab_tab_3_Sections {
tab_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_3 extends DevKit.Controls.ITab {
Section: tab_tab_3_Sections;
}
interface Tabs {
tab_3: tab_tab_3;
}
interface Body {
Tab: Tabs;
/** Link this product to Booking. If specified and warehouse is not set then product will be added to Resource Booking */
msdyn_AssociateToBooking: DevKit.Controls.Lookup;
/** Warehouse to which this product should be received to */
msdyn_AssociateToWarehouse: DevKit.Controls.Lookup;
/** Link this product to Work Order. If specified and warehouse is not set then product will be added to work order */
msdyn_AssociateToWorkOrder: DevKit.Controls.Lookup;
/** Enter the date you expect this product to arrive to the shipping address. This value defaults to the date set on the PO. */
msdyn_DateExpected: DevKit.Controls.Date;
/** Enter the product description to display for the vendor. */
msdyn_Description: DevKit.Controls.String;
/** Enter the current status of this product. */
msdyn_ItemStatus: DevKit.Controls.OptionSet;
/** Shows the order of this product within the purchase order. */
msdyn_LineOrder: DevKit.Controls.Integer;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Product to order */
msdyn_Product: DevKit.Controls.Lookup;
/** Purchase order this line item relates to */
msdyn_PurchaseOrder: DevKit.Controls.Lookup;
/** Enter the quantity currently billed. */
msdyn_QtyBilled: DevKit.Controls.Double;
/** Enter the quantity currently received. */
msdyn_QtyReceived: DevKit.Controls.Double;
/** Enter the quantity ordered. */
msdyn_Quantity: DevKit.Controls.Double;
/** Shows the total cost of this product. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs */
msdyn_TotalCost: DevKit.Controls.Money;
/** Unit for this product */
msdyn_Unit: DevKit.Controls.Lookup;
/** Enter the cost of this product per unit. */
msdyn_UnitCost: DevKit.Controls.Money;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Unique identifier of the currency associated with the entity. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Purchase Order Product */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
nav_msdyn_msdyn_purchaseorderproduct_msdyn_inventoryjournal_POProduct: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_purchaseorderproduct_msdyn_purchaseorderreceiptproduct_POProduct: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
}
class Formmsdyn_purchaseorderproduct_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_purchaseorderproduct_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_purchaseorderproduct_Information */
Body: DevKit.Formmsdyn_purchaseorderproduct_Information.Body;
/** The Footer section of form msdyn_purchaseorderproduct_Information */
Footer: DevKit.Formmsdyn_purchaseorderproduct_Information.Footer;
/** The Navigation of form msdyn_purchaseorderproduct_Information */
Navigation: DevKit.Formmsdyn_purchaseorderproduct_Information.Navigation;
}
namespace FormPurchase_Order_Product_Mobile {
interface tab_fstab_general_Sections {
_5AE19875_5712_4CB9_B3B7_F7583E96AE65_SECTION_3: DevKit.Controls.Section;
fstab_general_section_general: DevKit.Controls.Section;
}
interface tab_fstab_other_Sections {
tab_4_section_1: DevKit.Controls.Section;
tab_4_section_2: DevKit.Controls.Section;
tab_4_section_3: DevKit.Controls.Section;
}
interface tab_fstab_product_associates_to_Sections {
fstab_product_associates_to_section: DevKit.Controls.Section;
}
interface tab_fstab_general extends DevKit.Controls.ITab {
Section: tab_fstab_general_Sections;
}
interface tab_fstab_other extends DevKit.Controls.ITab {
Section: tab_fstab_other_Sections;
}
interface tab_fstab_product_associates_to extends DevKit.Controls.ITab {
Section: tab_fstab_product_associates_to_Sections;
}
interface Tabs {
fstab_general: tab_fstab_general;
fstab_other: tab_fstab_other;
fstab_product_associates_to: tab_fstab_product_associates_to;
}
interface Body {
Tab: Tabs;
/** Link this product to Booking. If specified and warehouse is not set then product will be added to Resource Booking */
msdyn_AssociateToBooking: DevKit.Controls.Lookup;
/** Warehouse to which this product should be received to */
msdyn_AssociateToWarehouse: DevKit.Controls.Lookup;
/** Link this product to Work Order. If specified and warehouse is not set then product will be added to work order */
msdyn_AssociateToWorkOrder: DevKit.Controls.Lookup;
/** Enter the date you expect this product to arrive to the shipping address. This value defaults to the date set on the PO. */
msdyn_DateExpected: DevKit.Controls.Date;
/** Enter the product description to display for the vendor. */
msdyn_Description: DevKit.Controls.String;
/** Enter the current status of this product. */
msdyn_ItemStatus: DevKit.Controls.OptionSet;
/** Shows the order of this product within the purchase order. */
msdyn_LineOrder: DevKit.Controls.Integer;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Product to order */
msdyn_Product: DevKit.Controls.Lookup;
/** Purchase order this line item relates to */
msdyn_PurchaseOrder: DevKit.Controls.Lookup;
/** Enter the quantity currently billed. */
msdyn_QtyBilled: DevKit.Controls.Double;
/** Enter the quantity currently received. */
msdyn_QtyReceived: DevKit.Controls.Double;
/** Enter the quantity ordered. */
msdyn_Quantity: DevKit.Controls.Double;
/** Shows the total cost of this product. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs */
msdyn_TotalCost: DevKit.Controls.Money;
/** Unit for this product */
msdyn_Unit: DevKit.Controls.Lookup;
/** Enter the cost of this product per unit. */
msdyn_UnitCost: DevKit.Controls.Money;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Unique identifier of the currency associated with the entity. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
interface Navigation {
nav_msdyn_msdyn_purchaseorderproduct_msdyn_inventoryjournal_POProduct: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_purchaseorderproduct_msdyn_purchaseorderreceiptproduct_POProduct: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
}
class FormPurchase_Order_Product_Mobile extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Purchase_Order_Product_Mobile
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Purchase_Order_Product_Mobile */
Body: DevKit.FormPurchase_Order_Product_Mobile.Body;
/** The Navigation of form Purchase_Order_Product_Mobile */
Navigation: DevKit.FormPurchase_Order_Product_Mobile.Navigation;
}
class msdyn_purchaseorderproductApi {
/**
* DynamicsCrm.DevKit msdyn_purchaseorderproductApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Link this product to Booking. If specified and warehouse is not set then product will be added to Resource Booking */
msdyn_AssociateToBooking: DevKit.WebApi.LookupValue;
/** Warehouse to which this product should be received to */
msdyn_AssociateToWarehouse: DevKit.WebApi.LookupValue;
/** Link this product to Work Order. If specified and warehouse is not set then product will be added to work order */
msdyn_AssociateToWorkOrder: DevKit.WebApi.LookupValue;
/** Enter the date you expect this product to arrive to the shipping address. This value defaults to the date set on the PO. */
msdyn_DateExpected_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the product description to display for the vendor. */
msdyn_Description: DevKit.WebApi.StringValue;
msdyn_InternalFlags: DevKit.WebApi.StringValue;
msdyn_IsOrdered: DevKit.WebApi.BooleanValue;
/** Enter the current status of this product. */
msdyn_ItemStatus: DevKit.WebApi.OptionSetValue;
/** Shows the order of this product within the purchase order. */
msdyn_LineOrder: DevKit.WebApi.IntegerValue;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Product to order */
msdyn_Product: DevKit.WebApi.LookupValue;
/** Purchase order this line item relates to */
msdyn_PurchaseOrder: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_purchaseorderproductId: DevKit.WebApi.GuidValue;
/** Enter the quantity currently billed. */
msdyn_QtyBilled: DevKit.WebApi.DoubleValue;
/** Enter the quantity currently received. */
msdyn_QtyReceived: DevKit.WebApi.DoubleValue;
/** Enter the quantity ordered. */
msdyn_Quantity: DevKit.WebApi.DoubleValue;
/** Shows the total cost of this product. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs */
msdyn_TotalCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the total cost in the base currency. */
msdyn_totalcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Unit for this product */
msdyn_Unit: DevKit.WebApi.LookupValue;
/** Enter the cost of this product per unit. */
msdyn_UnitCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the unit cost in the base currency. */
msdyn_unitcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Purchase Order Product */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Purchase Order Product */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the entity. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_purchaseorderproduct {
enum msdyn_ItemStatus {
/** 690970002 */
Canceled,
/** 690970000 */
Pending,
/** 690970001 */
Received
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information','Purchase Order Product - Mobile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {DB} from '../../Library/Infra/DB';
import {IssueEntity} from '../../Library/Type/IssueEntity';
import {DateUtil} from '../../Library/Util/DateUtil';
import {StreamEntity} from '../../Library/Type/StreamEntity';
import {StreamId} from '../StreamRepo';
import {color} from '../../Library/Style/color';
import {UserPrefRepo} from '../UserPrefRepo';
class _DBSetup {
private migrationNodeId: boolean = false;
async exec(dbPath: string): Promise<{error?: Error}> {
this.migrationNodeId = false;
const {error} = await DB.init(dbPath);
if (error) return {error};
await Promise.all([
this.createIssues(),
this.createStreams(),
this.createStreamsIssues(),
this.createSubscriptionIssues(),
this.createFilterHistories(),
this.createJumpNavigationHistories(),
]);
return {};
}
isMigrationNodeId(): boolean {
return this.migrationNodeId;
}
private async createIssues() {
await DB.exec(`
create table if not exists issues (
_id integer primary key autoincrement,
id integer unique not null,
node_id string unique not null,
type text not null,
title text not null,
created_at text not null,
updated_at text not null,
closed_at text,
merged_at text,
read_at text,
prev_read_at text,
unread_at text,
archived_at text,
marked_at text,
number integer not null,
user text not null,
repo text not null,
repo_private integer not null default 0,
author text not null,
assignees text,
labels text,
milestone text,
due_on text,
draft integer not null default 0,
involves text,
mentions text,
review_requested text,
reviews text,
project_urls text,
project_names text,
project_columns text,
last_timeline_user text,
last_timeline_at text,
html_url text not null,
body text,
read_body text,
prev_read_body text,
value text not null
)`);
// migration to v0.2.1 from v0.2.0
{
const {error} = await DB.exec('select assignees from issues limit 1');
if (error) {
console.log('start migration: assignees');
await DB.exec('alter table issues add column assignees text');
const {rows: issues} = await DB.select<IssueEntity>('select * from issues');
for (const issue of issues) {
const value = JSON.parse(issue.value as any);
let assignees = [];
if (value.assignees) {
assignees = value.assignees;
} else if (value.assignee) {
assignees = [value.assignee];
}
const names = assignees.length ? assignees.map((assignee)=> `<<<<${assignee.login}>>>>`).join('') : null; // hack
await DB.exec('update issues set assignees = ? where id = ?', [names, issue.id]);
}
console.log('end migration: assignees');
}
}
// migration to v0.3.0 from v0.2.5
{
const {error} = await DB.exec('select body from issues limit 1');
if (error) {
console.log('start migration: body');
await DB.exec('alter table issues add column body text');
const {rows: issues} = await DB.select<IssueEntity>('select * from issues');
for (const issue of issues) {
const value = JSON.parse(issue.value as any);
await DB.exec('update issues set body = ? where id = ?', [value.body, issue.id]);
}
console.log('end migration: body');
}
}
// migration to v0.4.0 from v0.3.1
{
const {error} = await DB.exec('select read_body from issues limit 1');
if (error) {
console.log('start migration: read_body');
await DB.exec('alter table issues add column read_body text');
await DB.exec('alter table issues add column prev_read_body text');
await DB.exec('update issues set read_body = body, prev_read_body = body');
console.log('end migration: read_body');
}
}
// migration draft to v0.10.0
{
const {error} = await DB.exec('select draft from issues limit 1');
if (error) {
console.log('start migration: draft');
await DB.exec('alter table issues add column draft integer not null default 0');
console.log('end migration: draft');
}
}
// migration merged_at to v0.10.0
{
const {error} = await DB.exec('select merged_at from issues limit 1');
if (error) {
console.log('start migration: merged_at');
await DB.exec('alter table issues add column merged_at text');
console.log('end migration: merged_at');
}
}
// migration node_id to v0.10.0
{
const {error} = await DB.exec('select node_id from issues limit 1');
if (error) {
const now = Date.now();
console.log('start migration: node_id');
await DB.exec('alter table issues add column node_id text');
const {error, rows} = await DB.select<{id: number; value: string}>('select id, value from issues');
if (error) throw error;
const whenRows: string[] = [];
for (const row of rows) {
const value = JSON.parse(row.value) as {node_id: string};
if (value.node_id) whenRows.push(`when ${row.id} then "${value.node_id}"`);
}
const res = await DB.exec(`update issues set node_id = case id ${whenRows.join('\n')} end`);
if (res.error) throw res.error;
this.migrationNodeId = true;
console.log(`end migration: node_id (${Date.now() - now}ms)`);
}
}
// migration repo_private, involves, review_requested, reviews to v0.10.0
{
const {error} = await DB.exec('select repo_private, involves, review_requested, reviews from issues limit 1');
if (error) {
console.log('start migration: repo_private, involves, review_requested, reviews');
await DB.exec('alter table issues add column repo_private integer');
await DB.exec('alter table issues add column involves text');
await DB.exec('alter table issues add column review_requested text');
await DB.exec('alter table issues add column reviews text');
console.log('end migration: repo_private, involves, review_requested, reviews');
}
}
// migration mentions to v1.0.0
{
const {error} = await DB.exec('select mentions from issues limit 1');
if (error) {
console.log('start migration: mentions');
await DB.exec('alter table issues add column mentions text');
console.log('end migration: mentions');
}
}
// migration last_timeline_user, last_timeline_at to v0.10.0
{
const {error} = await DB.exec('select last_timeline_user, last_timeline_at from issues limit 1');
if (error) {
console.log('start migration: last_timeline_user, last_timeline_at');
await DB.exec('alter table issues add column last_timeline_user text');
await DB.exec('alter table issues add column last_timeline_at text');
console.log('end migration: last_timeline_user, last_timeline_at');
}
}
// migration project_urls, project_names, project_columns to v0.10.0
{
const {error} = await DB.exec('select project_urls, project_names, project_columns from issues limit 1');
if (error) {
console.log('start migration: project_urls, project_names, project_columns');
await DB.exec('alter table issues add column project_urls text');
await DB.exec('alter table issues add column project_names text');
await DB.exec('alter table issues add column project_columns text');
console.log('end migration: project_urls, project_names, project_columns');
}
}
// migration unread_at to v0.10.0
{
const {error} = await DB.exec('select unread_at from issues limit 1');
if (error) {
console.log('start migration: unread_at');
await DB.exec('alter table issues add column unread_at text');
console.log('end migration: unread_at');
}
}
await DB.exec(`create index if not exists node_id_index on issues(node_id)`);
await DB.exec(`create index if not exists type_index on issues(type)`);
await DB.exec(`create index if not exists title_index on issues(title)`);
await DB.exec(`create index if not exists read_at_index on issues(read_at)`);
await DB.exec(`create index if not exists archived_at_index on issues(archived_at)`);
await DB.exec(`create index if not exists marked_at_index on issues(marked_at)`);
await DB.exec(`create index if not exists closed_at_index on issues(closed_at)`);
await DB.exec(`create index if not exists created_at_index on issues(created_at)`);
await DB.exec(`create index if not exists updated_at_index on issues(updated_at)`);
await DB.exec(`create index if not exists number_index on issues(number)`);
await DB.exec(`create index if not exists author_index on issues(author)`);
await DB.exec(`create index if not exists assignees_index on issues(assignees)`);
await DB.exec(`create index if not exists involves_index on issues(involves)`);
await DB.exec(`create index if not exists mentions_index on issues(mentions)`);
await DB.exec(`create index if not exists review_requested_index on issues(review_requested)`);
await DB.exec(`create index if not exists reviews_index on issues(reviews)`);
await DB.exec(`create index if not exists milestone_index on issues(milestone)`);
await DB.exec(`create index if not exists user_index on issues(user)`);
await DB.exec(`create index if not exists repo_index on issues(repo)`);
await DB.exec(`create index if not exists repo_private_index on issues(repo_private)`);
await DB.exec(`create index if not exists html_url_index on issues(html_url)`);
await DB.exec(`create index if not exists archived_updated_index on issues(archived_at,updated_at)`);
await DB.exec(`create index if not exists archived_created_index on issues(archived_at,created_at)`);
await DB.exec(`create index if not exists archived_closed_index on issues(archived_at,closed_at)`);
await DB.exec(`create index if not exists archived_read_index on issues(archived_at,read_at)`);
await DB.exec(`create index if not exists archived_due_index on issues(archived_at,due_on)`);
await DB.exec(`create index if not exists draft_index on issues(draft)`);
await DB.exec(`create index if not exists last_timeline_user_index on issues(last_timeline_user)`);
await DB.exec(`create index if not exists last_timeline_at_index on issues(last_timeline_at)`);
await DB.exec(`create index if not exists project_urls_index on issues(project_urls)`);
await DB.exec(`create index if not exists project_names_index on issues(project_names)`);
await DB.exec(`create index if not exists project_columns_index on issues(project_columns)`);
}
private async createStreams() {
await DB.exec(`
create table if not exists streams (
id integer primary key autoincrement,
type text,
name text not null,
query_stream_id integer default null,
queries text not null,
default_filter text,
user_filter text,
position integer,
notification integer,
icon text,
color text,
enabled integer not null default 1,
created_at text,
updated_at text,
searched_at text
)`);
// migration column to v0.10.0
{
const {error} = await DB.exec('select type from streams limit 1');
if (error) {
console.log('start migration: streams.type and etc');
await DB.exec('alter table streams add column type text');
await DB.exec('alter table streams add column query_stream_id integer default null');
await DB.exec('alter table streams add column default_filter text');
await DB.exec('alter table streams add column user_filter text');
await DB.exec('alter table streams add column icon text');
await DB.exec('alter table streams add column enabled integer not null default 1');
console.log('end migration: streams.type');
}
}
// migration stream.{type, query_stream_id, default_filter, icon} to v0.10.0
{
const type: StreamEntity['type'] = 'UserStream';
await DB.exec(`
update
streams
set
type = "${type}",
query_stream_id = id,
default_filter = "is:unarchived",
user_filter = "",
enabled = 1,
icon = "github"
where
id > 0
and type is null
`);
}
// migration filtered_streams to v0.10.0
{
const {error, rows} = await DB.select<{stream_id: number; name: string; position: number; notification: number; filter: string; color: string; created_at: string; updated_at: string}>('select * from filtered_streams');
if (!error) {
console.log('start migration: filtered_streams');
const type: StreamEntity['type'] = 'FilterStream';
for (const row of rows) {
const res = await DB.exec(`
insert into
streams (type, name, query_stream_id, queries, default_filter, user_filter, position, notification, icon, color, enabled, created_at, updated_at, searched_at)
values
("${type}", ?, ${row.stream_id}, "", "is:unarchived", ?, ${row.position}, ${row.notification}, "file-tree", "${row.color}", 1, "${row.created_at}", "${row.updated_at}", "")
`, [row.name, row.filter]);
if (res.error) throw res.error;
}
await DB.exec('alter table filtered_streams rename to deleted_filtered_streams');
console.log('start migration: filtered_streams');
}
}
// migration system_streams and library stream to v0.10.0
{
const {error} = await DB.selectSingle(`select * from system_streams`);
const {row} = await DB.selectSingle(`select * from streams where id = ?`, [StreamId.inbox]);
if (!error && !row) {
console.log('start migration: system_streams, library streams');
const {row} = await DB.selectSingle<{maxId: number}>('select max(id) as maxId from streams');
const meId = row.maxId + 1;
const meQueries = JSON.stringify([`involves:${UserPrefRepo.getUser().login}`, `user:${UserPrefRepo.getUser().login}`]);
const {rows} = await DB.select<{name: string, searched_at: string; enabled: number; notification: number}>('select * from system_streams');
const me = rows.find(row => row.name === 'Me');
const team = rows.find(row => row.name === 'Team');
const watch = rows.find(row => row.name === 'Watching');
const sub = rows.find(row => row.name === 'Subscription');
const createdAt = DateUtil.localToUTCString(new Date());
const uType: StreamEntity['type'] = 'UserStream';
const sType: StreamEntity['type'] = 'SystemStream';
const lType: StreamEntity['type'] = 'LibraryStream';
let res = await DB.exec(`
insert into
streams (id, type, name, query_stream_id, queries, default_filter, user_filter, position, notification, icon, color, enabled, created_at, updated_at, searched_at)
values
(${StreamId.inbox}, "${lType}", "Inbox", null, "", "is:unarchived", "", -1004, 0, "inbox-full", "${color.stream.blue}", 1, "${createdAt}", "${createdAt}", ""),
(${StreamId.unread}, "${lType}", "Unread", null, "", "is:unarchived is:unread", "", -1003, 0, "clipboard-outline", "${color.stream.blue}", 0, "${createdAt}", "${createdAt}", ""),
(${StreamId.open}, "${lType}", "Open", null, "", "is:unarchived is:open", "", -1002, 0, "book-open-variant", "${color.stream.blue}", 0, "${createdAt}", "${createdAt}", ""),
(${StreamId.mark}, "${lType}", "Bookmark", null, "", "is:unarchived is:bookmark", "", -1001, 0, "bookmark", "${color.stream.blue}", 1, "${createdAt}", "${createdAt}", ""),
(${StreamId.archived}, "${lType}", "Archived", null, "", "is:archived", "", -1000, 0, "archive", "${color.stream.blue}", 1, "${createdAt}", "${createdAt}", ""),
(${meId}, "${uType}", "Me", ${meId}, '${meQueries}', "is:unarchived", "", -103, ${me.notification}, "github", "${color.brand}", ${me.enabled}, "${createdAt}", "${createdAt}", "${me.searched_at}"),
(${StreamId.team}, "${sType}", "Team", ${StreamId.team}, "", "is:unarchived", "", -102, ${team.notification}, "account-multiple", "${color.brand}", ${team.enabled}, "${createdAt}", "${createdAt}", "${team.searched_at}"),
(${StreamId.watching}, "${sType}", "Watching", ${StreamId.watching}, "", "is:unarchived", "", -101, ${watch.notification}, "eye", "${color.brand}", ${watch.enabled}, "${createdAt}", "${createdAt}", "${watch.searched_at}"),
(${StreamId.subscription}, "${sType}", "Subscription", ${StreamId.subscription}, "", "is:unarchived", "", -100, ${sub.notification}, "volume-high", "${color.brand}", ${sub.enabled}, "${createdAt}", "${createdAt}", "${sub.searched_at}")
`);
if (res.error) throw res.error;
res = await DB.exec(`update streams_issues set stream_id = ? where stream_id = ?`, [meId, StreamId.me]);
if (res.error) throw res.error;
res = await DB.exec(`alter table system_streams rename to deleted_system_streams`);
if (res.error) throw res.error;
console.log('end migration: system_streams, library streams');
}
}
}
private async createSubscriptionIssues() {
await DB.exec(`
create table if not exists subscription_issues (
id integer primary key,
issue_id integer not null,
url text not null,
repo text not null,
created_at text not null
)`);
await DB.exec(`create index if not exists url_index on subscription_issues(url)`);
}
private async createStreamsIssues() {
await DB.exec(`
create table if not exists streams_issues (
id integer primary key autoincrement,
stream_id integer not null,
issue_id integer not null
)`);
await DB.exec(`create index if not exists stream_issue_index on streams_issues(stream_id, issue_id)`);
}
private async createFilterHistories() {
await DB.exec(`
create table if not exists filter_histories (
id integer primary key autoincrement,
filter text not null,
created_at text not null
)`);
await DB.exec(`create index if not exists filter_index on filter_histories(filter)`);
await DB.exec(`create index if not exists created_at_index on filter_histories(created_at)`);
}
private async createJumpNavigationHistories() {
await DB.exec(`
create table if not exists jump_navigation_histories (
id integer primary key autoincrement,
keyword text not null,
created_at text not null
)`);
await DB.exec(`create index if not exists keyword_index on jump_navigation_histories(keyword)`);
await DB.exec(`create index if not exists created_at_index on jump_navigation_histories(created_at)`);
}
}
export const DBSetup = new _DBSetup(); | the_stack |
import { GeoPackage } from '../geoPackage';
import { FeatureTableIndex } from './index/featureTableIndex';
import { GeometryIndexDao } from './index/geometryIndexDao';
import { TableIndexDao } from './index/tableIndexDao';
import { CoreSQLUtils } from '../db/coreSQLUtils';
import { TileScalingDao } from './scale/tileScalingDao';
import { TileScalingExtension } from './scale';
import { FeatureStyleExtension } from './style';
import { RelatedTablesExtension } from './relatedTables';
import { ContentsIdExtension } from './contents';
import { UserCustomTableReader } from '../user/custom/userCustomTableReader';
import { AlterTable } from '../db/alterTable';
import { TableMapping } from '../db/tableMapping';
import { UserMappingTable } from './relatedTables/userMappingTable';
import { ExtendedRelationDao } from './relatedTables/extendedRelationDao';
import { TableInfo } from '../db/table/tableInfo';
import { ContentsIdDao } from './contents/contentsIdDao';
export class NGAExtensions {
/**
* Delete all NGA table extensions for the table within the GeoPackage
* @param geoPackage GeoPackage
* @param table table name
*/
static deleteTableExtensions(geoPackage: GeoPackage, table: string) {
NGAExtensions.deleteGeometryIndex(geoPackage, table);
NGAExtensions.deleteTileScaling(geoPackage, table);
NGAExtensions.deleteFeatureStyle(geoPackage, table);
NGAExtensions.deleteContentsId(geoPackage, table);
// Delete future extensions for the table here
}
/**
* Delete all NGA extensions including custom extension tables for the
* GeoPackage
* @param geoPackage GeoPackage
*/
static deleteExtensions(geoPackage: GeoPackage) {
NGAExtensions.deleteGeometryIndexExtension(geoPackage);
NGAExtensions.deleteTileScalingExtension(geoPackage);
NGAExtensions.deleteFeatureStyleExtension(geoPackage);
NGAExtensions.deleteContentsIdExtension(geoPackage);
// Delete future extension tables here
}
/**
* Copy all NGA table extensions for the table within the GeoPackage
* @param geoPackage GeoPackage
* @param table table name
* @param newTable new table name
*/
static copyTableExtensions(geoPackage: GeoPackage, table: string, newTable: string) {
try {
NGAExtensions.copyContentsId(geoPackage, table, newTable);
NGAExtensions.copyFeatureStyle(geoPackage, table, newTable);
NGAExtensions.copyTileScaling(geoPackage, table, newTable);
NGAExtensions.copyGeometryIndex(geoPackage, table, newTable);
// Copy future extensions for the table here
} catch (e) {
console.warn('Failed to copy extensions for table: ' + newTable + ', copied from table: ' + table, e);
}
}
/**
* Delete the Geometry Index extension for the table
* @param geoPackage GeoPackage
* @param table table name
*/
static deleteGeometryIndex(geoPackage: GeoPackage, table: string) {
let tableIndexDao = geoPackage.tableIndexDao;
let extensionsDao = geoPackage.extensionDao;
try {
if (tableIndexDao.isTableExists()) {
tableIndexDao.deleteById(table)
}
if (extensionsDao.isTableExists()) {
extensionsDao.deleteByExtensionAndTableName(FeatureTableIndex.EXTENSION_NAME, table);
}
} catch (e) {
throw new Error('Failed to delete Table Index. GeoPackage: ' + geoPackage.name + ', Table: ' + table);
}
}
/**
* Delete the Geometry Index extension including the extension entries and
* custom tables
* @param geoPackage GeoPackage
*/
static deleteGeometryIndexExtension(geoPackage: GeoPackage) {
let geometryIndexDao = geoPackage.getGeometryIndexDao(null);
let tableIndexDao = geoPackage.tableIndexDao;
let extensionsDao = geoPackage.extensionDao;
try {
if (geometryIndexDao.isTableExists()) {
geoPackage.dropTable(GeometryIndexDao.TABLE_NAME);
}
if (tableIndexDao.isTableExists()) {
geoPackage.dropTable(TableIndexDao.TABLE_NAME);
}
if (extensionsDao.isTableExists()) {
extensionsDao.deleteByExtension(FeatureTableIndex.EXTENSION_NAME);
}
} catch (e) {
throw new Error('Failed to delete Table Index extension and tables. GeoPackage: ' + geoPackage.name);
}
}
/**
* Copy the Geometry Index extension for the table
* @param geoPackage GeoPackage
* @param table table name
* @param newTable new table name
*/
static copyGeometryIndex(geoPackage: GeoPackage, table: string, newTable: string) {
try {
let extensionsDao = geoPackage.extensionDao;
if (extensionsDao.isTableExists()) {
let extensions = extensionsDao.queryByExtensionAndTableName(FeatureTableIndex.EXTENSION_NAME, table);
if (extensions.length > 0) {
let extension = extensions[0];
extension.table_name = newTable;
extensionsDao.create(extension);
let tableIndexDao = geoPackage.tableIndexDao;
if (tableIndexDao.isTableExists()) {
let tableIndex = tableIndexDao.queryForId(table);
if (tableIndex != null) {
tableIndex.table_name = newTable;
tableIndexDao.create(tableIndex);
if (geoPackage.isTable(GeometryIndexDao.TABLE_NAME)) {
CoreSQLUtils.transferTableContent(
geoPackage.connection,
GeometryIndexDao.TABLE_NAME,
GeometryIndexDao.COLUMN_TABLE_NAME,
newTable, table);
}
}
}
}
}
} catch (e) {
console.warn(
'Failed to create Geometry Index for table: ' + newTable
+ ', copied from table: ' + table,
e);
}
}
/**
* Delete the Tile Scaling extensions for the table
* @param geoPackage GeoPackage
* @param table table name
*/
static deleteTileScaling(geoPackage: GeoPackage, table: string) {
let tileScalingDao = geoPackage.tileScalingDao;
let extensionsDao = geoPackage.extensionDao;
try {
if (tileScalingDao.isTableExists()) {
tileScalingDao.deleteByTableName(table);
}
if (extensionsDao.isTableExists()) {
extensionsDao.deleteByExtensionAndTableName(TileScalingExtension.EXTENSION_NAME, table);
}
} catch (e) {
throw new Error(
'Failed to delete Tile Scaling. GeoPackage: ' + geoPackage.name + ', Table: ' + table);
}
}
/**
* Delete the Tile Scaling extension including the extension entries and
* custom tables
* @param geoPackage GeoPackage
*/
static deleteTileScalingExtension(geoPackage: GeoPackage) {
let tileScalingDao = geoPackage.tileScalingDao;
let extensionsDao = geoPackage.extensionDao;
try {
if (tileScalingDao.isTableExists()) {
geoPackage.dropTable(tileScalingDao.gpkgTableName);
}
if (extensionsDao.isTableExists()) {
extensionsDao.deleteByExtension(TileScalingExtension.EXTENSION_NAME);
}
} catch (e) {
throw new Error(
'Failed to delete Tile Scaling extension and table. GeoPackage: '
+ geoPackage.name);
}
}
/**
* Copy the Tile Scaling extensions for the table
* @param geoPackage GeoPackage
* @param table table name
* @param newTable new table name
*/
static copyTileScaling(geoPackage: GeoPackage, table: string, newTable: string) {
try {
let tileTableScaling = new TileScalingExtension(geoPackage, table);
if (tileTableScaling.has()) {
let extension = tileTableScaling.getOrCreateExtension();
if (extension !== null && extension !== undefined) {
extension.setTableName(newTable);
tileTableScaling.getOrCreateExtension();
if (geoPackage.isTable(TileScalingDao.TABLE_NAME)) {
CoreSQLUtils.transferTableContent(
geoPackage.connection,
TileScalingDao.TABLE_NAME,
TileScalingDao.COLUMN_TABLE_NAME, newTable, table);
}
}
}
} catch (e) {
console.warn('Failed to create Tile Scaling for table: ' + newTable + ', copied from table: ' + table, e);
}
}
/**
* Delete the Feature Style extensions for the table
* @param geoPackage GeoPackage
* @param table table name
*/
static deleteFeatureStyle(geoPackage: GeoPackage, table: string) {
let featureStyleExtension = NGAExtensions.getFeatureStyleExtension(geoPackage);
if (featureStyleExtension.has(table)) {
featureStyleExtension.deleteRelationships(table);
}
}
/**
* Delete the Feature Style extension including the extension entries and
* custom tables
* @param geoPackage GeoPackage
*/
static deleteFeatureStyleExtension(geoPackage: GeoPackage) {
let featureStyleExtension = NGAExtensions.getFeatureStyleExtension(geoPackage);
if (featureStyleExtension.has(null)) {
featureStyleExtension.removeExtension();
}
}
/**
* Copy the Feature Style extensions for the table. Relies on
* {@link GeoPackageExtensions#copyRelatedTables(GeoPackageCore, String, String)}
* to be called first.
* @param geoPackage GeoPackage
* @param table table name
* @param newTable new table name
*/
static copyFeatureStyle(geoPackage: GeoPackage, table: string, newTable: string) {
try {
let featureStyleExtension = NGAExtensions.getFeatureStyleExtension(geoPackage);
if (featureStyleExtension.hasRelationship(table)) {
let extension = featureStyleExtension.getOrCreateExtension(table);
if (extension != null) {
extension.setTableName(newTable);
featureStyleExtension.extensionsDao.create(extension);
let contentsIdExtension = featureStyleExtension.getContentsId();
let contentsId = contentsIdExtension.getIdByTableName(table);
let newContentsId = contentsIdExtension.getIdByTableName(newTable);
if (contentsId !== null && contentsId !== undefined && newContentsId !== null && newContentsId !== undefined) {
if (featureStyleExtension.hasTableStyleRelationship(table)) {
NGAExtensions.copyFeatureTableStyle(featureStyleExtension, FeatureStyleExtension.TABLE_MAPPING_TABLE_STYLE, table, newTable, contentsId, newContentsId);
}
if (featureStyleExtension.hasTableIconRelationship(table)) {
NGAExtensions.copyFeatureTableStyle(featureStyleExtension, FeatureStyleExtension.TABLE_MAPPING_TABLE_ICON, table, newTable, contentsId, newContentsId);
}
}
}
}
} catch (e) {
console.warn(
'Failed to create Feature Style for table: ' + newTable
+ ', copied from table: ' + table, e);
}
}
/**
* Copy the feature table style
* @param featureStyleExtension feature style extension
* @param mappingTablePrefix mapping table prefix
* @param table table name
* @param newTable new table name
* @param contentsId contents id
* @param newContentsId new contents id
*/
static copyFeatureTableStyle(featureStyleExtension: FeatureStyleExtension, mappingTablePrefix: string, table: string, newTable: string, contentsId: number, newContentsId: number) {
let geoPackage: GeoPackage = featureStyleExtension.geoPackage;
let mappingTableName = featureStyleExtension.getMappingTableName(mappingTablePrefix, table);
let extensionsDao = geoPackage.extensionDao;
let extensions = extensionsDao.queryByExtensionAndTableName(RelatedTablesExtension.EXTENSION_NAME, mappingTableName);
if (extensions.length > 0) {
let newMappingTableName = featureStyleExtension.getMappingTableName(mappingTablePrefix, newTable);
let userTable = new UserCustomTableReader(mappingTableName).readTable(geoPackage.connection);
AlterTable.copyTable(geoPackage.connection, userTable, newMappingTableName, false);
let mappingTableTableMapping = new TableMapping(userTable.getTableName(), newMappingTableName, userTable.getUserColumns().getColumns());
let baseIdColumn = mappingTableTableMapping.getColumn(UserMappingTable.COLUMN_BASE_ID);
baseIdColumn.constantValue = newContentsId;
baseIdColumn.whereValue = contentsId;
CoreSQLUtils.transferTableContentForTableMapping(geoPackage.connection, mappingTableTableMapping);
let extension = extensions[0];
extension.setTableName(newMappingTableName);
extensionsDao.create(extension);
let extendedRelationTableMapping = TableMapping.fromTableInfo(TableInfo.info(geoPackage.connection, ExtendedRelationDao.TABLE_NAME));
extendedRelationTableMapping.removeColumn(ExtendedRelationDao.ID);
let baseTableNameColumn = extendedRelationTableMapping.getColumn(ExtendedRelationDao.BASE_TABLE_NAME);
baseTableNameColumn.whereValue = ContentsIdDao.TABLE_NAME;
let mappingTableNameColumn = extendedRelationTableMapping.getColumn(ExtendedRelationDao.MAPPING_TABLE_NAME);
mappingTableNameColumn.constantValue = newMappingTableName;
mappingTableNameColumn.whereValue = mappingTableName;
CoreSQLUtils.transferTableContentForTableMapping(geoPackage.connection, extendedRelationTableMapping);
}
}
/**
* Get a Feature Style Extension used only for deletions
* @param geoPackage GeoPackage
* @return Feature Style Extension
*/
static getFeatureStyleExtension(geoPackage: GeoPackage): FeatureStyleExtension {
return new FeatureStyleExtension(geoPackage);
}
/**
* Delete the Contents Id extensions for the table
* @param geoPackage GeoPackage
* @param table table name
*/
static deleteContentsId(geoPackage: GeoPackage, table: string) {
let contentsIdExtension = new ContentsIdExtension(geoPackage);
if (contentsIdExtension.has()) {
contentsIdExtension.deleteIdByTableName(table);
}
}
/**
* Delete the Contents Id extension including the extension entries and
* custom tables
* @param geoPackage GeoPackage
*/
static deleteContentsIdExtension(geoPackage: GeoPackage) {
let contentsIdExtension = new ContentsIdExtension(geoPackage);
if (contentsIdExtension.has()) {
contentsIdExtension.removeExtension();
}
}
/**
* Copy the Contents Id extensions for the table
* @param geoPackage GeoPackage
* @param table table name
* @param newTable new table name
*/
static copyContentsId(geoPackage: GeoPackage, table: string, newTable: string) {
try {
let contentsIdExtension = new ContentsIdExtension(geoPackage);
if (contentsIdExtension.has()) {
if (contentsIdExtension.getByTableName(table) !== null) {
contentsIdExtension.createWithTableName(newTable);
}
}
} catch (e) {
console.warn( 'Failed to create Contents Id for table: '
+ newTable + ', copied from table: ' + table, e);
}
}
} | the_stack |
import React, { useEffect, useState } from "react";
import { AutoComplete, Descriptions, Dropdown, Icon, Input, Menu, Modal, Table, Tooltip } from "antd";
import QuickInsertComponent from '../quick-insert';
import styles from './index.less';
import { MoreOutlined } from "@ant-design/icons";
// import MonacoEditor from 'react-monaco-editor';
import { getWebsocket } from "@/layouts/GlobalWebSocket";
import AceEditor from "react-ace";
import moment from "moment";
interface Props {
close: Function;
data: any;
metaDataList: any[];
formData: any;
}
const MagnifyComponent: React.FC<Props> = (props) => {
const [quickInsertVisible, setQuickInsertVisible] = useState<boolean>(props.data.isAssign);
const [assignVisible, setAssignVisible] = useState<boolean>(props.data.isAssign);
const [dataList, setDataList] = useState<any[]>([]);
const [result, setResult] = useState<any[]>([]);
const [subs, setSubs] = useState<any>();
const [sub, setSub] = useState<any>();
const [otherList, setOtherList] = useState<any[]>([]);
const [isBeginning, setIsBeginning] = useState(true);
const [editor, setEditor] = useState<any>(null);
const [script, setScript] = useState(props.data.script || '');
const [virtualRule, setVirtualRule] = useState(props.data.expands?.virtualRule || {});
const [virtualId, setVirtualId] = useState('');
const symbolList = [
{
key: 'add',
value: '+'
},
{
key: 'subtract',
value: '-'
},
{
key: 'multiply',
value: '*'
},
{
key: 'divide',
value: '/'
}, {
key: 'parentheses',
value: '()'
},
{
key: 'cubic',
value: '^'
}
]
const otherSymbolList = [
{
key: 'dayu',
value: '>'
},
{
key: 'dayudengyu',
value: '>='
},
{
key: 'dengyudengyu',
value: '=='
},
{
key: 'xiaoyudengyu',
value: '<='
}, {
key: 'xiaoyu',
value: '<'
},
{
key: 'jiankuohao',
value: '<>'
},
{
key: 'andand',
value: '&&'
},
{
key: 'huohuo',
value: '||'
},
{
key: 'fei',
value: '!'
},
{
key: 'and',
value: '&'
},
{
key: 'huo',
value: '|'
},
{
key: 'bolang',
value: '~'
}
]
const handleChange = (value: any, record: any) => {
for (let i in value) {
record[i] = value[i];
dataList.map((item) =>
item.key == record.key ? { ...item, [i]: value[i] } : item)
setDataList([...dataList])
}
}
const columns = [
{
title: '属性ID',
dataIndex: 'id',
key: 'id',
align: 'center',
render: (text: string, record: any) =>
<AutoComplete onChange={(value) => {
let data: any = otherList.find((item) => {
return item.id === value
})
handleChange({ id: value, type: data?.type }, record);
}}>
{
otherList.map(item => <AutoComplete.Option key={item.id}>{item.id}</AutoComplete.Option>)
}
</AutoComplete>
},
{
title: '属性当前值',
dataIndex: 'current',
key: 'current',
render: (text: string, record: any) => <Input value={text} onChange={(e) => {
handleChange({ current: e.target.value }, record);
}} />
},
{
title: '属性上一值',
dataIndex: 'last',
key: 'last',
render: (text: string, record: any) => <Input value={text} onChange={(e) => {
handleChange({ last: e.target.value }, record);
}} />
},
{
title: '',
with: 200,
align: 'center',
render: (text: string, record: any, index: number) => (
<span onClick={() => {
dataList.splice(index, 1);
setDataList([...dataList]);
}}>
<Icon type="delete" />
</span>
),
}
];
const debugProperty = () => {
console.log('开始调试...');
let data: any[] = [];
dataList.map(item => {
data.push({
id: item.id,
current: item.current,
last: item.last,
type: item.type
})
})
if (subs) {
subs.unsubscribe()
}
const ws = getWebsocket(
`virtual-property-debug-${props.data.id}-${new Date().getTime()}`,
`/virtual-property-debug`,
{
virtualId: virtualId,
property: props.data.id,
virtualRule: {
...virtualRule,
script: script
},
properties: [...data]
},
).subscribe(
(resp: any) => {
const { payload } = resp;
result.push({
time: new Date().getTime(),
log: JSON.stringify(payload)
})
setResult([...result]);
},
() => { }
, () => {
setIsBeginning(true);
}
)
setSubs(ws);
};
const debugPropertyAgain = () => {
let data: any[] = [];
dataList.map(item => {
data.push({
id: item.id,
current: item.current,
last: item.last,
type: item.type
})
})
if (sub) {
sub.unsubscribe()
}
const ws = getWebsocket(
`virtual-property-debug-${props.data.id}-${new Date().getTime()}`,
`/virtual-property-debug`,
{
virtualId: virtualId,
property: props.data.id,
virtualRule: {
...virtualRule,
script: script
},
properties: [...data]
},
).subscribe(
(resp: any) => {
// console.log(resp);
}
);
setSub(ws);
};
const insertContent = (content: string) => {
const cursorPosition = editor.getCursorPosition();
editor.session.insert(cursorPosition, content);
}
useEffect(() => {
let formData = props.formData.expands?.virtualRule || {
windows: []
};
let data = props.data.expands?.virtualRule || {};
let isUseWindow = props.formData?.windows?.includes('useWindow') || false;
let isTimeWindow = props.formData.windows?.includes('timeWindow') || false;
if (isUseWindow) {
setVirtualRule({
aggType: formData?.aggType || data?.aggType,
script: formData?.script || data?.script,
type: 'window',
window: formData?.window || data?.window,
windowType: isTimeWindow ? 'time' : 'num'
})
} else {
setVirtualRule({
type: 'script'
})
}
setVirtualId(`${new Date().getTime()}-virtual-id`)
if (props.metaDataList.length > 0) {
let data: any[] = [];
props.metaDataList.map(item => {
if (item.id !== props.data.id) {
data.push({ id: item.id, type: item.valueType?.type })
}
})
setOtherList([...data]);
}
}, []);
// const editorDidMountHandle = (editor: any, monaco: any) => {
// editor.focus();
// }
return (
<Modal
closable={false}
visible
width={quickInsertVisible ? 1200 : 850}
footer={false}
>
<div className={styles.box}>
<div className={styles.boxLeft} style={{ width: quickInsertVisible ? '70%' : "100%" }}>
<div className={styles.header}>
<span>设置属性计算规则</span>
<div onClick={() => {
props.close(script);
sub && sub.unsubscribe();
subs && subs.unsubscribe();
}}><Icon type="fullscreen-exit" /></div>
</div>
<div className={styles.editorBox} style={{ height: assignVisible ? '400px' : '740px' }}>
<div className={styles.editorTop}>
<div className={styles.topLeft}>
{symbolList.map((item: any, index: number) => {
return <span key={item.key} onClick={() => {
insertContent(symbolList[index].value)
}}>{item.value}</span>
})}
<span>
<Dropdown overlay={() => (
<Menu>
{
otherSymbolList.map((item, index) => (
<Menu.Item key={item.key} onClick={() => {
insertContent(otherSymbolList[index].value)
}}>{item.value}</Menu.Item>
))
}
</Menu>
)}>
<a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
<MoreOutlined />
</a>
</Dropdown>
</span>
</div>
<div className={styles.topRight}>
<span onClick={() => { setAssignVisible(true) }}><Tooltip title="进行调试"><a>进行调试</a></Tooltip></span>
<span onClick={() => { setQuickInsertVisible(true) }}><Tooltip title="快速添加"><a>快速添加</a></Tooltip></span>
</div>
</div>
{/* <MonacoEditor
ref={l => setEditor(l && l.editor)}
height={assignVisible ? 350 : 690}
language='groovy'
theme='vs'
value={script}
options={{
selectOnLineNumbers: true
}}
onChange={(value) => {
setScript(value);
virtualRule.script = value;
setVirtualRule(virtualRule);
}}
editorDidMount={(editor, monaco) => editorDidMountHandle(editor, monaco)}
/> */}
<AceEditor
ref={l => setEditor(l && l.editor)}
mode='groovy'
theme="eclipse"
name="app_code_editor"
key='simulator'
fontSize={14}
value={script}
showPrintMargin
showGutter
wrapEnabled
highlightActiveLine //突出活动线
enableSnippets //启用代码段
style={{ width: '100%', height: assignVisible ? 350 : 690 }}
onChange={(value) => {
setScript(value);
virtualRule.script = value;
setVirtualRule(virtualRule);
}}
setOptions={{
enableBasicAutocompletion: true, //启用基本自动完成功能
enableLiveAutocompletion: true, //启用实时自动完成功能 (比如:智能代码提示)
enableSnippets: true, //启用代码段
showLineNumbers: true,
tabSize: 2,
}}
/>
</div>
{assignVisible && <div className={styles.assignBox}>
<div className={styles.assignBoxLeft}>
<div className={styles.leftHeader}>
<div className={styles.itemLeft}>
<div className={styles.itemLeftHeader}>属性赋值</div>
<div className={styles.itemRight}>请对上方规则使用的属性进行赋值</div>
</div>
{!isBeginning && virtualRule?.type === 'window' && (<div className={styles.item} onClick={() => {
debugPropertyAgain();
}}><a>发送数据</a></div>)}
</div>
<Table rowKey="key" size="middle" columns={columns} dataSource={dataList} pagination={false} scroll={{ y: 195 }}
footer={() => <a onClick={() => {
dataList.push({
key: `${new Date().getTime()}`,
id: '',
current: '',
last: '',
type: ''
})
setDataList([...dataList]);
}}><Icon type="plus-circle" /> 添加</a>}
/>
</div>
<div className={styles.assignBoxRight}>
<div className={styles.editorTop}>
<div className={styles.topLeft}>
{/* <div>运行详情</div>
<div>错误</div> */}
<div>运行结果</div>
</div>
<div className={styles.topRight}>
<div>
{isBeginning ? (<a onClick={() => {
setIsBeginning(false);
debugProperty()
}}>开始运行</a>) : (<a onClick={() => {
setIsBeginning(true);
subs && subs.unsubscribe();
}}>停止运行</a>)}
</div>
<div onClick={() => {
setResult([]);
}}><a>清空</a></div>
</div>
</div>
{/* <MonacoEditor
height={295}
language='groovy'
theme='vs'
value={result}
options={{
selectOnLineNumbers: true,
readOnly: true
}}
editorDidMount={(editor, monaco) => editorDidMountHandle(editor, monaco)}
/> */}
<div className={styles.logBox}>
<Descriptions>
{result.map((item: any, index: number) => {
return <Descriptions.Item key={index} span={3}
label={moment(item.time).format('HH:mm:ss')}>
<Tooltip placement="top" title={item.log}>{item.log}</Tooltip>
</Descriptions.Item>
})}
</Descriptions>
</div>
</div>
</div>}
</div>
{quickInsertVisible && <div className={styles.boxRight}>
<div className={styles.rightHeader}>
<span>快速添加</span>
<div onClick={() => { setQuickInsertVisible(false) }}><Icon type="close" /></div>
</div>
<QuickInsertComponent insertContent={(data: string) => { insertContent(data) }} metaDataList={props.metaDataList} close={() => { }} />
</div>}
</div>
</Modal>
);
}
export default MagnifyComponent; | the_stack |
import assert from 'assert';
import Node, { SourceRange } from './base';
import NodeVisitor from './visitor';
import { FunctionDef } from './function_def';
import { Value } from './values';
import {
iterateSlots2InputParams,
makeScope,
DeviceAttributeSlot,
AbstractSlot,
OldSlot,
ScopeMap,
InvocationLike
} from './slots';
import { TokenStream } from '../new-syntax/tokenstream';
import List from '../utils/list';
import arrayEquals from './array_equals';
interface Device {
name : string;
}
/**
* An expression that maps to one or more devices in Thingpedia.
*
* Selectors correspond to the `@`-device part of the ThingTalk code,
* up to but not including the function name.
*
*/
export class DeviceSelector extends Node {
kind : string;
id : string|null;
principal : null;
attributes : InputParam[];
all : boolean;
device ?: Device;
/**
* Construct a new device selector.
*
* @param location - the position of this node in the source code
* @param kind - the Thingpedia class ID
* @param id - the unique ID of the device being selected, or null
* to select devices according to the attributes, or
* all devices if no attributes are specified
* @param principal - reserved/deprecated, must be `null`
* @param attributes - other attributes used to select a device, if ID is unspecified
* @param [all=false] - operate on all devices that match the attributes, instead of
* having the user choose
*/
constructor(location : SourceRange|null,
kind : string,
id : string|null,
principal : null,
attributes : InputParam[] = [],
all = false) {
super(location);
assert(typeof kind === 'string');
this.kind = kind;
assert(typeof id === 'string' || id === null);
this.id = id;
assert(principal === null);
this.principal = principal;
this.attributes = attributes;
this.all = all;
}
getAttribute(name : string) : InputParam|undefined {
for (const attr of this.attributes) {
if (attr.name === name)
return attr;
}
return undefined;
}
toSource() : TokenStream {
this.attributes.sort((p1, p2) => {
if (p1.name < p2.name)
return -1;
if (p1.name > p2.name)
return 1;
return 0;
});
const attributes : TokenStream[] = [];
if (this.all) {
attributes.push(List.concat('all', '=', 'true'));
} else if (this.id && this.id !== this.kind) {
// note: we omit the device ID if it is identical to the kind (which indicates there can only be
// one device of this type in the system)
// this reduces the amount of stuff we have to encode/predict for the common cases
const name = this.attributes.find((attr) => attr.name === 'name');
const id = new Value.Entity(this.id, 'tt:device_id', name ? name.value.toJS() as string : null);
attributes.push(List.concat('id', '=', id.toSource()));
}
for (const attr of this.attributes) {
if (attr.value.isUndefined)
continue;
if (attr.name === 'name' && this.id)
continue;
attributes.push(List.concat(attr.name, '=', attr.value.toSource()));
}
if (attributes.length === 0)
return List.singleton('@' + this.kind);
return List.concat('@' + this.kind, '(', List.join(attributes, ','), ')');
}
clone() : DeviceSelector {
const attributes = this.attributes.map((attr) => attr.clone());
return new DeviceSelector(this.location, this.kind, this.id, this.principal, attributes, this.all);
}
equals(other : DeviceSelector) : boolean {
return other instanceof DeviceSelector &&
this.kind === other.kind &&
this.id === other.id &&
arrayEquals(this.attributes, other.attributes) &&
this.all === other.all;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitDeviceSelector(this)) {
for (const attr of this.attributes)
attr.visit(visitor);
}
visitor.exit(this);
}
toString() : string {
return `Device(${this.kind}, ${this.id ? this.id : ''}, )`;
}
}
/**
* AST node corresponding to an input parameter passed to a function.
*/
export class InputParam extends Node {
isInputParam = true;
/**
* The input argument name.
*/
name : string;
/**
* The value being passed.
*/
value : Value;
/**
* Construct a new input parameter node.
*
* @param {Ast~SourceRange|null} location - the position of this node
* in the source code
* @param {string} name - the input argument name
* @param {Ast.Value} value - the value being passed
*/
constructor(location : SourceRange|null,
name : string,
value : Value) {
super(location);
assert(typeof name === 'string');
this.name = name;
assert(value instanceof Value);
this.value = value;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitInputParam(this))
this.value.visit(visitor);
visitor.exit(this);
}
toSource() : TokenStream {
return List.concat(this.name, '=', this.value.toSource());
}
clone() : InputParam {
return new InputParam(this.location, this.name, this.value.clone());
}
equals(other : InputParam) : boolean {
return this.name === other.name &&
this.value.equals(other.value);
}
toString() : string {
return `InputParam(${this.name}, ${this.value})`;
}
}
/**
* An invocation of a ThingTalk function.
*
*/
export class Invocation extends Node {
isInvocation = true;
/**
* The selector choosing where the function is invoked.
*/
selector : DeviceSelector;
/**
* The function name being invoked.
*/
channel : string;
/**
* The input parameters passed to the function.
*/
in_params : InputParam[];
/**
* Type signature of the invoked function.
* This property is guaranteed not `null` after type-checking.
*/
schema : FunctionDef|null;
__effectiveSelector : DeviceSelector|null = null;
/**
* Construct a new invocation.
*
* @param location - the position of this node in the source code
* @param {Ast.DeviceSelector} selector - the selector choosing where the function is invoked
* @param {string} channel - the function name
* @param {Ast.InputParam[]} in_params - input parameters passed to the function
* @param {Ast.FunctionDef|null} schema - type signature of the invoked function
*/
constructor(location : SourceRange|null,
selector : DeviceSelector,
channel : string,
in_params : InputParam[],
schema : FunctionDef|null) {
super(location);
assert(selector instanceof DeviceSelector);
this.selector = selector;
assert(typeof channel === 'string');
this.channel = channel;
assert(Array.isArray(in_params));
this.in_params = in_params;
assert(schema === null || schema instanceof FunctionDef);
this.schema = schema;
}
toSource() : TokenStream {
// filter out parameters that are required and undefined
let filteredParams = this.in_params;
if (this.schema) {
const schema : FunctionDef = this.schema;
filteredParams = this.in_params.filter((ip) => {
return !ip.value.isUndefined || !schema.isArgRequired(ip.name);
});
}
return List.concat(this.selector.toSource(), '.', this.channel,
'(', List.join(filteredParams.map((ip) => ip.toSource()), ','), ')');
}
clone() : Invocation {
const clone = new Invocation(
this.location,
this.selector.clone(),
this.channel,
this.in_params.map((p) => p.clone()),
this.schema ? this.schema.clone(): null
);
clone.__effectiveSelector = this.__effectiveSelector;
return clone;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitInvocation(this)) {
this.selector.visit(visitor);
for (const in_param of this.in_params)
in_param.visit(visitor);
}
visitor.exit(this);
}
toString() : string {
const in_params = this.in_params && this.in_params.length > 0 ? this.in_params.toString() : '';
return `Invocation(${this.selector.toString()}, ${this.channel}, ${in_params}, )`;
}
/**
* Iterate all slots (scalar value nodes) in this invocation.
*
* @param scope - available names for parameter passing
* @deprecated Use {@link Ast.Invocation.iterateSlots2} instead.
*/
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike, ScopeMap]> {
yield [null, this.selector, this, {}];
for (const in_param of this.in_params)
yield [this.schema, in_param, this, scope];
return [this, makeScope(this)];
}
/**
* Iterate all slots (scalar value nodes) in this invocation.
*
* @param {Object.<string, Ast~SlotScopeItem>} scope - available names for parameter passing
*/
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike, ScopeMap]> {
if (this.selector instanceof DeviceSelector) {
for (const attr of this.selector.attributes)
yield new DeviceAttributeSlot(this, attr);
// note that we yield the selector after the device attributes
// this way, almond-dialog-agent will first ask any question to slot-fill
// the device attributes (if somehow it needs to) and then use the chosen
// device attributes to choose the device
yield this.selector;
}
return yield* iterateSlots2InputParams(this, scope);
}
} | the_stack |
import { Component, Emit, Prop, Watch } from 'vue-property-decorator';
import { debounce, sleep } from '../../../../../utils/utils';
import { MediaDeviceService } from '../../../../../_common/agora/media-device.service';
import AppExpand from '../../../../../_common/expand/expand.vue';
import {
assignPreferredProducerDevices,
clearSelectedRecordingDevices,
FiresideRTCProducer,
PRODUCER_DEFAULT_GROUP_AUDIO,
PRODUCER_UNSET_DEVICE,
setSelectedDesktopAudioDeviceId,
setSelectedGroupAudioDeviceId,
setSelectedMicDeviceId,
setSelectedWebcamDeviceId,
setVideoPreviewElement,
startStreaming,
stopStreaming,
} from '../../../../../_common/fireside/rtc/producer';
import AppFormControlToggle from '../../../../../_common/form-vue/control/toggle/toggle.vue';
import { BaseForm, FormOnInit } from '../../../../../_common/form-vue/form.service';
import AppForm from '../../../../../_common/form-vue/form.vue';
import AppFormLegend from '../../../../../_common/form-vue/legend/legend.vue';
import AppLoadingFade from '../../../../../_common/loading/fade/fade.vue';
import { Navigate } from '../../../../../_common/navigate/navigate.service';
import { FiresideController } from '../../controller/controller';
import { StreamSetupModal } from './setup-modal.service';
import AppVolumeMeter from './volume-meter.vue';
type FormModel = {
selectedWebcamDeviceId: string;
selectedMicDeviceId: string;
selectedDesktopAudioDeviceId: string;
selectedGroupAudioDeviceId: string;
tempSelectedMicDeviceId: string | null;
tempSelectedDesktopAudioDeviceId: string | null;
tempSelectedGroupAudioDeviceId: string;
};
@Component({
components: {
AppExpand,
AppVolumeMeter,
AppFormControlToggle,
AppFormLegend,
AppLoadingFade,
},
})
export default class AppStreamSetup extends BaseForm<FormModel> implements FormOnInit {
@Prop({ type: FiresideController, required: true })
c!: FiresideController;
isStarting = false;
private shouldShowAdvanced = false;
private _didDetectDevices = false;
private _producer!: FiresideRTCProducer;
private networkQualityDebounce: () => void = null as any;
readonly PRODUCER_UNSET_DEVICE = PRODUCER_UNSET_DEVICE;
@Emit('close') emitClose() {}
$refs!: {
form: AppForm;
videoPreview?: HTMLDivElement;
};
get rtc() {
return this.c.rtc!;
}
// This could potentially get cleared out if the user loses their hosting
// permissions in the middle of streaming.
get producer() {
return this.c.rtc!.producer!;
}
onInit() {
this._producer = this.producer;
this.c.isShowingStreamSetup = true;
const webcamId = this.getDeviceFromId(
this.producer.selectedWebcamDeviceId,
'webcam'
)?.deviceId;
const micId = this.getDeviceFromId(this.producer.selectedMicDeviceId, 'mic')?.deviceId;
const desktopId = this.getDeviceFromId(
this.producer.selectedDesktopAudioDeviceId,
'mic'
)?.deviceId;
const groupId = this.getDeviceFromId(
this.producer.selectedGroupAudioDeviceId,
'speaker'
)?.deviceId;
this.setField('selectedWebcamDeviceId', webcamId ?? PRODUCER_UNSET_DEVICE);
this.setField('tempSelectedMicDeviceId', micId ?? PRODUCER_UNSET_DEVICE);
this.setField('tempSelectedDesktopAudioDeviceId', desktopId ?? PRODUCER_UNSET_DEVICE);
this.setField('tempSelectedGroupAudioDeviceId', groupId ?? PRODUCER_DEFAULT_GROUP_AUDIO);
}
mounted() {
// If we don't prompt here, the user can end up denying permissions and
// then opening this form again to an empty device list.
this._detectDevices();
}
private async _detectDevices() {
try {
await MediaDeviceService.detectDevices({ prompt: true, skipIfPrompted: false });
} finally {
assignPreferredProducerDevices(this.producer);
this._didDetectDevices = true;
// Reinitialize so that the form fields match with our producer.
this.onInit();
}
}
destroyed() {
// If we're not streaming or about to, clear the selected device ids so
// that the browser doesn't think we're still recording.
if (!(this.isStreaming || this.isStarting)) {
clearSelectedRecordingDevices(this._producer);
}
this.c.isShowingStreamSetup = false;
}
get isStreaming() {
return this.producer?.isStreaming === true;
}
get hasMicAudio() {
return (
(this.formModel.selectedMicDeviceId ?? PRODUCER_UNSET_DEVICE) !== PRODUCER_UNSET_DEVICE
);
}
get hasDesktopAudio() {
return (
(this.formModel.selectedDesktopAudioDeviceId ?? PRODUCER_UNSET_DEVICE) !==
PRODUCER_UNSET_DEVICE
);
}
get hasWebcam() {
return (
(this.formModel.selectedWebcamDeviceId ?? PRODUCER_UNSET_DEVICE) !==
PRODUCER_UNSET_DEVICE
);
}
get selectedMicGroupId() {
return this.getDeviceFromId(this.formModel.selectedMicDeviceId, 'mic')?.groupId;
}
get selectedDesktopAudioGroupId() {
return this.getDeviceFromId(this.formModel.selectedDesktopAudioDeviceId, 'mic')?.groupId;
}
@Watch('producer')
onProducerChanged() {
// The only way this should trigger is if we get removed as a cohost
// while we're creating/modifying a stream setup.
if (!this.producer) {
StreamSetupModal.close();
}
}
@Watch('canStreamVideo', { immediate: true })
async onCanStreamVideoChanged() {
// Wait to let the video element get mounted
await this.$nextTick();
setVideoPreviewElement(
this.producer,
this.canStreamVideo ? this.$refs.videoPreview ?? null : null
);
}
get canStreamVideo() {
return this.producer.canStreamVideo;
}
get canStreamAudio() {
return this.producer.canStreamAudio;
}
get hasWebcamPermissions() {
return MediaDeviceService.hasWebcamPermissions;
}
get webcamPermissionsWerePrompted() {
return MediaDeviceService.webcamPermissionsWerePrompted;
}
get webcams() {
return MediaDeviceService.webcams;
}
onClickPromptWebcamPermissions() {
MediaDeviceService.detectWebcams({ prompt: true, skipIfPrompted: false });
}
get hasMicPermissions() {
return MediaDeviceService.hasMicPermissions;
}
get micPermissionsWerePrompted() {
return MediaDeviceService.micPermissionsWerePrompted;
}
get mics() {
return MediaDeviceService.mics;
}
onClickPromptMicPermissions() {
MediaDeviceService.detectMics({ prompt: true, skipIfPrompted: false });
}
get isInvalidMicConfig() {
return (
this.formModel.selectedMicDeviceId !== PRODUCER_UNSET_DEVICE &&
this.formModel.selectedDesktopAudioDeviceId !== PRODUCER_UNSET_DEVICE &&
this.formModel.selectedMicDeviceId === this.formModel.selectedDesktopAudioDeviceId
);
}
get canToggleAdvanced() {
if (!this.isStreaming) {
return true;
}
return Object.entries(this.requiredFields).some(
([_key, value]) => value !== PRODUCER_UNSET_DEVICE
);
}
// We required at least one of these fields to be filled out.
get requiredFields(): Record<string, string> {
return {
selectedWebcamDeviceId: this.formModel.selectedWebcamDeviceId,
selectedMicDeviceId: this.formModel.selectedMicDeviceId,
};
}
get audioInputFields(): Record<string, string> {
return {
selectedMicDeviceId: this.formModel.selectedMicDeviceId,
selectedDesktopAudioDeviceId: this.formModel.selectedDesktopAudioDeviceId,
};
}
get canSwapAudioInputs() {
if (!this.isStreaming) {
return true;
}
// If we could potentially swap away from our only valid required
// device, we need to check if we'll either get a new one or have a
// different device active that meets the form requirements.
if (this.formModel.selectedMicDeviceId !== PRODUCER_UNSET_DEVICE) {
const required = Object.assign({}, this.requiredFields, this.audioInputFields);
delete required['selectedMicDeviceId'];
return Object.entries(required).some(
([_key, value]) => value !== PRODUCER_UNSET_DEVICE
);
}
return Object.entries(this.audioInputFields).some(
([_key, value]) => value !== PRODUCER_UNSET_DEVICE
);
}
openHelpLink(event: Event) {
if (event.currentTarget instanceof HTMLAnchorElement) {
Navigate.newWindow(event.currentTarget.href!);
event.stopPropagation();
event.preventDefault();
}
}
wouldInvalidateIfRemoved(fieldToRemove: string) {
if (!this.isStreaming) {
return false;
}
const required = Object.assign({}, this.requiredFields);
delete required[fieldToRemove];
return Object.entries(required).every(([_key, value]) => value === PRODUCER_UNSET_DEVICE);
}
onToggleAdvanced() {
this.shouldShowAdvanced = !this.shouldShowAdvanced;
}
onClickCancel() {
this.emitClose();
}
async onClickStartStreaming() {
if (this.isStarting) {
return;
}
this.isStarting = true;
try {
await startStreaming(this.producer);
} catch {}
this.isStarting = false;
// Only close the modal if we were able to start streaming.
if (this.producer.isStreaming) {
this.emitClose();
}
}
get hasSpeakerPermissions() {
return MediaDeviceService.hasSpeakerPermissions;
}
get speakerPermissionsWerePrompted() {
return MediaDeviceService.speakerPermissionsWerePrompted;
}
get speakers() {
return MediaDeviceService.speakers;
}
onClickPromptSpeakerPermissions() {
MediaDeviceService.detectSpeakers({ prompt: true, skipIfPrompted: false });
}
/**
* This will be `false` if we detected anything wrong with the config.
*/
get isInvalidConfig() {
if (this.isInvalidMicConfig) {
return true;
}
// Need to stream something
return (
!this.getDeviceFromId(this.formModel.selectedWebcamDeviceId, 'webcam') &&
!this.getDeviceFromId(this.formModel.selectedMicDeviceId, 'mic')
);
}
private getDeviceFromId(id: string | null, deviceType: 'mic' | 'webcam' | 'speaker') {
if (id === null) {
return;
}
switch (deviceType) {
case 'mic':
return this.mics.find(i => i.deviceId == id);
case 'speaker':
return this.speakers.find(i => i.deviceId == id);
case 'webcam':
return this.webcams.find(i => i.deviceId == id);
}
}
@Watch('isInvalidConfig')
async onInvalidConfigChanged() {
// The form will become invalid from the mic and desktop audio tracks
// having the same ID, so we need to see if it's still invalid after
// giving it a chance to resolve itself.
await sleep(0);
if (this.isInvalidConfig && this.isStreaming) {
stopStreaming(this.producer);
}
}
@Watch('formModel.tempSelectedMicDeviceId')
onTempSelectedMicChanged() {
const oldMic = this.getDeviceFromId(this.formModel.selectedMicDeviceId, 'mic');
const oldDesktop = this.getDeviceFromId(this.formModel.selectedDesktopAudioDeviceId, 'mic');
const newMic = this.getDeviceFromId(this.formModel.tempSelectedMicDeviceId, 'mic');
const newId = newMic?.deviceId ?? PRODUCER_UNSET_DEVICE;
this.setField('selectedMicDeviceId', newMic?.deviceId ?? PRODUCER_UNSET_DEVICE);
if (newId !== PRODUCER_UNSET_DEVICE && newMic?.groupId == oldDesktop?.groupId) {
this.setField(
'tempSelectedDesktopAudioDeviceId',
oldMic?.deviceId ?? PRODUCER_UNSET_DEVICE
);
}
}
@Watch('formModel.tempSelectedDesktopAudioDeviceId')
onTempSelectedDesktopAudioChanged() {
const oldMic = this.getDeviceFromId(this.formModel.selectedMicDeviceId, 'mic');
const oldDesktop = this.getDeviceFromId(this.formModel.selectedDesktopAudioDeviceId, 'mic');
const newDesktop = this.getDeviceFromId(
this.formModel.tempSelectedDesktopAudioDeviceId,
'mic'
);
const newId = newDesktop?.deviceId ?? PRODUCER_UNSET_DEVICE;
this.setField(
'selectedDesktopAudioDeviceId',
newDesktop?.deviceId ?? PRODUCER_UNSET_DEVICE
);
if (newId !== PRODUCER_UNSET_DEVICE && newDesktop?.groupId == oldMic?.groupId) {
this.setField('tempSelectedMicDeviceId', oldDesktop?.deviceId ?? PRODUCER_UNSET_DEVICE);
}
}
@Watch('formModel.tempSelectedGroupAudioDeviceId')
onTempSelectedGroupAudioChanged() {
this.setField(
'selectedGroupAudioDeviceId',
this.formModel.tempSelectedGroupAudioDeviceId ?? PRODUCER_DEFAULT_GROUP_AUDIO
);
}
@Watch('formModel.selectedWebcamDeviceId')
@Watch('formModel.selectedMicDeviceId')
@Watch('formModel.selectedDesktopAudioDeviceId')
@Watch('formModel.selectedGroupAudioDeviceId')
onSelectedDevicesChanged() {
// When streaming, only apply changes to selected devices if the config is valid.
if ((this.isInvalidConfig && this.isStreaming) || !this._didDetectDevices) {
// TODO: show error status on the form model values that do not match with whats set on firesideHostRtc.
return;
}
setSelectedWebcamDeviceId(this.producer, this.formModel.selectedWebcamDeviceId);
setSelectedMicDeviceId(this.producer, this.formModel.selectedMicDeviceId);
setSelectedDesktopAudioDeviceId(this.producer, this.formModel.selectedDesktopAudioDeviceId);
setSelectedGroupAudioDeviceId(this.producer, this.formModel.selectedGroupAudioDeviceId);
}
@Watch('rtc.isPoorNetworkQuality')
onNetworkQualityChanged() {
this.networkQualityDebounce ??= debounce(() => {
if (this.rtc.isPoorNetworkQuality) {
console.log('Network quality is poor.');
} else {
console.log('Network quality is very nice.');
}
}, 3_000);
this.networkQualityDebounce();
}
} | the_stack |
import '@cds/core/icon/register.js';
import { ClarityIcons } from '@cds/core/icon/icon.service.js';
import { imageIcon } from '@cds/core/icon/shapes/image.js';
import { userIcon } from '@cds/core/icon/shapes/user.js';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators/custom-element.js';
import { state } from 'lit/decorators/state.js';
import { homeIcon } from '@cds/core/icon/shapes/home.js';
// import { boolean, select, text } from '@storybook/addon-knobs';
// import { classMap } from 'lit/directives/class-map.js';
// import customElements from '../../dist/core/custom-elements.json';
// import {
// loadChartIconSet,
// loadCommerceIconSet,
// loadCoreIconSet,
// loadEssentialIconSet,
// loadMediaIconSet,
// loadMiniIconSet,
// loadSocialIconSet,
// loadTechnologyIconSet,
// loadTextEditIconSet,
// loadTravelIconSet,
// } from '@cds/core/icon';
import { spreadProps, getElementStorybookArgs } from '@cds/core/internal';
// import { ifDefined } from 'lit/directives/if-defined.js';
// import { IconShapeTuple } from './interfaces/icon.interfaces.js';
// here for testing
ClarityIcons.addIcons(userIcon, imageIcon, homeIcon);
export default {
title: 'Stories/Icon',
component: 'cds-icon',
parameters: {
options: { showPanel: true },
design: {
type: 'figma',
url: 'https://www.figma.com/file/v2mkhzKQdhECXOx8BElgdA/Clarity-UI-Library---light-2.2.0?node-id=0%3A2700',
},
},
};
@customElement('demo-all-icons')
class AllIcons extends LitElement {
@state() icons: string[] = [];
connectedCallback() {
super.connectedCallback();
import('@cds/core/icon').then(module => {
module.loadChartIconSet();
module.loadCommerceIconSet();
module.loadCoreIconSet();
module.loadEssentialIconSet();
module.loadMediaIconSet();
module.loadMiniIconSet();
module.loadSocialIconSet();
module.loadTechnologyIconSet();
module.loadTextEditIconSet();
module.loadTravelIconSet();
this.icons = Object.keys(ClarityIcons.registry);
});
}
render() {
return html`
<div cds-layout="horizontal gap:lg">
${this.icons.map(
icon =>
html`<cds-icon
size="lg"
.shape=${icon}
aria-label="This is an example of an icon using the ${icon} shape"
></cds-icon>`
)}
</div>
`;
}
}
all.element = AllIcons; // get around unused class
export function all() {
return html`<demo-all-icons></demo-all-icons>`;
}
// export function all() {
// import('@cds/core/icon').then(module => {
// module.loadChartIconSet();
// module.loadCommerceIconSet();
// module.loadCoreIconSet();
// module.loadEssentialIconSet();
// module.loadMediaIconSet();
// module.loadMiniIconSet();
// module.loadSocialIconSet();
// module.loadTechnologyIconSet();
// module.loadTextEditIconSet();
// module.loadTravelIconSet();
// });
// const search = text('search', '', propertiesGroup);
// const size = select(
// 'size',
// { xs: 'xs', 'sm (default)': 'sm', md: 'md', lg: 'lg', xl: 'xl', xxl: 'xxl' },
// 'lg',
// propertiesGroup
// );
// const dir = select(
// 'direction',
// { 'up (default)': undefined, down: 'down', left: 'left', right: 'right' },
// undefined,
// propertiesGroup
// );
// const fl = select(
// 'flip',
// { 'none (default)': undefined, vertical: 'vertical', horizontal: 'horizontal' },
// undefined,
// propertiesGroup
// );
// const badge = select(
// 'badge',
// {
// 'none (default)': '',
// info: 'info',
// success: 'success',
// warning: 'warning',
// danger: 'danger',
// inherit: 'inherit',
// 'warning-triangle': 'warning-triangle',
// 'inherit-triangle': 'inherit-triangle',
// },
// '',
// propertiesGroup
// );
// const iconStatus = select(
// 'status',
// { 'none (default)': '', info: 'info', success: 'success', warning: 'warning', danger: 'danger' },
// '',
// propertiesGroup
// );
// const inverse = boolean('inverse', false, propertiesGroup);
// const solid = boolean('solid', false, propertiesGroup);
// function createIconIndices(icons: IconShapeTuple[], aliases: [string, string[]][]): string[] {
// const iconsMap = icons.map(iconTuple => iconTuple[0]);
// const aliasMap = aliases.map(aliasTuple => aliasTuple[1]).reduce((acc, val) => acc.concat(val), []);
// return iconsMap.concat(aliasMap).sort();
// }
// const iconIndex: { [key: string]: string[] } = {
// Chart: createIconIndices(chartCollectionIcons, chartCollectionAliases),
// Commerce: createIconIndices(commerceCollectionIcons, commerceCollectionAliases),
// Core: createIconIndices(coreCollectionIcons, coreCollectionAliases),
// Essential: createIconIndices(essentialCollectionIcons, essentialCollectionAliases),
// Media: createIconIndices(mediaCollectionIcons, mediaCollectionAliases),
// Mini: createIconIndices(miniCollectionIcons, miniCollectionAliases),
// Social: createIconIndices(socialCollectionIcons, socialCollectionAliases),
// Technology: createIconIndices(technologyCollectionIcons, technologyCollectionAliases),
// 'Text-Edit': createIconIndices(textEditCollectionIcons, textEditCollectionAliases),
// Travel: createIconIndices(travelCollectionIcons, travelCollectionAliases),
// };
// const iconSets = Object.keys(iconIndex);
// return html`
// <style>
// .dc-icon-set {
// max-width: 60rem;
// }
// .dc-icon-boxes {
// padding: 1.2rem 0.4rem 0;
// background: #f4f4f4;
// display: grid;
// grid-gap: 16px;
// grid-template-columns: repeat(12, 1fr);
// }
// .dc-icon-boxes.inverse {
// background: #565656;
// }
// .dc-icon-boxes.inverse .dc-icon-name {
// color: #fff;
// }
// .dc-icon-box {
// text-align: center;
// grid-column: span 2 / span 2;
// }
// .dc-icon-box p {
// margin: 0;
// padding: 0.2rem 0 1.2rem;
// }
// </style>
// ${iconSets.map(
// k => html`
// <section class="dc-icon-set">
// <h2>${k}</h2>
// <div class="dc-icon-boxes ${classMap({ inverse: inverse })}">
// ${iconIndex[k].map(
// i => html`
// <div class="dc-icon-box" .hidden=${!i.includes(search)}>
// <cds-icon
// aria-label="This is an example of an icon using the ${i} shape"
// badge=${badge}
// status=${iconStatus}
// ?solid=${solid}
// size=${size}
// shape=${i}
// direction=${ifDefined(dir)}
// ?inverse=${inverse}
// flip=${ifDefined(fl)}
// >
// </cds-icon>
// <span cds-layout="display:screen-reader-only"
// >${'The shape needed to display this icon is ' + i}</span
// >
// <p class="dc-icon-name" aria-hidden="true">${i}</p>
// </div>
// `
// )}
// </div>
// </section>
// `
// )}
// `;
// }
export function API(args: any) {
return html`
<cds-demo inline-block>
<cds-icon
...="${spreadProps(getElementStorybookArgs(args))}"
aria-label="This is an icon example that can be used to try out the Clarity icon element's API"
></cds-icon>
</cds-demo>
`;
}
/** @website */
export function icon() {
return html`<cds-icon
shape="user"
aria-label="This is an icon example that shows how to use the icon element in an application"
></cds-icon>`;
}
/** @website */
export function sizes() {
return html`
<cds-icon
shape="home"
size="xs"
aria-label="This is an example of an icon using a pre-defined extra small size"
></cds-icon>
<cds-icon
shape="home"
size="sm"
aria-label="This is an example of an icon using a pre-defined small size"
></cds-icon>
<cds-icon
shape="home"
size="md"
aria-label="This is an example of an icon using a pre-defined medium size"
></cds-icon>
<cds-icon
shape="home"
size="lg"
aria-label="This is an example of an icon using a pre-defined large size"
></cds-icon>
<cds-icon
shape="home"
size="xl"
aria-label="This is an example of an icon using a pre-defined extra large size"
></cds-icon>
<cds-icon
shape="home"
size="xxl"
aria-label="This is an example of an icon using a pre-defined extra extra large size"
></cds-icon>
<cds-icon
shape="home"
size="16"
aria-label="This is an example of an icon using a custom size of 16 pixels wide and tall"
></cds-icon>
<cds-icon
shape="home"
size="24"
aria-label="This is an example of an icon using a custom size of 24 pixels wide and tall"
></cds-icon>
<cds-icon
shape="home"
size="48"
aria-label="This is an example of an icon using a custom size of 48 pixels wide and tall"
></cds-icon>
<cds-icon
shape="home"
size="64"
aria-label="This is an example of an icon using a custom size of 64 pixels wide and tall"
></cds-icon>
<cds-icon
shape="home"
size="128"
loading
aria-label="This is an example of an icon using a custom size of 128 pixels wide and tall"
></cds-icon>
`;
}
/** @website */
export function badges() {
return html`
<cds-icon
shape="user"
size="lg"
badge="info"
aria-label="This is an example of an icon of a user with a blue informational badge"
></cds-icon>
<cds-icon
shape="user"
size="lg"
badge="success"
aria-label="This is an example of an icon of a user with a green badge indicating success"
></cds-icon>
<cds-icon
shape="user"
size="lg"
badge="danger"
aria-label="This is an example of an icon of a user with a red badge indicating danger or an error"
></cds-icon>
<cds-icon
shape="user"
size="lg"
badge="warning"
aria-label="This is an example of an icon of a user with a dark orange badge indicating a warning"
></cds-icon>
<cds-icon
shape="user"
size="lg"
badge="warning-triangle"
aria-label="This is an example of an icon of a user with a dark orange triangle indicating something may be wrong"
></cds-icon>
<cds-demo inverse inline-block>
<cds-icon
shape="user"
size="lg"
badge="inherit-triangle"
inverse
aria-label="This is an example of an icon of a user on a dark background with a warning triangle that is the same color as the icon"
></cds-icon>
</cds-demo>
`;
}
/** @website */
export function status() {
return html`
<cds-icon
shape="user"
size="lg"
aria-label="This is an example of an icon of a user with the default color of the surrounding text"
></cds-icon>
<cds-icon
shape="user"
status="info"
size="lg"
aria-label="This is an example of a blue, informational icon of a user"
></cds-icon>
<cds-icon
shape="user"
status="success"
size="lg"
aria-label="This is an example of a green icon of a user indicating success"
></cds-icon>
<cds-icon
shape="user"
status="warning"
size="lg"
aria-label="This is an example of a dark orange icon of a user indicating a warning"
></cds-icon>
<cds-icon
shape="user"
status="danger"
size="lg"
aria-label="This is an example of a red icon of a user indicating danger or an error"
></cds-icon>
<cds-icon
shape="user"
size="lg"
solid
aria-label="This is an example of an icon of a user completely filled in with the default color of the surrounding text"
></cds-icon>
<cds-icon
shape="user"
status="info"
size="lg"
solid
aria-label="This is an example of an icon of a user completely filled in with the blue, informational color"
></cds-icon>
<cds-icon
shape="user"
status="success"
size="lg"
solid
aria-label="This is an example of an icon of a user completely filled in with a green color indicating success"
></cds-icon>
<cds-icon
shape="user"
status="warning"
size="lg"
solid
aria-label="This is an example of an icon of a user completely filled in with a dark orange color indicating warning"
></cds-icon>
<cds-icon
shape="user"
status="danger"
size="lg"
solid
aria-label="This is an example of an icon of a user completely filled in with a red color indicating danger or an error"
></cds-icon>
`;
}
/** @website */
export function statusInverse() {
return html`
<cds-demo inverse inline-block>
<cds-icon shape="user" inverse size="lg" aria-label="This is an example of an icon of a user on a dark background with the default color of the surrounding text"></cds-icon>
<cds-icon shape="user" inverse status="info" size="lg" aria-label="This is an example of a blue, informational icon of a user on a dark background"></cds-icon>
<cds-icon shape="user" inverse status="success" size="lg" aria-label="This is an example of a green icon of a user on a dark background indicating success"></cds-icon>
<cds-icon shape="user" inverse status="warning" size="lg" aria-label="This is an example of a dark orange icon of a user on a dark background indicating a warning"></cds-icon>
<cds-icon shape="user" inverse status="danger" size="lg" aria-label="This is an example of a red icon of a user on a dark background indicating danger or an error"></cds-icon>
<cds-icon shape="user" inverse size="lg" solid aria-label="This is an example of an icon of a user completely filled in with the default color of the surrounding text on a dark background"></cds-icon>
<cds-icon shape="user" inverse status="info" size="lg" solid aria-label="This is an example of an icon of a user completely filled in with the blue, informational color on a dark background"></cds-icon>
<cds-icon shape="user" inverse status="success" size="lg" solid aria-label="This is an example of an icon of a user on a dark background completely filled in with a green color indicating success"></cds-icon>
<cds-icon shape="user" inverse status="warning" size="lg" solid aria-label="This is an example of an icon of a user on a dark background completely filled in with a dark orange color indicating warning"></cds-icon>
<cds-icon shape="user" inverse status="danger" size="lg" solid aria-label="This is an example of an icon of a user on a dark background completely filled in with a red color indicating danger or an error"></cds-icon></cds-icon>
</cds-demo>
`;
}
/** @website */
export function direction() {
return html`
<cds-icon
shape="image"
size="lg"
direction="up"
aria-label="This is an example of an icon whose glyph is directed with its top to point upward. This is the default icon direction."
></cds-icon>
<cds-icon
shape="image"
size="lg"
direction="left"
aria-label="This is an example of an icon whose glyph is directed with its top to point to the left."
></cds-icon>
<cds-icon
shape="image"
size="lg"
direction="down"
aria-label="This is an example of an icon whose glyph is directed with its top to point downward."
></cds-icon>
<cds-icon
shape="image"
size="lg"
direction="right"
aria-label="This is an example of an icon whose glyph is directed with its top to point to the right."
></cds-icon>
`;
}
/** @website */
export function customStyles() {
return html`
<style>
.custom-icon-colors {
background: black;
padding: 8px 12px;
border-radius: 3px;
display: inline-block;
margin-left: 12px;
position: relative;
}
.custom-icon-colors.c {
background: #dcdcdc;
}
.custom-icon-colors::before {
content: 'X';
font-size: 14px;
position: absolute;
display: block;
top: 0;
left: 4px;
color: white;
}
.custom-icon-colors.a::before {
content: 'A';
}
.custom-icon-colors.b::before {
content: 'B';
}
.custom-icon-colors.c::before {
content: 'C';
color: #313131;
}
.custom-icon-colors cds-icon {
height: 36px;
width: 36px;
}
.icon-a {
--color: limegreen;
--badge-color: yellow;
}
.icon-b {
--color: fuchsia;
--badge-color: fuchsia;
}
.icon-c {
--badge-color: fuchsia;
}
</style>
<div class="custom-icon-colors a">
<cds-icon
shape="user"
badge="default"
class="icon-a"
aria-label="This is an example of how an icon can be visually customized."
></cds-icon>
</div>
<div class="custom-icon-colors b">
<cds-icon
shape="user"
class="icon-b"
badge="warning-triangle"
aria-label="This is another example of how an icon can be visually customized."
></cds-icon>
</div>
<div class="custom-icon-colors c">
<cds-icon
shape="user"
badge="default"
class="icon-c"
aria-label="This is a third example of how an icon can be visually customized."
></cds-icon>
</div>
<p>
<i>The first icon should be green with a yellow badge</i><br />
<i>The second icon should be all pink (even the warning triangle should be pink)</i><br />
<i>The third icon should be default gray color with a custom pink badge</i>
</p>
`;
}
/** @website */
export function flip() {
return html`
<cds-icon
size="lg"
shape="image"
aria-label="This is an example of an icon whose glyph is positioned upright. This is the default."
></cds-icon>
<cds-icon
size="lg"
flip="vertical"
shape="image"
aria-label="This is an example of an icon whose glyph is flipped vertically."
></cds-icon>
<cds-icon
size="lg"
flip="horizontal"
shape="image"
aria-label="This is an example of an icon whose glyph is flipped horizontally."
></cds-icon>
`;
}
/** @website */
export function darkTheme() {
return html`
<div cds-layout="vertical gap:sm" cds-theme="dark" cds-text="body">
<div cds-layout="horizontal gap:sm">
<cds-icon shape="user" size="lg" badge="info"></cds-icon>
<cds-icon shape="user" size="lg" badge="success"></cds-icon>
<cds-icon shape="user" size="lg" badge="danger"></cds-icon>
<cds-icon shape="user" size="lg" badge="warning"></cds-icon>
<cds-icon shape="user" size="lg" badge="warning-triangle"></cds-icon>
</div>
<div cds-layout="horizontal gap:sm">
<cds-icon shape="user" size="lg"></cds-icon>
<cds-icon shape="user" status="info" size="lg"></cds-icon>
<cds-icon shape="user" status="success" size="lg"></cds-icon>
<cds-icon shape="user" status="warning" size="lg"></cds-icon>
<cds-icon shape="user" status="danger" size="lg"></cds-icon>
</div>
<div cds-layout="horizontal gap:sm">
<cds-icon shape="user" size="lg" solid></cds-icon>
<cds-icon shape="user" status="info" size="lg" solid></cds-icon>
<cds-icon shape="user" status="success" size="lg" solid></cds-icon>
<cds-icon shape="user" status="warning" size="lg" solid></cds-icon>
<cds-icon shape="user" status="danger" size="lg" solid></cds-icon>
</div>
</div>
`;
}
export function lazyLoading() {
let shapeName = 'jabberwockee';
return html`
<div cds-layout="horizontal gap:sm">
<div cds-layout="p-r:md">
<cds-icon
size="lg"
id="lazy-load-icon"
shape="jabberwockee"
aria-label="This is an example of an icon that takes a little while to load its shape."
></cds-icon>
</div>
<div>
<cds-button @click=${toggleLazyIcon}>Toggle Icon</cds-button>
</div>
</div>
`;
function toggleLazyIcon() {
const mySvg =
'<svg viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M14.29,11.4a1.49,1.49,0,0,1,1.28-.72h1a2.89,2.89,0,0,0,2.75,2.09,3,3,0,0,0,0-5.91,2.9,2.9,0,0,0-2.67,1.82H15.57a3.49,3.49,0,0,0-3,1.66l-3,4.83h2.36Zm5-2.94A1.36,1.36,0,1,1,18,9.81,1.32,1.32,0,0,1,19.33,8.46Z"></path><path d="M34.3,17.37l-6.11-3.66a.7.7,0,0,0-.7,0,.71.71,0,0,0-.36.61V17H6.92a2.33,2.33,0,0,1,.32,1.17,2.47,2.47,0,1,1-2.47-2.46,2.37,2.37,0,0,1,1.15.3l.93-1.76A4.44,4.44,0,1,0,9.15,19h3.58l4.17,6.65a3.49,3.49,0,0,0,3,1.66h1.66v1.28a.79.79,0,0,0,.8.79h4.49a.79.79,0,0,0,.8-.79v-4.4a.79.79,0,0,0-.8-.8H22.34a.8.8,0,0,0-.8.8v1.12H19.88a1.51,1.51,0,0,1-1.28-.72L15.09,19h12v2.66a.69.69,0,0,0,.36.61.67.67,0,0,0,.34.09.65.65,0,0,0,.36-.1l6.11-3.66a.69.69,0,0,0,.34-.6A.71.71,0,0,0,34.3,17.37ZM23.14,25H26v2.8H23.14Zm5.39-4.56V15.55l4,2.42Z"></path></svg>';
if (ClarityIcons.registry[shapeName]) {
shapeName = shapeName + 'e';
document.getElementById('lazy-load-icon').setAttribute('shape', shapeName);
} else {
ClarityIcons.addIcons([shapeName, mySvg]);
}
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Manages a maintenance assignment to a virtual machine scale set.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleVirtualNetwork = new azure.network.VirtualNetwork("exampleVirtualNetwork", {
* addressSpaces: ["10.0.0.0/16"],
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* });
* const exampleSubnet = new azure.network.Subnet("exampleSubnet", {
* resourceGroupName: exampleResourceGroup.name,
* virtualNetworkName: exampleVirtualNetwork.name,
* addressPrefixes: ["10.0.2.0/24"],
* });
* const examplePublicIp = new azure.network.PublicIp("examplePublicIp", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* allocationMethod: "Static",
* });
* const exampleLoadBalancer = new azure.lb.LoadBalancer("exampleLoadBalancer", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* frontendIpConfigurations: [{
* name: "internal",
* publicIpAddressId: azurerm_public_ip.test.id,
* }],
* });
* const exampleBackendAddressPool = new azure.lb.BackendAddressPool("exampleBackendAddressPool", {
* resourceGroupName: exampleResourceGroup.name,
* loadbalancerId: azurerm_lb.test.id,
* });
* const exampleProbe = new azure.lb.Probe("exampleProbe", {
* resourceGroupName: exampleResourceGroup.name,
* loadbalancerId: azurerm_lb.test.id,
* port: 22,
* protocol: "Tcp",
* });
* const exampleRule = new azure.lb.Rule("exampleRule", {
* resourceGroupName: exampleResourceGroup.name,
* loadbalancerId: azurerm_lb.test.id,
* probeId: azurerm_lb_probe.test.id,
* backendAddressPoolId: azurerm_lb_backend_address_pool.test.id,
* frontendIpConfigurationName: "internal",
* protocol: "Tcp",
* frontendPort: 22,
* backendPort: 22,
* });
* const exampleConfiguration = new azure.maintenance.Configuration("exampleConfiguration", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* scope: "OSImage",
* visibility: "Custom",
* window: {
* startDateTime: "2021-12-31 00:00",
* expirationDateTime: "9999-12-31 00:00",
* duration: "06:00",
* timeZone: "Pacific Standard Time",
* recurEvery: "1Days",
* },
* });
* const exampleLinuxVirtualMachineScaleSet = new azure.compute.LinuxVirtualMachineScaleSet("exampleLinuxVirtualMachineScaleSet", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* sku: "Standard_F2",
* instances: 1,
* adminUsername: "adminuser",
* adminPassword: "P@ssword1234!",
* upgradeMode: "Automatic",
* healthProbeId: exampleProbe.id,
* disablePasswordAuthentication: false,
* sourceImageReference: {
* publisher: "Canonical",
* offer: "UbuntuServer",
* sku: "16.04-LTS",
* version: "latest",
* },
* osDisk: {
* storageAccountType: "Standard_LRS",
* caching: "ReadWrite",
* },
* networkInterfaces: [{
* name: "example",
* primary: true,
* ipConfigurations: [{
* name: "internal",
* primary: true,
* subnetId: exampleSubnet.id,
* loadBalancerBackendAddressPoolIds: [exampleBackendAddressPool.id],
* }],
* }],
* automaticOsUpgradePolicy: {
* disableAutomaticRollback: true,
* enableAutomaticOsUpgrade: true,
* },
* rollingUpgradePolicy: {
* maxBatchInstancePercent: 20,
* maxUnhealthyInstancePercent: 20,
* maxUnhealthyUpgradedInstancePercent: 20,
* pauseTimeBetweenBatches: "PT0S",
* },
* }, {
* dependsOn: ["azurerm_lb_rule.example"],
* });
* const exampleAssignmentVirtualMachineScaleSet = new azure.maintenance.AssignmentVirtualMachineScaleSet("exampleAssignmentVirtualMachineScaleSet", {
* location: exampleResourceGroup.location,
* maintenanceConfigurationId: exampleConfiguration.id,
* virtualMachineScaleSetId: azurerm_linux_virtual_machine.example.id,
* });
* ```
*
* ## Import
*
* Maintenance Assignment can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:maintenance/assignmentVirtualMachineScaleSet:AssignmentVirtualMachineScaleSet example /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resGroup1/providers/microsoft.compute/virtualMachineScaleSets/vmss1/providers/Microsoft.Maintenance/configurationAssignments/assign1
* ```
*/
export class AssignmentVirtualMachineScaleSet extends pulumi.CustomResource {
/**
* Get an existing AssignmentVirtualMachineScaleSet resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: AssignmentVirtualMachineScaleSetState, opts?: pulumi.CustomResourceOptions): AssignmentVirtualMachineScaleSet {
return new AssignmentVirtualMachineScaleSet(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:maintenance/assignmentVirtualMachineScaleSet:AssignmentVirtualMachineScaleSet';
/**
* Returns true if the given object is an instance of AssignmentVirtualMachineScaleSet. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is AssignmentVirtualMachineScaleSet {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === AssignmentVirtualMachineScaleSet.__pulumiType;
}
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* Specifies the ID of the Maintenance Configuration Resource. Changing this forces a new resource to be created.
*/
public readonly maintenanceConfigurationId!: pulumi.Output<string>;
/**
* Specifies the Virtual Machine Scale Set ID to which the Maintenance Configuration will be assigned. Changing this forces a new resource to be created.
*/
public readonly virtualMachineScaleSetId!: pulumi.Output<string>;
/**
* Create a AssignmentVirtualMachineScaleSet resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: AssignmentVirtualMachineScaleSetArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: AssignmentVirtualMachineScaleSetArgs | AssignmentVirtualMachineScaleSetState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as AssignmentVirtualMachineScaleSetState | undefined;
inputs["location"] = state ? state.location : undefined;
inputs["maintenanceConfigurationId"] = state ? state.maintenanceConfigurationId : undefined;
inputs["virtualMachineScaleSetId"] = state ? state.virtualMachineScaleSetId : undefined;
} else {
const args = argsOrState as AssignmentVirtualMachineScaleSetArgs | undefined;
if ((!args || args.maintenanceConfigurationId === undefined) && !opts.urn) {
throw new Error("Missing required property 'maintenanceConfigurationId'");
}
if ((!args || args.virtualMachineScaleSetId === undefined) && !opts.urn) {
throw new Error("Missing required property 'virtualMachineScaleSetId'");
}
inputs["location"] = args ? args.location : undefined;
inputs["maintenanceConfigurationId"] = args ? args.maintenanceConfigurationId : undefined;
inputs["virtualMachineScaleSetId"] = args ? args.virtualMachineScaleSetId : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(AssignmentVirtualMachineScaleSet.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering AssignmentVirtualMachineScaleSet resources.
*/
export interface AssignmentVirtualMachineScaleSetState {
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the ID of the Maintenance Configuration Resource. Changing this forces a new resource to be created.
*/
maintenanceConfigurationId?: pulumi.Input<string>;
/**
* Specifies the Virtual Machine Scale Set ID to which the Maintenance Configuration will be assigned. Changing this forces a new resource to be created.
*/
virtualMachineScaleSetId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a AssignmentVirtualMachineScaleSet resource.
*/
export interface AssignmentVirtualMachineScaleSetArgs {
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the ID of the Maintenance Configuration Resource. Changing this forces a new resource to be created.
*/
maintenanceConfigurationId: pulumi.Input<string>;
/**
* Specifies the Virtual Machine Scale Set ID to which the Maintenance Configuration will be assigned. Changing this forces a new resource to be created.
*/
virtualMachineScaleSetId: pulumi.Input<string>;
} | the_stack |
namespace Textor {
export class HtmlLanguage implements ILanguage {
private _languages: any[];
private _textReader: ITextReader;
private _tokenStack: any[] = [];
private _languageToken: any;
private _state: string;
private _token: any;
constructor(languages: any[]) {
// mixed content languages by mime-type
this._languages = languages;
}
public begin(textReader: ITextReader, state: string) {
this._textReader = textReader;
this._tokenStack = [ { type: this.readText } ];
// used for mixed content in JavaScript or CSS
this._languageToken = null;
if (state !== null) {
const states: string[] = state.split(":");
if (states.length > 1) {
const mimeType: string = states[0];
const closeTag: string = states[1];
const language = this._languages[mimeType];
if (language) {
language.begin(this._textReader, states[2]);
this.push({ type: this.readLanguage, mimeType: mimeType, language: language, closeTag: closeTag, contentData: 0 });
}
}
}
}
public read(): ILanguageStyle {
this._state = null;
this._token = this._tokenStack[this._tokenStack.length - 1];
if (this._token.type === this.readLanguage) {
return this._token.type.apply(this);
}
return { style: this._token.type.apply(this), state: this._state };
}
private readText(): string {
if (this._textReader.match("<")) {
if (this._tokenStack.length === 1) {
this._state = "base";
}
if (this._textReader.match("!")) {
if (this._textReader.match("--")) {
// comment
this.push({ type: this.readComment });
return "comment";
} else if (this._textReader.match("[CDATA[")) {
// constant data
this.push({ type: this.readConstantData });
return "literal";
} else {
// doc type
this.push({ type: this.readDocType });
return "punctuation";
}
} else if (this._textReader.match("?")) {
// processing instruction
this.push({ type: this.readProcessingInstruction });
return "punctuation";
} else if (this._textReader.match("/")) {
// close tag
this.push({ type: this.readEndTag });
return "punctuation";
} else {
// open tag
this.push({ type: this.readStartTag, name: "", hasAttributes: false });
return "punctuation";
}
} else if (this._textReader.match("&")) {
// entity
this.push({ type: this.readEntity });
return "literal";
}
this._textReader.read();
return "text";
}
private readStartTag(): string {
if (this._textReader.skipWhitespaces()) {
this._token.hasAttributes = true;
this.push({ type: this.readAttribute, name: "", hasValue: false });
return "text";
}
if (this._textReader.match(">") || (this._textReader.match("/>"))) {
this.pop();
this.setLanguage();
return "punctuation";
}
const c: string = this._textReader.read();
if (!this._token.hasAttributes) {
this._token.name += c;
}
return "element";
}
private readEndTag(): string {
if (this._textReader.match(">")) {
this.pop();
return "punctuation";
}
this._token.name += this._textReader.read();
return "element";
}
private readAttribute(): string {
if (this._textReader.skipWhitespaces()) {
return "text";
} else if (this._textReader.match(">")) {
this.pop();
this.pop();
this.setLanguage();
return "punctuation";
} else if (this._textReader.match("=")) {
this.push({ type: this.readAttributeValue, value: "", quote: "" });
this._token.hasValue = true;
return "punctuation";
}
const c: string = this._textReader.peek();
if (c === "/") {
this.pop();
return "punctuation";
}
this._textReader.read();
if (!this._token.hasValue) {
this._token.name += c;
}
return "attribute";
}
private readAttributeValue(): string {
const c: string = this._textReader.peek();
if (this._token.quote === "") {
if (c === "'") {
this._textReader.read();
this._token.quote = "s"; // single-quote
return "literal";
} else if (c === '"') {
this._textReader.read();
this._token.quote = "d"; // double-quote
return "literal";
} else if (this._textReader.skipWhitespaces()) {
return "text";
} else {
this._token.quote = "-"; // none
}
}
let closeTag: boolean = false;
let style: string = "";
if (this._token.quote === "s" && c === "'") {
this._textReader.read();
this.pop();
style = "literal";
} else if (this._token.quote === "d" && c === '"') {
this._textReader.read();
this.pop();
style = "literal";
} else if (this._token.quote === "-" && this._textReader.skipWhitespaces()) {
this.pop();
style = "text";
} else if (this._token.quote === "-" && c === ">") {
this._textReader.read();
this.pop();
closeTag = true;
style = "punctuation";
}
if (style.length === 0) {
this._token.value += this._textReader.read();
return "literal";
}
// check if element has mixed content
const attributeName: string = this._tokenStack[this._tokenStack.length - 1].name.toUpperCase();
const elementName: string = this._tokenStack[this._tokenStack.length - 2].name.toUpperCase();
if ((attributeName === "TYPE" && elementName === "SCRIPT") || (attributeName === "TYPE" && elementName === "STYLE")) {
const mimeType = this._token.value;
const language = this._languages[mimeType];
if (language) {
language.begin(this._textReader, null);
this._languageToken = { type: this.readLanguage, mimeType: mimeType, language: language, closeTag: "</" + elementName + ">", contentData: 0 };
}
}
// pop attribute
this.pop();
if (closeTag) {
// pop start tag
this.pop();
this.setLanguage();
} else {
// next attribute
this.push({ type: this.readAttribute, name: "", value: false });
}
return style;
}
private readComment(): string {
this.terminate("-->");
return "comment";
}
private readConstantData(): string {
this.terminate("]]>");
return "literal";
}
private readEntity(): string {
const c: string = this._textReader.read();
if ((c === "\n") || (c === ";")) {
this.pop();
}
return "literal";
}
private readDocType(): string {
return this.terminate(">") ? "punctuation" : "element";
}
private readProcessingInstruction(): string {
return this.terminate("?>") ? "punctuation" : "literal";
}
private readLanguage(): any {
const c: string = this._textReader.peek();
if (c === "<" || c === "]") {
if (this.testIgnoreCase("<![CDATA[")) {
this._token.contentData++;
} else if (this.testIgnoreCase("]]>") && (this._token.contentData > 0)) {
this._token.contentData--;
}
// check for </style> or </script> end tag.
if ((this._token.contentData === 0) && this.testIgnoreCase(this._token.closeTag)) {
this.pop();
return this.read();
}
}
const result = this._token.language.read();
result.state = (result.state !== null) ? (this._token.mimeType + ":" + this._token.closeTag + ":" + result.state) : null;
return result;
}
private push(token) {
this._tokenStack.push(token);
}
private pop() {
this._tokenStack.pop();
}
private setLanguage() {
if (this._languageToken !== null) {
this.push(this._languageToken);
this._languageToken = null;
}
}
private terminate(terminator: string): boolean {
if (this._textReader.match(terminator)) {
this.pop();
return true;
}
this._textReader.read();
return false;
}
private testIgnoreCase(text: string): boolean {
this._textReader.save();
for (const item of text) {
const c = this._textReader.read();
if ((c.length === 0) || (c.toUpperCase() !== item.toUpperCase())) {
this._textReader.restore();
return false;
}
}
this._textReader.restore();
return true;
}
}
} | the_stack |
import * as builder from "botbuilder";
import { TriggerActionDialog } from "../../../utils/TriggerActionDialog";
import { DialogIds } from "../../../utils/DialogIds";
import { DialogMatches } from "../../../utils/DialogMatches";
export class AdaptiveCardDialog extends TriggerActionDialog {
private static async sendAdaptiveCard(session: builder.Session, args?: any | builder.IDialogResult<any>, next?: (args?: builder.IDialogResult<any>) => void): Promise<void> {
// Check for the property in the value set by the adaptive card submit action
if (session.message.value && session.message.value.isFromAdaptiveCard)
{
session.send(JSON.stringify(session.message.value));
} else { // create new adaptive card
let adaptiveCardMessage = new builder.Message(session)
.addAttachment(AdaptiveCardDialog.getAdaptiveCardAttachment());
session.send(adaptiveCardMessage);
}
}
// Get the adaptive card attachment
private static getAdaptiveCardAttachment(): any {
let textToTriggerThisDialog = "Adaptive Card";
let adaptiveCardJson = {
contentType: "application/vnd.microsoft.card.adaptive",
content: {
type: "AdaptiveCard",
version: "1.0",
body: [
{
type : "Container",
items:
[
// TextBlock Item allows for the inclusion of text, with various font sizes, weight and color,
{
type: "TextBlock",
size: "large", // set the size of text e.g. Extra Large, Large, Medium, Normal, Small
weight: "bolder", // set the weight of text e.g. Bolder, Light, Normal
color: null,
isSubtle: false,
text: "Adaptive Card!",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
speak: "<s>Adaptive card!</s>",
separation: null,
},
// Adaptive FactSet item makes it simple to display a series of facts (e.g. name/value pairs) in a tabular form
{
type: "FactSet",
facts: [
// Describes a fact in a Adaptive FactSet as a key/value pair
{
title: "Board:",
value: "Adaptive Card",
},
{
title: "List:",
value: "Backlog",
},
{
title: "Assigned to:",
value: "Matt Hidinger",
},
{
title: "Due date:",
value: "Not set",
},
],
separation: null,
},
// ImageSet allows for the inclusion of a collection images like a photogallery
{
type: "ImageSet",
images: [
// Image Item allows for the inclusion of images
{
type: "Image",
size: null,
style: null,
url: "http://contososcubabot.azurewebsites.net/assets/steak.jpg",
horizontalAlignment: "left",
separation: null,
},
{
type: "Image",
size: null,
style: null,
url: "http://contososcubabot.azurewebsites.net/assets/chicken.jpg",
horizontalAlignment: "left",
separation: null,
},
{
type: "Image",
size: null,
style: null,
url: "http://contososcubabot.azurewebsites.net/assets/tofu.jpg",
horizontalAlignment: "left",
separation: null,
},
],
imageSize: "medium",
separation: null,
},
// wrap the text in textblock
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
// markdown example for bold text
text: "'**Matt H. said** \"I'm compelled to give this place 5 stars due to the number of times I've chosen to eat here this past year!',",
horizontalAlignment: "left",
wrap: true, // True if text is allowed to wrap
maxLines: 0,
separation: null,
},
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
text: "Place your text here:",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
separation: null,
},
{
type: "Input.Text", // set the type of input box e.g Text, Tel, Email, Url
placeholder: "Text Input",
style: "text",
isMultiline: false,
maxLength: 0,
id: "textInputId",
isRequired: false,
speak: "<s>Please enter your text here</s>",
separation: null,
},
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
text: "Please select Date here?",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
separation: null,
},
// date input collects Date from the user
{
type: "Input.Date",
id: "dateInput",
isRequired: false,
speak: "<s>Please select Date here?</s>",
separation: null,
},
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
text: "Please enter time here?",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
separation: null,
},
// time input collects time from the user
{
type: "Input.Time",
id: "timeInput",
isRequired: false,
separation: null,
},
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
text: "Please select your choice here? (Compact Dropdown)",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
separation: null,
},
// Shows an array of Choice objects
{
type: "Input.ChoiceSet",
value: 1,
style: "compact", // set the style of Choice set to compact
isMultiSelect: false,
choices: [
// describes a choice input. the value should be a simple string without a ","
{
title: "Red",
value: 1, // do not use a “,” in the value, since MultiSelect ChoiceSet returns a comma-delimited string of choice values
isSelected: false,
},
{
title: "Green",
value: 2,
isSelected: false,
},
{
title: "Blue",
value: 3,
isSelected: false,
},
{
title: "White",
value: 4,
isSelected: false,
},
],
id: "choiceSetCompact",
isRequired: false,
separation: null,
},
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
text: "Please select your choice here? (Expanded Dropdown)",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
separation: null,
},
// Shows an array of Choice objects
{
type: "Input.ChoiceSet",
value: 1, // please set default value here
style: "expanded", // set the style of Choice set to expanded
isMultiSelect: false,
choices: [
{
title: "Red",
value: 1,
isSelected: false,
},
{
title: "Green",
value: 2,
isSelected: false,
},
{
title: "Blue",
value: 3,
isSelected: false,
},
{
title: "White",
value: 4,
isSelected: false,
},
],
id: "choiceSetExpandedRequired",
isRequired: true,
separation: null,
},
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
text: "Please select multiple items here? (Multiselect Dropdown)",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
separation: null,
},
// Shows an array of Choice objects (Multichoice)
{
type: "Input.ChoiceSet",
value: "1,2", // The initial choice (or set of choices) that should be selected. For multi-select, specifcy a comma-separated string of values
style: "expanded", // set the style of Choice set to expanded
isMultiSelect: true, // allow multiple choices to be selected
choices: [
{
title: "Red",
value: 1,
isSelected: false,
},
{
title: "Green",
value: 2,
isSelected: false,
},
{
title: "Blue",
value: 3,
isSelected: false,
},
{
title: "White",
value: 4,
isSelected: false,
},
],
id: "choiceSetExpanded",
isRequired: false,
separation: null,
},
// column set divides a region into Column's allowing elements to sit side-by-side
{
type: "ColumnSet",
columns: [
{
// defines a container that is part of a column set
type: "Column",
size: "Auto",
items: [
{
type: "Image",
size: "medium",
style: "person",
url: "https://placeholdit.imgix.net/~text?txtsize=65&txt=Adaptive+Cards&w=300&h=300",
horizontalAlignment: "left",
separation: null,
},
],
style: null,
separation: null,
},
{
type: "Column",
size: "Stretch",
items: [
{
type: "TextBlock",
size: null,
weight: "bolder",
color: null,
isSubtle: true,
text: "Hello!",
horizontalAlignment: "left",
wrap: false,
maxLines: 0,
separation: null,
},
{
type: "TextBlock",
size: null,
weight: null,
color: null,
isSubtle: false,
text: "Are you looking for a Tab or Bot?",
horizontalAlignment: "left",
wrap: true,
maxLines: 0,
separation: null,
},
],
style: null,
separation: null,
},
],
},
// input toggle collects a true/false response from the user
{
type: "Input.Toggle",
title: "I accept the terms and conditions (True/False)",
valueOn: "true", // the value when toggle is on (default: true)
valueOff: "false", // the value when toggle is off (default: false)
id: "AcceptsTerms",
isRequired: false,
separation: null,
},
],
},
],
actions: [
// submit action gathers up input fields, merges with optional data field and generates event to client asking for data to be submitted
{
type: "Action.Submit",
title: "Submit",
speak: "<s>Search</s>",
data: {
isFromAdaptiveCard: true,
messageText: textToTriggerThisDialog,
},
},
// show action defines an inline AdaptiveCard which is shown to the user when it is clicked
{
type: "Action.ShowCard",
card: {
type: "AdaptiveCard",
version: "1.0",
body: [
{
type: "Container",
items: [
{
type: "Input.Text",
placeholder: "text here",
style: "text",
isMultiline: false,
maxLength: 0,
id: "Text",
isRequired: false,
speak: "<s>Please enter your text here?</s>",
separation: null,
},
],
style: null,
separation: null,
},
],
actions: [
{
type: "Action.Submit",
title: "Submit",
speak: "<s>Search</s>",
data: {
isFromAdaptiveCard: true,
messageText: textToTriggerThisDialog,
},
},
],
},
},
// open url show the given url, either by launching it to an external web browser
{
type: "Action.OpenUrl",
url: "http://adaptivecards.io/explorer/Action.OpenUrl.html",
title: "Open Url",
},
],
},
};
return adaptiveCardJson;
}
constructor(
bot: builder.UniversalBot,
) {
super(bot,
DialogIds.AdaptiveCardDialogId,
[
DialogMatches.AdaptiveCardDialogMatch,
],
AdaptiveCardDialog.sendAdaptiveCard,
);
}
} | the_stack |
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as iam from '@aws-cdk/aws-iam';
import { CfnApplicationCloudWatchLoggingOptionV2, CfnApplicationV2 } from '@aws-cdk/aws-kinesisanalytics';
import * as logs from '@aws-cdk/aws-logs';
import * as core from '@aws-cdk/core';
import { Construct } from 'constructs';
import { ApplicationCode } from './application-code';
import { environmentProperties } from './private/environment-properties';
import { flinkApplicationConfiguration } from './private/flink-application-configuration';
import { validateFlinkApplicationProps as validateApplicationProps } from './private/validation';
import { LogLevel, MetricsLevel, PropertyGroups, Runtime } from './types';
/**
* An interface expressing the public properties on both an imported and
* CDK-created Flink application.
*/
export interface IApplication extends core.IResource, iam.IGrantable {
/**
* The application ARN.
*
* @attribute
*/
readonly applicationArn: string;
/**
* The name of the Flink application.
*
* @attribute
*/
readonly applicationName: string;
/**
* The application IAM role.
*/
readonly role?: iam.IRole;
/**
* Convenience method for adding a policy statement to the application role.
*/
addToRolePolicy(policyStatement: iam.PolicyStatement): boolean;
/**
* Return a CloudWatch metric associated with this Flink application.
*
* @param metricName The name of the metric
* @param props Customization properties
*/
metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of Kinesis Processing Units that are used to run your stream
* processing application. The average number of KPUs used each hour
* determines the billing for your application.
*
* Units: Count
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricKpus(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The time elapsed during an outage for failing/recovering jobs.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricDowntime(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The time that the job has been running without interruption.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default sample count over 5 minutes
*/
metricUptime(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total number of times this job has fully restarted since it was
* submitted. This metric does not measure fine-grained restarts.
*
* Units: Count
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricFullRestarts(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of times checkpointing has failed.
*
* Units: Count
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricNumberOfFailedCheckpoints(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The time it took to complete the last checkpoint.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default maximum over 5 minutes
*/
metricLastCheckpointDuration(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total size of the last checkpoint.
*
* Units: Bytes
*
* Reporting Level: Application
*
* @default maximum over 5 minutes
*/
metricLastCheckpointSize(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The overall percentage of CPU utilization across task managers. For
* example, if there are five task managers, Kinesis Data Analytics publishes
* five samples of this metric per reporting interval.
*
* Units: Percentage
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricCpuUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Overall heap memory utilization across task managers. For example, if there
* are five task managers, Kinesis Data Analytics publishes five samples of
* this metric per reporting interval.
*
* Units: Percentage
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricHeapMemoryUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total time spent performing old garbage collection operations.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricOldGenerationGCTime(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total number of old garbage collection operations that have occurred
* across all task managers.
*
* Units: Count
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricOldGenerationGCCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total number of live threads used by the application.
*
* Units: Count
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricThreadsCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total number of records this application, operator, or task has
* received.
*
* Units: Count
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsIn(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total number of records this application, operator or task has
* received per second.
*
* Units: Count/Second
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsInPerSecond(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total number of records this application, operator or task has emitted.
*
* Units: Count
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsOut(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total number of records this application, operator or task has emitted
* per second.
*
* Units: Count/Second
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsOutPerSecond(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The number of records this operator or task has dropped due to arriving late.
*
* Units: Count
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default sum over 5 minutes
*/
metricNumLateRecordsDropped(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The last watermark this application/operator/task/thread has received.
*
* Units: Milliseconds
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default maximum over 5 minutes
*/
metricCurrentInputWatermark(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The last watermark this application/operator/task/thread has received.
*
* Units: Milliseconds
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default maximum over 5 minutes
*/
metricCurrentOutputWatermark(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The amount of managed memory currently used.
*
* Units: Bytes
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricManagedMemoryUsed(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The total amount of managed memory.
*
* Units: Bytes
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricManagedMemoryTotal(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Derived from managedMemoryUsed/managedMemoryTotal.
*
* Units: Percentage
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricManagedMemoryUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The time (in milliseconds) this task or operator is idle (has no data to
* process) per second. Idle time excludes back pressured time, so if the task
* is back pressured it is not idle.
*
* Units: Milliseconds
*
* Reporting Level: Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricIdleTimeMsPerSecond(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The time (in milliseconds) this task or operator is back pressured per
* second.
*
* Units: Milliseconds
*
* Reporting Level: Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricBackPressuredTimeMsPerSecond(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* The time (in milliseconds) this task or operator is busy (neither idle nor
* back pressured) per second. Can be NaN, if the value could not be
* calculated.
*
* Units: Milliseconds
*
* Reporting Level: Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricBusyTimePerMsPerSecond(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
}
/**
* Implements the functionality shared between CDK created and imported
* IApplications.
*/
abstract class ApplicationBase extends core.Resource implements IApplication {
public abstract readonly applicationArn: string;
public abstract readonly applicationName: string;
public abstract readonly role?: iam.IRole;
// Implement iam.IGrantable interface
public abstract readonly grantPrincipal: iam.IPrincipal;
/** Implement the convenience {@link IApplication.addToPrincipalPolicy} method. */
public addToRolePolicy(policyStatement: iam.PolicyStatement): boolean {
if (this.role) {
this.role.addToPrincipalPolicy(policyStatement);
return true;
}
return false;
}
/**
* Return a CloudWatch metric associated with this Flink application.
*
* @param metricName The name of the metric
* @param props Customization properties
*/
metric(metricName: string, props?: cloudwatch.MetricOptions) {
return new cloudwatch.Metric({
namespace: 'AWS/KinesisAnalytics',
metricName,
dimensionsMap: { Application: this.applicationName },
...props,
}).attachTo(this);
}
/**
* The number of Kinesis Processing Units that are used to run your stream
* processing application. The average number of KPUs used each hour
* determines the billing for your application.
*
* Units: Count
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricKpus(props?: cloudwatch.MetricOptions) {
return this.metric('KPUs', { statistic: 'Average', ...props });
}
/**
* The time elapsed during an outage for failing/recovering jobs.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricDowntime(props?: cloudwatch.MetricOptions) {
return this.metric('downtime', { statistic: 'Average', ...props });
}
/**
* The time that the job has been running without interruption.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricUptime(props?: cloudwatch.MetricOptions) {
return this.metric('uptime', { statistic: 'Average', ...props });
}
/**
* The total number of times this job has fully restarted since it was
* submitted. This metric does not measure fine-grained restarts.
*
* Units: Count
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricFullRestarts(props?: cloudwatch.MetricOptions) {
return this.metric('fullRestarts', { statistic: 'Sum', ...props });
}
/**
* The number of times checkpointing has failed.
*
* Units: Count
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricNumberOfFailedCheckpoints(props?: cloudwatch.MetricOptions) {
return this.metric('numberOfFailedCheckpoints', { statistic: 'Sum', ...props });
}
/**
* The time it took to complete the last checkpoint.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default maximum over 5 minutes
*/
metricLastCheckpointDuration(props?: cloudwatch.MetricOptions) {
return this.metric('lastCheckpointDuration', { statistic: 'Maximum', ...props });
}
/**
* The total size of the last checkpoint.
*
* Units: Bytes
*
* Reporting Level: Application
*
* @default maximum over 5 minutes
*/
metricLastCheckpointSize(props?: cloudwatch.MetricOptions) {
return this.metric('lastCheckpointSize', { statistic: 'Maximum', ...props });
}
/**
* The overall percentage of CPU utilization across task managers. For
* example, if there are five task managers, Kinesis Data Analytics publishes
* five samples of this metric per reporting interval.
*
* Units: Percentage
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricCpuUtilization(props?: cloudwatch.MetricOptions) {
return this.metric('cpuUtilization', { statistic: 'Average', ...props });
}
/**
* Overall heap memory utilization across task managers. For example, if there
* are five task managers, Kinesis Data Analytics publishes five samples of
* this metric per reporting interval.
*
* Units: Percentage
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricHeapMemoryUtilization(props?: cloudwatch.MetricOptions) {
return this.metric('heapMemoryUtilization', { statistic: 'Average', ...props });
}
/**
* The total time spent performing old garbage collection operations.
*
* Units: Milliseconds
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricOldGenerationGCTime(props?: cloudwatch.MetricOptions) {
return this.metric('oldGenerationGCTime', { statistic: 'Sum', ...props });
}
/**
* The total number of old garbage collection operations that have occurred
* across all task managers.
*
* Units: Count
*
* Reporting Level: Application
*
* @default sum over 5 minutes
*/
metricOldGenerationGCCount(props?: cloudwatch.MetricOptions) {
return this.metric('oldGenerationGCCount', { statistic: 'Sum', ...props });
}
/**
* The total number of live threads used by the application.
*
* Units: Count
*
* Reporting Level: Application
*
* @default average over 5 minutes
*/
metricThreadsCount(props?: cloudwatch.MetricOptions) {
return this.metric('threadsCount', { statistic: 'Average', ...props });
}
/**
* The total number of records this application, operator, or task has
* received.
*
* Units: Count
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsIn(props?: cloudwatch.MetricOptions) {
return this.metric('numRecordsIn', { statistic: 'Average', ...props });
}
/**
* The total number of records this application, operator or task has received
* per second.
*
* Units: Count/Second
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsInPerSecond(props?: cloudwatch.MetricOptions) {
return this.metric('numRecordsInPerSecond', { statistic: 'Average', ...props });
}
/**
* The total number of records this application, operator or task has emitted.
*
* Units: Count
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsOut(props?: cloudwatch.MetricOptions) {
return this.metric('numRecordsOut', { statistic: 'Average', ...props });
}
/**
* The total number of records this application, operator or task has emitted
* per second.
*
* Units: Count/Second
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricNumRecordsOutPerSecond(props?: cloudwatch.MetricOptions) {
return this.metric('numRecordsOutPerSecond', { statistic: 'Average', ...props });
}
/**
* The number of records this operator or task has dropped due to arriving
* late.
*
* Units: Count
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default sum over 5 minutes
*/
metricNumLateRecordsDropped(props?: cloudwatch.MetricOptions) {
return this.metric('numLateRecordsDropped', { statistic: 'Sum', ...props });
}
/**
* The last watermark this application/operator/task/thread has received.
*
* Units: Milliseconds
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default maximum over 5 minutes
*/
metricCurrentInputWatermark(props?: cloudwatch.MetricOptions) {
return this.metric('currentInputWatermark', { statistic: 'Maximum', ...props });
}
/**
* The last watermark this application/operator/task/thread has received.
*
* Units: Milliseconds
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default maximum over 5 minutes
*/
metricCurrentOutputWatermark(props?: cloudwatch.MetricOptions) {
return this.metric('currentOutputWatermark', { statistic: 'Maximum', ...props });
}
/**
* The amount of managed memory currently used.
*
* Units: Bytes
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricManagedMemoryUsed(props?: cloudwatch.MetricOptions) {
return this.metric('managedMemoryUsed', { statistic: 'Average', ...props });
}
/**
* The total amount of managed memory.
*
* Units: Bytes
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricManagedMemoryTotal(props?: cloudwatch.MetricOptions) {
return this.metric('managedMemoryTotal', { statistic: 'Average', ...props });
}
/**
* Derived from managedMemoryUsed/managedMemoryTotal.
*
* Units: Percentage
*
* Reporting Level: Application, Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricManagedMemoryUtilization(props?: cloudwatch.MetricOptions) {
return this.metric('managedMemoryUtilization', { statistic: 'Average', ...props });
}
/**
* The time (in milliseconds) this task or operator is idle (has no data to
* process) per second. Idle time excludes back pressured time, so if the task
* is back pressured it is not idle.
*
* Units: Milliseconds
*
* Reporting Level: Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricIdleTimeMsPerSecond(props?: cloudwatch.MetricOptions) {
return this.metric('idleTimeMsPerSecond', { statistic: 'Average', ...props });
}
/**
* The time (in milliseconds) this task or operator is back pressured per
* second.
*
* Units: Milliseconds
*
* Reporting Level: Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricBackPressuredTimeMsPerSecond(props?: cloudwatch.MetricOptions) {
return this.metric('backPressuredTimeMsPerSecond', { statistic: 'Average', ...props });
}
/**
* The time (in milliseconds) this task or operator is busy (neither idle nor
* back pressured) per second. Can be NaN, if the value could not be
* calculated.
*
* Units: Milliseconds
*
* Reporting Level: Operator, Task, Parallelism
*
* @default average over 5 minutes
*/
metricBusyTimePerMsPerSecond(props?: cloudwatch.MetricOptions) {
return this.metric('busyTimePerMsPerSecond', { statistic: 'Average', ...props });
}
}
/**
* Props for creating an Application construct.
*/
export interface ApplicationProps {
/**
* A name for your Application that is unique to an AWS account.
*
* @default - CloudFormation-generated name
*/
readonly applicationName?: string;
/**
* The Flink version to use for this application.
*/
readonly runtime: Runtime;
/**
* The Flink code asset to run.
*/
readonly code: ApplicationCode;
/**
* Whether checkpointing is enabled while your application runs.
*
* @default true
*/
readonly checkpointingEnabled?: boolean;
/**
* The interval between checkpoints.
*
* @default 1 minute
*/
readonly checkpointInterval?: core.Duration;
/**
* The minimum amount of time in to wait after a checkpoint finishes to start
* a new checkpoint.
*
* @default 5 seconds
*/
readonly minPauseBetweenCheckpoints?: core.Duration;
/**
* The level of log verbosity from the Flink application.
*
* @default FlinkLogLevel.INFO
*/
readonly logLevel?: LogLevel;
/**
* Describes the granularity of the CloudWatch metrics for an application.
* Use caution with Parallelism level metrics. Parallelism granularity logs
* metrics for each parallel thread and can quickly become expensive when
* parallelism is high (e.g. > 64).
*
* @default MetricsLevel.APPLICATION
*/
readonly metricsLevel?: MetricsLevel;
/**
* Whether the Kinesis Data Analytics service can increase the parallelism of
* the application in response to resource usage.
*
* @default true
*/
readonly autoScalingEnabled?: boolean;
/**
* The initial parallelism for the application. Kinesis Data Analytics can
* stop the app, increase the parallelism, and start the app again if
* autoScalingEnabled is true (the default value).
*
* @default 1
*/
readonly parallelism?: number;
/**
* The Flink parallelism allowed per Kinesis Processing Unit (KPU).
*
* @default 1
*/
readonly parallelismPerKpu?: number
/**
* Determines if Flink snapshots are enabled.
*
* @default true
*/
readonly snapshotsEnabled?: boolean;
/**
* Configuration PropertyGroups. You can use these property groups to pass
* arbitrary runtime configuration values to your Flink app.
*
* @default No property group configuration provided to the Flink app
*/
readonly propertyGroups?: PropertyGroups;
/**
* A role to use to grant permissions to your application. Prefer omitting
* this property and using the default role.
*
* @default - a new Role will be created
*/
readonly role?: iam.IRole;
/**
* Provide a RemovalPolicy to override the default.
*
* @default RemovalPolicy.DESTROY
*/
readonly removalPolicy?: core.RemovalPolicy;
/**
* The log group to send log entries to.
*
* @default CDK's default LogGroup
*/
readonly logGroup?: logs.ILogGroup;
}
/**
* An imported Flink application.
*/
class Import extends ApplicationBase {
public readonly grantPrincipal: iam.IPrincipal;
public readonly role?: iam.IRole;
public readonly applicationName: string;
public readonly applicationArn: string;
constructor(scope: Construct, id: string, attrs: { applicationArn: string, applicationName: string }) {
super(scope, id);
// Imported applications have no associated role or grantPrincipal
this.grantPrincipal = new iam.UnknownPrincipal({ resource: this });
this.role = undefined;
this.applicationArn = attrs.applicationArn;
this.applicationName = attrs.applicationName;
}
}
/**
* The L2 construct for Flink Kinesis Data Applications.
*
* @resource AWS::KinesisAnalyticsV2::Application
*
*/
export class Application extends ApplicationBase {
/**
* Import an existing Flink application defined outside of CDK code by
* applicationName.
*/
public static fromApplicationName(scope: Construct, id: string, applicationName: string): IApplication {
const applicationArn = core.Stack.of(scope).formatArn(applicationArnComponents(applicationName));
return new Import(scope, id, { applicationArn, applicationName });
}
/**
* Import an existing application defined outside of CDK code by
* applicationArn.
*/
public static fromApplicationArn(scope: Construct, id: string, applicationArn: string): IApplication {
const applicationName = core.Stack.of(scope).splitArn(applicationArn, core.ArnFormat.SLASH_RESOURCE_NAME).resourceName;
if (!applicationName) {
throw new Error(`applicationArn for fromApplicationArn (${applicationArn}) must include resource name`);
}
return new Import(scope, id, { applicationArn, applicationName });
}
public readonly applicationArn: string;
public readonly applicationName: string;
// Role must be optional for JSII compatibility
public readonly role?: iam.IRole;
public readonly grantPrincipal: iam.IPrincipal;
constructor(scope: Construct, id: string, props: ApplicationProps) {
super(scope, id, { physicalName: props.applicationName });
validateApplicationProps(props);
this.role = props.role ?? new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('kinesisanalytics.amazonaws.com'),
});
this.grantPrincipal = this.role;
// Permit metric publishing to CloudWatch
this.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['cloudwatch:PutMetricData'],
resources: ['*'],
}));
const code = props.code.bind(this);
code.bucket.grantRead(this);
const resource = new CfnApplicationV2(this, 'Resource', {
applicationName: props.applicationName,
runtimeEnvironment: props.runtime.value,
serviceExecutionRole: this.role.roleArn,
applicationConfiguration: {
...code.applicationCodeConfigurationProperty,
environmentProperties: environmentProperties(props.propertyGroups),
flinkApplicationConfiguration: flinkApplicationConfiguration({
checkpointingEnabled: props.checkpointingEnabled,
checkpointInterval: props.checkpointInterval,
minPauseBetweenCheckpoints: props.minPauseBetweenCheckpoints,
logLevel: props.logLevel,
metricsLevel: props.metricsLevel,
autoScalingEnabled: props.autoScalingEnabled,
parallelism: props.parallelism,
parallelismPerKpu: props.parallelismPerKpu,
}),
applicationSnapshotConfiguration: {
snapshotsEnabled: props.snapshotsEnabled ?? true,
},
},
});
resource.node.addDependency(this.role);
const logGroup = props.logGroup ?? new logs.LogGroup(this, 'LogGroup');
const logStream = new logs.LogStream(this, 'LogStream', { logGroup });
/* Permit logging */
this.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['logs:DescribeLogGroups'],
resources: [
core.Stack.of(this).formatArn({
service: 'logs',
resource: 'log-group',
arnFormat: core.ArnFormat.COLON_RESOURCE_NAME,
resourceName: '*',
}),
],
}));
this.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['logs:DescribeLogStreams'],
resources: [logGroup.logGroupArn],
}));
const logStreamArn = `arn:${core.Aws.PARTITION}:logs:${core.Aws.REGION}:${core.Aws.ACCOUNT_ID}:log-group:${logGroup.logGroupName}:log-stream:${logStream.logStreamName}`;
this.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['logs:PutLogEvents'],
resources: [logStreamArn],
}));
new CfnApplicationCloudWatchLoggingOptionV2(this, 'LoggingOption', {
applicationName: resource.ref,
cloudWatchLoggingOption: {
logStreamArn,
},
});
this.applicationName = this.getResourceNameAttribute(resource.ref);
this.applicationArn = this.getResourceArnAttribute(
core.Stack.of(this).formatArn(applicationArnComponents(resource.ref)),
applicationArnComponents(this.physicalName),
);
resource.applyRemovalPolicy(props.removalPolicy, {
default: core.RemovalPolicy.DESTROY,
});
}
}
function applicationArnComponents(resourceName: string): core.ArnComponents {
return {
service: 'kinesisanalytics',
resource: 'application',
resourceName,
};
} | the_stack |
import { Injectable, Autowired, INJECTOR_TOKEN, Injector } from '@opensumi/di';
import { positionToRange, URI, CommandService } from '@opensumi/ide-core-common';
import { IDocPersistentCacheProvider } from '@opensumi/ide-editor';
import { EmptyDocCacheImpl, IEditorDocumentModelService } from '@opensumi/ide-editor/src/browser';
import { IEditorDocumentModel } from '@opensumi/ide-editor/src/browser/';
import { EditorDocumentModel } from '@opensumi/ide-editor/src/browser/doc-model/main';
import { createBrowserInjector } from '../../../../../tools/dev-tool/src/injector-helper';
import { MockInjector } from '../../../../../tools/dev-tool/src/mock-injector';
import { createMockedMonaco } from '../../../../monaco/__mocks__/monaco';
import { SCMService } from '../../../src';
import { DirtyDiffModel } from '../../../src/browser/dirty-diff/dirty-diff-model';
import { DirtyDiffWidget } from '../../../src/browser/dirty-diff/dirty-diff-widget';
@Injectable()
class MockEditorDocumentModelService {
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
async createModelReference(uri: URI) {
const instance = this.injector.get(EditorDocumentModel, [uri, 'test-content']);
return { instance };
}
}
const mockedMonaco = createMockedMonaco();
(global as any).monaco = mockedMonaco;
jest.useFakeTimers();
// mock ThrottledDelayer to take it easy in unit test
jest.mock('@opensumi/ide-core-common', () => ({
...jest.requireActual('@opensumi/ide-core-common'),
ThrottledDelayer: class {
constructor() {}
trigger(value) {
return Promise.resolve(value);
}
},
}));
describe('scm/src/browser/dirty-diff/dirty-diff-widget.ts', () => {
describe('test for DirtyDiffDecorator', () => {
let injector: MockInjector;
let editorModel: IEditorDocumentModel;
let commandService: CommandService;
const fakeExecCmd = jest.fn();
const codeEditor = mockedMonaco.editor!.create(document.createElement('div'));
beforeEach(() => {
injector = createBrowserInjector(
[],
new MockInjector([
{
token: IDocPersistentCacheProvider,
useClass: EmptyDocCacheImpl,
},
{
token: IEditorDocumentModelService,
useClass: MockEditorDocumentModelService,
},
{
token: CommandService,
useValue: {
executeCommand: fakeExecCmd,
},
},
SCMService,
]),
);
editorModel = injector.get(EditorDocumentModel, [URI.file('/test/workspace/abc.ts'), 'test']);
codeEditor.setModel(editorModel.getMonacoModel());
commandService = injector.get(CommandService);
});
afterEach(() => {
editorModel.dispose();
});
afterAll(() => {
codeEditor.dispose();
});
it('ok for basic checking', () => {
const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]);
const dirtyDiffWidget = injector.get(DirtyDiffWidget, [codeEditor, dirtyDiffModel, commandService]);
expect(dirtyDiffWidget.currentIndex).toBe(0);
dirtyDiffWidget.updateCurrent(10);
expect(dirtyDiffWidget.currentIndex).toBe(10);
});
it('ok for applyClass', () => {
const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]);
const dirtyDiffWidget = injector.get(DirtyDiffWidget, [codeEditor, dirtyDiffModel, commandService]);
const changes = [
{
originalStartLineNumber: 11,
originalEndLineNumber: 11,
modifiedStartLineNumber: 11,
modifiedEndLineNumber: 11,
},
{
originalStartLineNumber: 12,
originalEndLineNumber: 12,
modifiedStartLineNumber: 12,
modifiedEndLineNumber: 12,
},
{
originalStartLineNumber: 14,
originalEndLineNumber: 14,
modifiedStartLineNumber: 14,
modifiedEndLineNumber: 14,
},
{
originalStartLineNumber: 15,
originalEndLineNumber: 15,
modifiedStartLineNumber: 15,
modifiedEndLineNumber: 15,
},
];
dirtyDiffModel['_changes'] = changes;
dirtyDiffWidget.updateCurrent(2);
dirtyDiffWidget['applyClass']();
const head = dirtyDiffWidget['_head'];
expect(head.className).toBe('dirty-diff-widget-header');
const wrapper = dirtyDiffWidget['_wrapper'];
expect(wrapper.className).toBe('dirty-diff-widget-wrapper');
const content = dirtyDiffWidget['_content'];
expect(content.className).toBe('dirty-diff-widget-content');
expect(dirtyDiffWidget.getContentNode()).toBe(content);
const title = dirtyDiffWidget['_title'];
expect(title.innerText).toBe('abc.ts');
expect(title.className).toBe('file-name');
expect(title.tagName).toBe('DIV');
expect(title.parentNode).toBe(head);
const actions = dirtyDiffWidget['_actions'];
expect(actions.className).toBe('file-actions');
expect(actions.parentNode).toBe(head);
codeEditor.setModel(null);
try {
dirtyDiffWidget['applyClass']();
} catch (err) {
expect(err.message).toBe('Not found model');
}
codeEditor.setModel(editorModel.getMonacoModel());
});
it('ok for actions', () => {
const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]);
const dirtyDiffWidget = injector.get(DirtyDiffWidget, [codeEditor, dirtyDiffModel, commandService]);
const fakeDispose = jest.fn();
dirtyDiffWidget['dispose'] = fakeDispose;
const changes = [
{
originalStartLineNumber: 11,
originalEndLineNumber: 11,
modifiedStartLineNumber: 11,
modifiedEndLineNumber: 11,
},
{
originalStartLineNumber: 12,
originalEndLineNumber: 12,
modifiedStartLineNumber: 12,
modifiedEndLineNumber: 12,
},
{
originalStartLineNumber: 14,
originalEndLineNumber: 14,
modifiedStartLineNumber: 14,
modifiedEndLineNumber: 14,
},
{
originalStartLineNumber: 15,
originalEndLineNumber: 15,
modifiedStartLineNumber: 15,
modifiedEndLineNumber: 15,
},
];
dirtyDiffModel['_changes'] = changes;
dirtyDiffWidget.updateCurrent(2);
dirtyDiffWidget['_current'] = positionToRange(13);
dirtyDiffWidget['applyClass']();
const actions = dirtyDiffWidget['_actions'];
expect(actions.className).toBe('file-actions');
const actionList = Array.from(actions.children) as HTMLElement[];
expect(actionList.length).toBe(5);
expect(actionList.map((n) => n.className)).toEqual(
['plus', 'rollback', 'up', 'down', 'close'].map((n) => `kaitian-icon kticon-${n}`),
);
// onclick test
// add
actionList[0].click();
expect(fakeExecCmd).toBeCalledTimes(1);
expect(fakeExecCmd.mock.calls[0]).toEqual(['git.stageChange', URI.file('/test/workspace/abc.ts'), changes, 1]);
expect(fakeDispose).toHaveBeenCalledTimes(1);
// revert
actionList[1].click();
expect(fakeExecCmd).toBeCalledTimes(2);
expect(fakeExecCmd.mock.calls[1]).toEqual(['git.revertChange', URI.file('/test/workspace/abc.ts'), changes, 1]);
expect(fakeDispose).toHaveBeenCalledTimes(2);
// next
actionList[2].click();
expect(fakeExecCmd).toBeCalledTimes(3);
expect(fakeExecCmd.mock.calls[2]).toEqual(['OPEN_DIRTY_DIFF_WIDGET', 14]);
// prev
actionList[3].click();
expect(fakeExecCmd).toBeCalledTimes(4);
expect(fakeExecCmd.mock.calls[3]).toEqual(['OPEN_DIRTY_DIFF_WIDGET', 12]);
// close
actionList[4].click();
expect(fakeExecCmd).toBeCalledTimes(4);
expect(fakeDispose).toHaveBeenCalledTimes(3);
dirtyDiffWidget['_current'] = positionToRange(14);
dirtyDiffModel['findNextClosestChangeLineNumber'] = (n) => n;
actionList[2].click();
dirtyDiffModel['findPreviousClosestChangeLineNumber'] = (n) => n;
actionList[3].click();
expect(fakeExecCmd).toBeCalledTimes(4);
});
it('ok for applyStyle', () => {
const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]);
dirtyDiffModel['_changes'] = [
{
originalStartLineNumber: 11,
originalEndLineNumber: 11,
modifiedStartLineNumber: 11,
modifiedEndLineNumber: 11,
},
{
originalStartLineNumber: 12,
originalEndLineNumber: 12,
modifiedStartLineNumber: 12,
modifiedEndLineNumber: 12,
},
{
originalStartLineNumber: 14,
originalEndLineNumber: 14,
modifiedStartLineNumber: 14,
modifiedEndLineNumber: 14,
},
{
originalStartLineNumber: 15,
originalEndLineNumber: 15,
modifiedStartLineNumber: 15,
modifiedEndLineNumber: 15,
},
];
const dirtyDiffWidget = injector.get(DirtyDiffWidget, [codeEditor, dirtyDiffModel, commandService]);
dirtyDiffWidget.updateCurrent(2);
dirtyDiffWidget['applyClass']();
dirtyDiffWidget['applyStyle']();
const title = dirtyDiffWidget['_title'];
expect(title.children.length).toBe(1);
const detail = title.children[0];
expect(detail.tagName).toBe('SPAN');
expect(detail.className).toBe('dirty-diff-widget-title-detail');
expect((detail as HTMLElement).innerText).toBe('第 2 个更改(共 4 个)');
dirtyDiffWidget.updateCurrent(4);
dirtyDiffWidget['applyStyle']();
// 上一个 children[0] 已经被移除了
expect((title.children[0] as HTMLElement).innerText).toBe('第 4 个更改(共 4 个)');
});
it('ok for relayout', () => {
const dirtyDiffModel = injector.get(DirtyDiffModel, [editorModel]);
const dirtyDiffWidget = injector.get(DirtyDiffWidget, [codeEditor, dirtyDiffModel, commandService]);
const fakeRelayout = jest.fn();
// store the real method
const realRelayout = dirtyDiffWidget['_relayout'];
dirtyDiffWidget['_relayout'] = fakeRelayout;
dirtyDiffWidget.relayout(20);
expect(fakeRelayout).toHaveBeenCalledTimes(1);
expect(fakeRelayout).toHaveBeenCalledWith(20);
// reset
dirtyDiffWidget['_relayout'] = realRelayout;
});
});
}); | the_stack |
import { EventEmitter } from 'events';
import BlockChangeSFX from '../assets/sfx/plop.ogg';
import { AABB, Clouds, ServerChunkType, Sky } from '../libs';
import { Coords3, Coords2 } from '../libs/types';
import { Helper } from '../utils';
import { Chunk } from './chunk';
import { Engine } from './engine';
import { TargetBlock } from './player';
type WorldOptionsType = {
name?: string;
maxHeight?: number;
chunkSize?: number;
subChunks?: number;
dimension?: number;
renderRadius: number;
requestRadius: number;
maxChunkProcessPerFrame: number;
maxBlockPerFrame: number;
chunkAnimation: boolean;
animationTime: number;
};
const BLOCK_SFX_NAME = 'block break';
class World extends EventEmitter {
public name: string;
// has all chunks been generated within render radius at start
public isReady = false;
public sky: Sky;
public clouds: Clouds;
// uniforms
public uSunlightIntensity = { value: 0.1 };
public blockData: { passables: number[] } = {
passables: [],
};
private camChunkName: string;
private camChunkPos: Coords2;
private pendingChunks: Coords2[] = [];
private requestedChunks: Set<string> = new Set();
private receivedChunks: ServerChunkType[] = [];
private chunks: Map<string, Chunk> = new Map();
constructor(public engine: Engine, public options: WorldOptionsType) {
super();
this.sky = new Sky(engine.rendering);
this.clouds = new Clouds(engine.rendering);
// kinda ugly
this.name = options.name;
engine.on('start', () => {
this.updateRenderRadius(this.options.renderRadius);
engine.inputs.bind('esc', engine.lock, 'menu', { occasion: 'keyup' });
engine.inputs.bind('p', this.reloadChunks, '*');
});
engine.on('ready', () => {
engine.sounds.add(BLOCK_SFX_NAME, BlockChangeSFX);
});
engine.on('focus', async () => {
if (this.engine.tickSpeed === 0) return;
const [time, processed] = JSON.parse(await engine.network.fetchData('/time'));
const received = Date.now();
this.setTime(time + (received - processed) / this.engine.tickSpeed, false);
});
}
setup = (worldData: any) => {
const { chunk_size, dimension, max_height, sub_chunks } = worldData;
this.options.chunkSize = chunk_size;
this.options.dimension = dimension;
this.options.maxHeight = max_height;
this.options.subChunks = sub_chunks;
};
tick = () => {
this.checkCamChunk();
this.requestChunks();
this.meshChunks();
this.animateSky();
};
getChunkByCPos = (cCoords: Coords2) => {
return this.getChunkByName(Helper.getChunkName(cCoords));
};
getChunkByName = (chunkName: string) => {
return this.chunks.get(chunkName);
};
getChunkByVoxel = (vCoords: Coords3) => {
const { chunkSize } = this.options;
const chunkCoords = Helper.mapVoxelPosToChunkPos(vCoords, chunkSize);
return this.getChunkByCPos(chunkCoords);
};
getNeighborChunksByVoxel = (vCoords: Coords3, padding = 0) => {
const { chunkSize } = this.options;
const chunk = this.getChunkByVoxel(vCoords);
const [cx, cz] = Helper.mapVoxelPosToChunkPos(vCoords, chunkSize);
const [lx, , lz] = Helper.mapVoxelPosToChunkLocalPos(vCoords, chunkSize);
const neighborChunks: (Chunk | null)[] = [];
// check if local position is on the edge
// TODO: fix this hacky way of doing so.
const a = lx < padding;
const b = lz < padding;
const c = lx >= chunkSize - padding;
const d = lz >= chunkSize - padding;
// direct neighbors
if (a) neighborChunks.push(this.getChunkByCPos([cx - 1, cz]));
if (b) neighborChunks.push(this.getChunkByCPos([cx, cz - 1]));
if (c) neighborChunks.push(this.getChunkByCPos([cx + 1, cz]));
if (d) neighborChunks.push(this.getChunkByCPos([cx, cz + 1]));
// side-to-side diagonals
if (a && b) neighborChunks.push(this.getChunkByCPos([cx - 1, cz - 1]));
if (a && d) neighborChunks.push(this.getChunkByCPos([cx - 1, cz + 1]));
if (b && c) neighborChunks.push(this.getChunkByCPos([cx + 1, cz - 1]));
if (c && d) neighborChunks.push(this.getChunkByCPos([cx + 1, cz + 1]));
return neighborChunks.filter(Boolean).filter((c) => c !== chunk);
};
getVoxelByVoxel = (vCoords: Coords3) => {
const chunk = this.getChunkByVoxel(vCoords);
return chunk ? chunk.getVoxel(...vCoords) : null;
};
getVoxelByWorld = (wCoords: Coords3) => {
const vCoords = Helper.mapWorldPosToVoxelPos(wCoords, this.options.dimension);
return this.getVoxelByVoxel(vCoords);
};
getSolidityByVoxel = (vCoords: Coords3) => {
const type = this.getVoxelByVoxel(vCoords);
const block = this.engine.registry.getBlock(type);
return (
vCoords[1] < this.options.maxHeight && !block?.isFluid && type !== 0 && !this.blockData.passables.includes(type)
);
};
getFluidityByVoxel = (vCoords: Coords3) => {
const type = this.getVoxelByVoxel(vCoords);
return this.engine.registry.getBlock(type)?.isFluid;
};
getSolidityByWorld = (wCoords: Coords3) => {
const vCoords = Helper.mapWorldPosToVoxelPos(wCoords, this.options.dimension);
return this.getSolidityByVoxel(vCoords);
};
getFluidityByWorld = (wCoords: Coords3) => {
const vCoords = Helper.mapWorldPosToVoxelPos(wCoords, this.options.dimension);
return this.getFluidityByVoxel(vCoords);
};
getRedLight = (vCoords: Coords3) => {
const chunk = this.getChunkByVoxel(vCoords);
return chunk?.getRedLight(...vCoords) || 0;
};
getGreenLight = (vCoords: Coords3) => {
const chunk = this.getChunkByVoxel(vCoords);
return chunk?.getGreenLight(...vCoords) || 0;
};
getBlueLight = (vCoords: Coords3) => {
const chunk = this.getChunkByVoxel(vCoords);
return chunk?.getBlueLight(...vCoords) || 0;
};
getSunlight = (vCoords: Coords3) => {
const chunk = this.getChunkByVoxel(vCoords);
return chunk?.getSunlight(...vCoords);
};
handleServerChunk = (serverChunk: ServerChunkType, prioritized = false) => {
serverChunk.x = serverChunk.x || 0;
serverChunk.z = serverChunk.z || 0;
const { x: cx, z: cz } = serverChunk;
const coords = [cx, cz] as Coords2;
this.requestedChunks.delete(Helper.getChunkName(coords));
if (prioritized) this.meshChunk(serverChunk);
else this.receivedChunks.push(serverChunk);
if (this.receivedChunks.length >= this.engine.config.network.maxServerUpdates) {
this.receivedChunks.shift();
}
};
setChunk = (chunk: Chunk) => {
// TODO: remove chunks that are too far away
return this.chunks.set(chunk.name, chunk);
};
setVoxel = (target: TargetBlock, type: number, sideEffects = true) => {
const { voxel, rotation, yRotation } = target;
const [vx, vy, vz] = voxel;
const currType = this.getVoxelByVoxel(voxel);
if (currType !== 0 && !this.engine.registry.isFluid(currType) && type !== 0) {
return;
}
if (sideEffects) {
this.engine.network.server.sendEvent({
type: 'UPDATE',
updates: [{ vx, vy, vz, type, rotation, yRotation }],
});
}
};
setManyVoxels = (targets: { target: TargetBlock; type: number }[], sideEffects = true) => {
if (!targets.length) return;
if (targets.length > this.options.maxBlockPerFrame) {
// console.warn('Changing more voxels than recommended...');
// TODO: maybe split the whole thing into chunks of updates?
}
if (sideEffects) {
this.engine.network.server.sendEvent({
type: 'UPDATE',
updates: targets.map(
({
target: {
voxel: [vx, vy, vz],
rotation,
yRotation,
},
type,
}) => ({
vx,
vy,
vz,
type,
rotation,
yRotation,
}),
),
});
} else {
this.engine.particles.addBreakParticles(
targets.map(({ target: { voxel } }) => ({ voxel, type: this.engine.world.getVoxelByVoxel(voxel) })),
{ count: targets.length > 3 ? 1 : 6 },
);
targets.slice(0, 3).forEach(({ target: { voxel } }) => {
this.engine.sounds.play(BLOCK_SFX_NAME, { position: voxel });
});
targets.forEach(({ target: { voxel, rotation, yRotation }, type }) => {
this.getChunkByVoxel(voxel)?.setVoxel(voxel[0], voxel[1], voxel[2], type, rotation, yRotation);
});
}
};
breakVoxel = () => {
const voxel = this.engine.player.lookBlock;
if (voxel) {
// TODO: use type.air instead of 0
this.setVoxel({ voxel }, 0);
}
};
placeVoxel = (type: number) => {
const { dimension } = this.options;
const { targetBlock, spectatorMode } = this.engine.player;
if (spectatorMode) {
if (targetBlock) this.setVoxel(targetBlock, type);
} else {
const {
entity: {
body: { aabb },
},
} = this.engine.player;
const blockSize = dimension - 0.05;
if (targetBlock) {
const [tx, ty, tz] = targetBlock.voxel;
const offset = (dimension - blockSize) / 2;
const blockAABB = new AABB([tx + offset, ty + offset, tz + offset], [blockSize, blockSize, blockSize]);
if (!aabb.intersects(blockAABB)) this.setVoxel(targetBlock, type);
}
}
};
updateRenderRadius = (renderRadiuus: number) => {
const { registry } = this.engine;
const { chunkSize, dimension } = this.options;
registry.opaqueChunkMaterial.uniforms.uFogNear.value = renderRadiuus * 0.6 * chunkSize * dimension;
registry.opaqueChunkMaterial.uniforms.uFogFar.value = renderRadiuus * chunkSize * dimension;
this.checkCamChunk();
this.surroundCamChunks();
};
setTime = (time: number, sideEffect = true) => {
this.sky.tracker.time = time % 2400;
// full cycle to sync up the colors
for (let i = 0; i < 2400; i++) {
this.sky.tick(1 / 0.1, true, 0.1);
}
if (sideEffect) {
this.engine.network.server.sendEvent({
type: 'CONFIG',
json: {
time: this.sky.tracker.time,
},
});
}
};
setBlockData = ({ passables }) => {
if (passables && passables.length) this.blockData.passables = passables;
};
sortPendingChunks = () => {
const [cx, cz] = this.camChunkPos;
this.pendingChunks.sort((a, b) => (cx - a[0]) ** 2 + (cz - a[1]) ** 2 - (cx - b[0]) ** 2 - (cz - b[1]) ** 2);
};
reloadChunks = () => {
this.chunks.forEach((chunk) => {
chunk.removeFromScene(false);
chunk.dispose();
});
this.pendingChunks = [];
this.receivedChunks = [];
this.chunks.clear();
this.requestedChunks.clear();
this.surroundCamChunks();
};
handleReconnection = () => {
this.reloadChunks();
};
get chunksLoaded() {
return this.chunks.size;
}
get camChunkPosStr() {
const local = Helper.mapVoxelPosToChunkLocalPos(this.engine.player.voxel, this.options.chunkSize);
return `${local[0]} ${local[1]} ${local[2]} in ${this.camChunkPos[0]} ${this.camChunkPos[1]}`;
}
get chunkMeshes() {
const meshes = [];
this.chunks.forEach((chunk) => {
chunk.meshes.forEach((subMeshes) => {
meshes.push(...subMeshes.filter((e) => !!e));
});
});
return meshes;
}
private checkCamChunk = () => {
const { chunkSize, renderRadius } = this.options;
const pos = this.engine.player.voxel;
const chunkPos = Helper.mapVoxelPosToChunkPos(pos, chunkSize);
const chunkName = Helper.getChunkName(chunkPos);
if (chunkName !== this.camChunkName) {
this.engine.emit('chunk-changed', chunkPos);
this.camChunkName = chunkName;
this.camChunkPos = chunkPos;
this.surroundCamChunks();
}
let supposed = 0;
const [cx, cz] = this.camChunkPos;
for (let x = cx - renderRadius; x <= cx + renderRadius; x++) {
for (let z = cz - renderRadius; z <= cz + renderRadius; z++) {
const dx = x - cx;
const dz = z - cz;
// circle of chunks around camera effect
if (dx * dx + dz * dz > renderRadius * renderRadius) continue;
const chunk = this.getChunkByCPos([x, z]);
if (chunk) {
chunk.addToScene();
}
supposed++;
}
}
if (!this.isReady && supposed <= this.chunks.size) {
this.isReady = true;
this.engine.emit('world-ready');
}
};
private surroundCamChunks = () => {
const { renderRadius, requestRadius, chunkSize } = this.options;
const [cx, cz] = this.camChunkPos;
for (let x = cx - requestRadius; x <= cx + requestRadius; x++) {
for (let z = cz - requestRadius; z <= cz + requestRadius; z++) {
const dx = x - cx;
const dz = z - cz;
if (dx * dx + dz * dz > requestRadius * requestRadius) continue;
const chunk = this.getChunkByCPos([x, z]);
if (!chunk && !this.requestedChunks.has(Helper.getChunkName([x, z]))) {
this.pendingChunks.push([x, z]);
}
}
}
this.pendingChunks = Array.from(new Set(this.pendingChunks.map((pc) => Helper.getChunkName(pc)))).map(
(pcStr) => Helper.parseChunkName(pcStr) as Coords2,
);
// make pending chunks radiate from player, might have easier ways of doing so
this.sortPendingChunks();
// if the chunk is too far away, remove from scene.
const deleteDistance = renderRadius * chunkSize * 1.414;
const removeDistance = requestRadius * chunkSize * 1.414;
for (const chunk of this.chunks.values()) {
const dist = chunk.distTo(...this.engine.player.voxel);
if (dist > deleteDistance) {
chunk.removeFromScene();
}
if (dist > removeDistance) {
chunk.dispose();
this.chunks.delete(chunk.name);
}
}
};
private requestChunks = () => {
// separate chunk request into frames to avoid clogging
if (this.pendingChunks.length === 0 || !this.engine.connected) return;
// don't clog up the server
const framePendingChunks = this.pendingChunks.splice(0, 2);
framePendingChunks.forEach(([cx, cz]) => {
const rep = Helper.getChunkName([cx, cz]);
if (this.requestedChunks.has(rep)) return;
this.engine.network.server.sendEvent({
type: 'REQUEST',
json: { x: cx, z: cz },
});
this.requestedChunks.add(rep);
});
};
private meshChunks = () => {
// separate chunk meshing into frames to avoid clogging
if (this.receivedChunks.length === 0) return;
const { maxChunkProcessPerFrame } = this.options;
const frameReceivedChunks = this.receivedChunks.splice(0, maxChunkProcessPerFrame);
frameReceivedChunks.forEach(this.meshChunk);
};
private meshChunk = (serverChunk: ServerChunkType) => {
const { x: cx, z: cz } = serverChunk;
const coords = [cx, cz] as Coords2;
let chunk = this.getChunkByCPos(coords);
if (!chunk) {
const { chunkSize, subChunks, dimension, maxHeight } = this.options;
chunk = new Chunk(this.engine, coords, { size: chunkSize, subChunks, dimension, maxHeight });
this.setChunk(chunk);
}
const { meshes, voxels, lights } = serverChunk;
chunk.setupMesh(meshes);
if (voxels.length) chunk.voxels.data = serverChunk.voxels;
if (lights.length) chunk.lights.data = serverChunk.lights;
};
private animateSky = () => {
const { delta } = this.engine.clock;
this.sky.tick(delta);
this.clouds.tick(delta);
};
}
export { World, WorldOptionsType }; | the_stack |
import {printArray} from '../text'
import {assert} from './assert'
import {CtxConfig, Declarator, ExecutionPlan} from './types'
import {isDeclarator} from './isRef'
type ValueCtx = {
value: Record<string, any>
executedIds: string[]
}
type VariantGroupCfg = {
type: 'variantGroup'
name: string
group: VariantCfg[]
}
type VariantCfg = {
type: 'variant'
name: string
acceptableShapes: Record<string, any>[]
}
function normalizeSplitConfig(def: {
variant: Record<string, Record<string, unknown> | Record<string, unknown>[]>
cases: Record<string, Declarator | Record<string, unknown>>
}) {
const {cases, variant: variants} = def
const variantsSeq: VariantGroupCfg[] = Object.entries(variants).map(
([variantGroupName, variantGroup]): VariantGroupCfg => ({
type: 'variantGroup',
name: variantGroupName,
group: Object.entries(variantGroup).map(
([variantName, variant]): VariantCfg => ({
type: 'variant',
name: variantName,
acceptableShapes: Array.isArray(variant) ? variant : [variant],
}),
),
}),
)
variantsSeq.forEach(group => {
if (group.group.every(e => e.name !== '__')) {
group.group.push({
type: 'variant',
name: '__',
acceptableShapes: [{}],
})
}
})
function processSubcase(
path: string[],
caseValue:
| Declarator
| Record<string, Declarator | Record<string, unknown>>,
): Array<{
usedVariantsGroups: VariantGroupCfg[]
matchedVariants: VariantCfg[]
operation: Declarator
}> {
const usedVariantsGroups = variantsSeq.slice(0, path.length)
const isLastVariantGroup = variantsSeq.length <= path.length
const matchedVariants = [...path.entries()].map(([idx, variantName]) => {
const variantGroupSeq = usedVariantsGroups[idx]
const variant = variantGroupSeq.group.find(e => e.name === variantName)
assert(
variant !== undefined,
() => `no variant "${[...path, variantName].join(' | ')}"`,
)
return variant
})
assert(
!isLastVariantGroup || isDeclarator(caseValue),
'deepest case should contain only declarators',
)
/** if current case is plain value then it assumed to be constant */
if (isDeclarator(caseValue))
return [
{
usedVariantsGroups,
matchedVariants,
operation: caseValue,
},
]
if (typeof caseValue === 'object' && caseValue !== null) {
const caseKeys = Object.keys(caseValue)
assert(!Array.isArray(caseValue), 'not implemented')
const validBranchNames = variantsSeq[usedVariantsGroups.length].group.map(
e => e.name,
)
if (caseKeys.every(key => validBranchNames.includes(key))) {
/** if current case contains only valid branch names then it is branch selector */
return caseKeys.flatMap(key =>
processSubcase(
[...path, key],
caseValue[key] as Record<
string,
Declarator | Record<string, unknown>
>,
),
)
} else {
/** otherwise current case is a value */
throw Error('not implemented')
// return [
// {
// usedVariantsGroups,
// matchedVariants,
// operation: {value: caseValue},
// },
// ]
}
} else {
assert(typeof caseValue !== 'function', 'not implemented')
throw Error('not implemented')
// return [
// {
// usedVariantsGroups,
// matchedVariants,
// operation: {value: caseValue},
// },
// ]
}
}
const caseSeq = Object.entries(cases).flatMap(([caseName, caseValue]) =>
processSubcase(
[caseName],
caseValue as
| Declarator
| Record<string, Declarator | Record<string, unknown>>,
),
)
return caseSeq
}
let currCfg: {
cfg: CtxConfig
plan: ExecutionPlan
items: Record<string, Declarator>
namesToIds: Record<string, string>
// executedIds: Set<string>
// pendingIds: Set<string>
}
export function byFields(
plan: ExecutionPlan,
config: CtxConfig,
items: Record<string, Declarator>,
) {
const prevCfg = currCfg
const shapeIds = Object.keys(items)
const namesToIds: Record<string, string> = {}
const idsToNames: Record<string, string> = {}
for (const id of shapeIds) {
const item = items[id]
idsToNames[id] = item.name
namesToIds[item.name] = id
}
currCfg = {
cfg: config,
plan,
items,
namesToIds,
// executedIds: new Set(),
// pendingIds: new Set(),
}
try {
let values: ValueCtx[] = [{value: {}, executedIds: []}]
for (const key in plan.shape) {
const def = plan.shape[key]
values = addFieldToValues(values, key, def)
}
return values
} finally {
currCfg = prevCfg
}
}
function addFieldToValues(values: ValueCtx[], key: string, def: Declarator) {
switch (def.kind) {
case 'union': {
values = permuteField(values, key, {
items: def.variants as readonly any[],
amount: {min: 1, max: 1},
unbox: true,
})
break
}
case 'value': {
values = values.map(
(val): ValueCtx => ({
executedIds: [...val.executedIds, key],
value: {...val.value, [key]: def.value},
}),
)
break
}
case 'permute': {
values = permuteField(values, key, {
items: def.permute.items,
amount: def.permute.amount,
noReorder: def.permute.noReorder,
unbox: false,
})
break
}
case 'bool': {
values = processBranches(values, key, {
variant: {
_: def.bool.true
? {
true: def.bool.true,
false: {},
}
: {
false: def.bool.false!,
true: {},
},
},
cases: {true: def.decls.true, false: def.decls.false},
})
break
}
case 'fn': {
values = values.map(
(val): ValueCtx => ({
executedIds: [...val.executedIds, key],
value: {...val.value, [key]: def.fn(val.value)},
}),
)
break
}
case 'computeVariant': {
values = processBranches(values, key, def)
break
}
case 'flag': {
values = permuteField(values, key, {
items(val) {
if (
def.needs.every(id => !!val[id]) &&
def.avoid.every(id => !val[id])
)
return [false, true]
return [false]
},
amount: {min: 1, max: 1},
unbox: true,
})
break
}
case 'separate': {
values = processBranches(values, key, def)
break
}
}
return values
}
function processBranches(
values: ValueCtx[],
key: string,
def: {
variant: Record<string, Record<string, unknown> | Record<string, unknown>[]>
cases: Record<string, Declarator | Record<string, unknown>>
},
) {
const normalizedSplit = normalizeSplitConfig(def)
return values.flatMap(value => {
for (const item of normalizedSplit) {
const areAccepted = areMatchedVariantsAccepted(
value.value,
item.matchedVariants,
)
if (areAccepted) return addFieldToValues([value], key, item.operation)
}
/** when no declaration is matched return value untouched */
return [value]
})
}
function areMatchedVariantsAccepted(value: any, matchedVariants: VariantCfg[]) {
for (const variantItem of matchedVariants) {
const isAccepted = isOneOfShapesAccepted(
value,
variantItem.acceptableShapes,
)
if (!isAccepted) return false
}
return true
}
function isOneOfShapesAccepted(
value: any,
acceptableShapes: Record<string, any>[],
) {
for (const item of acceptableShapes) {
if (isShapeAccepted(value, item)) return true
}
return false
}
function isShapeAccepted(value: any, acceptableShape: Record<string, any>) {
for (const key in acceptableShape) {
const acceptableValue = acceptableShape[key]
if (!(key in value) || value[key] !== acceptableValue) return false
}
return true
}
function permuteField(
values: ValueCtx[],
field: string,
config: {
items: readonly any[] | ((val: any) => readonly any[])
unbox: boolean
amount?: {min: number; max: number}
ignore?: ((val: any) => boolean) | null
noReorder?: boolean
},
): ValueCtx[] {
const {
items,
amount: {min = 0, max = items.length - 1} = {},
ignore,
unbox,
noReorder = false,
} = config
let results: ValueCtx[]
if (typeof items === 'function') {
results = values.flatMap(value => {
return selectFromNToM(items(value.value), min, max, noReorder).map(
(combination): ValueCtx => ({
executedIds: [...value.executedIds, field],
value: {
...value.value,
[field]: unbox ? combination[0] : combination,
},
}),
)
})
} else {
results = selectFromNToM(items, min, max, noReorder).flatMap(combination =>
values.map(
(val): ValueCtx => ({
executedIds: [...val.executedIds, field],
value: {
...val.value,
[field]: unbox ? combination[0] : combination,
},
}),
),
)
}
if (ignore) return results.filter(ignore)
return results
}
function selectFromNToM<T>(
items: readonly T[],
from: number,
to: number,
noReorder: boolean,
) {
const result = [] as T[][]
const fn = noReorder ? selectNNoReorder : selectN
for (let i = from; i < Math.min(to + 1, items.length + 1); i++) {
result.push(...fn(items, i))
}
return result
}
function selectNNoReorder<T>(items: readonly T[], n: number): T[][] {
if (n > items.length) return [[]]
if (n === 0) return [[]]
if (n === 1) return items.map(item => [item])
const result = []
const subItems = [...items]
for (let i = 0; i < items.length; i++) {
subItems.splice(i, 1)
result.push(
...selectNNoReorder(subItems, n - 1)
.map(nested => [items[i], ...nested])
.filter(
selection => [...new Set(selection)].length === selection.length,
),
)
}
return result
}
function selectN<T>(items: readonly T[], n: number): T[][] {
if (n === 0) return [[]]
if (n === 1) return items.map(item => [item])
const result = []
for (let i = 0; i < items.length; i++) {
const subItems = [...items]
subItems.splice(i, 1)
result.push(
...selectN(subItems, n - 1).map(nested => [items[i], ...nested]),
)
}
return result
} | the_stack |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See the LICENSE file in the project root for full license information.
*/
class SizedStructInfo
{
constructor(
public startPos: number,
public size: number
) {}
};
export interface TpmMarshaller
{
/** Convert this object to its TPM representation and store it in the given marshalng buffer
* @param buf Output marshaling buffer
*/
toTpm(buf: TpmBuffer) : void;
/** Populate this object from the TPM representation in the given marshaling buffer
* @param buf Input marshaling buffer
*/
initFromTpm(buf: TpmBuffer) : void;
} // interface TpmMarshaller
export class TpmBuffer
{
protected buf: Buffer = null;
protected pos: number = 0;
protected outOfBounds: boolean = false;
private sizedStructSizes: Array<SizedStructInfo> = null;
/** Constructs output (default) or input marshaling buffer depending on the parameter.
* @param capacityOrSrcBuf For output marshling buffer this is the buffer's capacity
* (i.e. the maximum allowed total size of the marshaled data).
* For input marshling buffer this is an existing TpmBuffer or any kind of
* a byte buffer or array that can be used to construct a Buffer object.
*/
constructor(capacityOrSrcBuf: TpmBuffer | any = 4096)
{
if (capacityOrSrcBuf instanceof TpmBuffer)
{
this.buf = new Buffer(capacityOrSrcBuf.buf);
this.pos = capacityOrSrcBuf.pos;
}
else
{
if (capacityOrSrcBuf === undefined)
capacityOrSrcBuf = 4096
this.buf = new Buffer(capacityOrSrcBuf);
}
this.sizedStructSizes = new Array<SizedStructInfo>();
}
/** @return Reference to the backing byte buffer */
get buffer(): Buffer { return this.buf; }
/** @return Size of the backing byte buffer.
* Note that during marshaling this size normally exceeds the amount of actually
* stored data until trim() is invoked.
*/
get size(): number { return this.buf.length; }
/** @return Current read/write position in the the backing byte buffer. */
get curPos(): number { return this.pos; }
/** Sets the current read/write position in the the backing byte buffer. */
set curPos(newPos: number)
{
this.pos = newPos;
this.outOfBounds = this.size < newPos;
}
/** @return True unless a previous read/write operation caused under/overflow correspondingly. */
public isOk(): boolean { return !this.outOfBounds; }
/** Shrinks the backing byte buffer so that it ends at the current position
* @return Reference to the shrunk backing byte buffer
*/
public trim() : Buffer
{
// New buffer references the same memory
return this.buf = this.buf.slice(0, this.pos)
}
public getCurStuctRemainingSize() : number
{
let ssi: SizedStructInfo = this.sizedStructSizes[this.sizedStructSizes.length - 1];
return ssi.size - (this.pos - ssi.startPos);
}
protected checkLen(len: number): boolean
{
if (this.size < this.pos + len)
{
this.outOfBounds = true;
return false;
}
return true;
}
protected writeNum(val: number, len: number) : void
{
if (!this.checkLen(len))
return;
if (len == 8) {
this.buf[this.pos++] = (val >> 56) & 0x00FF;
this.buf[this.pos++] = (val >> 48) & 0x00FF;
this.buf[this.pos++] = (val >> 40) & 0x00FF;
this.buf[this.pos++] = (val >> 32) & 0x00FF;
}
if (len >= 4) {
this.buf[this.pos++] = (val >> 24) & 0x00FF;
this.buf[this.pos++] = (val >> 16) & 0x00FF;
}
if (len >= 2)
this.buf[this.pos++] = (val >> 8) & 0x00FF;
this.buf[this.pos++] = val & 0x00FF;
}
protected readNum(len: number) : number
{
if (!this.checkLen(len))
return 0;
let res : number = 0;
if (len == 8) {
res += (this.buf[this.pos++] << 56);
res += (this.buf[this.pos++] << 48);
res += (this.buf[this.pos++] << 40);
res += (this.buf[this.pos++] << 32);
}
if (len >= 4) {
res += (this.buf[this.pos++] << 24);
res += (this.buf[this.pos++] << 16);
}
if (len >= 2)
res += (this.buf[this.pos++] << 8);
res += this.buf[this.pos++];
return res;
}
public writeNumAtPos(val: number, pos: number, len: number = 4) : void
{
let curPos = this.pos;
this.pos = pos;
this.writeNum(val, len);
this.pos = curPos;
}
/** Writes the given 8-bit integer to this buffer
* @param val 8-bit integer value to marshal
*/
public writeByte(val: number) : void
{
if (this.checkLen(1))
this.buf[this.pos++] = val & 0x00FF;
}
/** Marshals the given 16-bit integer to this buffer.
* @param val 16-bit integer value to marshal
*/
public writeShort(val: number) : void
{
this.writeNum(val, 2);
}
/** Marshals the given 32-bit integer to this buffer.
* @param val 32-bit integer value to marshal
*/
public writeInt(val: number) : void
{
this.writeNum(val, 4);
}
/** Marshals the given 64-bit integer to this buffer.
* @param val 64-bit integer value to marshal
*/
public writeInt64(val: number) : void
{
this.writeNum(val, 8);
}
/** Reads a byte from this buffer.
* @return The byte read
*/
public readByte() : number
{
if (this.checkLen(1))
return this.buf[this.pos++];
}
/** Unmarshals a 16-bit integer from this buffer.
* @return Unmarshaled 16-bit integer
*/
public readShort() : number
{
return this.readNum(2);
}
/** Unmarshals a 32-bit integer from this buffer.
* @return Unmarshaled 32-bit integer
*/
public readInt() : number
{
return this.readNum(4);
}
/** Unmarshals a 64-bit integer from this buffer.
* @return Unmarshaled 64-bit integer
*/
public readInt64() : number
{
return this.readNum(8);
}
/** Marshalls the given byte buffer with no length prefix.
* @param data Byte buffer to marshal
*/
public writeByteBuf(data: Buffer) : void
{
let dataSize = data != null ? data.length : 0;
if (dataSize == 0 || !this.checkLen(dataSize))
return;
data.copy(this.buf, this.pos);
this.pos += dataSize;
}
/** Unmarshalls a byte buffer of the given size (no marshaled length prefix).
* @param size Size of the byte buffer to unmarshal
* @return Unmarshaled byte buffer
*/
public readByteBuf(size: number) : Buffer
{
if (!this.checkLen(size))
return null;
let newBuf = new Buffer(size);
this.buf.copy(newBuf, 0, this.pos, this.pos + size);
this.pos += size;
return newBuf;
}
/** Marshalls the given byte buffer with a length prefix.
* @param data Byte buffer to marshal
* @param sizeLen Length of the size prefix in bytes
*/
public writeSizedByteBuf(data: Buffer, sizeLen: number = 2) : void
{
this.writeNum(data != null ? data.length : 0, sizeLen);
this.writeByteBuf(data);
}
/** Unmarshals a byte buffer from its size-prefixed representation in the TPM wire format.
* @param sizeLen Length of the size prefix in bytes
* @return Unmarshaled byte buffer
*/
public readSizedByteBuf(sizeLen: number = 2) : Buffer
{
return this.readByteBuf(this.readNum(sizeLen));
}
public createObj<T extends TpmMarshaller>(type: {new(): T}): T
{
let newObj = new type();
newObj.initFromTpm(this);
return newObj;
}
public writeSizedObj<T extends TpmMarshaller>(obj: T) : void
{
const lenSize = 2; // Length of the object size is always 2 bytes
if (obj == null)
return this.writeShort(0);
if (!this.checkLen(lenSize))
return;
// Remember position to marshal the size of the data structure
let sizePos = this.pos;
// Account for the reserved size area
this.pos += lenSize;
// Marshal the object
obj.toTpm(this);
// Calc marshaled object len
let objSize = this.pos - (sizePos + lenSize);
// Marshal it in the appropriate position
this.writeNumAtPos(objSize, sizePos, lenSize);
}
public createSizedObj<T extends TpmMarshaller>(type: {new(): T}) : T
{
const lenSize = 2; // Length of the object size is always 2 bytes
let size = this.readShort();
if (size == 0)
return null;
this.sizedStructSizes.push(new SizedStructInfo(this.pos, size));
let newObj = this.createObj(type);
this.sizedStructSizes.pop();
return newObj;
}
public writeObjArr(arr: TpmMarshaller[]) : void
{
// Length of the array size is always 4 bytes
if (arr == null)
return this.writeInt(0);
this.writeInt(arr.length);
for (let elt of arr)
{
if (!this.isOk())
break;
elt.toTpm(this);
}
}
public readObjArr<T extends TpmMarshaller>(type: {new(): T}) : T[]
{
// Length of the array size is always 4 bytes
let len = this.readInt();
if (len == 0)
return [];
let newArr = new Array<T>(len);
for (let i = 0; i < len; ++i)
{
if (!this.isOk())
break;
newArr[i] = new type();
newArr[i].initFromTpm(this);
}
return newArr;
}
public writeValArr(arr: number[], valSize: number) : void
{
// Length of the array size is always 4 bytes
if (arr == null)
return this.writeInt(0);
this.writeInt(arr.length);
for (let val of arr)
{
if (!this.isOk())
break;
this.writeNum(val, valSize);
}
}
public readValArr<T extends number>(valSize: number): T[]
{
// Length of the array size is always 4 bytes
let len = this.readInt();
if (len == 0)
return [];
let newArr = new Array<T>(len);
for (let i = 0; i < len; ++i)
{
if (!this.isOk())
break;
newArr[i] = <T>this.readNum(valSize);
}
return newArr;
}
}; // class TpmBuffer | the_stack |
import { Session, TerminalAPI } from '@jupyterlab/services';
import {
test as base,
Page,
PlaywrightTestArgs,
PlaywrightTestOptions,
PlaywrightWorkerArgs,
PlaywrightWorkerOptions,
TestType
} from '@playwright/test';
import { ContentsHelper } from './contents';
import { galata } from './galata';
import { IJupyterLabPage, IJupyterLabPageFixture } from './jupyterlabpage';
/**
* Galata test arguments
*/
export interface IGalataTestArgs extends PlaywrightTestArgs {
/**
* JupyterLab test page.
*
* It brings the following feature on top of Playwright Page object:
* - Goto to JupyterLab URL and wait for the application to be ready
* - Helpers for JupyterLab
* - Settings mock-up
* - State mock-up
* - Track sessions and terminals opened during a test to close them at the end
*
* Note: If autoGoto is true, the filebrowser will be set inside tmpPath.
* Nothing is preventing you to navigate to some other folders.
* So you must avoid creating files outside that directory to avoid
* coupling effects between tests.
*
*/
page: IJupyterLabPageFixture;
}
/**
* Galata test configuration
*/
export type GalataOptions = {
/**
* Application URL path fragment.
*
* Default: /lab
*/
appPath: string;
/**
* Whether to go to JupyterLab page within the fixture or not.
*
* Default: true
*/
autoGoto: boolean;
/**
* Galata can keep the uploaded and created files in ``tmpPath`` on
* the server root for debugging purpose. By default the files are
* always deleted
*
* - 'off' - ``tmpPath`` is deleted after each tests
* - 'on' - ``tmpPath`` is never deleted
* - 'only-on-failure' - ``tmpPath`` is deleted except if a test failed or timed out.
*/
serverFiles: 'on' | 'off' | 'only-on-failure';
/**
* Mock JupyterLab state in-memory or not.
*
* Possible values are:
* - true (default): JupyterLab state will be mocked on a per test basis
* - false: JupyterLab state won't be mocked (Be careful it will write state in local files)
* - Record<string, unknown>: Initial JupyterLab data state - Mapping (state key, value).
*
* By default the state is stored in-memory.
*/
mockState: boolean | Record<string, unknown>;
/**
* Mock JupyterLab settings in-memory or not.
*
* Possible values are:
* - true: JupyterLab settings will be mocked on a per test basis
* - false: JupyterLab settings won't be mocked (Be careful it will read & write settings local files)
* - Record<string, unknown>: Mapping {pluginId: settings} that will be default user settings
*
* The default value is `galata.DEFAULT_SETTINGS`
*
* By default the settings are stored in-memory. However the
* they are still initialized with the hard drive values.
*/
mockSettings: boolean | Record<string, unknown>;
/**
* Sessions created during the test.
*
* Possible values are:
* - null: The sessions API won't be mocked
* - Map<string, Session.IModel>: The sessions created during a test.
*
* By default the sessions created during a test will be tracked and disposed at the end.
*/
sessions: Map<string, Session.IModel> | null;
/**
* Terminals created during the test.
*
* Possible values are:
* - null: The Terminals API won't be mocked
* - Map<string, TerminalsAPI.IModel>: The Terminals created during a test.
*
* By default the Terminals created during a test will be tracked and disposed at the end.
*/
terminals: Map<string, TerminalAPI.IModel> | null;
/**
* Unique test temporary path created on the server.
*
* Note: if you override this string, you will need to take care of creating the
* folder and cleaning it.
*/
tmpPath: string;
/**
* Wait for the application page to be ready
*
* @param page Playwright Page model
* @param helpers JupyterLab helpers
*/
waitForApplication: (page: Page, helpers: IJupyterLabPage) => Promise<void>;
};
/**
* JupyterLab customized test.
*/
// @ts-ignore
export const test: TestType<
IGalataTestArgs & GalataOptions & PlaywrightTestOptions,
PlaywrightWorkerArgs & PlaywrightWorkerOptions
> = base.extend<GalataOptions>({
/**
* `baseURL` used for all pages in the test. Takes priority over `contextOptions`.
* @see BrowserContextOptions
*
* It can also be set with `TARGET_URL` environment variable and default to `http://localhost:8888`.
*/
baseURL: async ({ baseURL }, use) => {
await use(baseURL ?? process.env.TARGET_URL ?? 'http://localhost:8888');
},
/**
* Application URL path fragment.
*
* Default: /lab
*/
appPath: '/lab',
/**
* Whether to go to JupyterLab page within the fixture or not.
*
* Default: true.
*
* Note: Setting it to false allows to register new route mock-ups for example.
*/
autoGoto: true,
/**
* Mock JupyterLab state in-memory or not.
*
* Possible values are:
* - true (default): JupyterLab state will be mocked on a per test basis
* - false: JupyterLab state won't be mocked (Be careful it will write state in local files)
* - Record<string, unknown>: Initial JupyterLab data state - Mapping (state key, value).
*
* By default the state is stored in-memory
*/
mockState: true,
/**
* Mock JupyterLab settings in-memory or not.
*
* Possible values are:
* - true: JupyterLab settings will be mocked on a per test basis
* - false: JupyterLab settings won't be mocked (Be careful it may write settings local files)
* - Record<string, unknown>: Mapping {pluginId: settings} that will be default user settings
*
* The default value is `galata.DEFAULT_SETTINGS`
*
* By default the settings are stored in-memory. However the
* they are still initialized with the hard drive values.
*/
mockSettings: galata.DEFAULT_SETTINGS,
/**
* Galata can keep the uploaded and created files in ``tmpPath`` on
* the server root for debugging purpose. By default the files are
* always deleted.
*
* - 'off' - ``tmpPath`` is deleted after each tests
* - 'on' - ``tmpPath`` is never deleted
* - 'only-on-failure' - ``tmpPath`` is deleted except if a test failed or timed out.
*/
serverFiles: 'off',
/**
* Sessions created during the test.
*
* Possible values are:
* - null: The sessions API won't be mocked
* - Map<string, Session.IModel>: The sessions created during a test.
*
* By default the sessions created during a test will be tracked and disposed at the end.
*/
sessions: async ({ baseURL }, use) => {
const sessions = new Map<string, Session.IModel>();
await use(sessions);
if (sessions.size > 0) {
await galata.Mock.clearRunners(
baseURL!,
[...sessions.keys()],
'sessions'
);
}
},
/**
* Terminals created during the test.
*
* Possible values are:
* - null: The Terminals API won't be mocked
* - Map<string, TerminalsAPI.IModel>: The Terminals created during a test.
*
* By default the Terminals created during a test will be tracked and disposed at the end.
*/
terminals: async ({ baseURL }, use) => {
const terminals = new Map<string, TerminalAPI.IModel>();
await use(terminals);
if (terminals.size > 0) {
await galata.Mock.clearRunners(
baseURL!,
[...terminals.keys()],
'terminals'
);
}
},
/**
* Unique test temporary path created on the server.
*
* Note: if you override this string, you will need to take care of creating the
* folder and cleaning it.
*/
tmpPath: async ({ baseURL, serverFiles }, use, testInfo) => {
const parts = testInfo.outputDir.split('/');
// Remove appended retry part for reproducibility
const testFolder = parts[parts.length - 1].replace(/-retry\d+$/i, '');
const contents = new ContentsHelper(baseURL!);
if (await contents.directoryExists(testFolder)) {
await contents.deleteDirectory(testFolder);
}
// Create the test folder on the server
await contents.createDirectory(testFolder);
await use(testFolder);
// Delete the test folder on the server
// If serverFiles is 'on' or 'only-on-failure', keep the server files for the test
if (
serverFiles === 'off' ||
(serverFiles === 'only-on-failure' &&
(testInfo.status === 'passed' || testInfo.status === 'skipped'))
) {
await contents.deleteDirectory(testFolder);
}
},
/**
* Wait for the application page to be ready
*
* @param page Playwright Page model
* @param helpers JupyterLab helpers
*/
waitForApplication: async ({ baseURL }, use, testInfo) => {
const waitIsReady = async (
page: Page,
helpers: IJupyterLabPage
): Promise<void> => {
await page.waitForSelector('#jupyterlab-splash', {
state: 'detached'
});
await helpers.waitForCondition(() => {
return helpers.activity.isTabActive('Launcher');
});
// Oddly current tab is not always set to active
if (!(await helpers.isInSimpleMode())) {
await helpers.activity.activateTab('Launcher');
}
};
await use(waitIsReady);
},
/**
* JupyterLab test page.
*
* It brings the following feature on top of Playwright Page object:
* - Goto to JupyterLab URL and wait for the application to be ready (autoGoto == true)
* - Helpers for JupyterLab
* - Settings mock-up
* - State mock-up
* - Track sessions and terminals opened during a test to close them at the end
*
* Note: If autoGoto is true, the filebrowser will be set inside tmpPath.
* Nothing is preventing you to navigate to some other folders.
* So you must avoid creating files outside that directory to avoid
* coupling effects between tests.
*/
// @ts-ignore
page: async (
{
appPath,
autoGoto,
baseURL,
mockSettings,
mockState,
page,
sessions,
terminals,
tmpPath,
waitForApplication
},
use
) => {
await use(
await galata.initTestPage(
appPath,
autoGoto,
baseURL!,
mockSettings,
mockState,
page,
sessions,
terminals,
tmpPath,
waitForApplication
)
);
}
}); | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type OrderInformation_Test_QueryVariables = {};
export type OrderInformation_Test_QueryResponse = {
readonly me: {
readonly conversation: {
readonly orderConnection: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly " $fragmentRefs": FragmentRefs<"OrderInformation_order">;
} | null;
} | null> | null;
} | null;
} | null;
} | null;
readonly artwork: {
readonly " $fragmentRefs": FragmentRefs<"OrderInformation_artwork">;
} | null;
};
export type OrderInformation_Test_Query = {
readonly response: OrderInformation_Test_QueryResponse;
readonly variables: OrderInformation_Test_QueryVariables;
};
/*
query OrderInformation_Test_Query {
me {
conversation(id: "test-id") {
orderConnection(first: 10) {
edges {
node {
__typename
...OrderInformation_order
id
}
}
}
id
}
id
}
artwork(id: "test-artwork") {
...OrderInformation_artwork
id
}
}
fragment OrderInformation_artwork on Artwork {
listPrice {
__typename
... on Money {
display
}
... on PriceRange {
display
}
}
}
fragment OrderInformation_order on CommerceOrder {
__isCommerceOrder: __typename
code
shippingTotal(precision: 2)
taxTotal(precision: 2)
buyerTotal(precision: 2)
... on CommerceOfferOrder {
lastOffer {
amount(precision: 2)
fromParticipant
id
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "Literal",
"name": "id",
"value": "test-id"
}
],
v1 = [
{
"kind": "Literal",
"name": "first",
"value": 10
}
],
v2 = [
{
"kind": "Literal",
"name": "id",
"value": "test-artwork"
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v4 = [
{
"kind": "Literal",
"name": "precision",
"value": 2
}
],
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v6 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
];
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "OrderInformation_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "OrderInformation_order"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "orderConnection(first:10)"
}
],
"storageKey": "conversation(id:\"test-id\")"
}
],
"storageKey": null
},
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "OrderInformation_artwork"
}
],
"storageKey": "artwork(id:\"test-artwork\")"
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "OrderInformation_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "TypeDiscriminator",
"abstractKey": "__isCommerceOrder"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "code",
"storageKey": null
},
{
"alias": null,
"args": (v4/*: any*/),
"kind": "ScalarField",
"name": "shippingTotal",
"storageKey": "shippingTotal(precision:2)"
},
{
"alias": null,
"args": (v4/*: any*/),
"kind": "ScalarField",
"name": "taxTotal",
"storageKey": "taxTotal(precision:2)"
},
{
"alias": null,
"args": (v4/*: any*/),
"kind": "ScalarField",
"name": "buyerTotal",
"storageKey": "buyerTotal(precision:2)"
},
(v5/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOffer",
"kind": "LinkedField",
"name": "lastOffer",
"plural": false,
"selections": [
{
"alias": null,
"args": (v4/*: any*/),
"kind": "ScalarField",
"name": "amount",
"storageKey": "amount(precision:2)"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "fromParticipant",
"storageKey": null
},
(v5/*: any*/)
],
"storageKey": null
}
],
"type": "CommerceOfferOrder",
"abstractKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "orderConnection(first:10)"
},
(v5/*: any*/)
],
"storageKey": "conversation(id:\"test-id\")"
},
(v5/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "listPrice",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "InlineFragment",
"selections": (v6/*: any*/),
"type": "Money",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v6/*: any*/),
"type": "PriceRange",
"abstractKey": null
}
],
"storageKey": null
},
(v5/*: any*/)
],
"storageKey": "artwork(id:\"test-artwork\")"
}
]
},
"params": {
"id": "515409a62cdec6b734da0a804d4f5bfb",
"metadata": {},
"name": "OrderInformation_Test_Query",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '67bab0803414abfe42ae648a0f97ef51';
export default node; | the_stack |
import { Prerequisite, DetectionSteps, DetectionResultResponse } from '../model/AutoDetectionData'
import { Property } from '../model/Property'
export const GET_AUTO_DETECTION_PREREQUISITE_REQUEST = 'AUTO_DETECTION/GET_AUTO_DETECTION_PREREQUISITE_REQUEST'
export const GET_AUTO_DETECTION_PREREQUISITE_SUCCESS = 'AUTO_DETECTION/GET_AUTO_DETECTION_PREREQUISITE_SUCCESS'
export const GET_AUTO_DETECTION_PREREQUISITE_FAILURE = 'AUTO_DETECTION/GET_AUTO_DETECTION_PREREQUISITE_FAILURE'
export const GET_AUTO_DETECTION_STEPS_REQUEST = 'AUTO_DETECTION/GET_AUTO_DETECTION_STEPS_REQUEST'
export const GET_AUTO_DETECTION_STEPS_SUCCESS = 'AUTO_DETECTION/GET_AUTO_DETECTION_STEPS_SUCCESS'
export const GET_AUTO_DETECTION_STEPS_FAILURE = 'AUTO_DETECTION/GET_AUTO_DETECTION_STEPS_FAILURE'
export const UPDATE_AUTO_DETECTION_STEPS_REQUEST = 'AUTO_DETECTION/UPDATE_AUTO_DETECTION_STEPS_REQUEST'
export const UPDATE_AUTO_DETECTION_STEPS_SUCCESS = 'AUTO_DETECTION/UPDATE_AUTO_DETECTION_STEPS_SUCCESS'
export const UPDATE_AUTO_DETECTION_STEPS_FAILURE = 'AUTO_DETECTION/UPDATE_AUTO_DETECTION_STEPS_FAILURE'
export const START_AUTO_DETECTION_REQUEST = 'AUTO_DETECTION/START_AUTO_DETECTION_REQUEST'
export const START_AUTO_DETECTION_SUCCESS = 'AUTO_DETECTION/START_AUTO_DETECTION_SUCCESS'
export const START_AUTO_DETECTION_FAILURE = 'AUTO_DETECTION/START_AUTO_DETECTION_FAILURE'
export const STOP_AUTO_DETECTION_REQUEST = 'AUTO_DETECTION/STOP_AUTO_DETECTION_REQUEST'
export const STOP_AUTO_DETECTION_SUCCESS = 'AUTO_DETECTION/STOP_AUTO_DETECTION_SUCCESS'
export const STOP_AUTO_DETECTION_FAILURE = 'AUTO_DETECTION/STOP_AUTO_DETECTION_FAILURE'
export const APPLY_AUTO_DETECTION_RESULT_REQUEST = 'AUTO_DETECTION/APPLY_AUTO_DETECTION_RESULT_REQUEST'
export const APPLY_AUTO_DETECTION_RESULT_SUCCESS = 'AUTO_DETECTION/APPLY_AUTO_DETECTION_RESULT_SUCCESS'
export const APPLY_AUTO_DETECTION_RESULT_FAILURE = 'AUTO_DETECTION/APPLY_AUTO_DETECTION_RESULT_FAILURE'
export const UPDATE_AUTO_DETECTION_PREREQUISITE = 'AUTO_DETECTION/UPDATE_AUTO_DETECTION_PREREQUISITE'
export const GET_AUTO_DETECTION_LOG_REQUEST = 'AUTO_DETECTION/GET_AUTO_DETECTION_LOG_REQUEST'
export const GET_AUTO_DETECTION_LOG_SUCCESS = 'AUTO_DETECTION/GET_AUTO_DETECTION_LOG_SUCCESS'
export const GET_AUTO_DETECTION_LOG_FAILURE = 'AUTO_DETECTION/GET_AUTO_DETECTION_LOG_FAILURE'
export const SET_AUTO_DETECTION_LOG = 'AUTO_DETECTION/SET_AUTO_DETECTION_LOG'
// define action types
interface GetAutoDetectionPrerequisiteActionRequestType { type: typeof GET_AUTO_DETECTION_PREREQUISITE_REQUEST }
interface GetAutoDetectionPrerequisiteActionSuccessType { type: typeof GET_AUTO_DETECTION_PREREQUISITE_SUCCESS, payload: Prerequisite }
interface GetAutoDetectionPrerequisiteActionFailureType { type: typeof GET_AUTO_DETECTION_PREREQUISITE_FAILURE, errorMsg: string }
interface GetAutoDetectionStepsActionRequestType { type: typeof GET_AUTO_DETECTION_STEPS_REQUEST }
interface GetAutoDetectionStepsActionSuccessType { type: typeof GET_AUTO_DETECTION_STEPS_SUCCESS, payload: DetectionSteps }
interface GetAutoDetectionStepsActionFailureType { type: typeof GET_AUTO_DETECTION_STEPS_FAILURE, errorMsg: string }
interface UpdateAutoDetectionStepsActionRequestType { type: typeof UPDATE_AUTO_DETECTION_STEPS_REQUEST }
interface UpdateAutoDetectionStepsActionSuccessType { type: typeof UPDATE_AUTO_DETECTION_STEPS_SUCCESS, payload: DetectionSteps }
interface UpdateAutoDetectionStepsActionFailureType { type: typeof UPDATE_AUTO_DETECTION_STEPS_FAILURE, errorMsg: string }
interface StartAutoDetectionActionRequestType { type: typeof START_AUTO_DETECTION_REQUEST }
interface StartAutoDetectionActionSuccessType { type: typeof START_AUTO_DETECTION_SUCCESS }
interface StartAutoDetectionActionFailureType { type: typeof START_AUTO_DETECTION_FAILURE, errorMsg: string }
interface StopAutoDetectionActionRequestType { type: typeof STOP_AUTO_DETECTION_REQUEST }
interface StopAutoDetectionActionSuccessType { type: typeof STOP_AUTO_DETECTION_SUCCESS }
interface StopAutoDetectionActionFailureType { type: typeof STOP_AUTO_DETECTION_FAILURE, errorMsg: string }
interface ApplyAutoDetectionResultActionRequestType { type: typeof APPLY_AUTO_DETECTION_RESULT_REQUEST }
interface ApplyAutoDetectionResultActionSuccessType { type: typeof APPLY_AUTO_DETECTION_RESULT_SUCCESS }
interface ApplyAutoDetectionResultActionFailureType { type: typeof APPLY_AUTO_DETECTION_RESULT_FAILURE, errorMsg: string }
interface UpdateAutoDetectionPrerequisiteActionType { type: typeof UPDATE_AUTO_DETECTION_PREREQUISITE, payload: Property };
interface GetAutoDetectionLogActionRequestType { type: typeof GET_AUTO_DETECTION_LOG_REQUEST };
interface GetAutoDetectionLogActionSuccessType { type: typeof GET_AUTO_DETECTION_LOG_SUCCESS, payload: Blob };
interface GetAutoDetectionLogActionFailureType { type: typeof GET_AUTO_DETECTION_LOG_FAILURE, errorMsg: string };
interface SetAutoDetectionLogActionType { type: typeof SET_AUTO_DETECTION_LOG, payload: string }
export type TestSuiteAutoDetectionActionTypes = GetAutoDetectionPrerequisiteActionRequestType
| GetAutoDetectionPrerequisiteActionSuccessType
| GetAutoDetectionPrerequisiteActionFailureType
| GetAutoDetectionStepsActionRequestType
| GetAutoDetectionStepsActionSuccessType
| GetAutoDetectionStepsActionFailureType
| UpdateAutoDetectionStepsActionRequestType
| UpdateAutoDetectionStepsActionSuccessType
| UpdateAutoDetectionStepsActionFailureType
| StartAutoDetectionActionRequestType
| StartAutoDetectionActionSuccessType
| StartAutoDetectionActionFailureType
| StopAutoDetectionActionRequestType
| StopAutoDetectionActionSuccessType
| StopAutoDetectionActionFailureType
| ApplyAutoDetectionResultActionRequestType
| ApplyAutoDetectionResultActionSuccessType
| ApplyAutoDetectionResultActionFailureType
| UpdateAutoDetectionPrerequisiteActionType
| GetAutoDetectionLogActionRequestType
| GetAutoDetectionLogActionSuccessType
| GetAutoDetectionLogActionFailureType
| SetAutoDetectionLogActionType
// define actions
export const AutoDetectionActions = {
getAutoDetectionPrerequisiteAction_Request: (): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_PREREQUISITE_REQUEST
}
},
getAutoDetectionPrerequisiteAction_Success: (data: Prerequisite): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_PREREQUISITE_SUCCESS,
payload: data
}
},
getAutoDetectionPrerequisiteAction_Failure: (error: string): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_PREREQUISITE_FAILURE,
errorMsg: error
}
},
getAutoDetectionStepsAction_Request: (): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_STEPS_REQUEST
}
},
getAutoDetectionStepsAction_Success: (data: DetectionResultResponse): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_STEPS_SUCCESS,
payload: {
...{} as DetectionSteps,
DetectingItems: data.DetectionSteps.map(e => { return { Name: e.DetectingContent, Status: e.DetectingStatus } }),
Result: data.Result
}
}
},
getAutoDetectionStepsAction_Failure: (error: string): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_STEPS_FAILURE,
errorMsg: error
}
},
updateAutoDetectionStepsAction_Request: (): TestSuiteAutoDetectionActionTypes => {
return {
type: UPDATE_AUTO_DETECTION_STEPS_REQUEST
}
},
updateAutoDetectionStepsAction_Success: (data: DetectionResultResponse): TestSuiteAutoDetectionActionTypes => {
return {
type: UPDATE_AUTO_DETECTION_STEPS_SUCCESS,
payload: {
...{} as DetectionSteps,
DetectingItems: data.DetectionSteps.map(e => { return { Name: e.DetectingContent, Status: e.DetectingStatus } }),
Result: data.Result
}
}
},
updateAutoDetectionStepsAction_Failure: (error: string): TestSuiteAutoDetectionActionTypes => {
return {
type: UPDATE_AUTO_DETECTION_STEPS_FAILURE,
errorMsg: error
}
},
startAutoDetectionAction_Request: (): TestSuiteAutoDetectionActionTypes => {
return {
type: START_AUTO_DETECTION_REQUEST
}
},
startAutoDetectionAction_Success: (): TestSuiteAutoDetectionActionTypes => {
return {
type: START_AUTO_DETECTION_SUCCESS
}
},
startAutoDetectionAction_Failure: (error: string): TestSuiteAutoDetectionActionTypes => {
return {
type: START_AUTO_DETECTION_FAILURE,
errorMsg: error
}
},
stopAutoDetectionAction_Request: (): TestSuiteAutoDetectionActionTypes => {
return {
type: STOP_AUTO_DETECTION_REQUEST
}
},
stopAutoDetectionAction_Success: (): TestSuiteAutoDetectionActionTypes => {
return {
type: STOP_AUTO_DETECTION_SUCCESS
}
},
stopAutoDetectionAction_Failure: (error: string): TestSuiteAutoDetectionActionTypes => {
return {
type: STOP_AUTO_DETECTION_FAILURE,
errorMsg: error
}
},
updateAutoDetectionPrerequisiteAction: (property: Property): TestSuiteAutoDetectionActionTypes => {
return {
type: UPDATE_AUTO_DETECTION_PREREQUISITE,
payload: property
}
},
getAutoDetectionLogAction_Request: (): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_LOG_REQUEST,
}
},
getAutoDetectionLogAction_Success: (log: Blob): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_LOG_SUCCESS,
payload: log
}
},
getAutoDetectionLogAction_Failure: (error: string): TestSuiteAutoDetectionActionTypes => {
return {
type: GET_AUTO_DETECTION_LOG_FAILURE,
errorMsg: error
}
},
setAutoDetectionLogAction: (log: string): TestSuiteAutoDetectionActionTypes => {
return {
type: SET_AUTO_DETECTION_LOG,
payload: log
}
},
applyAutoDetectionResultAction_Request: (): TestSuiteAutoDetectionActionTypes => {
return {
type: APPLY_AUTO_DETECTION_RESULT_REQUEST
}
},
applyAutoDetectionResultAction_Success: (): TestSuiteAutoDetectionActionTypes => {
return {
type: APPLY_AUTO_DETECTION_RESULT_SUCCESS
}
},
applyAutoDetectionResultAction_Failure: (error: string): TestSuiteAutoDetectionActionTypes => {
return {
type: APPLY_AUTO_DETECTION_RESULT_FAILURE,
errorMsg: error
}
}
} | the_stack |
import { Injectable, Type } from '@angular/core';
import { CoreDelegate, CoreDelegateHandler } from '@classes/delegate';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton } from '@singletons';
import { AddonModQuizAttemptWSData, AddonModQuizQuizWSData } from './quiz';
/**
* Interface that all access rules handlers must implement.
*/
export interface AddonModQuizAccessRuleHandler extends CoreDelegateHandler {
/**
* Name of the rule the handler supports. E.g. 'password'.
*/
ruleName: string;
/**
* Whether the rule requires a preflight check when prefetch/start/continue an attempt.
*
* @param quiz The quiz the rule belongs to.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Whether the rule requires a preflight check.
*/
isPreflightCheckRequired(
quiz: AddonModQuizQuizWSData,
attempt?: AddonModQuizAttemptWSData,
prefetch?: boolean,
siteId?: string,
): boolean | Promise<boolean>;
/**
* Add preflight data that doesn't require user interaction. The data should be added to the preflightData param.
*
* @param quiz The quiz the rule belongs to.
* @param preflightData Object where to add the preflight data.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done if async, void if it's synchronous.
*/
getFixedPreflightData?(
quiz: AddonModQuizQuizWSData,
preflightData: Record<string, string>,
attempt?: AddonModQuizAttemptWSData,
prefetch?: boolean,
siteId?: string,
): void | Promise<void>;
/**
* Return the Component to use to display the access rule preflight.
* Implement this if your access rule requires a preflight check with user interaction.
* It's recommended to return the class of the component, but you can also return an instance of the component.
*
* @return The component (or promise resolved with component) to use, undefined if not found.
*/
getPreflightComponent?(): undefined | Type<unknown> | Promise<Type<unknown>>;
/**
* Function called when the preflight check has passed. This is a chance to record that fact in some way.
*
* @param quiz The quiz the rule belongs to.
* @param attempt The attempt started/continued.
* @param preflightData Preflight data gathered.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done if async, void if it's synchronous.
*/
notifyPreflightCheckPassed?(
quiz: AddonModQuizQuizWSData,
attempt: AddonModQuizAttemptWSData | undefined,
preflightData: Record<string, string>,
prefetch?: boolean,
siteId?: string,
): void | Promise<void>;
/**
* Function called when the preflight check fails. This is a chance to record that fact in some way.
*
* @param quiz The quiz the rule belongs to.
* @param attempt The attempt started/continued.
* @param preflightData Preflight data gathered.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done if async, void if it's synchronous.
*/
notifyPreflightCheckFailed?(
quiz: AddonModQuizQuizWSData,
attempt: AddonModQuizAttemptWSData | undefined,
preflightData: Record<string, string>,
prefetch?: boolean,
siteId?: string,
): void | Promise<void>;
/**
* Whether or not the time left of an attempt should be displayed.
*
* @param attempt The attempt.
* @param endTime The attempt end time (in seconds).
* @param timeNow The current time in seconds.
* @return Whether it should be displayed.
*/
shouldShowTimeLeft?(attempt: AddonModQuizAttemptWSData, endTime: number, timeNow: number): boolean;
}
/**
* Delegate to register access rules for quiz module.
*/
@Injectable({ providedIn: 'root' })
export class AddonModQuizAccessRuleDelegateService extends CoreDelegate<AddonModQuizAccessRuleHandler> {
protected handlerNameProperty = 'ruleName';
constructor() {
super('AddonModQuizAccessRulesDelegate', true);
}
/**
* Get the handler for a certain rule.
*
* @param ruleName Name of the access rule.
* @return Handler. Undefined if no handler found for the rule.
*/
getAccessRuleHandler(ruleName: string): AddonModQuizAccessRuleHandler {
return this.getHandler(ruleName, true);
}
/**
* Given a list of rules, get some fixed preflight data (data that doesn't require user interaction).
*
* @param rules List of active rules names.
* @param quiz Quiz.
* @param preflightData Object where to store the preflight data.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when all the data has been gathered.
*/
async getFixedPreflightData(
rules: string[],
quiz: AddonModQuizQuizWSData,
preflightData: Record<string, string>,
attempt?: AddonModQuizAttemptWSData,
prefetch?: boolean,
siteId?: string,
): Promise<void> {
rules = rules || [];
await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => {
await this.executeFunctionOnEnabled(rule, 'getFixedPreflightData', [quiz, preflightData, attempt, prefetch, siteId]);
})));
}
/**
* Get the Component to use to display the access rule preflight.
*
* @param rule Rule.
* @return Promise resolved with the component to use, undefined if not found.
*/
getPreflightComponent(rule: string): Promise<Type<unknown> | undefined> {
return Promise.resolve(this.executeFunctionOnEnabled(rule, 'getPreflightComponent', []));
}
/**
* Check if an access rule is supported.
*
* @param ruleName Name of the rule.
* @return Whether it's supported.
*/
isAccessRuleSupported(ruleName: string): boolean {
return this.hasHandler(ruleName, true);
}
/**
* Given a list of rules, check if preflight check is required.
*
* @param rules List of active rules names.
* @param quiz Quiz.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: whether it's required.
*/
async isPreflightCheckRequired(
rules: string[],
quiz: AddonModQuizQuizWSData,
attempt?: AddonModQuizAttemptWSData,
prefetch?: boolean,
siteId?: string,
): Promise<boolean> {
rules = rules || [];
let isRequired = false;
await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => {
const ruleRequired = await this.isPreflightCheckRequiredForRule(rule, quiz, attempt, prefetch, siteId);
isRequired = isRequired || ruleRequired;
})));
return isRequired;
}
/**
* Check if preflight check is required for a certain rule.
*
* @param rule Rule name.
* @param quiz Quiz.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: whether it's required.
*/
async isPreflightCheckRequiredForRule(
rule: string,
quiz: AddonModQuizQuizWSData,
attempt?: AddonModQuizAttemptWSData,
prefetch?: boolean,
siteId?: string,
): Promise<boolean> {
const isRequired = await this.executeFunctionOnEnabled(rule, 'isPreflightCheckRequired', [quiz, attempt, prefetch, siteId]);
return !!isRequired;
}
/**
* Notify all rules that the preflight check has passed.
*
* @param rules List of active rules names.
* @param quiz Quiz.
* @param attempt Attempt.
* @param preflightData Preflight data gathered.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async notifyPreflightCheckPassed(
rules: string[],
quiz: AddonModQuizQuizWSData,
attempt: AddonModQuizAttemptWSData | undefined,
preflightData: Record<string, string>,
prefetch?: boolean,
siteId?: string,
): Promise<void> {
rules = rules || [];
await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => {
await this.executeFunctionOnEnabled(
rule,
'notifyPreflightCheckPassed',
[quiz, attempt, preflightData, prefetch, siteId],
);
})));
}
/**
* Notify all rules that the preflight check has failed.
*
* @param rules List of active rules names.
* @param quiz Quiz.
* @param attempt Attempt.
* @param preflightData Preflight data gathered.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async notifyPreflightCheckFailed(
rules: string[],
quiz: AddonModQuizQuizWSData,
attempt: AddonModQuizAttemptWSData | undefined,
preflightData: Record<string, string>,
prefetch?: boolean,
siteId?: string,
): Promise<void> {
rules = rules || [];
await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => {
await this.executeFunctionOnEnabled(
rule,
'notifyPreflightCheckFailed',
[quiz, attempt, preflightData, prefetch, siteId],
);
})));
}
/**
* Whether or not the time left of an attempt should be displayed.
*
* @param rules List of active rules names.
* @param attempt The attempt.
* @param endTime The attempt end time (in seconds).
* @param timeNow The current time in seconds.
* @return Whether it should be displayed.
*/
shouldShowTimeLeft(rules: string[], attempt: AddonModQuizAttemptWSData, endTime: number, timeNow: number): boolean {
rules = rules || [];
for (const i in rules) {
const rule = rules[i];
if (this.executeFunctionOnEnabled(rule, 'shouldShowTimeLeft', [attempt, endTime, timeNow])) {
return true;
}
}
return false;
}
}
export const AddonModQuizAccessRuleDelegate = makeSingleton(AddonModQuizAccessRuleDelegateService); | the_stack |
import type { Exporting, ExportingFormats, ExportingTypes } from "./Exporting"
import { Entity, IEntitySettings, IEntityPrivate, IEntityEvents } from "../../core/util/Entity"
import { IDisposer, Disposer } from "../../core/util/Disposer";
import exportingCSS from "./ExportingCSS";
import * as $array from "../../core/util/Array";
import * as $utils from "../../core/util/Utils";
export interface IExportingMenuItem {
/**
* Indicates type of the menu item:
* * `"format"` - indicates export action
* * `"separator"` - will show horizontal divider.
* * `"custom"` - will invoke custom function when clicked.
*/
type: "format" | "separator" | "custom";
/**
* If `type` is set to `"format"`, clicking item will initiate export in
* that format.
*/
format?: ExportingFormats;
/**
* Indicates export type: `"image"`, `"data"`, or `"print"`.
*/
exportType?: ExportingTypes;
/**
* Menu label.
*/
label?: string;
/**
* Additional information.
*/
sublabel?: string;
/**
* If `type` is set to `"custom"`, this needs to be set to a function.
*/
callback?: (menuItem?: any) => any;
/**
* A target for callback function.
*/
callbackTarget?: any;
/**
* A DOM element for the menu item.
*
* @readonly
*/
element?: HTMLAnchorElement;
}
export interface IExportingMenuSettings extends IEntitySettings {
/**
* Horizontal alignment of the menu.
*
* @default "right"
*/
align?: "left" | "right";
/**
* Vertical alignment of the menu.
*
* @default "top"
*/
valign?: "top" | "bottom";
/**
* A reference to an element in the document to place export menu in.
*
* If not set, will use root element's container.
*/
container?: HTMLElement;
/**
* A list of menu items.
*/
items?: IExportingMenuItem[];
/**
* A reference to related [[Exporting]] object.
*/
exporting?: Exporting;
/**
* If set to `false` the legend will not load default CSS.
*
* @default true
*/
useDefaultCSS?: boolean;
/**
* If set to `true` the menu will close automatically when export operation
* is initiated.
*
* @default true
*/
autoClose?: boolean;
/**
* Menu will disable all interactions for the underlying chart when browsing
* the menu.
*
* @default true
*/
deactivateRoot?: boolean;
}
export interface IExportingMenuPrivate extends IEntityPrivate {
}
export interface IExportingMenuEvents extends IEntityEvents {
"menucreated": {}
"menuopened": {}
"menuclosed": {}
}
/**
* Displays a menu for [[Exporting]].
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/exporting/} for more info
*/
export class ExportingMenu extends Entity {
public static className: string = "ExportingMenu";
public static classNames: Array<string> = Entity.classNames.concat([ExportingMenu.className]);
declare public _settings: IExportingMenuSettings;
declare public _privateSettings: IExportingMenuPrivate;
declare public _events: IExportingMenuEvents;
private _menuElement?: HTMLDivElement;
private _iconElement?: HTMLElement;
private _listElement?: HTMLUListElement;
private _itemElements?: HTMLLIElement[] = [];
private _itemDisposers: Array<IDisposer> = [];
private _cssDisposer?: IDisposer;
private _activeItem?: IExportingMenuItem;
public isOpen: boolean = false;
private _isOver: boolean = false;
protected _afterNew() {
super._afterNew();
this._setRawDefault("container", this._root._inner);
this._setRawDefault("align", "right");
this._setRawDefault("valign", "top");
this._setRawDefault("useDefaultCSS", true);
this._setRawDefault("autoClose", true);
this._setRawDefault("deactivateRoot", true);
this._setRawDefault("items", [{
type: "separator",
label: this._t("Export")
}, {
type: "format",
format: "png",
exportType: "image",
label: this._t("PNG"),
sublabel: this._t("Image")
}, {
type: "format",
format: "jpg",
exportType: "image",
label: this._t("JPG"),
sublabel: this._t("Image")
}, {
type: "format",
format: "pdf",
exportType: "image",
label: this._t("PDF"),
sublabel: this._t("Image")
}, {
type: "separator",
exportType: "data",
//label: this._t("Data")
}, {
type: "format",
format: "json",
exportType: "data",
label: this._t("JSON"),
sublabel: this._t("Data")
}, {
type: "format",
format: "csv",
exportType: "data",
label: this._t("CSV"),
sublabel: this._t("Data")
}, {
type: "format",
format: "xlsx",
exportType: "data",
label: this._t("XLSX"),
sublabel: this._t("Data")
}, {
type: "format",
format: "pdfdata",
exportType: "data",
label: this._t("PDF"),
sublabel: this._t("Data")
}, {
type: "format",
format: "html",
exportType: "data",
label: this._t("HTML"),
sublabel: this._t("Data")
}, {
type: "separator"
}, {
type: "format",
format: "print",
exportType: "print",
label: this._t("Print")
}]);
const menuElement = document.createElement("div");
this._menuElement = menuElement;
const iconElement = document.createElement("a");
this._iconElement = iconElement;
this._listElement = document.createElement("ul");
this._listElement.setAttribute("role", "menu");
this._applyClassNames();
iconElement.innerHTML = '<svg fill="none" height="20" width="20" xmlns="http://www.w3.org/2000/svg"><path d="M6 10a2 2 0 11-4 0 2 2 0 014 0zM12 10a2 2 0 11-4 0 2 2 0 014 0zM16 12a2 2 0 100-4 2 2 0 000 4z"/></svg>';
iconElement.setAttribute("tabindex", this._root.tabindex.toString());
iconElement.setAttribute("aria-label", this._t("Export"));
iconElement.setAttribute("aria-description", this._t("Press ENTER to open"));
if ($utils.supports("keyboardevents")) {
this._disposers.push($utils.addEventListener(document, "keydown", (ev: KeyboardEvent) => {
if (document.activeElement == this._iconElement || this.isOpen) {
if (ev.keyCode == 27) {
// ESC
this.close();
}
else if (ev.keyCode == 13) {
// ENTER
if (this._activeItem) {
this._handleClick(this._activeItem);
}
else {
this.toggle();
}
}
else if (ev.keyCode == 38 || ev.keyCode == 40) {
const items = this.get("items", []);
let currentIndex = (<any>items).indexOf(this._activeItem);
if (this.get("valign") == "top" && currentIndex == -1) {
currentIndex = items.length;
}
const dir = ev.keyCode == 38 ? -1 : 1;
let newIndex = currentIndex + dir;
let newItem;
do {
if (newIndex < 0) {
newIndex = items.length - 1;
}
else if (newIndex > (items.length - 1)) {
newIndex = 0;
}
if (items[newIndex].type == "separator") {
newIndex += dir;
}
else {
newItem = items[newIndex];
}
} while(!newItem);
if (newItem) {
this._handleItemFocus(newItem);
}
}
}
}));
}
this._disposers.push($utils.addEventListener(iconElement, "click", (ev: MouseEvent) => {
ev.stopImmediatePropagation();
this.toggle();
}));
menuElement.appendChild(this._iconElement);
menuElement.appendChild(this._listElement);
this._root._inner.appendChild(this._menuElement);
this._disposers.push($utils.addEventListener(menuElement, $utils.getRendererEvent("pointerover"), (_ev) => {
this._isOver = true;
if (this.get("deactivateRoot")) {
this._root._renderer.interactionsEnabled = false;
}
}));
this._disposers.push($utils.addEventListener(menuElement, $utils.getRendererEvent("pointerout"), (_ev) => {
this._isOver = false;
if (this.get("deactivateRoot")) {
this._root._renderer.interactionsEnabled = true;
}
}));
this._disposers.push(new Disposer(() => {
if (this._menuElement) {
this._root._inner.removeChild(this._menuElement);
}
}));
this._disposers.push($utils.addEventListener(document, "click", (_ev) => {
if (this.isOpen && !this._isOver) {
this.close();
}
}));
this.loadDefaultCSS();
this._root.addDisposer(this);
this.events.dispatch("menucreated", {
type: "menucreated",
target: this
});
}
public _afterChanged() {
super._afterChanged();
if (this._itemElements!.length == 0) {
this.createItems();
}
if (this.isDirty("useDefaultCSS")) {
if (this.get("useDefaultCSS")) {
this.loadDefaultCSS();
}
else if (this._cssDisposer) {
this._cssDisposer.dispose();
}
}
if (this.isDirty("exporting")) {
const exporting = this.get("exporting");
if (exporting) {
this.createItems();
}
}
if (this.isDirty("align") || this.isDirty("valign")) {
this._applyClassNames();
}
if (this.isDirty("container")) {
const container = this.get("container");
if (container) {
container.appendChild(this._menuElement!);
}
}
}
protected _dispose(): void {
super._dispose();
$array.each(this._itemDisposers, (x) => {
x.dispose();
});
}
private _applyClassNames(): void {
const align = this.get("align", "right");
const valign = this.get("valign", "top");
const status = this.isOpen ? "am5exporting-menu-open" : "am5exporting-menu-closed";
this._menuElement!.className = "am5exporting am5exporting-menu am5exporting-align-" + align + " am5exporting-valign-" + valign + " " + status;
this._iconElement!.className = "am5exporting am5exporting-icon am5exporting-align-" + align + " am5exporting-valign-" + valign;
this._listElement!.className = "am5exporting am5exporting-list am5exporting-align-" + align + " am5exporting-valign-" + valign;
}
/**
* @ignore
*/
public createItems(): void {
const exporting = this.get("exporting");
if (!exporting) {
return;
}
this._listElement!.innerHTML = "";
this._itemElements = [];
const items = this.get("items", []);
const supportedFormats = exporting.supportedFormats();
const supportedExportTypes = exporting.supportedExportTypes();
$array.each(this._itemDisposers, (x) => {
x.dispose();
});
this._itemDisposers.length = 0;
$array.each(items, (item) => {
if (item.format && supportedFormats.indexOf(item.format) == -1) {
return;
}
if (item.exportType && supportedExportTypes.indexOf(item.exportType) == -1) {
return;
}
const li = document.createElement("li");
li.setAttribute("role", "menuitem");
li.className = "am5exporting am5exporting-item am5exporting-type-" + item.type;
if (item.format) {
li.className += " am5exporting-format-" + item.format;
}
const a = document.createElement("a");
let ariaLabel = this._t("Export");
if (item.label) {
a.innerHTML = item.label;
ariaLabel += " " + item.label;
}
if (item.sublabel) {
a.innerHTML += " <span class=\"am5exporting-label-alt\">" + item.sublabel + "</span>";
ariaLabel += " (" + item.sublabel + ")";
}
if (item.callback) {
this._itemDisposers.push($utils.addEventListener(a, "click", (_ev) => {
item.callback!.call(item.callbackTarget || this)
}));
a.setAttribute("tabindex", this._root.tabindex.toString());
}
else if (item.format && exporting) {
this._itemDisposers.push($utils.addEventListener(a, "click", (_ev) => {
this._handleClick(item);
}));
this._itemDisposers.push($utils.addEventListener(a, "focus", (_ev) => {
this._handleItemFocus(item);
}));
this._itemDisposers.push($utils.addEventListener(a, "blur", (_ev) => {
this._handleItemBlur(item);
}));
a.setAttribute("tabindex", this._root.tabindex.toString());
a.setAttribute("aria-label", ariaLabel);
}
item.element = a;
li.appendChild(a);
this._listElement!.appendChild(li);
this._itemElements!.push(li);
});
}
private _handleClick(item: IExportingMenuItem): void {
const exporting = this.get("exporting")!;
if (this.get("autoClose")) {
this.close();
}
if (item.format == "print") {
exporting.print();
}
else {
exporting.download(item.format!);
}
}
private _handleItemFocus(item: IExportingMenuItem): void {
if (item != this._activeItem) {
if (this._activeItem) {
this._activeItem.element!.className = "";
}
this._activeItem = item;
item.element!.className = "am5exporting-item-active";
item.element!.focus();
}
}
private _handleItemBlur(item: IExportingMenuItem): void {
item.element!.className = "";
if (item == this._activeItem) {
this._activeItem = undefined
}
this.setTimeout(() => {
if (!document.activeElement || !$utils.contains(this.get("container")!, document.activeElement!)) {
this.close();
}
}, 10);
}
/**
* Loads the default CSS.
*
* @ignore Exclude from docs
*/
public loadDefaultCSS(): void {
const disposer = exportingCSS($utils.getShadowRoot(this._root.dom), this._root);
this._disposers.push(disposer);
this._cssDisposer = disposer;
// if (this._element) {
// this._element.style.display = "";
// }
}
/**
* Opens menu.
*/
public open(): void {
this.isOpen = true;
this._applyClassNames();
this.events.dispatch("menuopened", {
type: "menuopened",
target: this
});
}
/**
* Closes menu.
*/
public close(): void {
this.isOpen = false;
$utils.blur();
this._applyClassNames();
this.events.dispatch("menuclosed", {
type: "menuclosed",
target: this
});
}
/**
* Toggles menu open and close.
*/
public toggle(): void {
if (this.isOpen) {
this.close();
}
else {
this.open();
}
}
} | the_stack |
module android.view{
import SparseArray = android.util.SparseArray;
/**
* Contains methods to standard constants used in the UI for timeouts, sizes, and distances.
*/
export class ViewConfiguration{
/**
* Defines the width of the horizontal scrollbar and the height of the vertical scrollbar in
* dips
*/
private static SCROLL_BAR_SIZE = 8;
/**
* Duration of the fade when scrollbars fade away in milliseconds
*/
private static SCROLL_BAR_FADE_DURATION = 250;
/**
* Default delay before the scrollbars fade in milliseconds
*/
private static SCROLL_BAR_DEFAULT_DELAY = 300;
/**
* Defines the length of the fading edges in dips
*/
private static FADING_EDGE_LENGTH = 12;
/**
* Defines the duration in milliseconds of the pressed state in child
* components.
*/
private static PRESSED_STATE_DURATION = 64;
/**
* Defines the default duration in milliseconds before a press turns into
* a long press
*/
private static DEFAULT_LONG_PRESS_TIMEOUT = 500;
/**
* Defines the time between successive key repeats in milliseconds.
*/
private static KEY_REPEAT_DELAY = 50;
/**
* Defines the duration in milliseconds a user needs to hold down the
* appropriate button to bring up the global actions dialog (power off,
* lock screen, etc).
*/
private static GLOBAL_ACTIONS_KEY_TIMEOUT = 500;
/**
* Defines the duration in milliseconds we will wait to see if a touch event
* is a tap or a scroll. If the user does not move within this interval, it is
* considered to be a tap.
*/
private static TAP_TIMEOUT = 180;
/**
* Defines the duration in milliseconds we will wait to see if a touch event
* is a jump tap. If the user does not complete the jump tap within this interval, it is
* considered to be a tap.
*/
private static JUMP_TAP_TIMEOUT = 500;
/**
* Defines the duration in milliseconds between the first tap's up event and
* the second tap's down event for an interaction to be considered a
* double-tap.
*/
private static DOUBLE_TAP_TIMEOUT = 300;
/**
* Defines the minimum duration in milliseconds between the first tap's up event and
* the second tap's down event for an interaction to be considered a
* double-tap.
*/
private static DOUBLE_TAP_MIN_TIME = 40;
/**
* Defines the maximum duration in milliseconds between a touch pad
* touch and release for a given touch to be considered a tap (click) as
* opposed to a hover movement gesture.
*/
private static HOVER_TAP_TIMEOUT = 150;
/**
* Defines the maximum distance in pixels that a touch pad touch can move
* before being released for it to be considered a tap (click) as opposed
* to a hover movement gesture.
*/
private static HOVER_TAP_SLOP = 20;
/**
* Defines the duration in milliseconds we want to display zoom controls in response
* to a user panning within an application.
*/
private static ZOOM_CONTROLS_TIMEOUT = 3000;
/**
* Inset in dips to look for touchable content when the user touches the edge of the screen
*/
public static EDGE_SLOP = 12;
/**
* Distance a touch can wander before we think the user is scrolling in dips.
* Note that this value defined here is only used as a fallback by legacy/misbehaving
* applications that do not provide a Context for determining density/configuration-dependent
* values.
*
* To alter this value, see the configuration resource config_viewConfigurationTouchSlop
* in frameworks/base/core/res/res/values/config.xml or the appropriate device resource overlay.
* It may be appropriate to tweak this on a device-specific basis in an overlay based on
* the characteristics of the touch panel and firmware.
*/
private static TOUCH_SLOP = 8;
/**
* Distance the first touch can wander before we stop considering this event a double tap
* (in dips)
*/
private static DOUBLE_TAP_TOUCH_SLOP = ViewConfiguration.TOUCH_SLOP;
/**
* Distance a touch can wander before we think the user is attempting a paged scroll
* (in dips)
*
* Note that this value defined here is only used as a fallback by legacy/misbehaving
* applications that do not provide a Context for determining density/configuration-dependent
* values.
*
* See the note above on {@link #TOUCH_SLOP} regarding the dimen resource
* config_viewConfigurationTouchSlop. ViewConfiguration will report a paging touch slop of
* config_viewConfigurationTouchSlop * 2 when provided with a Context.
*/
private static PAGING_TOUCH_SLOP = ViewConfiguration.TOUCH_SLOP * 2;
/**
* Distance in dips between the first touch and second touch to still be considered a double tap
*/
private static DOUBLE_TAP_SLOP = 100;
/**
* Distance in dips a touch needs to be outside of a window's bounds for it to
* count as outside for purposes of dismissing the window.
*/
private static WINDOW_TOUCH_SLOP = 16;
/**
* Minimum velocity to initiate a fling, as measured in dips per second
*/
private static MINIMUM_FLING_VELOCITY = 50;
/**
* Maximum velocity to initiate a fling, as measured in dips per second
*/
private static MAXIMUM_FLING_VELOCITY = 8000;
/**
* The maximum size of View's drawing cache, expressed in bytes. This size
* should be at least equal to the size of the screen in ARGB888 format.
*/
//private static MAXIMUM_DRAWING_CACHE_SIZE:number = 480 * 800 * 4;
/**
* The coefficient of friction applied to flings/scrolls.
*/
private static SCROLL_FRICTION = 0.015;
/**
* Max distance in dips to overscroll for edge effects
*/
private static OVERSCROLL_DISTANCE = 800;//defaul 0
/**
* Max distance in dips to overfling for edge effects
*/
private static OVERFLING_DISTANCE = 100;//default 6
static instance : ViewConfiguration;
/**
* Returns a configuration for the specified context. The configuration depends on
* various parameters of the context, like the dimension of the display or the
* density of the display.
*
* @param context The application context used to initialize the view configuration.
*/
static get(arg?:any):ViewConfiguration{
if(!ViewConfiguration.instance){
ViewConfiguration.instance = new ViewConfiguration();
}
return ViewConfiguration.instance;
}
private density = android.content.res.Resources.getDisplayMetrics().density;
private sizeAndDensity = this.density;
mEdgeSlop:number = this.sizeAndDensity * ViewConfiguration.EDGE_SLOP;
mFadingEdgeLength:number = this.sizeAndDensity * ViewConfiguration.FADING_EDGE_LENGTH;
mMinimumFlingVelocity:number = this.density * ViewConfiguration.MINIMUM_FLING_VELOCITY;
mMaximumFlingVelocity:number = this.density * ViewConfiguration.MAXIMUM_FLING_VELOCITY;
mScrollbarSize:number = this.density * ViewConfiguration.SCROLL_BAR_SIZE;
mTouchSlop:number = this.density * ViewConfiguration.TOUCH_SLOP;
mDoubleTapTouchSlop:number = this.sizeAndDensity * ViewConfiguration.DOUBLE_TAP_TOUCH_SLOP;
mPagingTouchSlop:number = this.density * ViewConfiguration.PAGING_TOUCH_SLOP;
mDoubleTapSlop:number = this.density * ViewConfiguration.DOUBLE_TAP_SLOP;
mWindowTouchSlop:number = this.sizeAndDensity * ViewConfiguration.WINDOW_TOUCH_SLOP;
mOverscrollDistance:number = this.sizeAndDensity * ViewConfiguration.OVERSCROLL_DISTANCE;
mOverflingDistance:number = this.sizeAndDensity * ViewConfiguration.OVERFLING_DISTANCE;
mMaximumDrawingCacheSize:number = android.content.res.Resources.getDisplayMetrics().widthPixels
* android.content.res.Resources.getDisplayMetrics().heightPixels * 4 * 2;//android ui x2
/**
* @return The width of the horizontal scrollbar and the height of the vertical
* scrollbar in pixels
*/
getScaledScrollBarSize():number {
return this.mScrollbarSize;
}
/**
* @return Duration of the fade when scrollbars fade away in milliseconds
*/
static getScrollBarFadeDuration():number {
return ViewConfiguration.SCROLL_BAR_FADE_DURATION;
}
/**
* @return Default delay before the scrollbars fade in milliseconds
*/
static getScrollDefaultDelay():number {
return ViewConfiguration.SCROLL_BAR_DEFAULT_DELAY;
}
/**
* @return the length of the fading edges in pixels
*/
getScaledFadingEdgeLength():number {
return this.mFadingEdgeLength;
}
/**
* @return the duration in milliseconds of the pressed state in child
* components.
*/
static getPressedStateDuration():number {
return ViewConfiguration.PRESSED_STATE_DURATION;
}
/**
* @return the duration in milliseconds before a press turns into
* a long press
*/
static getLongPressTimeout():number {
return ViewConfiguration.DEFAULT_LONG_PRESS_TIMEOUT;
}
/**
* @return the time between successive key repeats in milliseconds.
*/
static getKeyRepeatDelay():number {
return ViewConfiguration.KEY_REPEAT_DELAY;
}
/**
* @return the duration in milliseconds we will wait to see if a touch event
* is a tap or a scroll. If the user does not move within this interval, it is
* considered to be a tap.
*/
static getTapTimeout():number {
return ViewConfiguration.TAP_TIMEOUT;
}
/**
* @return the duration in milliseconds we will wait to see if a touch event
* is a jump tap. If the user does not move within this interval, it is
* considered to be a tap.
*/
static getJumpTapTimeout():number {
return ViewConfiguration.JUMP_TAP_TIMEOUT;
}
/**
* @return the duration in milliseconds between the first tap's up event and
* the second tap's down event for an interaction to be considered a
* double-tap.
*/
static getDoubleTapTimeout():number {
return ViewConfiguration.DOUBLE_TAP_TIMEOUT;
}
/**
* @return the minimum duration in milliseconds between the first tap's
* up event and the second tap's down event for an interaction to be considered a
* double-tap.
*
* @hide
*/
static getDoubleTapMinTime():number {
return ViewConfiguration.DOUBLE_TAP_MIN_TIME;
}
/**
* @return Inset in pixels to look for touchable content when the user touches the edge of the
* screen
*/
getScaledEdgeSlop():number {
return this.mEdgeSlop;
}
/**
* @return Distance in pixels a touch can wander before we think the user is scrolling
*/
getScaledTouchSlop():number {
return this.mTouchSlop;
}
/**
* @return Distance in pixels the first touch can wander before we do not consider this a
* potential double tap event
* @hide
*/
getScaledDoubleTapTouchSlop():number {
return this.mDoubleTapTouchSlop;
}
/**
* @return Distance in pixels a touch can wander before we think the user is scrolling a full
* page
*/
getScaledPagingTouchSlop() {
return this.mPagingTouchSlop;
}
/**
* @return Distance in pixels between the first touch and second touch to still be
* considered a double tap
*/
getScaledDoubleTapSlop() {
return this.mDoubleTapSlop;
}
/**
* @return Distance in pixels a touch must be outside the bounds of a window for it
* to be counted as outside the window for purposes of dismissing that window.
*/
getScaledWindowTouchSlop() {
return this.mWindowTouchSlop;
}
/**
* @return Minimum velocity to initiate a fling, as measured in pixels per second.
*/
getScaledMinimumFlingVelocity() {
return this.mMinimumFlingVelocity;
}
/**
* @return Maximum velocity to initiate a fling, as measured in pixels per second.
*/
getScaledMaximumFlingVelocity() {
return this.mMaximumFlingVelocity;
}
/**
* The maximum drawing cache size expressed in bytes.
*
* @return the maximum size of View's drawing cache expressed in bytes
*/
getScaledMaximumDrawingCacheSize():number {
return this.mMaximumDrawingCacheSize;
}
/**
* @return The maximum distance a View should overscroll by when showing edge effects (in
* pixels).
*/
getScaledOverscrollDistance() {
return this.mOverscrollDistance;
}
/**
* @return The maximum distance a View should overfling by when showing edge effects (in
* pixels).
*/
getScaledOverflingDistance() {
return this.mOverflingDistance;
}
/**
* The amount of friction applied to scrolls and flings.
*
* @return A scalar dimensionless value representing the coefficient of
* friction.
*/
static getScrollFriction() {
return ViewConfiguration.SCROLL_FRICTION;
}
}
} | the_stack |
* Patch for Colyseus:
* -------------------
*
* added `offset` on Decoder constructor, for messages arriving with a code
* before actual msgpack data
*/
//
// DECODER
//
function Decoder(buffer, offset) {
this._offset = offset;
if (buffer instanceof ArrayBuffer) {
this._buffer = buffer;
this._view = new DataView(this._buffer);
} else if (ArrayBuffer.isView(buffer)) {
this._buffer = buffer.buffer;
this._view = new DataView(this._buffer, buffer.byteOffset, buffer.byteLength);
} else {
throw new Error('Invalid argument');
}
}
function utf8Read(view, offset, length) {
var string = '', chr = 0;
for (var i = offset, end = offset + length; i < end; i++) {
var byte = view.getUint8(i);
if ((byte & 0x80) === 0x00) {
string += String.fromCharCode(byte);
continue;
}
if ((byte & 0xe0) === 0xc0) {
string += String.fromCharCode(
((byte & 0x1f) << 6) |
(view.getUint8(++i) & 0x3f)
);
continue;
}
if ((byte & 0xf0) === 0xe0) {
string += String.fromCharCode(
((byte & 0x0f) << 12) |
((view.getUint8(++i) & 0x3f) << 6) |
((view.getUint8(++i) & 0x3f) << 0)
);
continue;
}
if ((byte & 0xf8) === 0xf0) {
chr = ((byte & 0x07) << 18) |
((view.getUint8(++i) & 0x3f) << 12) |
((view.getUint8(++i) & 0x3f) << 6) |
((view.getUint8(++i) & 0x3f) << 0);
if (chr >= 0x010000) { // surrogate pair
chr -= 0x010000;
string += String.fromCharCode((chr >>> 10) + 0xD800, (chr & 0x3FF) + 0xDC00);
} else {
string += String.fromCharCode(chr);
}
continue;
}
throw new Error('Invalid byte ' + byte.toString(16));
}
return string;
}
Decoder.prototype._array = function (length) {
var value = new Array(length);
for (var i = 0; i < length; i++) {
value[i] = this._parse();
}
return value;
};
Decoder.prototype._map = function (length) {
var key = '', value = {};
for (var i = 0; i < length; i++) {
key = this._parse();
value[key] = this._parse();
}
return value;
};
Decoder.prototype._str = function (length) {
var value = utf8Read(this._view, this._offset, length);
this._offset += length;
return value;
};
Decoder.prototype._bin = function (length) {
var value = this._buffer.slice(this._offset, this._offset + length);
this._offset += length;
return value;
};
Decoder.prototype._parse = function () {
var prefix = this._view.getUint8(this._offset++);
var value, length = 0, type = 0, hi = 0, lo = 0;
if (prefix < 0xc0) {
// positive fixint
if (prefix < 0x80) {
return prefix;
}
// fixmap
if (prefix < 0x90) {
return this._map(prefix & 0x0f);
}
// fixarray
if (prefix < 0xa0) {
return this._array(prefix & 0x0f);
}
// fixstr
return this._str(prefix & 0x1f);
}
// negative fixint
if (prefix > 0xdf) {
return (0xff - prefix + 1) * -1;
}
switch (prefix) {
// nil
case 0xc0:
return null;
// false
case 0xc2:
return false;
// true
case 0xc3:
return true;
// bin
case 0xc4:
length = this._view.getUint8(this._offset);
this._offset += 1;
return this._bin(length);
case 0xc5:
length = this._view.getUint16(this._offset);
this._offset += 2;
return this._bin(length);
case 0xc6:
length = this._view.getUint32(this._offset);
this._offset += 4;
return this._bin(length);
// ext
case 0xc7:
length = this._view.getUint8(this._offset);
type = this._view.getInt8(this._offset + 1);
this._offset += 2;
return [type, this._bin(length)];
case 0xc8:
length = this._view.getUint16(this._offset);
type = this._view.getInt8(this._offset + 2);
this._offset += 3;
return [type, this._bin(length)];
case 0xc9:
length = this._view.getUint32(this._offset);
type = this._view.getInt8(this._offset + 4);
this._offset += 5;
return [type, this._bin(length)];
// float
case 0xca:
value = this._view.getFloat32(this._offset);
this._offset += 4;
return value;
case 0xcb:
value = this._view.getFloat64(this._offset);
this._offset += 8;
return value;
// uint
case 0xcc:
value = this._view.getUint8(this._offset);
this._offset += 1;
return value;
case 0xcd:
value = this._view.getUint16(this._offset);
this._offset += 2;
return value;
case 0xce:
value = this._view.getUint32(this._offset);
this._offset += 4;
return value;
case 0xcf:
hi = this._view.getUint32(this._offset) * Math.pow(2, 32);
lo = this._view.getUint32(this._offset + 4);
this._offset += 8;
return hi + lo;
// int
case 0xd0:
value = this._view.getInt8(this._offset);
this._offset += 1;
return value;
case 0xd1:
value = this._view.getInt16(this._offset);
this._offset += 2;
return value;
case 0xd2:
value = this._view.getInt32(this._offset);
this._offset += 4;
return value;
case 0xd3:
hi = this._view.getInt32(this._offset) * Math.pow(2, 32);
lo = this._view.getUint32(this._offset + 4);
this._offset += 8;
return hi + lo;
// fixext
case 0xd4:
type = this._view.getInt8(this._offset);
this._offset += 1;
if (type === 0x00) {
this._offset += 1;
return void 0;
}
return [type, this._bin(1)];
case 0xd5:
type = this._view.getInt8(this._offset);
this._offset += 1;
return [type, this._bin(2)];
case 0xd6:
type = this._view.getInt8(this._offset);
this._offset += 1;
return [type, this._bin(4)];
case 0xd7:
type = this._view.getInt8(this._offset);
this._offset += 1;
if (type === 0x00) {
hi = this._view.getInt32(this._offset) * Math.pow(2, 32);
lo = this._view.getUint32(this._offset + 4);
this._offset += 8;
return new Date(hi + lo);
}
return [type, this._bin(8)];
case 0xd8:
type = this._view.getInt8(this._offset);
this._offset += 1;
return [type, this._bin(16)];
// str
case 0xd9:
length = this._view.getUint8(this._offset);
this._offset += 1;
return this._str(length);
case 0xda:
length = this._view.getUint16(this._offset);
this._offset += 2;
return this._str(length);
case 0xdb:
length = this._view.getUint32(this._offset);
this._offset += 4;
return this._str(length);
// array
case 0xdc:
length = this._view.getUint16(this._offset);
this._offset += 2;
return this._array(length);
case 0xdd:
length = this._view.getUint32(this._offset);
this._offset += 4;
return this._array(length);
// map
case 0xde:
length = this._view.getUint16(this._offset);
this._offset += 2;
return this._map(length);
case 0xdf:
length = this._view.getUint32(this._offset);
this._offset += 4;
return this._map(length);
}
throw new Error('Could not parse');
};
function decode(buffer, offset = 0) {
var decoder = new Decoder(buffer, offset);
var value = decoder._parse();
if (decoder._offset !== buffer.byteLength) {
throw new Error((buffer.byteLength - decoder._offset) + ' trailing bytes');
}
return value;
}
//
// ENCODER
//
function utf8Write(view, offset, str) {
var c = 0;
for (var i = 0, l = str.length; i < l; i++) {
c = str.charCodeAt(i);
if (c < 0x80) {
view.setUint8(offset++, c);
}
else if (c < 0x800) {
view.setUint8(offset++, 0xc0 | (c >> 6));
view.setUint8(offset++, 0x80 | (c & 0x3f));
}
else if (c < 0xd800 || c >= 0xe000) {
view.setUint8(offset++, 0xe0 | (c >> 12));
view.setUint8(offset++, 0x80 | (c >> 6) & 0x3f);
view.setUint8(offset++, 0x80 | (c & 0x3f));
}
else {
i++;
c = 0x10000 + (((c & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
view.setUint8(offset++, 0xf0 | (c >> 18));
view.setUint8(offset++, 0x80 | (c >> 12) & 0x3f);
view.setUint8(offset++, 0x80 | (c >> 6) & 0x3f);
view.setUint8(offset++, 0x80 | (c & 0x3f));
}
}
}
function utf8Length(str) {
var c = 0, length = 0;
for (var i = 0, l = str.length; i < l; i++) {
c = str.charCodeAt(i);
if (c < 0x80) {
length += 1;
}
else if (c < 0x800) {
length += 2;
}
else if (c < 0xd800 || c >= 0xe000) {
length += 3;
}
else {
i++;
length += 4;
}
}
return length;
}
function _encode(bytes, defers, value) {
var type = typeof value, i = 0, l = 0, hi = 0, lo = 0, length = 0, size = 0;
if (type === 'string') {
length = utf8Length(value);
// fixstr
if (length < 0x20) {
bytes.push(length | 0xa0);
size = 1;
}
// str 8
else if (length < 0x100) {
bytes.push(0xd9, length);
size = 2;
}
// str 16
else if (length < 0x10000) {
bytes.push(0xda, length >> 8, length);
size = 3;
}
// str 32
else if (length < 0x100000000) {
bytes.push(0xdb, length >> 24, length >> 16, length >> 8, length);
size = 5;
} else {
throw new Error('String too long');
}
defers.push({ _str: value, _length: length, _offset: bytes.length });
return size + length;
}
if (type === 'number') {
// TODO: encode to float 32?
// float 64
if (Math.floor(value) !== value || !isFinite(value)) {
bytes.push(0xcb);
defers.push({ _float: value, _length: 8, _offset: bytes.length });
return 9;
}
if (value >= 0) {
// positive fixnum
if (value < 0x80) {
bytes.push(value);
return 1;
}
// uint 8
if (value < 0x100) {
bytes.push(0xcc, value);
return 2;
}
// uint 16
if (value < 0x10000) {
bytes.push(0xcd, value >> 8, value);
return 3;
}
// uint 32
if (value < 0x100000000) {
bytes.push(0xce, value >> 24, value >> 16, value >> 8, value);
return 5;
}
// uint 64
hi = (value / Math.pow(2, 32)) >> 0;
lo = value >>> 0;
bytes.push(0xcf, hi >> 24, hi >> 16, hi >> 8, hi, lo >> 24, lo >> 16, lo >> 8, lo);
return 9;
} else {
// negative fixnum
if (value >= -0x20) {
bytes.push(value);
return 1;
}
// int 8
if (value >= -0x80) {
bytes.push(0xd0, value);
return 2;
}
// int 16
if (value >= -0x8000) {
bytes.push(0xd1, value >> 8, value);
return 3;
}
// int 32
if (value >= -0x80000000) {
bytes.push(0xd2, value >> 24, value >> 16, value >> 8, value);
return 5;
}
// int 64
hi = Math.floor(value / Math.pow(2, 32));
lo = value >>> 0;
bytes.push(0xd3, hi >> 24, hi >> 16, hi >> 8, hi, lo >> 24, lo >> 16, lo >> 8, lo);
return 9;
}
}
if (type === 'object') {
// nil
if (value === null) {
bytes.push(0xc0);
return 1;
}
if (Array.isArray(value)) {
length = value.length;
// fixarray
if (length < 0x10) {
bytes.push(length | 0x90);
size = 1;
}
// array 16
else if (length < 0x10000) {
bytes.push(0xdc, length >> 8, length);
size = 3;
}
// array 32
else if (length < 0x100000000) {
bytes.push(0xdd, length >> 24, length >> 16, length >> 8, length);
size = 5;
} else {
throw new Error('Array too large');
}
for (i = 0; i < length; i++) {
size += _encode(bytes, defers, value[i]);
}
return size;
}
// fixext 8 / Date
if (value instanceof Date) {
var time = value.getTime();
hi = Math.floor(time / Math.pow(2, 32));
lo = time >>> 0;
bytes.push(0xd7, 0, hi >> 24, hi >> 16, hi >> 8, hi, lo >> 24, lo >> 16, lo >> 8, lo);
return 10;
}
if (value instanceof ArrayBuffer) {
length = value.byteLength;
// bin 8
if (length < 0x100) {
bytes.push(0xc4, length);
size = 2;
} else
// bin 16
if (length < 0x10000) {
bytes.push(0xc5, length >> 8, length);
size = 3;
} else
// bin 32
if (length < 0x100000000) {
bytes.push(0xc6, length >> 24, length >> 16, length >> 8, length);
size = 5;
} else {
throw new Error('Buffer too large');
}
defers.push({ _bin: value, _length: length, _offset: bytes.length });
return size + length;
}
if (typeof value.toJSON === 'function') {
return _encode(bytes, defers, value.toJSON());
}
var keys = [], key = '';
var allKeys = Object.keys(value);
for (i = 0, l = allKeys.length; i < l; i++) {
key = allKeys[i];
if (typeof value[key] !== 'function') {
keys.push(key);
}
}
length = keys.length;
// fixmap
if (length < 0x10) {
bytes.push(length | 0x80);
size = 1;
}
// map 16
else if (length < 0x10000) {
bytes.push(0xde, length >> 8, length);
size = 3;
}
// map 32
else if (length < 0x100000000) {
bytes.push(0xdf, length >> 24, length >> 16, length >> 8, length);
size = 5;
} else {
throw new Error('Object too large');
}
for (i = 0; i < length; i++) {
key = keys[i];
size += _encode(bytes, defers, key);
size += _encode(bytes, defers, value[key]);
}
return size;
}
// false/true
if (type === 'boolean') {
bytes.push(value ? 0xc3 : 0xc2);
return 1;
}
// fixext 1 / undefined
if (type === 'undefined') {
bytes.push(0xd4, 0, 0);
return 3;
}
throw new Error('Could not encode');
}
function encode(value) {
var bytes = [];
var defers = [];
var size = _encode(bytes, defers, value);
var buf = new ArrayBuffer(size);
var view = new DataView(buf);
var deferIndex = 0;
var deferWritten = 0;
var nextOffset = -1;
if (defers.length > 0) {
nextOffset = defers[0]._offset;
}
var defer, deferLength = 0, offset = 0;
for (var i = 0, l = bytes.length; i < l; i++) {
view.setUint8(deferWritten + i, bytes[i]);
if (i + 1 !== nextOffset) { continue; }
defer = defers[deferIndex];
deferLength = defer._length;
offset = deferWritten + nextOffset;
if (defer._bin) {
var bin = new Uint8Array(defer._bin);
for (var j = 0; j < deferLength; j++) {
view.setUint8(offset + j, bin[j]);
}
} else if (defer._str) {
utf8Write(view, offset, defer._str);
} else if (defer._float !== undefined) {
view.setFloat64(offset, defer._float);
}
deferIndex++;
deferWritten += deferLength;
if (defers[deferIndex]) {
nextOffset = defers[deferIndex]._offset;
}
}
return buf;
}
export { encode, decode }; | the_stack |
import { AnyShape, ArrayShape, BinaryShape, bool, boolean, BoolShape, CollectionShape, Fields, FunctionShape, literal, LiteralShape, map, MapShape, NeverShape, NothingShape, NumberShape, Pointer, set, SetShape, Shape, ShapeGuards, ShapeVisitor, string, StringShape, TimestampShape, Type, TypeClass, TypeShape, union, UnionShape } from '@punchcard/shape';
import { AttributeValue } from '@punchcard/shape-dynamodb';
import { VExpression } from './expression';
import { stash } from './statement';
import { StashProps } from './statement';
import { VTL, vtl } from './vtl';
import { VBinary, VBool, VFloat, VInteger, VList, VMap, VNever, VObject, VString, VTimestamp } from './vtl-object';
/**
* https://docs.aws.amazon.com/appsync/latest/devguide/resolver-util-reference.html
*/
export namespace $util {
export function validate(condition: VBool, message: VString | string, errorType?: VString | string): VTL<VNever> {
throw new Error('todo');
}
export function *autoId(): VTL<VString> {
// return yield new Statements.Set(value, id);
return yield* stash(new VString(VExpression.text('$util.autoId()')));
}
export function matches(str: VString, regex: RegExp | string): VBool {
return new VBool(VExpression.call('$util.matches', [
str,
typeof regex === 'string' ? regex : regex.source
]));
}
export function unauthorized(): VNever {
return new VNever(VExpression.text('$util.unauthorized()'));
}
/**
* Returns a String describing the type of the Object. Supported type identifications
* are: `Null`, `Number`, `String`, `Map`, `List`, `Boolean`. If a type cannot be
* identified, the return type is `Object`.
*/
export function typeOf<T extends VObject<Shape>>(obj: T): VString {
return new VString(VExpression.concat(
'$util.typeOf(', obj, ')'
));
}
// tslint:disable: unified-signatures
export function error(message: VString | string, errorType: VString | string, data: VObject, errorInfo: VObject): VNever;
export function error(message: VString | string, errorType: VString | string, data: VObject): VNever;
export function error(message: VString | string, errorType: VString | string): VNever;
export function error(message: VString | string): VNever;
/**
* @param message
* @see https://docs.aws.amazon.com/appsync/latest/devguide/resolver-util-reference.html
*/
export function error(message: VString | string, errorType?: VString | string, data?: VObject, errorInfo?: VObject): VNever {
return new VNever(call('$util.error', [
typeof message === 'string' ? `"${message}"` : message,
typeof errorType === 'string' ? `"${errorType}"` : errorType,
data,
errorInfo
]));
}
export function isNull(value: VObject): VBool {
return new VBool(new VExpression(state => state.write('$util.isNull(', value, ')')));
}
export function isNullOrEmpty(value: VObject): VBool {
return new VBool(new VExpression(state => state.write('$util.isNullOrEmpty(', value, ')')));
}
export function isNotNull(value: VObject): VBool {
return new VBool(new VExpression(state => state.write(`!$util.isNull(`, value, `)`)));
}
export function *defaultIfNull<T extends VObject>(obj: T, defaultValue: VObject.Like<VObject.TypeOf<T>>): VTL<T> {
const type = VObject.getType(obj);
const defaultV = yield* VObject.of(type, defaultValue);
return VObject.fromExpr(type, new VExpression(state => state.write(
'$util.defaultIfNull(', obj, ',', defaultV, ')'
))) as any;
}
}
function call(functionName: string, args: (string | VObject | undefined)[]) {
return new VExpression(state => {
const parameters = [];
for (const arg of args) {
if (arg === undefined) {
// we do this weird loop so we stop when we hit the first undefined parameter
// that's so we can support overloaded methods like `$util.error`.
break;
}
parameters.push(arg);
}
state.write(functionName, '(', ...parameters, ')');
});
}
export namespace $util.dynamodb {
/**
* General object conversion tool for DynamoDB that converts input objects to the appropriate
* DynamoDB representation. Unlike the built-in `$util.dynamodb.toDynamoDB` utility, the
* extended form supports sets.
*
* @param object value to convert to its DynamoDB encoding
*/
export function toDynamoDBExtended<T extends VObject>(object: T): VTL<VObject.Of<AttributeValue.ShapeOf<VObject.TypeOf<T>>>>;
export function toDynamoDBExtended<T extends Shape>(type: T, obj: VObject.Like<T>): VTL<VObject.Of<AttributeValue.ShapeOf<T>>>;
export function *toDynamoDBExtended(a: any, b?: any) {
const stashProps: StashProps = {
local: true // use local variables for intermediate stashes
};
const shape = ShapeGuards.isShape(a) ? a : VObject.getType(a);
const dynamoShape = AttributeValue.shapeOf(shape) as Shape;
const value: VObject.Like<Shape> = VObject.isObject(a) ? a : b;
if (!hasSet(shape) && VObject.isObject(value)) {
// if the object doesn't have any set types and is a reference, then use the built-in utility
return toDynamoDB(value);
}
if (ShapeGuards.isStringShape(shape) || ShapeGuards.isTimestampShape(shape)) {
return toString(value);
} else if (ShapeGuards.isNumberShape(shape)) {
return yield* vtl(dynamoShape, stashProps)`${toNumber(value)}`;
} else if (ShapeGuards.isBoolShape(shape)) {
return yield* vtl(dynamoShape, stashProps)`${toBoolean(value)}`;
} else if (ShapeGuards.isNothingShape(shape)) {
return yield* vtl(dynamoShape, stashProps)`${toNull()}`;
} else if (ShapeGuards.isArrayShape(shape)) {
return yield* toList(shape);
} else if (ShapeGuards.isMapShape(shape)) {
} else if (ShapeGuards.isArrayShape(shape)) {
return yield* toList(shape);
} else if (ShapeGuards.isSetShape(shape)) {
if (VObject.isList(value)) {
return ShapeGuards.isStringShape(shape.Items) || ShapeGuards.isTimestampShape(shape.Items) ? toStringSet(value as VList<VString>) :
ShapeGuards.isNumberShape(shape.Items) ? toNumberSet(value as VList<VInteger>) :
ShapeGuards.isBinaryShape(shape.Items) ? toBinarySet(value as VList<VBinary>) :
yield* toList(shape);
} else {
const tag =
ShapeGuards.isStringShape(shape.Items) || ShapeGuards.isTimestampShape(shape.Items) ? 'SS' :
ShapeGuards.isNumberShape(shape.Items) ? 'NS' :
ShapeGuards.isBinaryShape(shape.Items) ? 'BS' :
'L'
;
const set = yield* vtl(dynamoShape)`{${tag}:[]}`;
for (const item of value) {
yield* (set as any)[tag].add(yield* toDynamoDBExtended(shape.Items, item));
}
}
}
function *toList(shape: CollectionShape<Shape>) {
const list = yield* vtl(AttributeValue.List(AttributeValue.shapeOf(shape.Items)), stashProps)`{L: []}`;
if (VObject.isList(value)) {
yield* value.forEach(function*(item) {
yield* list.L.add(yield* toDynamoDBExtended(shape.Items, item));
});
} else {
for (const item of value) {
yield* list.L.add(yield* toDynamoDBExtended(shape.Items, item));
}
}
return list;
}
return null as any;
}
/**
* General object conversion tool for DynamoDB that converts input objects to the appropriate
* DynamoDB representation. It’s opinionated about how it represents some types: e.g., it will
* use lists (“L”) rather than sets (“SS”, “NS”, “BS”). This returns an object that describes
* the DynamoDB attribute value.
*
* @param object value to convert to its DynamoDB encoding
*/
export function toDynamoDB<T extends VObject>(object: T): VObject.Of<AppSyncDynamoDBFormat<VObject.TypeOf<T>>> {
return VObject.fromExpr(
appSyncDynamoDBFormat(VObject.getType(object)),
VExpression.call('$util.dynamodb.toDynamoDB', [object])
) as VObject.Of<AppSyncDynamoDBFormat<VObject.TypeOf<T>>>;
}
/**
* The same as $util.dynamodb.toDynamoDB(Object) : Map, but returns the DynamoDB attribute value
* as a JSON encoded string.
*
* @param object value to convert to its DynamoDB encoding
*/
export function toDynamoDBJson<T extends VObject>(object: T): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toDynamoDBJson', [object]));
}
/**
* Returns a null in DynamoDB null format. This returns an object that describes the DynamoDB attribute value.
* ```
* Input: $util.dynamodb.toNull()
* Output: { "NULL" : null }
* ```
*/
export function toNull(): VObject.Of<typeof AttributeValue.Nothing> {
return VObject.fromExpr(AttributeValue.Nothing, VExpression.call('$util.dynamodb.toNull', []));
}
/**
* The same as `$util.dynamodb.toNull`, but returns the DynamoDB attribute value as a JSON encoded string.
*/
export function toNullJson(): VString {
return new VString(VExpression.call('$util.dynamodb.toNullJson', []));
}
/**
* Converts a boolean to the appropriate DynamoDB boolean format. This returns an object that describes the DynamoDB attribute value.
* ```
* Input: $util.dynamodb.toBoolean(true)
* Output: { "BOOL" : true }
* ```
* @param bool to convert to a DynamoDB BOOL object.
*/
export function toBoolean(bool: VBool | boolean): VObject.Of<typeof AttributeValue.Bool> {
return VObject.fromExpr(AttributeValue.Bool, VExpression.call('$util.dynamodb.toBoolean', [typeof bool === 'boolean' ? bool.toString() : bool]));
}
/**
* The same as `$util.dynamodb.toBoolean`, but returns the DynamoDB attribute value as a JSON encoded string.
*
* @param bool to convert to a DynamoDB BOOL object.
*/
export function toBooleanJson(bool: VBool): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toBooleanJson', [typeof bool === 'boolean' ? `${bool}` : bool]));
}
/**
* Converts binary data encoded as a base64 string to DynamoDB binary format. This returns an object that describes the DynamoDB attribute value.
* ```
* Input: $util.dynamodb.toBinary("foo")
* Output: { "B" : "foo" }
* ```
* @param string to convert to a DynamoDB binary object.
*/
export function toBinary(string: VString | string): VObject.Of<typeof AttributeValue.Binary> {
return VObject.fromExpr(AttributeValue.Binary, VExpression.call('$util.dynamodb.toBinary', [string]));
}
/**
* The same as `$util.dynamodb.toBinary`, but returns the DynamoDB attribute value as a JSON encoded string.
*
* @param str to convert to a DynamoDB binary object JSON string.
*/
export function toBinaryJson(str: VString | string): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toBinaryJson', [str]));
}
/**
* Converts a list of binary data encoded as base64 strings to DynamoDB binary set format. This returns an object that describes the DynamoDB attribute value.
* ```
* Input: $util.dynamodb.toBinarySet([ "foo", "bar", "baz" ])
* Output: { "BS" : [ "foo", "bar", "baz" ] }
* ```
* @param list of strings to convert to a DynamoDB binary set.
*/
export function toBinarySet(list: VList<VString> | VList<VBinary>): VObject.Of<typeof AttributeValue.BinarySet> {
return VObject.fromExpr(AttributeValue.BinarySet, VExpression.call('$util.dynamodb.toBinarySet', [list]));
}
/**
* The same as `$util.dynamodb.toBinarySet`, but returns the DynamoDB attribute value as a JSON encoded string.
*
* @param list of strings to convert to a DynamoDB binary set.
*/
export function toBinarySetJson(list: VList<VString> | VList<VBinary>): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toBinarySet', [list]));
}
/**
* Converts a number to the DynamoDB number format. This returns an object that describes the DynamoDB attribute value.
* ```
* Input: $util.dynamodb.toNumber(12345)
* Output: { "N" : 12345 }
* ```
* @param number to convert to a DynamoDB number object.
*/
export function toNumber(number: VInteger | VFloat | number): VObject.Of<typeof AttributeValue.Number> {
return VObject.fromExpr(AttributeValue.Number, VExpression.call('$util.dynamodb.toNumber', [number]));
}
/**
* The same as `$util.dynamodb.toNumber`, but returns the DynamoDB attribute value as a JSON encoded string.
* @param number to convert to a DynamoDB number object.
*/
export function toNumberJson(number: VInteger | VFloat | number): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toNumberJson', [number]));
}
/**
* Converts a list of numbers to the DynamoDB number set format. This returns an object that describes the DynamoDB attribute value.
*
* ```
* Input: $util.dynamodb.toNumberSet([ 1, 23, 4.56 ])
* Output: { "NS" : [ 1, 23, 4.56 ] }
* ```
* @param list of numbers to convert to a DynamoDB number set.
*/
export function toNumberSet(list: VList<VInteger>): VObject.Of<typeof AttributeValue.NumberSet> {
return VObject.fromExpr(AttributeValue.NumberSet, VExpression.call('$util.dynamodb.toNumberSet', [list]));
}
/**
* The same as `$util.dynamodb.toNumberSet`, but returns the DynamoDB attribute value as a JSON encoded string.
*
* @param list of numbers to convert to a DynamoDB number set JSON string.
*/
export function toNumberSetJson(value: VList<VInteger>): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toNumberSetJson', [value]));
}
/**
* Convert an input string to the DynamoDB string format. This returns an object that describes the DynamoDB attribute value.
*
* ```
* Input: $util.dynamodb.toString("foo")
* Output: { "S" : "foo" }
* ```
* @param value string to convert into a DynamoDB string object.
*/
export function toString(value: VString | string): VObject.Of<typeof AttributeValue.String> {
return VObject.fromExpr(AttributeValue.String, VExpression.call('$util.dynamodb.toString', [value]));
}
/**
* The same as `$util.dynamodb.toString(String)`, but returns the DynamoDB attribute value as a JSON encoded string.
*
* @param value string to convert into a DynamoDB string object JSON string.
*/
export function toStringJson(value: VString): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toStringJson', [value]));
}
/**
* Converts a lists with Strings to the DynamoDB string set format. This returns an object that describes the DynamoDB attribute value.
* ```
* Input: $util.dynamodb.toStringSet([ "foo", "bar", "baz" ])
* Output: { "SS" : [ "foo", "bar", "baz" ] }
* ```
* @param list list of strings to convert to a DynamoDB string set.
*/
export function toStringSet(list: VList<VString | VTimestamp>): VObject.Of<typeof AttributeValue.StringSet> {
return VObject.fromExpr(AttributeValue.StringSet, VExpression.call('$util.dynamodb.toStringSet', [list]));
}
/**
* The same as `$util.dynamodb.toStringSet`, but returns the DynamoDB attribute value as a JSON encoded string.
*
* @param list list of strings to convert to a DynamoDB string set JSON string.
*/
export function toStringSetJson(list: VList<VString>): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toStringSetJson', [list]));
}
/**
* Converts a list of object to DynamoDB list format. Each item in the list is also converted to
* its appropriate DynamoDB format. It’s opinionated about how it represents some of the nested
* objects: e.g., it will use lists (`L`) rather than sets (`SS`, `NS`, `BS`). This returns an
* object that describes the DynamoDB attribute value.
*
* ```
* Input: $util.dynamodb.toList([ "foo", 123, { "bar" : "baz" } ])
* Output:
* {
* "L" : [
* { "S" : "foo" },
* { "N" : 123 },
* {
* "M" : {
* "bar" : { "S" : "baz" }
* }
* }
* ]
* }
* ```
* @param list to convert to a DynamoDB list object.
*/
export function toList<T extends VObject>(list: VList<T>): VObject.Of<AttributeValue.List<AppSyncDynamoDBFormat<VObject.TypeOf<T>>>> {
return VObject.fromExpr(
appSyncDynamoDBFormat(VObject.getType(list)),
VExpression.call('$util.dynamodb.toList', [list])
) as VObject.Of<AttributeValue.List<AppSyncDynamoDBFormat<VObject.TypeOf<T>>>>;
}
/**
* The same as `$util.dynamodb.toList`, but returns the DynamoDB attribute value as a JSON encoded string.
*
* @param list to convert to a DynamoDB list object JSON string.
*/
export function toListJson<T extends VObject>(list: VList<T>): VString {
return VObject.fromExpr(string, VExpression.call('$util.dynamodb.toListJson', [list]));
}
/**
* Converts a map to DynamoDB map format. Each value in the map is also converted to its
* appropriate DynamoDB format. It’s opinionated about how it represents some of the nested
* objects: e.g., it will use lists (`L`) rather than sets (`SS`, `NS`, `BS`). This returns an
* object that describes the DynamoDB attribute value.
*
* ```
* Input: $util.dynamodb.toMap({ "foo": "bar", "baz" : 1234, "beep": [ "boop"] })
* Output: {
* "M" : {
* "foo" : { "S" : "bar" },
* "baz" : { "N" : 1234 },
* "beep" : {
* "L" : [
* { "S" : "boop" }
* ]
* }
* }
* }
* ```
* @param map to convert to a DynamoDB map.
*/
export function toMap<T extends VObject>(map: VMap<T>): VObject.Of<AttributeValue.Map<AppSyncDynamoDBFormat<VObject.TypeOf<T>>>> {
return VObject.fromExpr(
appSyncDynamoDBFormat(VObject.getType(map)),
VExpression.call('$util.dynamodb.toMap', [map])
) as VObject.Of<AttributeValue.Map<AppSyncDynamoDBFormat<VObject.TypeOf<T>>>>;
}
/**
* The same as `$util.dynamodb.toMap`, but returns the DynamoDB attribute value as a JSON encoded string.
* @param map to convert to a DynamoDB map.
*/
export function toMapJson<T extends VObject>(map: VMap<T>): VString {
return new VString(VExpression.call('$util.dynamodb.toMapJson', [map]));
}
/**
* AppSync is opinionated about how it represents some types: e.g., it will
* use lists (“L”) rather than sets (“SS”, “NS”, “BS”). This returns an object that describes
* the DynamoDB attribute value.
*/
type AppSyncDynamoDBFormat<T extends Shape> = AttributeValue.ShapeOf<T, {
setAsList: true
}>;
function appSyncDynamoDBFormat<T extends Shape>(shape: T): AppSyncDynamoDBFormat<T> {
return AttributeValue.shapeOf(shape, {
// AppSync's built-in toDynamoDB utility treats all sets as lists ... :(
setAsList: true
} as const) as any as AppSyncDynamoDBFormat<T>;
}
/**
* Converts a Shape to its DynamoDB representation.
*
* According to the opinonated approach of `$util.dynamodb.toDynamoDB`
*
* @see https://docs.aws.amazon.com/appsync/latest/devguide/resolver-util-reference.html
*/
export type ToDynamoDBJson<T extends Shape> =
T extends AnyShape ? AttributeValue :
T extends BoolShape ? typeof AttributeValue.Bool :
T extends NothingShape ? typeof AttributeValue.Nothing :
T extends NumberShape ? typeof AttributeValue.Number :
T extends StringShape ? typeof AttributeValue.String :
T extends TimestampShape ? typeof AttributeValue.String :
T extends BinaryShape ? typeof AttributeValue.Binary :
T extends SetShape<infer I> ? AttributeValue.List<ToDynamoDBJson<I>> :
T extends ArrayShape<infer I> ? AttributeValue.List<ToDynamoDBJson<I>> :
T extends MapShape<infer V> ? AttributeValue.Map<ToDynamoDBJson<V>> :
T extends TypeShape<infer M> ? AttributeValue.Struct<{
[m in keyof M]: ToDynamoDBJson<M[m]>;
}> :
AttributeValue // <- never?
;
}
export namespace $util.time {
export function *nowISO8601(): VTL<VTimestamp> {
return yield* stash(new VTimestamp(VExpression.text('$util.time.nowISO8601()')));
}
export function *nowEpochSeconds() : VTL<VInteger> {
return yield* stash(new VInteger(VExpression.text('$util.time.nowISO8601()')));
}
export function *nowEpochMilliSeconds() : VTL<VInteger> {
return yield* stash(new VInteger(VExpression.text('$util.time.nowEpochMilliSeconds()')));
}
export function *nowFormatted(format: VString) : VTL<VString> {
return yield* stash(new VString(VExpression.concat(
VExpression.text('$util.time.nowFormatted('),
format,
VExpression.text(')')
)));
}
// export function parseFormattedToEpochMilliSeconds(VString, VString) : VTL<VInteger> {
// }
// export function parseFormattedToEpochMilliSeconds(VString, VString, VString) : VTL<VInteger> {
// }
export function parseISO8601ToEpochMilliSeconds(s: VTL<VString>) : VTL<VInteger> {
throw new Error('not implemented');
}
// export function epochMilliSecondsToSeconds(VInteger) : VTL<VInteger> {
// throw new Error('not implemented');
// }
// export function epochMilliSecondsToISO8601(VInteger) : VTL<VString> {
// throw new Error('not implemented');
// }
// export function epochMilliSecondsToFormatted(VInteger, VString) : VTL<VString> {
// throw new Error('not implemented');
// }
// export function epochMilliSecondsToFormatted(VInteger, VString, VString) : VTL<VString> {
// throw new Error('not implemented');
// }
}
type _HasSet<T extends Shape> =
T extends SetShape<any> ? true :
T extends TypeShape<infer F> ? Extract<{
[f in keyof F]: HasSet<F[f]>
}[keyof F], boolean> :
T extends CollectionShape<infer I> ? Extract<{
[i in keyof I]: HasSet<I>
}[keyof I], boolean> :
T extends UnionShape<infer I> ? Extract<{
[i in Extract<keyof I, number>]: HasSet<I[i]>;
}[Extract<keyof I, number>], boolean> :
false
;
export type HasSet<T extends Shape> =
true extends _HasSet<T> ? true :
false
;
function hasSet<T extends Shape>(shape: T): HasSet<T> {
if (ShapeGuards.isSetShape(shape)) {
return true as HasSet<T>;
} else if (ShapeGuards.isRecordShape(shape)) {
return (Object.values(shape.Members).find(m => hasSet(m)) !== undefined) as HasSet<T>;
} else if (ShapeGuards.isCollectionShape(shape)) {
return hasSet(shape.Items) as HasSet<T>;
} else if (ShapeGuards.isUnionShape(shape)) {
return (shape.Items.find(i => hasSet(i)) !== undefined) as HasSet<T>;
}
return false as HasSet<T>;
} | the_stack |
import MutableMatrix33 from './MutableMatrix33';
import MutableVector3 from './MutableVector3';
import {Count, Size} from '../../types/CommonTypes';
function radianToDegree(rad: number) {
return (rad * 180) / Math.PI;
}
function degreeToRadian(deg: number) {
return (deg * Math.PI) / 180;
}
// https://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
const toHalfFloat = () => {
/* This method is faster than the OpenEXR implementation (very often
* used, eg. in Ogre), with the additional benefit of rounding, inspired
* by James Tursa?s half-precision code. */
return function toHalf(val: number) {
const floatView = new Float32Array(1);
const int32View = new Int32Array(floatView.buffer);
floatView[0] = val;
const x = int32View[0];
let bits = (x >> 16) & 0x8000; /* Get the sign */
let m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
const e = (x >> 23) & 0xff; /* Using int is faster here */
/* If zero, or denormal, or exponent underflows too much for a denormal
* half, return signed zero. */
if (e < 103) {
return bits;
}
/* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
if (e > 142) {
bits |= 0x7c00;
/* If exponent was 0xff and one mantissa bit was set, it means NaN,
* not Inf, so make sure we set one mantissa bit too. */
bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
return bits;
}
/* If exponent underflows but not too much, return a denormal */
if (e < 113) {
m |= 0x0800;
/* Extra rounding may overflow and set mantissa to 0 and exponent
* to 1, which is OK. */
bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
return bits;
}
bits |= ((e - 112) << 10) | (m >> 1);
/* Extra rounding. An overflow will set mantissa to 0 and increment
* the exponent, which is OK. */
bits += m & 1;
return bits;
};
};
/**
* check whether or not this texture size is power of two.
*
* @param x texture size.
* @returns check whether or not the size x is power of two.
*/
function isPowerOfTwo(x: number): boolean {
return (x & (x - 1)) == 0;
}
function isPowerOfTwoTexture(width: Size, height: Size) {
return isPowerOfTwo(width) && isPowerOfTwo(height);
}
// values range must be [-1, 1]
function packNormalizedVec4ToVec2(
x: number,
y: number,
z: number,
w: number,
criteria: number
) {
// range to [0, s1]
x = (x + 1) / 2.0;
y = (y + 1) / 2.0;
z = (z + 1) / 2.0;
w = (w + 1) / 2.0;
const ir = Math.floor(x * (criteria - 1.0));
const ig = Math.floor(y * (criteria - 1.0));
const irg = ir * criteria + ig;
const v0 = irg / criteria;
const ib = Math.floor(z * (criteria - 1.0));
const ia = Math.floor(w * (criteria - 1.0));
const iba = ib * criteria + ia;
const v1 = iba / criteria;
return [v0, v1];
}
function erf(x: number) {
// Save the sign of x
let sign = 1;
if (x < 0) sign = -1;
x = Math.abs(x);
// A&S formula 7.1.26
const t: number = 1 / (1 + 0.3275911 * x);
const y: number =
1 -
((((1.061405429 * t + -1.453152027) * t + 1.421413741) * t + -0.284496736) *
t +
0.254829592) *
t *
Math.exp(-x * x);
return sign * y;
}
function invErf(x: number) {
let w: number,
p = 0;
w = -Math.log((1.0 - x) * (1.0 + x));
if (w < 5.0) {
w = w - 2.5;
p = 2.81022636e-8;
p = 3.43273939e-7 + p * w;
p = -3.5233877e-6 + p * w;
p = -4.39150654e-6 + p * w;
p = 0.00021858087 + p * w;
p = -0.00125372503 + p * w;
p = -0.00417768164 + p * w;
p = 0.246640727 + p * w;
p = 1.50140941 + p * w;
} else {
w = Math.sqrt(w) - 3;
p = -0.000200214257;
p = 0.000100950558 + p * w;
p = 0.00134934322 + p * w;
p = -0.00367342844 + p * w;
p = 0.00573950773 + p * w;
p = -0.0076224613 + p * w;
p = 0.00943887047 + p * w;
p = 1.00167406 + p * w;
p = 2.83297682 + p * w;
}
return p * x;
}
function gaussianCdf(x: number, mu: number, sigma: number) {
const U: number = 0.5 * (1 + erf((x - mu) / (sigma * Math.sqrt(2.0))));
return U;
}
function invGaussianCdf(U: number, mu: number, sigma: number) {
const x: number = sigma * Math.sqrt(2.0) * invErf(2.0 * U - 1) + mu;
return x;
}
function computeEigenValuesAndVectors(
A: MutableMatrix33,
Q: MutableMatrix33,
w: MutableVector3
) {
const n = 3;
let sd = 0;
let so = 0; // Sums of diagonal resp. off-diagonal elements
let s = 0;
let c = 0;
let t = 0; // sin(phi), cos(phi), tan(phi) and temporary storage
let g = 0;
let h = 0;
let z = 0;
let theta = 0; // More temporary storage
let thresh = 0;
// Initialize Q to the identitity matrix
for (let i = 0; i < n; i++) {
Q.setAt(i, i, 1.0);
for (let j = 0; j < i; j++) {
Q.setAt(i, j, 0.0);
Q.setAt(j, i, 0.0);
}
}
// Initialize w to diag(A)
for (let i = 0; i < n; i++) w.setAt(i, A.at(i, i));
// Calculate SQR(tr(A))
sd = 0.0;
for (let i = 0; i < n; i++) sd += Math.abs(w.at(i));
sd = sd * sd;
// Main iteration loop
for (let nIter = 0; nIter < 50; nIter++) {
// Test for convergence
so = 0.0;
for (let p = 0; p < n; p++) {
for (let q = p + 1; q < n; q++) so += Math.abs(A.at(p, q));
}
if (so == 0.0) return 0;
if (nIter < 4) thresh = (0.2 * so) / (n * n);
else thresh = 0.0;
// Do sweep
for (let p = 0; p < n; p++) {
for (let q = p + 1; q < n; q++) {
g = 100.0 * Math.abs(A.at(p, q));
if (
nIter > 4 &&
Math.abs(w.at(p)) + g == Math.abs(w.at(p)) &&
Math.abs(w.at(q)) + g == Math.abs(w.at(q))
) {
A.setAt(p, q, 0.0);
} else if (Math.abs(A.at(p, q)) > thresh) {
// Calculate Jacobi transformation
h = w.at(q) - w.at(p);
if (Math.abs(h) + g == Math.abs(h)) {
t = A.at(p, q) / h;
} else {
theta = (0.5 * h) / A.at(p, q);
if (theta < 0.0)
t = -1.0 / (Math.sqrt(1.0 + theta * theta) - theta);
else t = 1.0 / (Math.sqrt(1.0 + theta * theta) + theta);
}
c = 1.0 / Math.sqrt(1.0 + t * t);
s = t * c;
z = t * A.at(p, q);
// Apply Jacobi transformation
A.setAt(p, q, 0.0);
w.setAt(p, w.at(p) - z);
w.setAt(q, w.at(q) + z);
for (let r = 0; r < p; r++) {
t = A.at(r, p);
A.setAt(r, p, c * t - s * A.at(r, q));
A.setAt(r, q, s * t + c * A.at(r, q));
}
for (let r = p + 1; r < q; r++) {
t = A.at(p, r);
A.setAt(p, r, c * t - s * A.at(r, q));
A.setAt(r, q, s * t + c * A.at(r, q));
}
for (let r = q + 1; r < n; r++) {
t = A.at(p, r);
A.setAt(p, r, c * t - s * A.at(q, r));
A.setAt(q, r, s * t + c * A.at(q, r));
}
// Update eigenvectors
for (let r = 0; r < n; r++) {
t = Q.at(r, p);
Q.setAt(r, p, c * t - s * Q.at(r, q));
Q.setAt(r, q, s * t + c * Q.at(r, q));
}
}
}
}
}
return -1;
}
function convertToStringAsGLSLFloat(value: number): string {
if (Number.isInteger(value)) {
return `${value}.0`;
} else {
return '' + value;
}
}
function nearZeroToZero(value: number): number {
if (Math.abs(value) < 0.00001) {
value = 0;
} else if (0.99999 < value && value < 1.00001) {
value = 1;
} else if (-1.00001 < value && value < -0.99999) {
value = -1;
}
return value;
}
function financial(val: number|string) {
const fixedStr = Number.parseFloat(val as string).toFixed(7);
if (val >= 0) {
return ' ' + fixedStr;
}
return fixedStr;
}
function roundAsFloat(value: number): number {
return Math.round(value*10000000) / 10000000;
}
/**
* This function calculates the ratio of a discrete Gaussian distribution.
* The sampling points are one away from each other. The sum of the ratios is 1.
* @kernelSize number of sampling points
* @variance variance of the Gaussian distribution
* @mean mean of the Gaussian distribution
* e.g. kernelSize = 2 (mean=0) => the sampling points are -0.5 and 0.5
* e.g. kernelSize = 3 (mean=1) => the sampling points are 0.0, 1.0 and 2.0
* @effectiveDigit effectiveDigit of values in return array
* @returns array of the Gaussian distribution where the sum of the elements is 1
*/
function computeGaussianDistributionRatioWhoseSumIsOne({
kernelSize,
variance,
mean = 0,
effectiveDigit = 4,
}: {
kernelSize: Count;
variance: number;
mean?: number;
effectiveDigit?: Count;
}) {
const ceiledHalfKernelSize = Math.ceil(kernelSize / 2.0);
const gaussianDistributionRatio: number[] = new Array(ceiledHalfKernelSize);
let totalSize = 0;
// above mean side and center
for (let i = 0; i < ceiledHalfKernelSize; i++) {
gaussianDistributionRatio[i] = Math.exp(
-((i - mean) ** 2) / (2.0 * variance)
);
totalSize += gaussianDistributionRatio[i];
}
// below mean side
totalSize *= 2;
// if a center exists
if ((kernelSize / 2.0) % 2 !== 0.0) {
totalSize -= gaussianDistributionRatio[0];
}
const gaussianDistributionRatioWhoseSumIsOne = new Array(kernelSize);
let totalRatio = 0;
const changeDigitParam = Math.pow(10, effectiveDigit);
for (let i = 0; i < ceiledHalfKernelSize - 1; i++) {
let ratio =
gaussianDistributionRatio[ceiledHalfKernelSize - 1 - i] / totalSize;
ratio *= changeDigitParam;
ratio = Math.round(ratio);
ratio /= changeDigitParam;
gaussianDistributionRatioWhoseSumIsOne[i] = ratio;
gaussianDistributionRatioWhoseSumIsOne[kernelSize - 1 - i] = ratio;
totalRatio += 2 * ratio;
}
if (kernelSize % 2 === 0) {
const value = (1 - totalRatio) / 2.0;
gaussianDistributionRatioWhoseSumIsOne[ceiledHalfKernelSize - 1] = value;
gaussianDistributionRatioWhoseSumIsOne[ceiledHalfKernelSize] = value;
} else {
const value = 1 - totalRatio;
gaussianDistributionRatioWhoseSumIsOne[ceiledHalfKernelSize - 1] = value;
}
return gaussianDistributionRatioWhoseSumIsOne;
}
export const MathUtil = Object.freeze({
radianToDegree,
degreeToRadian,
toHalfFloat,
isPowerOfTwo,
isPowerOfTwoTexture,
packNormalizedVec4ToVec2,
convertToStringAsGLSLFloat,
nearZeroToZero,
gaussianCdf,
invGaussianCdf,
computeEigenValuesAndVectors,
computeGaussianDistributionRatioWhoseSumIsOne,
roundAsFloat,
financial
}); | the_stack |
import chalk from "chalk";
import * as readline from "readline";
import * as path from "path";
import { AssemblyFlavor, DEFAULT_TIMEOUT, workflowBSQCheck, workflowBSQInfeasibleSingle, workflowBSQWitnessSingle, workflowEmitToFile, workflowEvaluateSingle, workflowGetErrors, workflowInvertSingle, workflowLoadUserSrc } from "../tooling/verifier/smt_workflows";
import { VerifierOptions } from "../tooling/verifier/smt_exp";
function parseLocation(location: string): { file: string, line: number, pos: number } | undefined {
try {
const errfile = location.slice(0, location.indexOf("@"));
const errline = Number.parseInt(location.slice(location.indexOf("@") + 1, location.indexOf("#")));
const errpos = Number.parseInt(location.slice(location.indexOf("#") + 1));
return { file: errfile, line: errline, pos: errpos };
}
catch (ex) {
return undefined;
}
}
const mode = process.argv[2];
const args = process.argv.slice(3);
const vopts_unreachable = {
ISize: 8,
StringOpt: "ASCII",
EnableCollection_SmallHavoc: false,
EnableCollection_LargeHavoc: true,
EnableCollection_SmallOps: true,
EnableCollection_LargeOps: true
} as VerifierOptions;
const vopts_smallwitness = {
ISize: 5,
StringOpt: "ASCII",
EnableCollection_SmallHavoc: true,
EnableCollection_LargeHavoc: false,
EnableCollection_SmallOps: true,
EnableCollection_LargeOps: false
} as VerifierOptions;
const vopts_largewitness = {
ISize: 8,
StringOpt: "ASCII",
EnableCollection_SmallHavoc: true,
EnableCollection_LargeHavoc: true,
EnableCollection_SmallOps: true,
EnableCollection_LargeOps: true
} as VerifierOptions;
const vopts_evaluate = {
ISize: 8,
StringOpt: "ASCII",
EnableCollection_SmallHavoc: true,
EnableCollection_LargeHavoc: true,
EnableCollection_SmallOps: true,
EnableCollection_LargeOps: true
} as VerifierOptions;
const error_vopts = {
ISize: 64,
StringOpt: "ASCII",
EnableCollection_SmallHavoc: false,
EnableCollection_LargeHavoc: true,
EnableCollection_SmallOps: false,
EnableCollection_LargeOps: true
} as VerifierOptions;
if(mode === "--output") {
let smtmode = args[0];
if(smtmode !== "unreachable" && smtmode !== "smallwitness" && smtmode !== "largewitness" && smtmode !== "evaluate" && smtmode !== "invert") {
process.stdout.write("Valid mode options are unreachable | witness | evaluate | invert\n");
process.exit(1);
}
const smtonly = args[1] === "--smt";
const location = (smtmode !== "evaluate") ? parseLocation(args[smtonly ? 2 : 1]) : {file: "[ignore]", line: -1, pos: -1};
let files = (smtmode !== "evaluate") ? args.slice(smtonly ? 3 : 2) : args.slice(smtonly ? 2 : 1);
if(location === undefined) {
process.stdout.write("Location should be of the form file.bsq@line#pos\n");
process.exit(1);
}
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
const fparse = path.parse(files[0]);
const into = path.join(fparse.dir, fparse.name + (smtonly ? ".smt2" : ".json"));
process.stdout.write(`Writing file to ${into}\n`);
const asmflavor = smtmode === "unreachable" ? AssemblyFlavor.UFOverApproximate : AssemblyFlavor.RecuriveImpl;
let vopts = vopts_evaluate;
let mmode: "unreachable" | "witness" | "evaluate" | "invert" = "evaluate"
if(smtmode === "unreachable") {
vopts = vopts_unreachable;
mmode = "unreachable";
}
else if(smtmode === "smallwitness") {
vopts = vopts_smallwitness;
mmode = "witness";
}
else if(smtmode === "largewitness") {
vopts = vopts_largewitness;
mmode = "witness";
}
else {
if(smtmode === "invert") {
mmode = "invert";
}
}
workflowEmitToFile(into, usercode, asmflavor, mmode, DEFAULT_TIMEOUT, vopts, location, "NSMain::main", smtonly)
}
else if(mode === "--unreachable") {
const location = parseLocation(args[0]);
if(location === undefined) {
process.stderr.write("Location should be of the form file.bsq@line#pos\n");
process.exit(1);
}
const files = args.slice(1);
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
workflowBSQInfeasibleSingle(usercode, vopts_unreachable, DEFAULT_TIMEOUT, location, "NSMain::main", (res: string) => {
process.stdout.write(res + "\n");
});
}
else if(mode === "--smallwitness") {
const location = parseLocation(args[0]);
if(location === undefined) {
process.stderr.write("Location should be of the form file.bsq@line#pos\n");
process.exit(1);
}
const files = args.slice(1);
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
workflowBSQWitnessSingle(usercode, vopts_smallwitness, DEFAULT_TIMEOUT, location, "NSMain::main", (res: string) => {
process.stdout.write(res + "\n");
});
}
else if(mode === "--largewitness") {
const location = parseLocation(args[0]);
if(location === undefined) {
process.stderr.write("Location should be of the form file.bsq@line#pos\n");
process.exit(1);
}
const files = args.slice(1);
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
workflowBSQWitnessSingle(usercode, vopts_largewitness, DEFAULT_TIMEOUT, location, "NSMain::main", (res: string) => {
process.stdout.write(res + "\n");
});
}
else if(mode === "--check") {
const printprocess = (args[0] === "--verbose");
const quiet = (args[0] === "--quiet");
const files = args.slice((printprocess || quiet) ? 1 : 0);
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
const errors = workflowGetErrors(usercode, error_vopts, "NSMain::main");
if(errors === undefined) {
process.stdout.write("Failed to load error lines\n");
process.exit(1);
}
if(errors.length === 0) {
process.stdout.write(chalk.green("No errors are possible in this program!\n"));
process.exit(0);
}
process.stdout.write(chalk.bold(`Analyzing ${errors.length} possible error(s) in program...\n`));
//
//TODO: we probably want to make this a process parallel process
//
let icount = 0;
let wcount = 0;
let pcount = 0;
let ecount = 0;
let fcount = 0;
let witnesslist: {msg: string, position: string, input: any[]}[] = [];
for(let i = 0; i < errors.length; ++i) {
if(!quiet) {
process.stdout.write(`Checking error ${errors[i].msg} at ${errors[i].file}@${errors[i].line}#${errors[i].pos}...\n`);
}
const jres = workflowBSQCheck(usercode, DEFAULT_TIMEOUT, errors[i], "NSMain::main", printprocess);
if(jres === undefined) {
if(!quiet) {
process.stdout.write(chalk.red(`Failed with internal errors :(\n`));
}
fcount++;
}
else if(jres.result === "unreachable") {
if(!quiet) {
process.stdout.write(chalk.green(`Proved unreachable in ${jres.time}s!\n`));
}
icount++;
}
else if(jres.result === "witness") {
if(!quiet) {
process.stdout.write(chalk.magenta(`Generated witness input in ${jres.time}s!\n`));
//process.stdout.write(`${jres.input}\n`);
}
wcount++;
witnesslist.push({msg: errors[i].msg, position: `line ${errors[i].line} in ${errors[i].file}`, input: jres.input});
}
else if(jres.result === "partial") {
if(!quiet) {
process.stdout.write(chalk.blue(`Proved unreachable on partial space.\n`));
}
pcount++;
}
else if(jres.result === "nosmall") {
if(!quiet) {
process.stdout.write(chalk.blue(`No errors possible on partial space.\n`));
}
pcount++;
}
else {
if(!quiet) {
process.stdout.write(`Exhausted resource bounds without finding failures.\n`);
}
ecount++;
}
}
if(fcount !== 0) {
process.stdout.write(chalk.yellow(`Failed on ${fcount} error(s)!\n`));
}
if(icount !== 0) {
process.stdout.write(chalk.green(`Proved ${icount} error(s) unreachable on all executions!\n`));
}
if(wcount !== 0) {
process.stdout.write(chalk.red(`Found failing inputs for ${wcount} error(s)!\n`));
for(let i = 0; i < witnesslist.length; ++i) {
process.stdout.write(`${witnesslist[i].msg} -- ${witnesslist[i].position}\n`);
process.stdout.write(JSON.stringify(witnesslist[i].input, undefined, 2) + "\n");
}
}
if(pcount !== 0) {
process.stdout.write(chalk.blue(`Proved ${pcount} error(s) unreachable on a subset of excutions (and found no failing inputs)!\n`));
}
if(ecount !== 0) {
process.stdout.write(chalk.blue(`Exhausted search on ${ecount} error(s) and found no failing inputs.\n`));
}
}
else if(mode === "--evaluate") {
const files = args;
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(">> ", (input) => {
try {
const jinput = JSON.parse(input) as any[];
workflowEvaluateSingle(usercode, jinput, vopts_evaluate, DEFAULT_TIMEOUT, "NSMain::main", (res: string) => {
try {
const jres = JSON.parse(res);
if (jres["result"] === "unreachable") {
process.stdout.write(`No valid (non error) result exists for this input!\n`);
}
else if (jres["result"] === "output") {
process.stdout.write(`Generated output in ${jres["time"]} millis!\n`);
process.stdout.write(JSON.stringify(jres["output"], undefined, 2) + "\n");
}
else if (jres["result"] === "timeout") {
process.stdout.write(`Solver timeout :(\n`);
}
else {
process.stdout.write(`Failed with -- ${JSON.stringify(jres)}`);
}
process.exit(0);
}
catch (ex) {
process.stderr.write(`Failure ${ex}\n`);
process.exit(1);
}
});
}
catch (ex) {
process.stderr.write(`Failure ${ex}\n`);
process.exit(1);
}
});
}
else if(mode === "--invert") {
const files = args;
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(">> ", (input) => {
try {
const joutput = JSON.parse(input);
workflowInvertSingle(usercode, joutput, vopts_evaluate, DEFAULT_TIMEOUT, "NSMain::main", (res: string) => {
try {
const jres = JSON.parse(res);
if (jres["result"] === "unreachable") {
process.stdout.write(`No valid (non error) input exists for this output!\n`);
}
else if (jres["result"] === "witness") {
process.stdout.write(`Generated candidate input in ${jres["time"]} millis!\n`);
process.stdout.write(JSON.stringify(jres["input"], undefined, 2) + "\n");
}
else if (jres["result"] === "timeout") {
process.stdout.write(`Solver timeout :(\n`);
}
else {
process.stdout.write(`Failed with -- ${jres}`);
}
process.exit(0);
}
catch (ex) {
process.stderr.write(`Failure ${ex}\n`);
process.exit(1);
}
});
}
catch (ex) {
process.stderr.write(`Failure ${ex}\n`);
process.exit(1);
}
});
}
else {
const files = args;
const usercode = workflowLoadUserSrc(files);
if(usercode === undefined) {
process.stdout.write("Could not load code files\n");
process.exit(1);
}
const errors = workflowGetErrors(usercode, error_vopts, "NSMain::main");
if(errors === undefined) {
process.stderr.write("Failed to load error lines\n");
process.exit(1);
}
process.stdout.write("Possible Errors:\n");
process.stdout.write(JSON.stringify(errors, undefined, 2) + "\n");
} | the_stack |
import { assert } from "chai";
import { QuantityError } from "../Exception";
import { Format } from "../Formatter/Format";
import { DecimalPrecision, FormatTraits } from "../Formatter/FormatEnums";
import { FormatProps } from "../Formatter/Interfaces";
import { TestUnitsProvider } from "./TestUtils/TestHelper";
describe("Formatting tests:", () => {
it("A valid 'string' Type is required", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel", "fractionDash"],
precision: 8,
type: "badType",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'type' attribute.`);
});
});
it("Precision is required", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel"],
type: "Decimal",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test does not have the required 'precision' attribute.`);
});
});
it("Precision (int number) is required", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 8.8,
type: "Decimal",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'precision' attribute. It should be an integer.`);
});
});
it("Precision (int number < 12) is required", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 13,
type: "Decimal",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The 'precision' attribute must be an integer in the range 0-12.`);
});
});
it("Bad Show sign option", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 8,
type: "Decimal",
showSignOption: "bad",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'showSignOption' attribute.`);
});
});
it("Bad fractional precision", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 0,
type: "Fractional",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'precision' attribute.`);
});
});
it("Bad format trait", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["test"],
precision: 12,
type: "Decimal",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `Format has an invalid 'formatTraits' option.`);
});
});
it("Good round factor", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: [],
precision: 12,
type: "Decimal",
uomSeparator: " ",
roundFactor: 0.5,
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch(() => { });
});
it("Good default round factor", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: [],
precision: 12,
type: "Decimal",
uomSeparator: " ",
roundFactor: 0.0,
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch(() => { });
});
it("Bad minWidth value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: [],
precision: 12,
type: "Decimal",
uomSeparator: " ",
minWidth: -5,
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'minWidth' attribute. It should be a positive integer.`);
});
});
it("Good showSign entry", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: [],
precision: 12,
type: "Decimal",
uomSeparator: " ",
showSignOption: "onlyNegative",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch(() => {
assert.isTrue(false);
});
});
it("Bad decimal separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
type: "Decimal",
uomSeparator: " ",
decimalSeparator: "**",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'decimalSeparator' attribute. It must be a one character string.`);
});
});
it("Good decimal separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
type: "Decimal",
uomSeparator: " ",
decimalSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch(() => {
assert.isTrue(false);
});
});
it("Bad thousand separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
type: "Decimal",
uomSeparator: " ",
thousandSeparator: "**",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'thousandSeparator' attribute. It must be a one character string.`);
});
});
it("Good thousand separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
type: "Decimal",
uomSeparator: " ",
thousandSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch(() => {
assert.isTrue(false);
});
});
it("Bad uom separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
type: "Decimal",
uomSeparator: "**",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'uomSeparator' attribute. It must be empty or a string with a single character.`);
});
});
it("Good uom separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
type: "Decimal",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch(() => {
assert.isTrue(false);
});
});
it("Bad station separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
uomSeparator: " ",
stationOffsetSize: 2,
type: "Station",
stationSeparator: "**",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'stationSeparator' attribute. It must be a one character string.`);
});
});
it("Good station separator value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
precision: 12,
uomSeparator: " ",
stationOffsetSize: 2,
type: "Station",
stationSeparator: "+",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch(() => {
assert.isTrue(false);
});
});
it("Scientific type is required", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 8,
type: "Scientific",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has type 'Scientific' therefore attribute 'scientificType' is required.`);
});
});
it("A valid Scientific type is required", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 8,
type: "Scientific",
scientificType: "bad",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'SCIENTIFIC_TYPE' attribute.`);
});
});
it("No Composite Units", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
composite: {
includeZero: true,
spacer: "",
units: [],
},
formatTraits: ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
precision: 8,
type: "Fractional",
uomSeparator: "",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has a Composite with no valid 'units'`);
});
});
it("Invalid Composite cUnit name", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
composite: {
includeZero: true,
spacer: "",
units: [
{
name: "Units.F",
},
],
},
formatTraits: ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
precision: 8,
type: "Fractional",
uomSeparator: "",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `Invalid unit name 'Units.F'.`);
});
});
it("Invalid Composite duplicate units", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
composite: {
includeZero: true,
spacer: "",
units: [
{
label: "ft",
name: "Units.FT",
},
{
label: "'",
name: "Units.FT",
},
],
},
formatTraits: ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
precision: 8,
type: "Fractional",
uomSeparator: "",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The unit Units.FT has a duplicate name.`);
});
});
it("Missing station offset", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["trailZeroes", "keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
minWidth: 2,
precision: 2,
type: "Station",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has type 'Station' therefore attribute 'stationOffsetSize' is required.`);
});
});
it("Bad station offset value", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["trailZeroes", "keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
minWidth: 2,
precision: 2,
stationOffsetSize: 0,
type: "Station",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has an invalid 'stationOffsetSize' attribute. It should be a positive integer.`);
});
});
it("Bad spacer (too many characters) in Composite", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
composite: {
includeZero: true,
spacer: "**",
units: [
{
label: "'",
name: "Units.FT",
},
{
label: "\"",
name: "Units.IN",
},
],
},
formatTraits: ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
precision: 8,
type: "Fractional",
uomSeparator: "",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json).catch((err) => {
assert.isTrue(err instanceof QuantityError && err.message === `The Format test has a Composite with an invalid 'spacer' attribute. It must be empty or a string with a single character.`);
});
});
it("Read/Write All Format Traits", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: ["trailZeroes", "keepSingleZero", "zeroEmpty", "keepDecimalPoint", "applyRounding", "fractionDash", "showUnitLabel", "prependUnitLabel", "use1000Separator", "exponentOnlyNegative"],
precision: 8,
type: "Decimal",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json);
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.ApplyRounding));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.ExponentOnlyNegative));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.FractionDash));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.KeepDecimalPoint));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.KeepSingleZero));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.PrependUnitLabel));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.ShowUnitLabel));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.TrailZeroes));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.Use1000Separator));
assert.isTrue(testFormat.hasFormatTraitSet(FormatTraits.ZeroEmpty));
const outJson = testFormat.toJSON();
assert.isTrue(outJson.formatTraits!.length === 10);
// ensure we can modify
const modifiedFormatProps = { ...outJson, formatTraits: ["keepSingleZero"], precision: 3 };
const modifiedFormat = new Format("modified");
await modifiedFormat.fromJSON(unitsProvider, modifiedFormatProps);
assert.isTrue(modifiedFormat.hasFormatTraitSet(FormatTraits.KeepSingleZero));
assert.isFalse(modifiedFormat.hasFormatTraitSet(FormatTraits.ShowUnitLabel));
assert.isTrue(modifiedFormat.precision === DecimalPrecision.Three);
});
it("Read/Write Empty Format Traits", async () => {
const unitsProvider = new TestUnitsProvider();
const json = {
formatTraits: [],
precision: 8,
type: "Decimal",
uomSeparator: " ",
};
const testFormat = new Format("test");
await testFormat.fromJSON(unitsProvider, json);
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.ApplyRounding));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.ExponentOnlyNegative));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.FractionDash));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.KeepDecimalPoint));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.KeepSingleZero));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.PrependUnitLabel));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.ShowUnitLabel));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.TrailZeroes));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.Use1000Separator));
assert.isFalse(testFormat.hasFormatTraitSet(FormatTraits.ZeroEmpty));
const outJson = testFormat.toJSON();
assert.isTrue(outJson.formatTraits!.length === 0);
});
it("Load Formats from Json", async () => {
const unitsProvider = new TestUnitsProvider();
const formatDataArray = [{
formatTraits: ["keepSingleZero", "showUnitLabel", "fractionDash"],
precision: 1,
type: "Fractional",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 2,
type: "Fractional",
uomSeparator: "",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 4,
type: "Fractional",
uomSeparator: "",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 8,
type: "Fractional",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 16,
type: "Fractional",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 32,
type: "Fractional",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 64,
type: "Fractional",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 128,
type: "Fractional",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "showUnitLabel"],
precision: 256,
type: "Fractional",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel"],
precision: 0,
type: "Decimal",
uomSeparator: " ",
showSignOption: "negativeParentheses",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel"],
precision: 1,
type: "Decimal",
uomSeparator: " ",
showSignOption: "noSign",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel"],
precision: 2,
type: "Decimal",
uomSeparator: " ",
showSignOption: "signAlways",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel"],
precision: 3,
type: "Decimal",
uomSeparator: " ",
showSignOption: "onlyNegative",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 4,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 5,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 6,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 7,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 8,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 9,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 10,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 11,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel", "use1000Separator"],
precision: 12,
type: "Decimal",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
precision: 4,
type: "Scientific",
scientificType: "zeroNormalized",
uomSeparator: " ",
}, {
formatTraits: ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
precision: 4,
type: "Scientific",
scientificType: "normalized",
uomSeparator: " ",
}, {
formatTraits: ["trailZeroes", "keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
minWidth: 2,
precision: 2,
stationOffsetSize: 2,
type: "Station",
}, {
formatTraits: ["trailZeroes", "keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
minWidth: 2,
precision: 2,
stationOffsetSize: 2,
type: "Station",
}, {
composite: {
units: [
{
name: "Units.FT",
},
],
},
formatTraits: ["keepSingleZero", "applyRounding", "keepDecimalPoint", "showUnitLabel"],
precision: 4,
type: "Decimal",
uomSeparator: "",
}, {
composite: {
includeZero: true,
spacer: "",
units: [
{
label: "'",
name: "Units.FT",
},
{
label: "\"",
name: "Units.IN",
},
],
},
formatTraits: ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
precision: 8,
type: "Fractional",
uomSeparator: "",
}];
for (const formatData of formatDataArray) {
const format = new Format("test");
await format.fromJSON(unitsProvider, formatData).catch(() => { });
if (formatData.hasOwnProperty("precision"))
assert.isTrue(format.precision === formatData.precision);
assert.isTrue(Format.formatTypeToString(format.type).toUpperCase() === formatData.type.toUpperCase());
if (formatData.hasOwnProperty("uomSeparator"))
assert.isTrue(format.uomSeparator === formatData.uomSeparator);
for (const traitStr of formatData.formatTraits) {
const traitToValidate: FormatTraits = Format.parseFormatTrait(traitStr, 0);
assert.isTrue(format.hasFormatTraitSet(traitToValidate));
}
if (formatData.hasOwnProperty("composite")) {
assert.isTrue(format.hasUnits === true);
assert.isTrue(format.units!.length === formatData.composite!.units.length);
}
const jsonData = format.toJSON();
assert.isTrue(jsonData.type.toUpperCase() === Format.formatTypeToString(format.type).toUpperCase());
if (formatData.hasOwnProperty("showSignOption")) {
assert.isTrue(formatData.showSignOption!.toUpperCase() === jsonData.showSignOption!.toUpperCase());
}
}
});
it("isFormatTraitSetInProps works properly", () => {
const formatProps: FormatProps = {
type: "decimal",
formatTraits: [
"keepSingleZero",
"zeroEmpty",
"keepDecimalPoint",
"applyRounding",
"fractionDash",
"showUnitLabel",
"prependUnitLabel",
"use1000Separator",
"exponentOnlyNegative",
],
};
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ApplyRounding));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ExponentOnlyNegative));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.FractionDash));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.KeepDecimalPoint));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.KeepSingleZero));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.PrependUnitLabel));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ShowUnitLabel));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.TrailZeroes) === false);
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.Use1000Separator));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ZeroEmpty));
});
it("isFormatTraitSetInProps works properly", () => {
const formatProps: FormatProps = {
type: "decimal",
formatTraits: [
"trailZeroes",
],
};
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ApplyRounding));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ExponentOnlyNegative));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.FractionDash));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.KeepDecimalPoint));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.KeepSingleZero));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.PrependUnitLabel));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ShowUnitLabel));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.Use1000Separator));
assert.isFalse(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ZeroEmpty));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.TrailZeroes));
});
it("show old/optional trait format works properly", () => {
const formatProps: FormatProps = {
type: "decimal",
formatTraits: "trailZeroes,keepSingleZero,zeroEmpty,keepDecimalPoint,applyRounding,fractionDash,showUnitLabel,prependUnitLabel,use1000Separator,exponentOnlyNegative",
};
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ApplyRounding));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ExponentOnlyNegative));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.FractionDash));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.KeepDecimalPoint));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.KeepSingleZero));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.PrependUnitLabel));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ShowUnitLabel));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.TrailZeroes));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.Use1000Separator));
assert.isTrue(Format.isFormatTraitSetInProps(formatProps, FormatTraits.ZeroEmpty));
});
}); | the_stack |
import NetRegexes from '../../../../../resources/netregexes';
import ZoneId from '../../../../../resources/zone_id';
import { OopsyData } from '../../../../../types/data';
import { OopsyTriggerSet } from '../../../../../types/oopsy';
import { playerDamageFields } from '../../../oopsy_common';
export type Data = OopsyData;
// TODO: Dahu 5776 Spit Flame should always hit a Marchosias
// TODO: hitting phantom with ice spikes with anything but dispel?
// TODO: failing icy/fiery portent (guard and queen)
// `18:Pyretic DoT Tick on ${name} for ${damage} damage.`
// TODO: Winds Of Fate / Weight Of Fortune?
// TODO: Turret's Tour?
// general traps: explosion: 5A71, poison trap: 5A72, mini: 5A73
// duel traps: mini: 57A1, ice: 579F, toad: 57A0
// TODO: taking mana flame without reflect
// TODO: taking Maelstrom's Bolt without lightning buff
const triggerSet: OopsyTriggerSet<Data> = {
zoneId: ZoneId.DelubrumReginaeSavage,
damageWarn: {
'DelubrumSav Seeker Slimes Hellish Slash': '57EA', // Bozjan Soldier cleave
'DelubrumSav Seeker Slimes Viscous Rupture': '5016', // Fully merged viscous slime aoe
'DelubrumSav Seeker Golems Demolish': '5880', // interruptible Ruins Golem cast
'DelubrumSav Seeker Baleful Swathe': '5AD1', // Ground aoe to either side of boss
'DelubrumSav Seeker Baleful Blade': '5B2A', // Hide behind pillars attack
'DelubrumSav Seeker Scorching Shackle': '5ACB', // Chains
'DelubrumSav Seeker Mercy Fourfold 1': '5B94', // Four glowing sword half room cleaves
'DelubrumSav Seeker Mercy Fourfold 2': '5AB9', // Four glowing sword half room cleaves
'DelubrumSav Seeker Mercy Fourfold 3': '5ABA', // Four glowing sword half room cleaves
'DelubrumSav Seeker Mercy Fourfold 4': '5ABB', // Four glowing sword half room cleaves
'DelubrumSav Seeker Mercy Fourfold 5': '5ABC', // Four glowing sword half room cleaves
'DelubrumSav Seeker Merciful Breeze': '5AC8', // Waffle criss-cross floor markers
'DelubrumSav Seeker Baleful Comet': '5AD7', // Clone meteor dropping before charges
'DelubrumSav Seeker Baleful Firestorm': '5AD8', // Clone charge after Baleful Comet
'DelubrumSav Seeker Iron Rose': '5AD9', // Clone line aoes
'DelubrumSav Seeker Iron Splitter Blue 1': '5AC1', // Blue rin g explosion
'DelubrumSav Seeker Iron Splitter Blue 2': '5AC2', // Blue ring explosion
'DelubrumSav Seeker Iron Splitter Blue 3': '5AC3', // Blue ring explosion
'DelubrumSav Seeker Iron Splitter White 1': '5AC4', // White ring explosion
'DelubrumSav Seeker Iron Splitter White 2': '5AC5', // White ring explosion
'DelubrumSav Seeker Iron Splitter White 3': '5AC6', // White ring explosion
'DelubrumSav Seeker Act Of Mercy': '5ACF', // cross-shaped line aoes
'DelubrumSav Dahu Right-Sided Shockwave 1': '5770', // Right circular cleave
'DelubrumSav Dahu Right-Sided Shockwave 2': '5772', // Right circular cleave
'DelubrumSav Dahu Left-Sided Shockwave 1': '576F', // Left circular cleave
'DelubrumSav Dahu Left-Sided Shockwave 2': '5771', // Left circular cleave
'DelubrumSav Dahu Firebreathe': '5774', // Conal breath
'DelubrumSav Dahu Firebreathe Rotating': '576C', // Conal breath, rotating
'DelubrumSav Dahu Head Down': '5768', // line aoe charge from Marchosias add
'DelubrumSav Dahu Hunter\'s Claw': '5769', // circular ground aoe centered on Marchosias add
'DelubrumSav Dahu Falling Rock': '576E', // ground aoe from Reverberating Roar
'DelubrumSav Dahu Hot Charge': '5773', // double charge
'DelubrumSav Duel Massive Explosion': '579E', // bombs being cleared
'DelubrumSav Duel Vicious Swipe': '5797', // circular aoe around boss
'DelubrumSav Duel Focused Tremor 1': '578F', // square floor aoes
'DelubrumSav Duel Focused Tremor 2': '5791', // square floor aoes
'DelubrumSav Duel Devour': '5789', // conal aoe after withering curse
'DelubrumSav Duel Flailing Strike 1': '578C', // initial rotating cleave
'DelubrumSav Duel Flailing Strike 2': '578D', // rotating cleaves
'DelubrumSav Guard Optimal Offensive Sword': '5819', // middle explosion
'DelubrumSav Guard Optimal Offensive Shield': '581A', // middle explosion
'DelubrumSav Guard Optimal Play Sword': '5816', // Optimal Play Sword "get out"
'DelubrumSav Guard Optimal Play Shield': '5817', // Optimal play shield "get in"
'DelubrumSav Guard Optimal Play Cleave': '5818', // Optimal Play cleaves for sword/shield
'DelubrumSav Guard Unlucky Lot': '581D', // Queen's Knight orb explosion
'DelubrumSav Guard Burn 1': '583D', // small fire adds
'DelubrumSav Guard Burn 2': '583E', // large fire adds
'DelubrumSav Guard Pawn Off': '583A', // Queen's Soldier Secrets Revealed tethered clone aoe
'DelubrumSav Guard Turret\'s Tour Normal 1': '5847', // "normal mode" turrets, initial lines 1
'DelubrumSav Guard Turret\'s Tour Normal 2': '5848', // "normal mode" turrets, initial lines 2
'DelubrumSav Guard Turret\'s Tour Normal 3': '5849', // "normal mode" turrets, second lines
'DelubrumSav Guard Counterplay': '58F5', // Hitting aetherial ward directional barrier
'DelubrumSav Phantom Swirling Miasma 1': '57B8', // Initial phantom donut aoe
'DelubrumSav Phantom Swirling Miasma 2': '57B9', // Moving phantom donut aoes
'DelubrumSav Phantom Creeping Miasma 1': '57B4', // Initial phantom line aoe
'DelubrumSav Phantom Creeping Miasma 2': '57B5', // Later phantom line aoe
'DelubrumSav Phantom Lingering Miasma 1': '57B6', // Initial phantom circle aoe
'DelubrumSav Phantom Lingering Miasma 2': '57B7', // Moving phantom circle aoe
'DelubrumSav Phantom Vile Wave': '57BF', // phantom conal aoe
'DelubrumSav Avowed Fury Of Bozja': '594C', // Trinity Avowed Allegiant Arsenal "out"
'DelubrumSav Avowed Flashvane': '594B', // Trinity Avowed Allegiant Arsenal "get behind"
'DelubrumSav Avowed Infernal Slash': '594A', // Trinity Avowed Allegiant Arsenal "get front"
'DelubrumSav Avowed Flames Of Bozja': '5939', // 80% floor aoe before shimmering shot swords
'DelubrumSav Avowed Gleaming Arrow': '594D', // Trinity Avatar line aoes from outside
'DelubrumSav Lord Whack': '57D0', // cleave
'DelubrumSav Lord Devastating Bolt 1': '57C5', // lightning rings
'DelubrumSav Lord Devastating Bolt 2': '57C6', // lightning rings
'DelubrumSav Lord Electrocution': '57CC', // random circle aoes
'DelubrumSav Lord Rapid Bolts': '57C3', // dropped lightning aoes
'DelubrumSav Lord 1111-Tonze Swing': '57D8', // very large "get out" swing
'DelubrumSav Lord Monk Attack': '55A6', // Monk add auto-attack
'DelubrumSav Queen Northswain\'s Glow': '59F4', // expanding lines with explosion intersections
'DelubrumSav Queen The Means 1': '59E7', // The Queen's Beck and Call cross aoe from adds
'DelubrumSav Queen The Means 2': '59EA', // The Queen's Beck and Call cross aoe from adds
'DelubrumSav Queen The End 1': '59E8', // Also The Queen's Beck and Call cross aoe from adds
'DelubrumSav Queen The End 2': '59E9', // Also The Queen's Beck and Call cross aoe from adds
'DelubrumSav Queen Optimal Offensive Sword': '5A02', // middle explosion
'DelubrumSav Queen Optimal Offensive Shield': '5A03', // middle explosion
'DelubrumSav Queen Judgment Blade Left 1': '59F2', // dash across room with left cleave
'DelubrumSav Queen Judgment Blade Left 2': '5B85', // dash across room with left cleave
'DelubrumSav Queen Judgment Blade Right 1': '59F1', // dash across room with right cleave
'DelubrumSav Queen Judgment Blade Right 2': '5B84', // dash across room with right cleave
'DelubrumSav Queen Pawn Off': '5A1D', // Queen's Soldier Secrets Revealed tethered clone aoe
'DelubrumSav Queen Optimal Play Sword': '59FF', // Optimal Play Sword "get out"
'DelubrumSav Queen Optimal Play Shield': '5A00', // Optimal play shield "get in"
'DelubrumSav Queen Optimal Play Cleave': '5A01', // Optimal Play cleaves for sword/shield
'DelubrumSav Queen Turret\'s Tour Normal 1': '5A28', // "normal mode" turrets, initial lines 1
'DelubrumSav Queen Turret\'s Tour Normal 2': '5A2A', // "normal mode" turrets, initial lines 2
'DelubrumSav Queen Turret\'s Tour Normal 3': '5A29', // "normal mode" turrets, second lines
},
damageFail: {
'DelubrumSav Avowed Heat Shock': '5927', // too much heat or failing to regulate temperature
'DelubrumSav Avowed Cold Shock': '5928', // too much cold or failing to regulate temperature
'DelubrumSav Queen Queen\'s Justice': '59EB', // failing to walk the right number of squares
'DelubrumSav Queen Gunnhildr\'s Blades': '5B22', // not being in the chess blue safe square
'DelubrumSav Queen Unlucky Lot': '55B6', // lightning orb attack
},
gainsEffectWarn: {
'DelubrumSav Seeker Merciful Moon': '262', // "Petrification" from Aetherial Orb lookaway
},
shareWarn: {
'DelubrumSav Seeker Phantom Baleful Onslaught': '5AD6', // solo tank cleave
'DelubrumSav Lord Foe Splitter': '57D7', // tank cleave
},
triggers: [
{
// These ability ids can be ordered differently and "hit" people when levitating.
id: 'DelubrumSav Guard Lots Cast',
type: 'Ability',
netRegex: NetRegexes.abilityFull({ id: ['5827', '5828', '5B6C', '5B6D', '5BB6', '5BB7', '5B88', '5B89'], ...playerDamageFields }),
condition: (_data, matches) => matches.flags.slice(-2) === '03',
mistake: (_data, matches) => {
return { type: 'warn', blame: matches.target, text: matches.ability };
},
},
{
id: 'DelubrumSav Golem Compaction',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '5746' }),
mistake: (_data, matches) => {
return { type: 'fail', text: `${matches.source}: ${matches.ability}` };
},
},
{
id: 'DelubrumSav Slime Sanguine Fusion',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '554D' }),
mistake: (_data, matches) => {
return { type: 'fail', text: `${matches.source}: ${matches.ability}` };
},
},
],
};
export default triggerSet; | the_stack |
import { Buffer } from '../platform';
import {
IQType,
MessageType,
PresenceType,
SASLFailureCondition,
StanzaErrorCondition,
StreamErrorCondition,
StreamType
} from '../Constants';
import {
attribute,
childAlternateLanguageText,
childBoolean,
childEnum,
childText,
DefinitionOptions,
FieldDefinition,
JIDAttribute,
languageAttribute,
LanguageSet,
multipleChildText,
textBuffer
} from '../jxt';
import {
NS_BIND,
NS_CLIENT,
NS_SASL,
NS_STANZAS,
NS_STARTTLS,
NS_STREAM,
NS_STREAMS
} from '../Namespaces';
import { IQ, IQBase, Message, Presence } from './';
declare module './' {
export interface Stream {
type?: 'stream' | 'open' | 'close';
to?: string;
from?: string;
id?: string;
version?: string;
lang?: string;
}
export interface StreamFeatures {
sasl?: SASLFeature;
tls?: TLS;
bind?: Bind;
}
export interface StreamError {
condition: StreamErrorCondition;
text?: string;
alternateLanguageText?: LanguageSet<string>;
seeOtherHost?: string;
}
export interface StanzaError {
by?: string;
type?: string;
condition: StanzaErrorCondition;
text?: string;
alternateLanguageText?: LanguageSet<string>;
redirect?: string;
gone?: string;
}
export interface Message {
to?: string;
from?: string;
id?: string;
lang?: string;
streamType?: StreamType;
type?: MessageType;
error?: StanzaError;
}
export interface Presence {
to?: string;
from?: string;
id?: string;
lang?: string;
streamType?: StreamType;
type?: PresenceType;
error?: StanzaError;
}
export interface IQBase {
to?: string;
from?: string;
id?: string;
type: IQType;
lang?: string;
streamType?: StreamType;
error?: StanzaError;
payloadType?: Exclude<keyof IQ, keyof IQBase> | 'invalid-payload-count' | 'unknown-payload';
}
export interface IQ {
bind?: Bind;
}
}
export interface ReceivedIQ extends IQ {
to: string;
from: string;
id: string;
}
export interface ReceivedIQGet extends ReceivedIQ {
type: typeof IQType.Get;
}
export interface ReceivedIQSet extends ReceivedIQ {
type: typeof IQType.Set;
}
export interface ReceivedMessage extends Message {
to: string;
from: string;
}
export interface ReceivedPresence extends Presence {
to: string;
from: string;
}
export interface SASLFeature {
mechanisms: string[];
}
export interface SASLAbort {
type: 'abort';
}
export interface SASLChallengeResponse {
type: 'challenge' | 'response';
value?: Buffer;
}
export interface SASLSuccess {
type: 'success';
value?: Buffer;
}
export interface SASLAuth {
type: 'auth';
mechanism: string;
value?: Buffer;
}
export interface SASLFailure {
type: 'failure';
condition: SASLFailureCondition;
text?: string;
alternateLanguageText?: LanguageSet<string>;
}
export type SASL = SASLAbort | SASLChallengeResponse | SASLSuccess | SASLFailure | SASLAuth;
export interface TLS {
type?: 'start' | 'proceed' | 'failure';
required?: boolean;
}
export interface Bind {
jid?: string;
resource?: string;
}
const _Stream: DefinitionOptions = {
defaultType: 'stream',
element: 'stream',
fields: {
from: attribute('from'),
id: attribute('id'),
lang: languageAttribute(),
to: attribute('to'),
version: attribute('version')
},
namespace: NS_STREAM,
path: 'stream',
type: 'stream',
typeField: 'action'
};
const _StreamFeatures: DefinitionOptions = {
element: 'features',
namespace: NS_STREAM,
path: 'features'
};
const _StreamError: DefinitionOptions = {
element: 'error',
fields: {
alternateLanguageText: childAlternateLanguageText(NS_STREAMS, 'text'),
condition: childEnum(
NS_STREAMS,
Object.values(StreamErrorCondition),
StreamErrorCondition.UndefinedCondition
),
seeOtherHost: childText(NS_STREAMS, StreamErrorCondition.SeeOtherHost),
text: childText(NS_STREAMS, 'text')
},
namespace: NS_STREAM,
path: 'streamError'
};
// --------------------------------------------------------------------
const _StanzaError: DefinitionOptions[] = Object.values(StreamType).map(streamNS => ({
aliases: ['stanzaError', 'message.error', 'presence.error', 'iq.error'],
defaultType: NS_CLIENT,
element: 'error',
fields: {
alternateLanguageText: childAlternateLanguageText(NS_STANZAS, 'text'),
by: JIDAttribute('by'),
condition: childEnum(
NS_STANZAS,
Object.values(StanzaErrorCondition),
StanzaErrorCondition.UndefinedCondition
),
gone: childText(NS_STANZAS, StanzaErrorCondition.Gone),
redirect: childText(NS_STANZAS, StanzaErrorCondition.Redirect),
text: childText(NS_STANZAS, 'text'),
type: attribute('type')
},
namespace: streamNS,
type: streamNS,
typeField: 'streamType'
}));
// --------------------------------------------------------------------
const baseIQFields: Set<keyof IQBase> = new Set([
'from',
'id',
'lang',
'to',
'type',
'payloadType',
'error',
'streamType'
]);
const _IQ: DefinitionOptions[] = Object.values(StreamType).map(
(streamNS: string): DefinitionOptions => ({
childrenExportOrder: {
error: 200000
},
defaultType: NS_CLIENT,
element: 'iq',
fields: {
from: JIDAttribute('from'),
id: attribute('id'),
lang: languageAttribute(),
payloadType: {
order: -10000,
importer(xml, context) {
if (
(context.data! as IQ).type !== 'get' &&
(context.data! as IQ).type !== 'set'
) {
return;
}
const childCount = xml.children.filter(child => typeof child !== 'string')
.length;
if (childCount !== 1) {
return 'invalid-payload-count';
}
const extensions = Object.keys(context.data!).filter(
key => !baseIQFields.has(key as any)
);
if (extensions.length !== 1) {
return 'unknown-payload';
}
return extensions[0];
}
} as FieldDefinition<string>,
to: JIDAttribute('to'),
type: attribute('type')
},
namespace: streamNS,
path: 'iq',
type: streamNS,
typeField: 'streamType'
})
);
// --------------------------------------------------------------------
const _Message: DefinitionOptions[] = Object.values(StreamType).map(streamNS => ({
childrenExportOrder: {
error: 200000
},
defaultType: NS_CLIENT,
element: 'message',
fields: {
from: JIDAttribute('from'),
id: attribute('id'),
lang: languageAttribute(),
to: JIDAttribute('to')
},
namespace: streamNS,
path: 'message',
type: streamNS,
typeField: 'streamType'
}));
// --------------------------------------------------------------------
const _Presence = Object.values(StreamType).map(streamNS => ({
childrenExportOrder: {
error: 200000
},
defaultType: NS_CLIENT,
element: 'presence',
fields: {
from: JIDAttribute('from'),
id: attribute('id'),
lang: languageAttribute(),
to: JIDAttribute('to')
},
namespace: streamNS,
path: 'presence',
type: streamNS,
typeField: 'streamType'
}));
// --------------------------------------------------------------------
const _SASL: DefinitionOptions[] = [
{
element: 'mechanisms',
fields: {
mechanisms: multipleChildText(null, 'mechanism')
},
namespace: NS_SASL,
path: 'features.sasl'
},
{
element: 'abort',
namespace: NS_SASL,
path: 'sasl',
type: 'abort',
typeField: 'type'
},
{
element: 'auth',
fields: {
mechanism: attribute('mechanism'),
value: textBuffer('base64')
},
namespace: NS_SASL,
path: 'sasl',
type: 'auth',
typeField: 'type'
},
{
element: 'challenge',
fields: {
value: textBuffer('base64')
},
namespace: NS_SASL,
path: 'sasl',
type: 'challenge',
typeField: 'type'
},
{
element: 'response',
fields: {
value: textBuffer('base64')
},
namespace: NS_SASL,
path: 'sasl',
type: 'response',
typeField: 'type'
},
{
element: 'success',
fields: {
value: textBuffer('base64')
},
namespace: NS_SASL,
path: 'sasl',
type: 'success',
typeField: 'type'
},
{
element: 'failure',
fields: {
alternateLanguageText: childAlternateLanguageText(NS_SASL, 'text'),
condition: childEnum(NS_SASL, Object.values(SASLFailureCondition)),
text: childText(NS_SASL, 'text')
},
namespace: NS_SASL,
path: 'sasl',
type: 'failure',
typeField: 'type'
}
];
// --------------------------------------------------------------------
const _STARTTLS: DefinitionOptions[] = [
{
aliases: ['features.tls'],
defaultType: 'start',
element: 'starttls',
fields: {
required: childBoolean(null, 'required')
},
namespace: NS_STARTTLS,
path: 'tls',
type: 'start',
typeField: 'type'
},
{
element: 'proceed',
namespace: NS_STARTTLS,
path: 'tls',
type: 'proceed',
typeField: 'type'
},
{
element: 'failure',
namespace: NS_STARTTLS,
path: 'tls',
type: 'failure',
typeField: 'type'
}
];
// --------------------------------------------------------------------
const _Bind: DefinitionOptions = {
aliases: ['features.bind', 'iq.bind'],
element: 'bind',
fields: {
jid: childText(null, 'jid'),
resource: childText(null, 'resource')
},
namespace: NS_BIND
};
// --------------------------------------------------------------------
const Protocol: DefinitionOptions[] = [
_Stream,
_StreamFeatures,
_StreamError,
..._StanzaError,
..._SASL,
..._STARTTLS,
..._IQ,
..._Message,
..._Presence,
_Bind
];
export default Protocol; | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/connectionTypeOperationsMappers";
import * as Parameters from "../models/parameters";
import { AutomationClientContext } from "../automationClientContext";
/** Class representing a ConnectionTypeOperations. */
export class ConnectionTypeOperations {
private readonly client: AutomationClientContext;
/**
* Create a ConnectionTypeOperations.
* @param {AutomationClientContext} client Reference to the service client.
*/
constructor(client: AutomationClientContext) {
this.client = client;
}
/**
* Delete the connection type.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The name of connection type.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The name of connection type.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The name of connection type.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
connectionTypeName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Retrieve the connection type identified by connection type name.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The name of connection type.
* @param [options] The optional parameters
* @returns Promise<Models.ConnectionTypeGetResponse>
*/
get(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, options?: msRest.RequestOptionsBase): Promise<Models.ConnectionTypeGetResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The name of connection type.
* @param callback The callback
*/
get(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, callback: msRest.ServiceCallback<Models.ConnectionType>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The name of connection type.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectionType>): void;
get(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectionType>, callback?: msRest.ServiceCallback<Models.ConnectionType>): Promise<Models.ConnectionTypeGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
connectionTypeName,
options
},
getOperationSpec,
callback) as Promise<Models.ConnectionTypeGetResponse>;
}
/**
* Create a connection type.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The parameters supplied to the create or update connection type
* operation.
* @param parameters The parameters supplied to the create or update connection type operation.
* @param [options] The optional parameters
* @returns Promise<Models.ConnectionTypeCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, parameters: Models.ConnectionTypeCreateOrUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.ConnectionTypeCreateOrUpdateResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The parameters supplied to the create or update connection type
* operation.
* @param parameters The parameters supplied to the create or update connection type operation.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, parameters: Models.ConnectionTypeCreateOrUpdateParameters, callback: msRest.ServiceCallback<Models.ConnectionType>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param connectionTypeName The parameters supplied to the create or update connection type
* operation.
* @param parameters The parameters supplied to the create or update connection type operation.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, parameters: Models.ConnectionTypeCreateOrUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectionType>): void;
createOrUpdate(resourceGroupName: string, automationAccountName: string, connectionTypeName: string, parameters: Models.ConnectionTypeCreateOrUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectionType>, callback?: msRest.ServiceCallback<Models.ConnectionType>): Promise<Models.ConnectionTypeCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
connectionTypeName,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.ConnectionTypeCreateOrUpdateResponse>;
}
/**
* Retrieve a list of connection types.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param [options] The optional parameters
* @returns Promise<Models.ConnectionTypeListByAutomationAccountResponse>
*/
listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.ConnectionTypeListByAutomationAccountResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param callback The callback
*/
listByAutomationAccount(resourceGroupName: string, automationAccountName: string, callback: msRest.ServiceCallback<Models.ConnectionTypeListResult>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param options The optional parameters
* @param callback The callback
*/
listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectionTypeListResult>): void;
listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectionTypeListResult>, callback?: msRest.ServiceCallback<Models.ConnectionTypeListResult>): Promise<Models.ConnectionTypeListByAutomationAccountResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
options
},
listByAutomationAccountOperationSpec,
callback) as Promise<Models.ConnectionTypeListByAutomationAccountResponse>;
}
/**
* Retrieve a list of connection types.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ConnectionTypeListByAutomationAccountNextResponse>
*/
listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ConnectionTypeListByAutomationAccountNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByAutomationAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ConnectionTypeListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByAutomationAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConnectionTypeListResult>): void;
listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConnectionTypeListResult>, callback?: msRest.ServiceCallback<Models.ConnectionTypeListResult>): Promise<Models.ConnectionTypeListByAutomationAccountNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByAutomationAccountNextOperationSpec,
callback) as Promise<Models.ConnectionTypeListByAutomationAccountNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connectionTypes/{connectionTypeName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.connectionTypeName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connectionTypes/{connectionTypeName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.connectionTypeName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConnectionType
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connectionTypes/{connectionTypeName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.connectionTypeName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ConnectionTypeCreateOrUpdateParameters,
required: true
}
},
responses: {
201: {
bodyMapper: Mappers.ConnectionType
},
409: {
bodyMapper: Mappers.ConnectionType
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByAutomationAccountOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connectionTypes",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConnectionTypeListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByAutomationAccountNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConnectionTypeListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import { createElement, isNullOrUndefined, classList, L10n } from '@syncfusion/ej2-base';
import { DocumentEditor } from '../../document-editor/index';
import { DropDownList } from '@syncfusion/ej2-dropdowns';
import { Button } from '@syncfusion/ej2-buttons';
import { ItemModel, DropDownButton, SplitButton, SplitButtonModel, MenuEventArgs } from '@syncfusion/ej2-splitbuttons';
import { Query } from '@syncfusion/ej2-data';
import { DocumentEditorContainer } from '../document-editor-container';
/**
* Paragraph Properties
*
* @private
*/
export class Paragraph {
private container: DocumentEditorContainer;
private textProperties: HTMLElement;
private leftAlignment: HTMLElement;
private rightAlignment: HTMLElement;
private centerAlignment: HTMLElement;
private justify: HTMLElement;
private increaseIndent: HTMLElement;
private decreaseIndent: HTMLElement;
private lineSpacing: DropDownButton;
private style: DropDownList;
private isRetrieving: boolean = false;
private styleName: string;
public appliedBulletStyle: string = 'dot';
public appliedNumberingStyle: string = 'arabic';
public appliedLineSpacing: string = '';
private noneNumberTag: HTMLElement;
private numberList: HTMLElement;
private lowLetter: HTMLElement;
private upLetter: HTMLElement;
private lowRoman: HTMLElement;
private upRoman: HTMLElement;
private noneBulletTag: HTMLElement;
private dotBullet: HTMLElement;
private circleBullet: HTMLElement;
private squareBullet: HTMLElement;
private flowerBullet: HTMLElement;
private arrowBullet: HTMLElement;
private tickBullet: HTMLElement;
public localObj: L10n;
private isRtl: boolean;
private splitButtonClass: string = 'e-de-prop-splitbutton';
private bulletListBtn: SplitButton;
private numberedListBtn: SplitButton;
private get documentEditor(): DocumentEditor {
return this.container.documentEditor;
}
public constructor(container: DocumentEditorContainer) {
this.container = container;
}
public initializeParagraphPropertiesDiv(wholeDiv: HTMLElement, isRtl?: boolean): void {
this.localObj = new L10n('documenteditorcontainer', this.container.defaultLocale, this.container.locale);
this.isRtl = isRtl;
if (this.isRtl) {
this.splitButtonClass = 'e-rtl ' + this.splitButtonClass;
}
this.textProperties = wholeDiv;
const element: string = this.documentEditor.element.id + '_font_properties';
const paragraphDiv: HTMLElement = this.createDivElement(element + '_paragraph', wholeDiv, '');
classList(paragraphDiv, ['e-de-cntr-pane-padding'], []);
const label: HTMLElement = createElement('label', { styles: 'width:26px;', className: 'e-de-ctnr-prop-label' });
label.innerHTML = this.localObj.getConstant('Paragraph');
paragraphDiv.appendChild(label);
const styleDiv: HTMLElement = this.createDivElement(element + '_styleDiv', paragraphDiv);
styleDiv.classList.add('e-de-ctnr-segment', 'e-de-ctnr-style-div');
const styleSelect: HTMLSelectElement = createElement('input', { id: element + '_style', styles: 'width:248px;letter-spacing: 0.05px;' }) as HTMLSelectElement;
styleDiv.appendChild(styleSelect);
this.createStyleDropDownList(styleSelect);
const indentWholeDiv: HTMLElement = this.createDivElement(element + '_indentWholeDiv', paragraphDiv);
indentWholeDiv.style.display = 'flex';
indentWholeDiv.classList.add('e-de-ctnr-segment');
if (isRtl) {
classList(indentWholeDiv, ['e-de-ctnr-segment-rtl'], []);
}
const indentDiv: HTMLElement = this.createDivElement(element + '_indentDiv', indentWholeDiv, 'display:flex;');
let indentClassName: string = 'e-de-ctnr-group-btn e-de-char-fmt-btn-left e-btn-group';
if (isRtl) {
indentClassName = 'e-rtl ' + indentClassName;
}
indentDiv.className = indentClassName;
this.leftAlignment = this.createButtonTemplate(element + '_leftIndent', 'e-de-ctnr-alignleft e-icons', indentDiv, 'e-de-prop-indent-button', '40.5', this.localObj.getConstant('Align left Tooltip'));
this.centerAlignment = this.createButtonTemplate(element + '_centerIndent', 'e-de-ctnr-aligncenter e-icons', indentDiv, 'e-de-prop-indent-button', '40.5', this.localObj.getConstant('Center Tooltip'));
this.rightAlignment = this.createButtonTemplate(element + '_rightIndent', 'e-de-ctnr-alignright e-icons', indentDiv, 'e-de-prop-indent-button', '40.5', this.localObj.getConstant('Align right Tooltip'));
this.justify = this.createButtonTemplate(element + '_justify', 'e-de-ctnr-justify e-icons', indentDiv, 'e-de-prop-indent-last-button', '40.5', this.localObj.getConstant('Justify Tooltip'));
let increaseIndentIconCss: string = 'e-de-ctnr-increaseindent e-icons';
let decreaseIndentIconCss: string = 'e-de-ctnr-decreaseindent e-icons';
const incDecIndentDiv: HTMLElement = this.createDivElement(element + '_indentDiv', indentWholeDiv, 'display:flex;');
indentClassName = 'e-de-ctnr-group-btn e-de-char-fmt-btn-right e-btn-group';
if (isRtl) {
indentClassName = 'e-rtl ' + indentClassName;
increaseIndentIconCss += ' e-de-flip';
decreaseIndentIconCss += ' e-de-flip';
}
incDecIndentDiv.className = indentClassName;
this.decreaseIndent = this.createButtonTemplate(element + '_decreaseIndent', decreaseIndentIconCss, incDecIndentDiv, 'e-de-prop-indent-button', '37', this.localObj.getConstant('Decrease indent'));
this.increaseIndent = this.createButtonTemplate(element + '_increaseIndent', increaseIndentIconCss, incDecIndentDiv, 'e-de-prop-indent-last-button', '37', this.localObj.getConstant('Increase indent'));
const listDiv: HTMLElement = this.createDivElement(element + '_listDiv', paragraphDiv, 'display:flex;');
classList(listDiv, ['e-de-ctnr-segment', 'e-de-ctnr-group-btn'], []);
if (isRtl) {
classList(listDiv, ['e-de-ctnr-segment-rtl', 'e-de-ctnr-group-btn'], []);
}
const lineHeight: HTMLElement = createElement('button', { id: element + '_lineHeight', attrs: { type: 'button' } });
listDiv.appendChild(lineHeight);
this.lineSpacing = this.createLineSpacingDropdown(lineHeight);
const listDropDown: HTMLElement = this.createDivElement(element + '_listDropDiv', listDiv);
listDropDown.className = 'de-split-button';
const bulletButton: HTMLElement = createElement('button', { id: element + '_bullet', attrs: { type: 'button' } });
listDropDown.appendChild(bulletButton);
const numberingList: HTMLElement = createElement('button', { id: element + '_numberingList', attrs: { type: 'button' } });
listDropDown.appendChild(numberingList);
let bulletIconCss: string = 'e-de-ctnr-bullets e-icons';
let numberIconCss: string = 'e-de-ctnr-numbering e-icons';
if (isRtl) {
bulletIconCss += ' e-de-flip';
numberIconCss += ' e-de-flip';
}
this.createBulletListDropButton(bulletIconCss, bulletButton);
this.createNumberListDropButton(numberIconCss, numberingList);
}
private createSeparator(parentDiv: HTMLElement): void {
const separator: HTMLElement = createElement('div', { className: 'e-de-prop-vline' });
parentDiv.appendChild(separator);
}
private createDivElement(id: string, parentDiv: HTMLElement, style?: string): HTMLElement {
let element: HTMLElement;
if (style) {
element = createElement('div', { id: id, styles: style });
} else {
element = createElement('div', { id: id });
}
parentDiv.appendChild(element);
return element;
}
/* eslint-disable-next-line max-len */
private createButtonTemplate(id: string, iconcss: string, div: HTMLElement, buttonClass: string, width: string, toolTipText: string): HTMLButtonElement {
const buttonElement: HTMLButtonElement = createElement('Button', { id: id, attrs: { type: 'button' } }) as HTMLButtonElement;
// buttonElement.style.width = width + 'px';
// buttonElement.style.height = 32 + 'px';
div.appendChild(buttonElement);
const btn: Button = new Button({
cssClass: buttonClass, iconCss: iconcss
});
btn.appendTo(buttonElement);
buttonElement.setAttribute('title', toolTipText);
return buttonElement;
}
private createLineSpacingDropdown(button: HTMLElement): DropDownButton {
const items: ItemModel[] = [{
text: this.localObj.getConstant('Single')
}, {
text: '1.15'
}, {
text: '1.5'
}, {
text: this.localObj.getConstant('Double')
}];
const dropdown: DropDownButton = new DropDownButton({
items: items,
iconCss: 'e-de-ctnr-linespacing e-icons',
enableRtl: this.isRtl,
select: this.lineSpacingAction.bind(this),
cssClass: this.splitButtonClass,
beforeItemRender: (args: MenuEventArgs) => {
args.element.innerHTML = '<span></span>' + args.item.text;
const span: HTMLElement = args.element.children[0] as HTMLElement;
if (args.item.text === this.appliedLineSpacing) {
span.style.marginRight = '10px';
span.setAttribute('class', 'e-de-selected-item e-icons e-de-linespacing');
} else {
(args.element.children[0] as HTMLElement).style.marginRight = '25px';
(args.element.children[0] as HTMLElement).classList.remove('e-de-selected-item');
}
}
});
dropdown.appendTo(button);
button.setAttribute('title', this.localObj.getConstant('Line spacing'));
return dropdown;
}
private createNumberListDropButton(iconcss: string, button: HTMLElement): void {
const div: HTMLElement = createElement('div', { id: 'target', styles: 'width: 211px;height: auto;display:none' });
const ulTag: HTMLElement = createElement('ul', {
styles: 'display: block; outline: 0px;',
id: 'listMenu',
className: 'e-de-floating-menu e-de-bullets-menu e-de-list-container e-de-list-thumbnail'
});
div.appendChild(ulTag);
this.noneNumberTag = this.createNumberNoneListTag(ulTag);
this.noneNumberTag.addEventListener('click', this.numberedNoneClick.bind(this));
this.numberList = this.createNumberListTag(ulTag, '1.', '2.', '3.');
this.numberList.addEventListener('click', this.numberedNumberDotClick.bind(this));
this.lowLetter = this.createNumberListTag(ulTag, 'a.', 'b.', 'c.');
this.lowLetter.addEventListener('click', this.numberedLowLetterClick.bind(this));
this.upLetter = this.createNumberListTag(ulTag, 'A.', 'B.', 'C.');
this.upLetter.addEventListener('click', this.numberedUpLetterClick.bind(this));
this.lowRoman = this.createNumberListTag(ulTag, 'i.', 'ii.', 'iii.');
this.lowRoman.addEventListener('click', this.numberedLowRomanClick.bind(this));
this.upRoman = this.createNumberListTag(ulTag, 'I.', 'II.', 'III.');
this.upRoman.addEventListener('click', this.numberedUpRomanClick.bind(this));
const menuOptions: SplitButtonModel = {
target: div,
iconCss: iconcss,
cssClass: this.splitButtonClass,
beforeOpen: (): void => {
div.style.display = 'block';
this.updateSelectedNumberedListType(this.documentEditor.selection.paragraphFormat.listText);
},
beforeClose: (): void => {
div.style.display = 'none';
this.removeSelectedList();
}
};
this.numberedListBtn = new SplitButton(menuOptions);
this.numberedListBtn.click = (): void => {
this.applyLastAppliedNumbering();
};
this.numberedListBtn.appendTo(button);
button.parentElement.setAttribute('title', this.localObj.getConstant('Numbering'));
}
private updateSelectedBulletListType(listText: string): void {
switch (listText) {
case '\uf0b7':
this.dotBullet.classList.add('de-list-item-selected');
break;
case '\uf06f' + '\u0020':
this.circleBullet.classList.add('de-list-item-selected');
break;
case '\uf0a7':
this.squareBullet.classList.add('de-list-item-selected');
break;
case '\uf076':
this.flowerBullet.classList.add('de-list-item-selected');
break;
case '\uf0d8':
this.arrowBullet.classList.add('de-list-item-selected');
break;
case '\uf0fc':
this.tickBullet.classList.add('de-list-item-selected');
break;
default:
this.noneBulletTag.classList.add('de-list-item-selected');
break;
}
}
private updateSelectedNumberedListType(listText: string): void {
switch (listText) {
case '1.':
this.numberList.classList.add('de-list-item-selected');
break;
case 'I.':
this.upRoman.classList.add('de-list-item-selected');
break;
case 'A.':
this.upLetter.classList.add('de-list-item-selected');
break;
case 'a.':
this.lowLetter.classList.add('de-list-item-selected');
break;
case 'i.':
this.lowRoman.classList.add('de-list-item-selected');
break;
default:
this.noneNumberTag.classList.add('de-list-item-selected');
break;
}
}
private removeSelectedList(): void {
const className: string = 'de-list-item-selected';
this.noneNumberTag.classList.remove(className);
this.numberList.classList.remove(className);
this.lowLetter.classList.remove(className);
this.upLetter.classList.remove(className);
this.lowRoman.classList.remove(className);
this.upRoman.classList.remove(className);
this.noneBulletTag.classList.remove(className);
this.dotBullet.classList.remove(className);
this.circleBullet.classList.remove(className);
this.squareBullet.classList.remove(className);
this.flowerBullet.classList.remove(className);
this.arrowBullet.classList.remove(className);
this.tickBullet.classList.remove(className);
}
private applyLastAppliedNumbering(): void {
switch (this.appliedNumberingStyle) {
case 'arabic': this.numberedNumberDotClick(); break;
case 'lowletter': this.numberedLowLetterClick(); break;
case 'upletter': this.numberedUpLetterClick(); break;
case 'lowroman': this.numberedLowRomanClick(); break;
case 'uproman': this.numberedUpRomanClick(); break;
}
}
private applyLastAppliedBullet(): void {
switch (this.appliedBulletStyle) {
case 'dot': this.bulletDotClick(); break;
case 'circle': this.bulletCircleClick(); break;
case 'square': this.bulletSquareClick(); break;
case 'arrow': this.bulletArrowClick(); break;
case 'tick': this.bulletTickClick(); break;
case 'flower': this.bulletFlowerClick(); break;
}
}
private createBulletListDropButton(iconcss: string, button: HTMLElement): void {
const div: HTMLElement = createElement('div', { id: 'bullet_list', styles: 'width: 196px;height: auto;display:none' });
const ulTag: HTMLElement = createElement('ul', {
styles: 'display: block; outline: 0px;', id: 'listMenu',
className: 'e-de-floating-menu e-de-bullets-menu e-de-list-container e-de-list-thumbnail'
});
div.appendChild(ulTag);
this.noneBulletTag = this.createBulletListTag(ulTag, 'e-de-ctnr-bullet-none e-icons e-de-ctnr-list');
this.noneBulletTag.addEventListener('click', this.numberedNoneClick.bind(this));
this.dotBullet = this.createBulletListTag(ulTag, 'e-de-ctnr-bullet-dot e-icons e-de-ctnr-list');
this.dotBullet.addEventListener('click', this.bulletDotClick.bind(this));
this.circleBullet = this.createBulletListTag(ulTag, 'e-de-ctnr-bullet-circle e-icons e-de-ctnr-list');
this.circleBullet.addEventListener('click', this.bulletCircleClick.bind(this));
this.squareBullet = this.createBulletListTag(ulTag, 'e-de-ctnr-bullet-square e-icons e-de-ctnr-list');
this.squareBullet.addEventListener('click', this.bulletSquareClick.bind(this));
this.flowerBullet = this.createBulletListTag(ulTag, 'e-de-ctnr-bullet-flower e-icons e-de-ctnr-list');
this.flowerBullet.addEventListener('click', this.bulletFlowerClick.bind(this));
this.arrowBullet = this.createBulletListTag(ulTag, 'e-de-ctnr-bullet-arrow e-icons e-de-ctnr-list');
this.arrowBullet.addEventListener('click', this.bulletArrowClick.bind(this));
this.tickBullet = this.createBulletListTag(ulTag, 'e-de-ctnr-bullet-tick e-icons e-de-ctnr-list');
this.tickBullet.addEventListener('click', this.bulletTickClick.bind(this));
const menuOptions: SplitButtonModel = {
target: div,
iconCss: iconcss,
cssClass: this.splitButtonClass,
beforeOpen: (): void => {
div.style.display = 'block';
this.updateSelectedBulletListType(this.documentEditor.selection.paragraphFormat.listText);
},
beforeClose: (): void => {
div.style.display = 'none';
this.removeSelectedList();
}
};
this.bulletListBtn = new SplitButton(menuOptions);
this.bulletListBtn.click = (): void => {
this.applyLastAppliedBullet();
};
this.bulletListBtn.appendTo(button);
button.parentElement.setAttribute('title', this.localObj.getConstant('Bullets'));
}
private createNumberListTag(ulTag: HTMLElement, text1: string, text2: string, text3: string): HTMLElement {
const liTag: HTMLElement = createElement('li', {
styles: 'display:block',
className: 'e-de-floating-menuitem e-de-floating-menuitem-md e-de-list-items e-de-list-item-size'
});
ulTag.appendChild(liTag);
let innerHTML: string = '<div>' + text1 + '<span class="e-de-list-line"></span></div><div>' + text2 + '<span class="e-de-list-line">';
innerHTML += '</span></div><div>' + text3 + '<span class="e-de-list-line"> </span></div >';
const liInnerDiv: HTMLElement = createElement('div', {
className: 'e-de-list-header-presetmenu',
id: 'ui-zlist0', innerHTML: innerHTML
});
liTag.appendChild(liInnerDiv);
return liTag;
}
private createNumberNoneListTag(ulTag: HTMLElement): HTMLElement {
const liTag: HTMLElement = createElement('li', {
styles: 'display:block;',
className: 'e-de-floating-menuitem e-de-floating-menuitem-md e-de-list-items e-de-list-item-size'
});
ulTag.appendChild(liTag);
const innerHTML: string = '<div><span class="e-de-bullets">None</span></div>';
const liInnerDiv: HTMLElement = createElement('div', {
className: 'e-de-list-header-presetmenu', styles: 'position:relative;left:11px;top:13px',
id: 'ui-zlist0', innerHTML: innerHTML
});
liTag.appendChild(liInnerDiv);
return liTag;
}
private createBulletListTag(ulTag: HTMLElement, iconCss: string): HTMLElement {
const liTag: HTMLElement = createElement('li', {
styles: 'display:block;',
className: 'e-de-floating-menuitem e-de-floating-bullet-menuitem-md e-de-list-items e-de-list-item-size'
});
ulTag.appendChild(liTag);
const liInnerDiv: HTMLElement = createElement('div', { className: 'e-de-bullet-list-header-presetmenu', id: 'ui-zlist0' });
const spanDiv: HTMLElement = createElement('div');
liInnerDiv.appendChild(spanDiv);
const span: HTMLElement = createElement('span', { className: iconCss });
spanDiv.appendChild(span);
liTag.appendChild(liInnerDiv);
return liTag;
}
private createStyleDropDownList(selectElement: HTMLElement): void {
this.style = new DropDownList({
dataSource: [{ StyleName: 'Normal', Class: 'e-icons e-edit-font' }],
cssClass: 'e-de-prop-dropdown',
popupHeight: '240px',
enableRtl: this.isRtl,
query: new Query().select(['StyleName', 'Style']),
fields: { text: 'StyleName', value: 'StyleName' },
change: this.selectStyleValue.bind(this)
});
if (!this.container.enableCsp) {
this.style.open = this.updateOptions.bind(this);
this.style.itemTemplate = '<span style="${Style}">${StyleName}</span>';
this.style.footerTemplate = '<span class="e-de-ctnr-dropdown-ftr">'
+ this.localObj.getConstant('Manage Styles') + '...' + '</span>';
this.style.isStringTemplate = true;
}
this.style.appendTo(selectElement);
selectElement.parentElement.setAttribute('title', this.localObj.getConstant('Styles'));
}
/* eslint-disable @typescript-eslint/no-explicit-any */
private updateOptions(args: any): void {
this.updateStyleNames();
args.popup.element.getElementsByClassName('e-de-ctnr-dropdown-ftr')[0].addEventListener('click', this.createStyle.bind(this));
}
public updateStyleNames(): void {
this.styleName = !isNullOrUndefined((this.style as any).itemData) ? (this.style as any).itemData.StyleName : undefined;
this.style.dataSource = this.constructStyleDropItems(this.documentEditor.getStyles('Paragraph'));
this.style.dataBind();
this.onSelectionChange();
}
private createStyle(): void {
this.style.hidePopup();
if (!this.documentEditor.isReadOnly) {
this.documentEditor.showDialog('Styles');
}
}
private constructStyleDropItems(styles: unknown[]): any {
const collection: any = [];
for (const styleObj of styles) {
const obj: any = {};
const styleName: string = this.localObj.getConstant((styleObj as any).name);
obj.StyleName = styleName === '' ? (styleObj as any).name : styleName;
obj.Style = this.parseStyle((styleObj as any).style as string);
collection.push(obj);
}
return collection;
}
private parseStyle(style: string): string {
let domStyle: string = '';
const styleObj: any = JSON.parse(style);
let textDecoration: string = '';
if (!isNullOrUndefined(styleObj.characterFormat.baselineAlignment) && styleObj.characterFormat.baselineAlignment !== 'Normal') {
let vAlign: string = '';
switch (styleObj.characterFormat.baselineAlignment) {
case 'Superscript':
vAlign = 'super';
break;
case 'Subscript':
vAlign = 'sub';
break;
}
if (vAlign.length > 1) {
domStyle += 'vertical-align:' + vAlign + ';';
}
}
if (!isNullOrUndefined(styleObj.characterFormat.underline) && styleObj.characterFormat.underline !== 'None') {
textDecoration += 'underline ';
}
if (!isNullOrUndefined(styleObj.characterFormat.strikethrough) && styleObj.characterFormat.strikethrough !== 'None') {
textDecoration += 'line-through ';
}
if (!isNullOrUndefined(styleObj.characterFormat.fontSize)) {
domStyle += 'font-size:' + styleObj.characterFormat.fontSize + 'px;';
}
if (!isNullOrUndefined(styleObj.characterFormat.fontFamily)) {
domStyle += 'font-family:' + styleObj.characterFormat.fontFamily + ';';
}
if (!isNullOrUndefined(styleObj.characterFormat.bold) && styleObj.characterFormat.bold) {
domStyle += 'font-weight:bold;';
}
if (!isNullOrUndefined(styleObj.characterFormat.italic) && styleObj.characterFormat.italic) {
domStyle += 'font-style:italic;';
}
// if (!isNullOrUndefined(styleObj.characterFormat.fontColor)) {
// domStyle += 'color: ' + styleObj.characterFormat.fontColor + ';';
// }
if (textDecoration.length > 1) {
domStyle += 'text-decoration:' + textDecoration + ';';
}
return domStyle;
}
public wireEvent(): void {
this.leftAlignment.addEventListener('click', (): void => {
this.leftAlignmentAction();
});
this.rightAlignment.addEventListener('click', (): void => {
this.rightAlignmentAction();
});
this.centerAlignment.addEventListener('click', (): void => {
this.centerAlignmentAction();
});
this.justify.addEventListener('click', (): void => {
this.justifyAction();
});
this.increaseIndent.addEventListener('click', (): void => {
this.increaseIndentAction();
});
this.decreaseIndent.addEventListener('click', (): void => {
this.decreaseIndentAction();
});
this.lineSpacing.addEventListener('select', (args: MenuEventArgs): void => {
this.lineSpacingAction(args);
});
}
public unwireEvents(): void {
this.leftAlignment.click = undefined;
this.rightAlignment.click = undefined;
this.centerAlignment.click = undefined;
this.justify.click = undefined;
this.increaseIndent.click = undefined;
this.decreaseIndent.click = undefined;
this.lineSpacing.select = undefined;
this.style.select = undefined;
}
private leftAlignmentAction(): void {
if (this.isRetrieving) {
return;
}
if (!this.documentEditor.isReadOnly && this.documentEditor.editor) {
this.documentEditor.editor.toggleTextAlignment('Left');
}
}
private lineSpacingAction(args: any): void {
if (this.isRetrieving) {
return;
}
const text: string = args.item.text;
switch (text) {
case this.localObj.getConstant('Single'):
this.documentEditor.selection.paragraphFormat.lineSpacing = 1;
break;
case '1.15':
this.documentEditor.selection.paragraphFormat.lineSpacing = 1.15;
break;
case '1.5':
this.documentEditor.selection.paragraphFormat.lineSpacing = 1.5;
break;
case this.localObj.getConstant('Double'):
this.documentEditor.selection.paragraphFormat.lineSpacing = 2;
break;
}
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
private setLineSpacing(): void {
const lineSpacing: number = this.documentEditor.selection.paragraphFormat.lineSpacing;
if (lineSpacing === 1) {
this.appliedLineSpacing = this.localObj.getConstant('Single');
} else if (lineSpacing === 1.15) {
this.appliedLineSpacing = '1.15';
} else if (lineSpacing === 1.5) {
this.appliedLineSpacing = '1.5';
} else if (lineSpacing === 2) {
this.appliedLineSpacing = this.localObj.getConstant('Double');
} else {
this.appliedLineSpacing = '';
}
}
private selectStyleValue(args: any): void {
if (this.isRetrieving || !args.isInteracted) {
return;
}
setTimeout((): void => {
this.applyStyleValue(args);
}, 10);
}
private applyStyleValue(args: any): void {
if (!this.documentEditor.isReadOnly && this.documentEditor.editor) {
if (this.localObj.getConstant('Heading 1') === args.itemData.StyleName)
{
args.itemData.StyleName = 'Heading 1';
} else if (this.localObj.getConstant('Heading 2') === args.itemData.StyleName) {
args.itemData.StyleName = 'Heading 2';
} else if (this.localObj.getConstant('Heading 3') === args.itemData.StyleName) {
args.itemData.StyleName = 'Heading 3';
} else if (this.localObj.getConstant('Heading 4') === args.itemData.StyleName) {
args.itemData.StyleName = 'Heading 4';
} else if (this.localObj.getConstant('Heading 5') === args.itemData.StyleName) {
args.itemData.StyleName = 'Heading 5';
} else if (this.localObj.getConstant('Heading 6') === args.itemData.StyleName) {
args.itemData.StyleName = 'Heading 6';
} else if (this.localObj.getConstant('Normal') === args.itemData.StyleName) {
args.itemData.StyleName = 'Normal';
}
this.documentEditor.editor.applyStyle(args.itemData.StyleName, true);
}
}
/* eslint-enable @typescript-eslint/no-explicit-any */
private rightAlignmentAction(): void {
if (this.isRetrieving) {
return;
}
if (!this.documentEditor.isReadOnly && this.documentEditor.editor) {
this.documentEditor.editor.toggleTextAlignment('Right');
}
}
private centerAlignmentAction(): void {
if (this.isRetrieving) {
return;
}
if (!this.documentEditor.isReadOnly && this.documentEditor.editor) {
this.documentEditor.editor.toggleTextAlignment('Center');
}
}
private justifyAction(): void {
if (this.isRetrieving) {
return;
}
if (!this.documentEditor.isReadOnly && this.documentEditor.editor) {
this.documentEditor.editor.toggleTextAlignment('Justify');
}
}
private increaseIndentAction(): void {
if (this.isRetrieving) {
return;
}
if (!this.documentEditor.isReadOnly && this.documentEditor.editor) {
this.documentEditor.editor.increaseIndent();
}
}
private decreaseIndentAction(): void {
if (this.isRetrieving) {
return;
}
if (!this.documentEditor.isReadOnly && this.documentEditor.editor) {
this.documentEditor.editor.decreaseIndent();
}
}
private numberedNoneClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.documentEditor.editor.clearList();
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private numberedNumberDotClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedNumberingStyle = 'arabic';
this.documentEditor.editor.applyNumbering('%1.', 'Arabic');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private numberedUpRomanClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedNumberingStyle = 'uproman';
this.documentEditor.editor.applyNumbering('%1.', 'UpRoman');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private numberedUpLetterClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedNumberingStyle = 'upletter';
this.documentEditor.editor.applyNumbering('%1.', 'UpLetter');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private numberedLowLetterClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedNumberingStyle = 'lowletter';
this.documentEditor.editor.applyNumbering('%1.', 'LowLetter');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private numberedLowRomanClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedNumberingStyle = 'lowroman';
this.documentEditor.editor.applyNumbering('%1.', 'LowRoman');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private bulletDotClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedBulletStyle = 'dot';
this.documentEditor.editor.applyBullet('\uf0b7', 'Symbol');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private bulletCircleClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedBulletStyle = 'circle';
this.documentEditor.editor.applyBullet('\uf06f' + '\u0020', 'Symbol');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private bulletSquareClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedBulletStyle = 'square';
this.documentEditor.editor.applyBullet('\uf0a7', 'Wingdings');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private bulletFlowerClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedBulletStyle = 'flower';
this.documentEditor.editor.applyBullet('\uf076', 'Wingdings');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private bulletArrowClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedBulletStyle = 'arrow';
this.documentEditor.editor.applyBullet('\uf0d8', 'Wingdings');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
private bulletTickClick(): void {
if (this.isRetrieving) {
return;
}
if (this.documentEditor.editor) {
this.appliedBulletStyle = 'tick';
this.documentEditor.editor.applyBullet('\uf0fc', 'Wingdings');
setTimeout((): void => {
this.documentEditor.focusIn();
}, 30);
}
}
public onSelectionChange(): void {
this.isRetrieving = true;
if (this.documentEditor.editor) {
//#region paragraph format
const style: string = this.documentEditor.selection.paragraphFormat.styleName;
if (style) {
this.style.value = style;
this.style.dataBind();
} else {
this.style.value = null;
}
classList(this.leftAlignment, [], ['e-btn-toggle']);
classList(this.rightAlignment, [], ['e-btn-toggle']);
classList(this.centerAlignment, [], ['e-btn-toggle']);
classList(this.justify, [], ['e-btn-toggle']);
if (this.documentEditor.selection.paragraphFormat.textAlignment === 'Left') {
classList(this.leftAlignment, ['e-btn-toggle'], []);
} else if (this.documentEditor.selection.paragraphFormat.textAlignment === 'Right') {
classList(this.rightAlignment, ['e-btn-toggle'], []);
} else if (this.documentEditor.selection.paragraphFormat.textAlignment === 'Center') {
classList(this.centerAlignment, ['e-btn-toggle'], []);
} else if (this.documentEditor.selection.paragraphFormat.textAlignment === 'Justify') {
classList(this.justify, ['e-btn-toggle'], []);
}
//#endregion
}
this.setLineSpacing();
this.isRetrieving = false;
}
public destroy(): void {
this.container = undefined;
if (this.lineSpacing) {
this.lineSpacing.destroy();
this.lineSpacing = undefined;
}
if (this.style) {
this.style.destroy();
this.style = undefined;
}
if (this.bulletListBtn) {
this.bulletListBtn.destroy();
this.bulletListBtn = undefined;
}
if (this.numberedListBtn) {
this.numberedListBtn.destroy();
this.numberedListBtn = undefined;
}
}
} | the_stack |
declare module 'dns/promises' {
import {
LookupAddress,
LookupOneOptions,
LookupAllOptions,
LookupOptions,
AnyRecord,
CaaRecord,
MxRecord,
NaptrRecord,
SoaRecord,
SrvRecord,
ResolveWithTtlOptions,
RecordWithTtl,
ResolveOptions,
ResolverOptions,
} from 'node:dns';
/**
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
* that are currently configured for DNS resolution. A string will include a port
* section if a custom port is used.
*
* ```js
* [
* '4.4.4.4',
* '2001:4860:4860::8888',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]
* ```
* @since v10.6.0
*/
function getServers(): string[];
/**
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
* integer, then it must be `4` or `6` – if `options` is not provided, then IPv4
* and IPv6 addresses are both returned if found.
*
* With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`.
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code.
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
* the host name does not exist but also when the lookup fails in other ways
* such as no available file descriptors.
*
* `dnsPromises.lookup()` does not necessarily have anything to do with the DNS
* protocol. The implementation uses an operating system facility that can
* associate names with addresses, and vice versa. This implementation can have
* subtle but important consequences on the behavior of any Node.js program. Please
* take some time to consult the `Implementation considerations section` before
* using `dnsPromises.lookup()`.
*
* Example usage:
*
* ```js
* const dns = require('dns');
* const dnsPromises = dns.promises;
* const options = {
* family: 6,
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
* };
*
* dnsPromises.lookup('example.com', options).then((result) => {
* console.log('address: %j family: IPv%s', result.address, result.family);
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
* });
*
* // When options.all is true, the result will be an Array.
* options.all = true;
* dnsPromises.lookup('example.com', options).then((result) => {
* console.log('addresses: %j', result);
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
* });
* ```
* @since v10.6.0
*/
function lookup(hostname: string, family: number): Promise<LookupAddress>;
function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>;
function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
function lookup(hostname: string): Promise<LookupAddress>;
/**
* Resolves the given `address` and `port` into a host name and service using
* the operating system's underlying `getnameinfo` implementation.
*
* If `address` is not a valid IP address, a `TypeError` will be thrown.
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown.
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code.
*
* ```js
* const dnsPromises = require('dns').promises;
* dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
* console.log(result.hostname, result.service);
* // Prints: localhost ssh
* });
* ```
* @since v10.6.0
*/
function lookupService(
address: string,
port: number
): Promise<{
hostname: string;
service: string;
}>;
/**
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
* of the resource records. When successful, the `Promise` is resolved with an
* array of resource records. The type and structure of individual results vary
* based on `rrtype`:
*
* <omitted>
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`.
* @since v10.6.0
* @param hostname Host name to resolve.
* @param rrtype Resource record type.
*/
function resolve(hostname: string): Promise<string[]>;
function resolve(hostname: string, rrtype: 'A'): Promise<string[]>;
function resolve(hostname: string, rrtype: 'AAAA'): Promise<string[]>;
function resolve(hostname: string, rrtype: 'ANY'): Promise<AnyRecord[]>;
function resolve(hostname: string, rrtype: 'CAA'): Promise<CaaRecord[]>;
function resolve(hostname: string, rrtype: 'CNAME'): Promise<string[]>;
function resolve(hostname: string, rrtype: 'MX'): Promise<MxRecord[]>;
function resolve(hostname: string, rrtype: 'NAPTR'): Promise<NaptrRecord[]>;
function resolve(hostname: string, rrtype: 'NS'): Promise<string[]>;
function resolve(hostname: string, rrtype: 'PTR'): Promise<string[]>;
function resolve(hostname: string, rrtype: 'SOA'): Promise<SoaRecord>;
function resolve(hostname: string, rrtype: 'SRV'): Promise<SrvRecord[]>;
function resolve(hostname: string, rrtype: 'TXT'): Promise<string[][]>;
function resolve(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
/**
* Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4
* addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
* @since v10.6.0
* @param hostname Host name to resolve.
*/
function resolve4(hostname: string): Promise<string[]>;
function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
/**
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6
* addresses.
* @since v10.6.0
* @param hostname Host name to resolve.
*/
function resolve6(hostname: string): Promise<string[]>;
function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
/**
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
* On success, the `Promise` is resolved with an array containing various types of
* records. Each object has a property `type` that indicates the type of the
* current record. And depending on the `type`, additional properties will be
* present on the object:
*
* <omitted>
*
* Here is an example of the result object:
*
* ```js
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
* { type: 'CNAME', value: 'example.com' },
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
* { type: 'NS', value: 'ns1.example.com' },
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
* { type: 'SOA',
* nsname: 'ns1.example.com',
* hostmaster: 'admin.example.com',
* serial: 156696742,
* refresh: 900,
* retry: 900,
* expire: 1800,
* minttl: 60 } ]
* ```
* @since v10.6.0
*/
function resolveAny(hostname: string): Promise<AnyRecord[]>;
/**
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success,
* the `Promise` is resolved with an array of objects containing available
* certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`).
* @since v15.0.0
*/
function resolveCaa(hostname: string): Promise<CaaRecord[]>;
/**
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
* the `Promise` is resolved with an array of canonical name records available for
* the `hostname` (e.g. `['bar.example.com']`).
* @since v10.6.0
*/
function resolveCname(hostname: string): Promise<string[]>;
/**
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects
* containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
* @since v10.6.0
*/
function resolveMx(hostname: string): Promise<MxRecord[]>;
/**
* Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array
* of objects with the following properties:
*
* * `flags`
* * `service`
* * `regexp`
* * `replacement`
* * `order`
* * `preference`
*
* ```js
* {
* flags: 's',
* service: 'SIP+D2U',
* regexp: '',
* replacement: '_sip._udp.example.com',
* order: 30,
* preference: 100
* }
* ```
* @since v10.6.0
*/
function resolveNaptr(hostname: string): Promise<NaptrRecord[]>;
/**
* Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server
* records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`).
* @since v10.6.0
*/
function resolveNs(hostname: string): Promise<string[]>;
/**
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings
* containing the reply records.
* @since v10.6.0
*/
function resolvePtr(hostname: string): Promise<string[]>;
/**
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
* the `hostname`. On success, the `Promise` is resolved with an object with the
* following properties:
*
* * `nsname`
* * `hostmaster`
* * `serial`
* * `refresh`
* * `retry`
* * `expire`
* * `minttl`
*
* ```js
* {
* nsname: 'ns.example.com',
* hostmaster: 'root.example.com',
* serial: 2013101809,
* refresh: 10000,
* retry: 2400,
* expire: 604800,
* minttl: 3600
* }
* ```
* @since v10.6.0
*/
function resolveSoa(hostname: string): Promise<SoaRecord>;
/**
* Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with
* the following properties:
*
* * `priority`
* * `weight`
* * `port`
* * `name`
*
* ```js
* {
* priority: 10,
* weight: 5,
* port: 21223,
* name: 'service.example.com'
* }
* ```
* @since v10.6.0
*/
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
/**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array
* of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
* one record. Depending on the use case, these could be either joined together or
* treated separately.
* @since v10.6.0
*/
function resolveTxt(hostname: string): Promise<string[][]>;
/**
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
* array of host names.
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`.
* @since v10.6.0
*/
function reverse(ip: string): Promise<string[]>;
/**
* Sets the IP address and port of servers to be used when performing DNS
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
*
* ```js
* dnsPromises.setServers([
* '4.4.4.4',
* '[2001:4860:4860::8888]',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]);
* ```
*
* An error will be thrown if an invalid address is provided.
*
* The `dnsPromises.setServers()` method must not be called while a DNS query is in
* progress.
*
* This method works much like[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
* That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
* subsequent servers provided. Fallback DNS servers will only be used if the
* earlier ones time out or result in some other error.
* @since v10.6.0
* @param servers array of `RFC 5952` formatted addresses
*/
function setServers(servers: ReadonlyArray<string>): void;
class Resolver {
constructor(options?: ResolverOptions);
cancel(): void;
getServers: typeof getServers;
resolve: typeof resolve;
resolve4: typeof resolve4;
resolve6: typeof resolve6;
resolveAny: typeof resolveAny;
resolveCname: typeof resolveCname;
resolveMx: typeof resolveMx;
resolveNaptr: typeof resolveNaptr;
resolveNs: typeof resolveNs;
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
setLocalAddress(ipv4?: string, ipv6?: string): void;
setServers: typeof setServers;
}
}
declare module 'node:dns/promises' {
export * from 'dns/promises';
} | the_stack |
import type { AutoAcceptProof } from './ProofAutoAcceptType'
import type { PresentationPreview, RequestPresentationMessage } from './messages'
import type { RequestedCredentials, RetrievedCredentials } from './models'
import type { ProofRequestOptions } from './models/ProofRequest'
import type { ProofRecord } from './repository/ProofRecord'
import { Lifecycle, scoped } from 'tsyringe'
import { AgentConfig } from '../../agent/AgentConfig'
import { Dispatcher } from '../../agent/Dispatcher'
import { MessageSender } from '../../agent/MessageSender'
import { createOutboundMessage } from '../../agent/helpers'
import { ServiceDecorator } from '../../decorators/service/ServiceDecorator'
import { AriesFrameworkError } from '../../error'
import { ConnectionService } from '../connections/services/ConnectionService'
import { MediationRecipientService } from '../routing/services/MediationRecipientService'
import { ProofResponseCoordinator } from './ProofResponseCoordinator'
import { PresentationProblemReportReason } from './errors'
import {
ProposePresentationHandler,
RequestPresentationHandler,
PresentationAckHandler,
PresentationHandler,
PresentationProblemReportHandler,
} from './handlers'
import { PresentationProblemReportMessage } from './messages/PresentationProblemReportMessage'
import { ProofRequest } from './models/ProofRequest'
import { ProofService } from './services'
@scoped(Lifecycle.ContainerScoped)
export class ProofsModule {
private proofService: ProofService
private connectionService: ConnectionService
private messageSender: MessageSender
private mediationRecipientService: MediationRecipientService
private agentConfig: AgentConfig
private proofResponseCoordinator: ProofResponseCoordinator
public constructor(
dispatcher: Dispatcher,
proofService: ProofService,
connectionService: ConnectionService,
mediationRecipientService: MediationRecipientService,
agentConfig: AgentConfig,
messageSender: MessageSender,
proofResponseCoordinator: ProofResponseCoordinator
) {
this.proofService = proofService
this.connectionService = connectionService
this.messageSender = messageSender
this.mediationRecipientService = mediationRecipientService
this.agentConfig = agentConfig
this.proofResponseCoordinator = proofResponseCoordinator
this.registerHandlers(dispatcher)
}
/**
* Initiate a new presentation exchange as prover by sending a presentation proposal message
* to the connection with the specified connection id.
*
* @param connectionId The connection to send the proof proposal to
* @param presentationProposal The presentation proposal to include in the message
* @param config Additional configuration to use for the proposal
* @returns Proof record associated with the sent proposal message
*
*/
public async proposeProof(
connectionId: string,
presentationProposal: PresentationPreview,
config?: {
comment?: string
autoAcceptProof?: AutoAcceptProof
}
): Promise<ProofRecord> {
const connection = await this.connectionService.getById(connectionId)
const { message, proofRecord } = await this.proofService.createProposal(connection, presentationProposal, config)
const outbound = createOutboundMessage(connection, message)
await this.messageSender.sendMessage(outbound)
return proofRecord
}
/**
* Accept a presentation proposal as verifier (by sending a presentation request message) to the connection
* associated with the proof record.
*
* @param proofRecordId The id of the proof record for which to accept the proposal
* @param config Additional configuration to use for the request
* @returns Proof record associated with the presentation request
*
*/
public async acceptProposal(
proofRecordId: string,
config?: {
request?: {
name?: string
version?: string
nonce?: string
}
comment?: string
}
): Promise<ProofRecord> {
const proofRecord = await this.proofService.getById(proofRecordId)
if (!proofRecord.connectionId) {
throw new AriesFrameworkError(
`No connectionId found for credential record '${proofRecord.id}'. Connection-less issuance does not support presentation proposal or negotiation.`
)
}
const connection = await this.connectionService.getById(proofRecord.connectionId)
const presentationProposal = proofRecord.proposalMessage?.presentationProposal
if (!presentationProposal) {
throw new AriesFrameworkError(`Proof record with id ${proofRecordId} is missing required presentation proposal`)
}
const proofRequest = await this.proofService.createProofRequestFromProposal(presentationProposal, {
name: config?.request?.name ?? 'proof-request',
version: config?.request?.version ?? '1.0',
nonce: config?.request?.nonce,
})
const { message } = await this.proofService.createRequestAsResponse(proofRecord, proofRequest, {
comment: config?.comment,
})
const outboundMessage = createOutboundMessage(connection, message)
await this.messageSender.sendMessage(outboundMessage)
return proofRecord
}
/**
* Initiate a new presentation exchange as verifier by sending a presentation request message
* to the connection with the specified connection id
*
* @param connectionId The connection to send the proof request to
* @param proofRequestOptions Options to build the proof request
* @returns Proof record associated with the sent request message
*
*/
public async requestProof(
connectionId: string,
proofRequestOptions: CreateProofRequestOptions,
config?: ProofRequestConfig
): Promise<ProofRecord> {
const connection = await this.connectionService.getById(connectionId)
const nonce = proofRequestOptions.nonce ?? (await this.proofService.generateProofRequestNonce())
const proofRequest = new ProofRequest({
name: proofRequestOptions.name ?? 'proof-request',
version: proofRequestOptions.name ?? '1.0',
nonce,
requestedAttributes: proofRequestOptions.requestedAttributes,
requestedPredicates: proofRequestOptions.requestedPredicates,
})
const { message, proofRecord } = await this.proofService.createRequest(proofRequest, connection, config)
const outboundMessage = createOutboundMessage(connection, message)
await this.messageSender.sendMessage(outboundMessage)
return proofRecord
}
/**
* Initiate a new presentation exchange as verifier by creating a presentation request
* not bound to any connection. The request must be delivered out-of-band to the holder
*
* @param proofRequestOptions Options to build the proof request
* @returns The proof record and proof request message
*
*/
public async createOutOfBandRequest(
proofRequestOptions: CreateProofRequestOptions,
config?: ProofRequestConfig
): Promise<{
requestMessage: RequestPresentationMessage
proofRecord: ProofRecord
}> {
const nonce = proofRequestOptions.nonce ?? (await this.proofService.generateProofRequestNonce())
const proofRequest = new ProofRequest({
name: proofRequestOptions.name ?? 'proof-request',
version: proofRequestOptions.name ?? '1.0',
nonce,
requestedAttributes: proofRequestOptions.requestedAttributes,
requestedPredicates: proofRequestOptions.requestedPredicates,
})
const { message, proofRecord } = await this.proofService.createRequest(proofRequest, undefined, config)
// Create and set ~service decorator
const routing = await this.mediationRecipientService.getRouting()
message.service = new ServiceDecorator({
serviceEndpoint: routing.endpoints[0],
recipientKeys: [routing.verkey],
routingKeys: routing.routingKeys,
})
// Save ~service decorator to record (to remember our verkey)
proofRecord.requestMessage = message
await this.proofService.update(proofRecord)
return { proofRecord, requestMessage: message }
}
/**
* Accept a presentation request as prover (by sending a presentation message) to the connection
* associated with the proof record.
*
* @param proofRecordId The id of the proof record for which to accept the request
* @param requestedCredentials The requested credentials object specifying which credentials to use for the proof
* @param config Additional configuration to use for the presentation
* @returns Proof record associated with the sent presentation message
*
*/
public async acceptRequest(
proofRecordId: string,
requestedCredentials: RequestedCredentials,
config?: {
comment?: string
}
): Promise<ProofRecord> {
const record = await this.proofService.getById(proofRecordId)
const { message, proofRecord } = await this.proofService.createPresentation(record, requestedCredentials, config)
// Use connection if present
if (proofRecord.connectionId) {
const connection = await this.connectionService.getById(proofRecord.connectionId)
const outboundMessage = createOutboundMessage(connection, message)
await this.messageSender.sendMessage(outboundMessage)
return proofRecord
}
// Use ~service decorator otherwise
else if (proofRecord.requestMessage?.service) {
// Create ~service decorator
const routing = await this.mediationRecipientService.getRouting()
const ourService = new ServiceDecorator({
serviceEndpoint: routing.endpoints[0],
recipientKeys: [routing.verkey],
routingKeys: routing.routingKeys,
})
const recipientService = proofRecord.requestMessage.service
// Set and save ~service decorator to record (to remember our verkey)
message.service = ourService
proofRecord.presentationMessage = message
await this.proofService.update(proofRecord)
await this.messageSender.sendMessageToService({
message,
service: recipientService.toDidCommService(),
senderKey: ourService.recipientKeys[0],
returnRoute: true,
})
return proofRecord
}
// Cannot send message without connectionId or ~service decorator
else {
throw new AriesFrameworkError(
`Cannot accept presentation request without connectionId or ~service decorator on presentation request.`
)
}
}
/**
* Declines a proof request as holder
* @param proofRecordId the id of the proof request to be declined
* @returns proof record that was declined
*/
public async declineRequest(proofRecordId: string) {
const proofRecord = await this.proofService.getById(proofRecordId)
await this.proofService.declineRequest(proofRecord)
return proofRecord
}
/**
* Accept a presentation as prover (by sending a presentation acknowledgement message) to the connection
* associated with the proof record.
*
* @param proofRecordId The id of the proof record for which to accept the presentation
* @returns Proof record associated with the sent presentation acknowledgement message
*
*/
public async acceptPresentation(proofRecordId: string): Promise<ProofRecord> {
const record = await this.proofService.getById(proofRecordId)
const { message, proofRecord } = await this.proofService.createAck(record)
// Use connection if present
if (proofRecord.connectionId) {
const connection = await this.connectionService.getById(proofRecord.connectionId)
const outboundMessage = createOutboundMessage(connection, message)
await this.messageSender.sendMessage(outboundMessage)
}
// Use ~service decorator otherwise
else if (proofRecord.requestMessage?.service && proofRecord.presentationMessage?.service) {
const recipientService = proofRecord.presentationMessage?.service
const ourService = proofRecord.requestMessage?.service
await this.messageSender.sendMessageToService({
message,
service: recipientService.toDidCommService(),
senderKey: ourService.recipientKeys[0],
returnRoute: true,
})
}
// Cannot send message without credentialId or ~service decorator
else {
throw new AriesFrameworkError(
`Cannot accept presentation without connectionId or ~service decorator on presentation message.`
)
}
return proofRecord
}
/**
* Create a {@link RetrievedCredentials} object. Given input proof request and presentation proposal,
* use credentials in the wallet to build indy requested credentials object for input to proof creation.
* If restrictions allow, self attested attributes will be used.
*
*
* @param proofRecordId the id of the proof request to get the matching credentials for
* @param config optional configuration for credential selection process. Use `filterByPresentationPreview` (default `true`) to only include
* credentials that match the presentation preview from the presentation proposal (if available).
* @returns RetrievedCredentials object
*/
public async getRequestedCredentialsForProofRequest(
proofRecordId: string,
config?: GetRequestedCredentialsConfig
): Promise<RetrievedCredentials> {
const proofRecord = await this.proofService.getById(proofRecordId)
const indyProofRequest = proofRecord.requestMessage?.indyProofRequest
const presentationPreview = config?.filterByPresentationPreview
? proofRecord.proposalMessage?.presentationProposal
: undefined
if (!indyProofRequest) {
throw new AriesFrameworkError(
'Unable to get requested credentials for proof request. No proof request message was found or the proof request message does not contain an indy proof request.'
)
}
return this.proofService.getRequestedCredentialsForProofRequest(indyProofRequest, presentationPreview)
}
/**
* Takes a RetrievedCredentials object and auto selects credentials in a RequestedCredentials object
*
* Use the return value of this method as input to {@link ProofService.createPresentation} to
* automatically accept a received presentation request.
*
* @param retrievedCredentials The retrieved credentials object to get credentials from
*
* @returns RequestedCredentials
*/
public autoSelectCredentialsForProofRequest(retrievedCredentials: RetrievedCredentials): RequestedCredentials {
return this.proofService.autoSelectCredentialsForProofRequest(retrievedCredentials)
}
/**
* Send problem report message for a proof record
* @param proofRecordId The id of the proof record for which to send problem report
* @param message message to send
* @returns proof record associated with the proof problem report message
*/
public async sendProblemReport(proofRecordId: string, message: string) {
const record = await this.proofService.getById(proofRecordId)
if (!record.connectionId) {
throw new AriesFrameworkError(`No connectionId found for proof record '${record.id}'.`)
}
const connection = await this.connectionService.getById(record.connectionId)
const presentationProblemReportMessage = new PresentationProblemReportMessage({
description: {
en: message,
code: PresentationProblemReportReason.Abandoned,
},
})
presentationProblemReportMessage.setThread({
threadId: record.threadId,
})
const outboundMessage = createOutboundMessage(connection, presentationProblemReportMessage)
await this.messageSender.sendMessage(outboundMessage)
return record
}
/**
* Retrieve all proof records
*
* @returns List containing all proof records
*/
public getAll(): Promise<ProofRecord[]> {
return this.proofService.getAll()
}
/**
* Retrieve a proof record by id
*
* @param proofRecordId The proof record id
* @throws {RecordNotFoundError} If no record is found
* @throws {RecordDuplicateError} If multiple records are found
* @return The proof record
*
*/
public async getById(proofRecordId: string): Promise<ProofRecord> {
return this.proofService.getById(proofRecordId)
}
/**
* Retrieve a proof record by id
*
* @param proofRecordId The proof record id
* @return The proof record or null if not found
*
*/
public async findById(proofRecordId: string): Promise<ProofRecord | null> {
return this.proofService.findById(proofRecordId)
}
/**
* Delete a proof record by id
*
* @param proofId the proof record id
*/
public async deleteById(proofId: string) {
return this.proofService.deleteById(proofId)
}
private registerHandlers(dispatcher: Dispatcher) {
dispatcher.registerHandler(
new ProposePresentationHandler(this.proofService, this.agentConfig, this.proofResponseCoordinator)
)
dispatcher.registerHandler(
new RequestPresentationHandler(
this.proofService,
this.agentConfig,
this.proofResponseCoordinator,
this.mediationRecipientService
)
)
dispatcher.registerHandler(
new PresentationHandler(this.proofService, this.agentConfig, this.proofResponseCoordinator)
)
dispatcher.registerHandler(new PresentationAckHandler(this.proofService))
dispatcher.registerHandler(new PresentationProblemReportHandler(this.proofService))
}
}
export type CreateProofRequestOptions = Partial<
Pick<ProofRequestOptions, 'name' | 'nonce' | 'requestedAttributes' | 'requestedPredicates'>
>
export interface ProofRequestConfig {
comment?: string
autoAcceptProof?: AutoAcceptProof
}
export interface GetRequestedCredentialsConfig {
/**
* Whether to filter the retrieved credentials using the presentation preview.
* This configuration will only have effect if a presentation proposal message is available
* containing a presentation preview.
*/
filterByPresentationPreview?: boolean
} | the_stack |
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import url from 'url';
import Axios, { AxiosError } from 'axios';
import config from 'config';
import Debug from 'debug';
import { Request } from 'express';
import { isNull, omitBy, pick, startCase, toInteger, toUpper } from 'lodash';
import { TransferwiseError } from '../graphql/errors';
import {
AccessToken,
BatchGroup,
BorderlessAccount,
CurrencyPair,
Profile,
QuoteV2,
RecipientAccount,
TransactionRequirementsType,
Transfer,
Webhook,
WebhookCreateInput,
WebhookEvent,
} from '../types/transferwise';
import logger from './logger';
const debug = Debug('transferwise');
const fixieUrl = config.fixie.url && new url.URL(config.fixie.url);
const proxyOptions = fixieUrl
? {
proxy: {
host: fixieUrl.host,
port: toInteger(fixieUrl.port),
},
headers: {
'Proxy-Authorization': `Basic ${Buffer.from(`${fixieUrl.username}:${fixieUrl.password}`).toString('base64')}`,
},
}
: {};
const axios = Axios.create({
baseURL: config.transferwise.apiUrl,
...proxyOptions,
});
type TransferwiseErrorCodes = 'balance.payment-option-unavailable' | string;
const signString = (data: string) => {
const sign = crypto.createSign('SHA256');
sign.update(data);
sign.end();
const key = Buffer.from(config.transferwise.privateKey, 'base64').toString('ascii');
return sign.sign(key, 'base64');
};
const compactRecipientDetails = <T>(object: T): Partial<T> => <Partial<T>>omitBy(object, isNull);
const getData = <T extends { data?: Record<string, unknown> }>(obj: T | undefined): T['data'] | undefined =>
obj && obj.data;
const tap = fn => data => {
fn(data);
return data;
};
const parseError = (
error: AxiosError<{ errorCode?: TransferwiseErrorCodes; errors?: Record<string, unknown>[] }>,
defaultMessage?: string,
defaultCode?: string,
): string | Error => {
let message = defaultMessage;
let code = defaultCode;
if (error.response?.data?.errorCode) {
code = `transferwise.error.${error.response.data.errorCode}`;
}
if (error.response?.data?.errors) {
message = error.response.data.errors.map(e => e.message).join(' ');
}
if (error.response?.status === 422) {
message = `TransferWise validation error: ${message}`;
code = `transferwise.error.validation`;
}
return new TransferwiseError(message, code);
};
export const requestDataAndThrowParsedError = (
fn: Function,
url: string,
{
data,
...options
}: {
data?: Record<string, unknown>;
headers?: Record<string, unknown>;
params?: Record<string, unknown>;
auth?: Record<string, unknown>;
},
defaultErrorMessage?: string,
): Promise<any> => {
const start = process.hrtime.bigint();
debug(`calling ${config.transferwise.apiUrl}${url}: ${JSON.stringify({ data, params: options.params }, null, 2)}`);
const pRequest = data ? fn(url, data, options) : fn(url, options);
return pRequest
.then(getData)
.then(tap(data => debug(JSON.stringify(data, null, 2))))
.catch(e => {
// Implements Strong Customer Authentication
// https://api-docs.transferwise.com/#payouts-guide-strong-customer-authentication
const signatureFailed = e?.response?.headers['x-2fa-approval-result'] === 'REJECTED';
const hadSignature = e?.response?.headers['X-Signature'];
if (signatureFailed && !hadSignature) {
const ott = e.response.headers['x-2fa-approval'];
const signature = signString(ott);
options.headers = { ...options.headers, 'X-Signature': signature, 'x-2fa-approval': ott };
const request = data ? fn(url, data, options) : fn(url, options);
return request.then(getData);
} else {
throw e;
}
})
.catch(e => {
debug(JSON.stringify(e.response?.data, null, 2) || e);
const error = parseError(e, defaultErrorMessage);
logger.error(error.toString());
throw error;
})
.finally(() => {
const end = process.hrtime.bigint();
const executionTime = Math.round(Number(end - start) / 1000000);
debug(`called ${config.transferwise.apiUrl}${url} in ${executionTime}ms`);
});
};
interface CreateQuote {
profileId: number;
sourceCurrency: string;
targetCurrency: string;
targetAccount?: number;
targetAmount?: number;
sourceAmount?: number;
payOut?: 'BANK_TRANSFER' | 'BALANCE' | 'SWIFT' | 'INTERAC' | null;
}
export const createQuote = async (
token: string,
{
profileId: profile,
sourceCurrency,
targetCurrency,
targetAmount,
sourceAmount,
payOut,
targetAccount,
}: CreateQuote,
): Promise<QuoteV2> => {
const data = {
payOut,
profile,
sourceAmount,
sourceCurrency,
targetAccount,
targetAmount,
targetCurrency,
};
return requestDataAndThrowParsedError(
axios.post,
`/v2/quotes`,
{
headers: { Authorization: `Bearer ${token}` },
data,
},
'There was an error while creating the quote on Wise',
);
};
interface CreateRecipientAccount extends RecipientAccount {
profileId: number;
}
export const createRecipientAccount = async (
token: string,
{ profileId: profile, currency, type, accountHolderName, legalType, details }: CreateRecipientAccount,
): Promise<RecipientAccount> => {
const data = { profile, currency, type, accountHolderName, legalType, details };
const response = await requestDataAndThrowParsedError(
axios.post,
`/v1/accounts`,
{
data,
headers: { Authorization: `Bearer ${token}` },
},
"There was an error while creating Wise's recipient",
);
return {
...response,
details: compactRecipientDetails(response.details),
};
};
export interface CreateTransfer {
accountId: number;
quoteUuid: string;
customerTransactionId: string;
details?: {
reference?: string;
transferPurpose?: string;
sourceOfFunds?: string;
};
}
export const createTransfer = async (
token: string,
{ accountId: targetAccount, quoteUuid, customerTransactionId, details }: CreateTransfer,
): Promise<Transfer> => {
const data = { targetAccount, quoteUuid, customerTransactionId, details };
return requestDataAndThrowParsedError(
axios.post,
`/v1/transfers`,
{
data,
headers: { Authorization: `Bearer ${token}` },
},
'There was an error while creating the Wise transfer',
);
};
export const cancelTransfer = async (token: string, transferId: string | number): Promise<Transfer> => {
return requestDataAndThrowParsedError(
axios.put,
`/v1/transfers/${transferId}/cancel`,
{
data: {},
headers: { Authorization: `Bearer ${token}` },
},
'There was an error while cancelling the Wise transfer',
);
};
interface FundTransfer {
profileId: number;
transferId: number;
}
export const fundTransfer = async (
token: string,
{ profileId, transferId }: FundTransfer,
): Promise<{ status: 'COMPLETED' | 'REJECTED'; errorCode: string }> => {
return requestDataAndThrowParsedError(
axios.post,
`/v3/profiles/${profileId}/transfers/${transferId}/payments`,
{
data: { type: 'BALANCE' },
headers: { Authorization: `Bearer ${token}` },
},
'There was an error while funding the transfer for Wise',
);
};
export const getProfiles = async (token: string): Promise<Profile[]> => {
return requestDataAndThrowParsedError(
axios.get,
`/v1/profiles`,
{
headers: { Authorization: `Bearer ${token}` },
},
'There was an error fetching the profiles for Wise',
);
};
interface GetTemporaryQuote {
sourceCurrency: string;
targetCurrency: string;
targetAmount?: number;
sourceAmount?: number;
}
export const getTemporaryQuote = async (
token: string,
{ sourceCurrency, targetCurrency, ...amount }: GetTemporaryQuote,
): Promise<QuoteV2> => {
const data = {
sourceCurrency,
targetCurrency,
...amount,
};
return requestDataAndThrowParsedError(
axios.post,
`/v2/quotes`,
{
headers: { Authorization: `Bearer ${token}` },
data,
},
'There was an error while fetching the Wise quote',
);
};
export const getTransfer = async (token: string, transferId: number): Promise<Transfer> => {
return requestDataAndThrowParsedError(
axios.get,
`/v1/transfers/${transferId}`,
{
headers: { Authorization: `Bearer ${token}` },
},
'There was an error fetching transfer for Wise',
);
};
export const getAccountRequirements = async (
token: string,
{ sourceCurrency, targetCurrency, ...amount }: GetTemporaryQuote,
): Promise<Array<TransactionRequirementsType>> => {
const params = {
source: sourceCurrency,
target: targetCurrency,
...amount,
};
return requestDataAndThrowParsedError(
axios.get,
`/v1/account-requirements`,
{
headers: { Authorization: `Bearer ${token}`, 'Accept-Minor-Version': 1 },
params,
},
'There was an error while fetching account requirements for Wise',
);
};
export const validateAccountRequirements = async (
token: string,
{ sourceCurrency, targetCurrency, ...amount }: GetTemporaryQuote,
accountDetails: Record<string, unknown>,
): Promise<Array<TransactionRequirementsType>> => {
const params = {
source: sourceCurrency,
target: targetCurrency,
...amount,
};
return requestDataAndThrowParsedError(
axios.post,
`/v1/account-requirements`,
{
data: accountDetails,
headers: { Authorization: `Bearer ${token}`, 'Accept-Minor-Version': 1 },
params,
},
'There was an error while validating account requirements for Wise',
);
};
export const getCurrencyPairs = async (token: string): Promise<{ sourceCurrencies: CurrencyPair[] }> => {
return requestDataAndThrowParsedError(
axios.get,
`/v1/currency-pairs`,
{
headers: { Authorization: `Bearer ${token}` },
},
'There was an error while fetching account requirements for Wise',
);
};
export const getBorderlessAccount = async (token: string, profileId: string | number): Promise<BorderlessAccount> => {
try {
const accounts: BorderlessAccount[] = await requestDataAndThrowParsedError(
axios.get,
`/v1/borderless-accounts?profileId=${profileId}`,
{
headers: { Authorization: `Bearer ${token}` },
},
);
return accounts.find(a => a.profileId === profileId);
} catch (e) {
logger.error(e);
throw new Error("There was an error while fetching Host's Wise account");
}
};
export const createBatchGroup = async (
token: string,
profileId: string | number,
data: { name: string; sourceCurrency: string },
): Promise<BatchGroup> => {
try {
return requestDataAndThrowParsedError(axios.post, `/v3/profiles/${profileId}/batch-groups`, {
headers: { Authorization: `Bearer ${token}` },
data,
});
} catch (e) {
logger.error(e);
throw new Error('There was an error while creating the batch group.');
}
};
export const getBatchGroup = async (
token: string,
profileId: string | number,
batchGroupId: string,
): Promise<BatchGroup> => {
try {
return requestDataAndThrowParsedError(axios.get, `/v3/profiles/${profileId}/batch-groups/${batchGroupId}`, {
headers: { Authorization: `Bearer ${token}` },
});
} catch (e) {
logger.error(e);
throw new Error('There was an error while fetching the batch group.');
}
};
export const createBatchGroupTransfer = async (
token: string,
profileId: string | number,
batchGroupId: string,
{ accountId: targetAccount, quoteUuid, customerTransactionId, details }: CreateTransfer,
): Promise<Transfer> => {
const data = { targetAccount, quoteUuid, customerTransactionId, details };
try {
return requestDataAndThrowParsedError(
axios.post,
`/v3/profiles/${profileId}/batch-groups/${batchGroupId}/transfers`,
{
data,
headers: { Authorization: `Bearer ${token}` },
},
);
} catch (e) {
logger.error(e);
throw new Error('There was an error while creating the Wise transfer in the batch group');
}
};
export const completeBatchGroup = async (
token: string,
profileId: string | number,
batchGroupId: string,
version: number,
): Promise<BatchGroup> => {
try {
return requestDataAndThrowParsedError(axios.patch, `/v3/profiles/${profileId}/batch-groups/${batchGroupId}`, {
data: { version, status: 'COMPLETED' },
headers: { Authorization: `Bearer ${token}` },
});
} catch (e) {
logger.error(e);
throw new Error('There was an error while creating the Wise transfer in the batch group');
}
};
export const cancelBatchGroup = async (
token: string,
profileId: string | number,
batchGroupId: string,
version: number,
): Promise<BatchGroup> => {
try {
return requestDataAndThrowParsedError(axios.patch, `/v3/profiles/${profileId}/batch-groups/${batchGroupId}`, {
data: { version, status: 'CANCELLED' },
headers: { Authorization: `Bearer ${token}` },
});
} catch (e) {
logger.error(e);
throw new Error('There was an error while creating the Wise transfer in the batch group');
}
};
export type OTTResponse = {
status: number;
headers: {
'x-2fa-approval': string;
};
};
export const fundBatchGroup = async (
token: string,
profileId: string | number,
batchGroupId: string,
x2faApproval?: string,
): Promise<BatchGroup | OTTResponse> => {
const headers = { Authorization: `Bearer ${token}` };
if (x2faApproval) {
headers['x-2fa-approval'] = x2faApproval;
}
return axios
.post(`/v3/profiles/${profileId}/batch-payments/${batchGroupId}/payments`, { type: 'BALANCE' }, { headers })
.then(getData)
.catch(e => {
const headers = pick(e.response?.headers, ['x-2fa-approval']);
const status = e.response?.status;
if (status === 403 && headers['x-2fa-approval']) {
return { headers, status };
} else {
logger.error(e);
throw new Error('There was an error while funding the batch group');
}
});
};
const isProduction = config.env === 'production';
const publicKey = fs.readFileSync(
path.join(
__dirname,
'..',
'..',
'keys',
isProduction ? 'transferwise.webhook.live.pub' : 'transferwise.webhook.sandbox.pub',
),
{ encoding: 'utf-8' },
);
export const verifyEvent = (req: Request & { rawBody: string }): WebhookEvent => {
const signature = req.headers['x-signature'] as string;
const sig = crypto.createVerify('RSA-SHA1');
sig.update(req.rawBody);
const verified = sig.verify(publicKey, signature, 'base64');
if (!verified) {
throw new Error('Could not verify event signature');
}
return req.body;
};
export const formatAccountDetails = (payoutMethodData: Record<string, unknown>): string => {
const ignoredKeys = ['type', 'isManualBankTransfer', 'currency'];
const labels = {
abartn: 'Routing Number',
};
const formatKey = (s: string): string => {
if (labels[s]) {
return labels[s];
}
if (toUpper(s) === s) {
return s;
}
return startCase(s);
};
const renderObject = (object: Record<string, unknown>, prefix = ''): string[] =>
Object.entries(object).reduce((acc, [key, value]) => {
if (ignoredKeys.includes(key)) {
return acc;
}
if (typeof value === 'object') {
return [...acc, formatKey(key), ...renderObject(<Record<string, unknown>>value, ' ')];
}
return [...acc, `${prefix}${formatKey(key)}: ${value}`];
}, []);
const { accountHolderName, currency, ...data } = payoutMethodData;
const lines = renderObject({ accountHolderName, currency, ...data });
return lines.join('\n');
};
export const getOAuthUrl = (state: string): string => {
return `${config.transferwise.oauthUrl}/oauth/authorize/?client_id=${config.transferwise.clientId}&redirect_uri=${config.transferwise.redirectUri}&state=${state}`;
};
export const getOrRefreshToken = async ({
code,
refreshToken,
application,
}: {
code?: string;
refreshToken?: string;
application?: boolean;
}): Promise<AccessToken> => {
let data;
// Refresh Token
if (refreshToken) {
data = { grant_type: 'refresh_token', refresh_token: refreshToken };
}
// Request user token
else if (code) {
data = {
grant_type: 'authorization_code',
client_id: config.transferwise.clientId,
code,
redirect_uri: config.transferwise.redirectUri,
};
}
// Request application token
else if (application) {
data = { grant_type: 'client_credentials' };
} else {
return;
}
const params = new url.URLSearchParams(data);
try {
const token: AccessToken = await axios
.post(`/oauth/token`, params.toString(), {
auth: { username: config.transferwise.clientId, password: config.transferwise.clientSecret },
})
.then(getData);
debug(`getOrRefreshUserToken: ${JSON.stringify(token, null, 2)}`);
return token;
} catch (e) {
const error = parseError(e, "There was an error while refreshing host's Wise token");
logger.error(error.toString());
throw error;
}
};
export const listApplicationWebhooks = async (): Promise<Webhook[]> => {
const { access_token } = await getOrRefreshToken({ application: true });
try {
const webhooks = await axios
.get(`/v3/applications/${config.transferwise.clientKey}/subscriptions`, {
headers: { Authorization: `Bearer ${access_token}` },
})
.then(getData);
return webhooks;
} catch (e) {
logger.error(e);
throw new Error("There was an error while listing Wise's application webhooks");
}
};
export const createApplicationWebhook = async (webhookInfo: WebhookCreateInput): Promise<Webhook> => {
const { access_token } = await getOrRefreshToken({ application: true });
debug(`createApplicationWebhook: ${JSON.stringify(webhookInfo, null, 2)}`);
try {
const webhook: Webhook = await axios
.post(`/v3/applications/${config.transferwise.clientKey}/subscriptions`, webhookInfo, {
headers: { Authorization: `Bearer ${access_token}` },
})
.then(getData);
return webhook;
} catch (e) {
logger.error(e);
throw new Error("There was an error while creating Wise's application webhook");
}
};
export const deleteApplicationWebhook = async (id: string | number): Promise<any> => {
const { access_token } = await getOrRefreshToken({ application: true });
debug(`deleteApplicationWebhook: id ${id}`);
try {
return await axios
.delete(`/v3/applications/${config.transferwise.clientKey}/subscriptions/${id}`, {
headers: { Authorization: `Bearer ${access_token}` },
})
.then(getData);
} catch (e) {
logger.error(e);
throw new Error("There was an error while deleting Wise's application webhook");
}
}; | the_stack |
import Base, { IPluginBaseConfig } from '../base';
import {
IEdge,
IAbstractGraph as IGraph,
GraphData,
NodeConfig,
NodeConfigMap,
EdgeConfig,
} from '@antv/f6-core';
import { Point } from '@antv/g-base';
interface BundlingConfig extends IPluginBaseConfig {
edgeBundles?: IEdge[];
edgePoints?: NodeConfig[];
K?: number;
lambda?: number;
divisions?: number;
divRate?: number;
cycles?: number;
iterations?: number;
iterRate?: number;
bundleThreshold?: number;
eps?: number;
onLayoutEnd?: () => void;
onTick?: () => void;
}
interface VectorPosition {
source: {
x: number;
y: number;
};
target: {
x: number;
y: number;
};
vx: number;
vy: number;
length: number;
}
function getEucliDis(pointA: Point, pointB: Point, eps?: number): number {
const vx = pointA.x - pointB.x;
const vy = pointA.y - pointB.y;
if (!eps || Math.abs(vx) > eps || Math.abs(vy) > eps) {
return Math.sqrt(vx * vx + vy * vy);
}
return eps;
}
function getDotProduct(ei: Point, ej: Point): number {
return ei.x * ej.x + ei.y * ej.y;
}
function projectPointToEdge(p: Point, e: VectorPosition): Point {
const k = (e.source.y - e.target.y) / (e.source.x - e.target.x);
const x = (k * k * e.source.x + k * (p.y - e.source.y) + p.x) / (k * k + 1);
const y = k * (x - e.source.x) + e.source.y;
return { x, y };
}
export default class Bundling extends Base {
constructor(config?: BundlingConfig) {
super(config);
}
public getDefaultCfgs(): BundlingConfig {
return {
edgeBundles: [], // |edges| arrays, each one stores the related edges' id
edgePoints: [], // |edges| * divisions edge points
K: 0.1, // 边的强度
lambda: 0.1, // 初始步长
divisions: 1, // 初始切割点数
divRate: 2, // subdivision rate increase
cycles: 6, // number of cycles to perform
iterations: 90, // 每个 cycle 初始迭代次数
iterRate: 0.6666667, // 迭代下降率
bundleThreshold: 0.6,
eps: 1e-6,
onLayoutEnd() {}, // 布局完成回调
onTick() {}, // 每一迭代布局回调
};
}
public init() {
const graph: IGraph = this.get('graph');
const onTick = this.get('onTick');
const tick = () => {
if (onTick) {
onTick();
}
graph.refreshPositions();
};
this.set('tick', tick);
}
public bundling(data: GraphData): void {
const self = this;
self.set('data', data);
// 如果正在布局,忽略布局请求
if (self.isTicking()) {
return;
}
const edges = data.edges || [];
const nodes = data.nodes || [];
const nodeIdMap: NodeConfigMap = {};
let error = false;
nodes.forEach((node) => {
if (node.x === null || !node.y === null || node.x === undefined || !node.y === undefined) {
error = true;
}
nodeIdMap[node.id] = node;
});
if (error) throw new Error('please layout the graph or assign x and y for nodes first');
self.set('nodeIdMap', nodeIdMap);
// subdivide each edges
let divisions: number = self.get('divisions');
const divRate: number = self.get('divRate');
let edgePoints: Point[][] = self.divideEdges(divisions);
self.set('edgePoints', edgePoints);
// compute the bundles
const edgeBundles = self.getEdgeBundles();
self.set('edgeBundles', edgeBundles);
// iterations
const C: number = self.get('cycles');
let iterations: number = self.get('iterations');
const iterRate: number = self.get('iterRate');
let lambda: number = self.get('lambda');
for (let i = 0; i < C; i++) {
for (let j = 0; j < iterations; j++) {
const forces: Point[][] = [];
edges.forEach((e, k) => {
if (e.source === e.target) return;
const source = nodeIdMap[e.source as string];
const target = nodeIdMap[e.target as string];
forces[k] = self.getEdgeForces({ source, target }, k, divisions, lambda);
for (let p = 0; p < divisions + 1; p++) {
edgePoints[k][p].x += forces[k][p].x;
edgePoints[k][p].y += forces[k][p].y;
}
});
}
// parameters for nex cycle
lambda = lambda / 2;
divisions *= divRate;
iterations *= iterRate;
edgePoints = self.divideEdges(divisions);
self.set('edgePoints', edgePoints);
}
// change the edges according to edgePoints
edges.forEach((e, i) => {
if (e.source === e.target) return;
e.type = 'polyline';
e.controlPoints = edgePoints[i].slice(1, edgePoints[i].length - 1);
});
const graph = self.get('graph');
graph.refresh();
}
public updateBundling(cfg: BundlingConfig) {
const self = this;
const { data } = cfg;
if (data) {
self.set('data', data);
}
if (self.get('ticking')) {
self.set('ticking', false);
}
Object.keys(cfg).forEach((key) => {
self.set(key, cfg[key]);
});
if (cfg.onTick) {
const graph = this.get('graph');
self.set('tick', () => {
cfg.onTick!();
graph.refresh();
});
}
self.bundling(data);
}
public divideEdges(divisions: number): Point[][] {
const self = this;
const edges: EdgeConfig[] = self.get('data').edges;
const nodeIdMap: NodeConfigMap = self.get('nodeIdMap');
let edgePoints = self.get('edgePoints');
if (!edgePoints || edgePoints === undefined) edgePoints = [];
edges.forEach((edge, i) => {
if (!edgePoints[i] || edgePoints[i] === undefined) {
edgePoints[i] = [];
}
const source = nodeIdMap[edge.source as string];
const target = nodeIdMap[edge.target as string];
if (divisions === 1) {
edgePoints[i].push({ x: source.x, y: source.y }); // source
edgePoints[i].push({
x: 0.5 * (source.x! + target.x!),
y: 0.5 * (source.y! + target.y!),
}); // mid
edgePoints[i].push({ x: target.x, y: target.y }); // target
} else {
let edgeLength = 0;
if (!edgePoints[i] || edgePoints[i] === []) {
// it is a straight line
edgeLength = getEucliDis({ x: source.x!, y: source.y! }, { x: target.x!, y: target.y! });
} else {
edgeLength = self.getEdgeLength(edgePoints[i]);
}
const divisionLength = edgeLength / (divisions + 1);
let currentDivisonLength = divisionLength;
const newEdgePoints = [{ x: source.x, y: source.y }]; // source
edgePoints[i].forEach((ep: Point, j: number) => {
if (j === 0) return;
let oriDivisionLength = getEucliDis(ep, edgePoints[i][j - 1]);
while (oriDivisionLength > currentDivisonLength) {
const ratio = currentDivisonLength / oriDivisionLength;
const edgePoint = { x: edgePoints[i][j - 1].x, y: edgePoints[i][j - 1].y };
edgePoint.x += ratio * (ep.x - edgePoints[i][j - 1].x);
edgePoint.y += ratio * (ep.y - edgePoints[i][j - 1].y);
newEdgePoints.push(edgePoint);
oriDivisionLength -= currentDivisonLength;
currentDivisonLength = divisionLength;
}
currentDivisonLength -= oriDivisionLength;
});
newEdgePoints.push({ x: target.x, y: target.y }); // target
edgePoints[i] = newEdgePoints;
}
});
return edgePoints;
}
/**
* 计算边的长度
* @param points
*/
public getEdgeLength(points: Point[]): number {
let length = 0;
points.forEach((p, i) => {
if (i === 0) return;
length += getEucliDis(p, points[i - 1]);
});
return length;
}
public getEdgeBundles(): number[] {
const self = this;
const data: GraphData = self.get('data');
const edges = data.edges || [];
const bundleThreshold: number = self.get('bundleThreshold');
const nodeIdMap: NodeConfigMap = self.get('nodeIdMap');
let edgeBundles = self.get('edgeBundles');
if (!edgeBundles) edgeBundles = [];
edges.forEach((e, i) => {
if (!edgeBundles[i] || edgeBundles[i] === undefined) {
edgeBundles[i] = [];
}
});
edges.forEach((ei, i) => {
const iSource = nodeIdMap[ei.source as string];
const iTarget = nodeIdMap[ei.target as string];
edges.forEach((ej, j) => {
if (j <= i) return;
const jSource = nodeIdMap[ej.source as string];
const jTarget = nodeIdMap[ej.target as string];
const score = self.getBundleScore(
{ source: iSource, target: iTarget },
{ source: jSource, target: jTarget },
);
if (score >= bundleThreshold) {
edgeBundles[i].push(j);
edgeBundles[j].push(i);
}
});
});
return edgeBundles;
}
public getBundleScore(ei: any, ej: any): number {
const self = this;
ei.vx = ei.target.x - ei.source.x;
ei.vy = ei.target.y - ei.source.y;
ej.vx = ej.target.x - ej.source.x;
ej.vy = ej.target.y - ej.source.y;
ei.length = getEucliDis(
{
x: ei.source.x,
y: ei.source.y,
},
{
x: ei.target.x,
y: ei.target.y,
},
);
ej.length = getEucliDis(
{
x: ej.source.x,
y: ej.source.y,
},
{
x: ej.target.x,
y: ej.target.y,
},
);
// angle score
const aScore = self.getAngleScore(ei, ej);
// scale score
const sScore = self.getScaleScore(ei, ej);
// position score
const pScore = self.getPositionScore(ei, ej);
// visibility socre
const vScore = self.getVisibilityScore(ei, ej);
return aScore * sScore * pScore * vScore;
}
protected getAngleScore(ei: VectorPosition, ej: VectorPosition): number {
const dotProduct = getDotProduct({ x: ei.vx, y: ei.vy }, { x: ej.vx, y: ej.vy });
return dotProduct / (ei.length * ej.length);
}
protected getScaleScore(ei: VectorPosition, ej: VectorPosition): number {
const aLength = (ei.length + ej.length) / 2;
const score =
2 / (aLength / Math.min(ei.length, ej.length) + Math.max(ei.length, ej.length) / aLength);
return score;
}
protected getPositionScore(ei: VectorPosition, ej: VectorPosition): number {
const aLength = (ei.length + ej.length) / 2;
const iMid = {
x: (ei.source.x + ei.target.x) / 2,
y: (ei.source.y + ei.target.y) / 2,
};
const jMid = {
x: (ej.source.x + ej.target.x) / 2,
y: (ej.source.y + ej.target.y) / 2,
};
const distance = getEucliDis(iMid, jMid);
return aLength / (aLength + distance);
}
protected getVisibilityScore(ei: VectorPosition, ej: VectorPosition): number {
const vij = this.getEdgeVisibility(ei, ej);
const vji = this.getEdgeVisibility(ej, ei);
return vij < vji ? vij : vji;
}
protected getEdgeVisibility(ei: VectorPosition, ej: VectorPosition): number {
const ps = projectPointToEdge(ej.source, ei);
const pt = projectPointToEdge(ej.target, ei);
const pMid = {
x: (ps.x + pt.x) / 2,
y: (ps.y + pt.y) / 2,
};
const iMid = {
x: (ei.source.x + ei.target.x) / 2,
y: (ei.source.y + ei.target.y) / 2,
};
return Math.max(0, 1 - (2 * getEucliDis(pMid, iMid)) / getEucliDis(ps, pt));
}
protected getEdgeForces(e: any, eidx: number, divisions: number, lambda: number): Point[] {
const self = this;
const edgePoints = self.get('edgePoints');
const K = self.get('K');
const kp = K / (getEucliDis(e.source, e.target) * (divisions + 1));
const edgePointForces = [{ x: 0, y: 0 }];
for (let i = 1; i < divisions; i++) {
const force = { x: 0, y: 0 };
const spring = self.getSpringForce(
{ pre: edgePoints[eidx][i - 1], cur: edgePoints[eidx][i], next: edgePoints[eidx][i + 1] },
kp,
);
const electrostatic = self.getElectrostaticForce(i, eidx);
force.x = lambda * (spring.x + electrostatic.x);
force.y = lambda * (spring.y + electrostatic.y);
edgePointForces.push(force);
}
edgePointForces.push({ x: 0, y: 0 });
return edgePointForces;
}
protected getSpringForce(divisions: any, kp: number): Point {
let x = divisions.pre.x + divisions.next.x - 2 * divisions.cur.x;
let y = divisions.pre.y + divisions.next.y - 2 * divisions.cur.y;
x *= kp;
y *= kp;
return { x, y };
}
protected getElectrostaticForce(pidx: number, eidx: number): Point {
const self = this;
const eps = self.get('eps');
const edgeBundles = self.get('edgeBundles');
const edgePoints = self.get('edgePoints');
const edgeBundle = edgeBundles[eidx];
const resForce = { x: 0, y: 0 };
edgeBundle.forEach((eb: number) => {
const force = {
x: edgePoints[eb][pidx].x - edgePoints[eidx][pidx].x,
y: edgePoints[eb][pidx].y - edgePoints[eidx][pidx].y,
};
if (Math.abs(force.x) > eps || Math.abs(force.y) > eps) {
const length = getEucliDis(edgePoints[eb][pidx], edgePoints[eidx][pidx]);
const diff = 1 / length;
resForce.x += force.x * diff;
resForce.y += force.y * diff;
}
});
return resForce;
}
public isTicking(): boolean {
return this.get('ticking');
}
public getSimulation() {
return this.get('forceSimulation');
}
public destroy() {
if (this.get('ticking')) {
this.getSimulation().stop();
}
super.destroy();
}
} | the_stack |
import {DataType, Scalar, serialization, Tensor, tidy, util} from '@tensorflow/tfjs-core';
import {getNextUniqueTensorId, getUid} from '../backend/state';
import {getScopedTensorName, getUniqueTensorName, nameScope} from '../common';
import {Constraint} from '../constraints';
import {AttributeError, NotImplementedError, RuntimeError, ValueError} from '../errors';
import {getInitializer, Initializer} from '../initializers';
import {Shape} from '../keras_format/common';
import {Regularizer} from '../regularizers';
import {Kwargs, RegularizerFn} from '../types';
import * as generic_utils from '../utils/generic_utils';
import * as types_utils from '../utils/types_utils';
import * as variable_utils from '../utils/variable_utils';
import {batchGetValue, batchSetValue, LayerVariable} from '../variables';
// TODO(michaelterry): This is a stub until it's defined.
export type Op = (x: LayerVariable) => LayerVariable;
/**
* Constructor arguments for InputSpec.
*/
export interface InputSpecArgs {
/** Expected datatype of the input. */
dtype?: DataType;
/** Expected shape of the input (may include null for unchecked axes). */
shape?: Shape;
/** Expected rank of the input. */
ndim?: number;
/** Maximum rank of the input. */
maxNDim?: number;
/** Minimum rank of the input. */
minNDim?: number;
/** Dictionary mapping integer axes to a specific dimension value. */
axes?: {[axis: number]: number};
}
/**
* Specifies the ndim, dtype and shape of every input to a layer.
*
* Every layer should expose (if appropriate) an `inputSpec` attribute:
* a list of instances of InputSpec (one per input tensor).
*
* A null entry in a shape is compatible with any dimension,
* a null shape is compatible with any shape.
*/
export class InputSpec {
/** Expected datatype of the input. */
dtype?: DataType;
/** Expected shape of the input (may include null for unchecked axes). */
shape?: Shape;
/** Expected rank of the input. */
ndim?: number;
/** Maximum rank of the input. */
maxNDim?: number;
/** Minimum rank of the input. */
minNDim?: number;
/** Dictionary mapping integer axes to a specific dimension value. */
axes?: {[axis: number]: number};
constructor(args: InputSpecArgs) {
this.dtype = args.dtype;
this.shape = args.shape;
/*
TODO(michaelterry): Could throw error if ndim and shape are both defined
(then backport).
*/
if (args.shape != null) {
this.ndim = args.shape.length;
} else {
this.ndim = args.ndim;
}
this.maxNDim = args.maxNDim;
this.minNDim = args.minNDim;
this.axes = args.axes || {};
}
}
/**
* `tf.SymbolicTensor` is a placeholder for a Tensor without any concrete value.
*
* They are most often encountered when building a graph of `Layer`s for a
* a `tf.LayersModel` and the input data's shape, but not values are known.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
export class SymbolicTensor {
/* A unique ID for the tensor to be able to differentiate tensors. */
readonly id: number;
// The fully scoped name of this Variable, including a unique suffix if needed
readonly name: string;
// The originally requested fully scoped name of this Variable, not including
// any unique suffix. This may be needed when restoring weights because this
// original name is used as a key.
readonly originalName?: string;
/**
* Rank/dimensionality of the tensor.
*/
readonly rank: number;
/**
* Replacement for _keras_history.
*/
nodeIndex: number;
/**
* Replacement for _keras_history.
*/
tensorIndex: number;
/**
*
* @param dtype
* @param shape
* @param sourceLayer The Layer that produced this symbolic tensor.
* @param inputs The inputs passed to sourceLayer's __call__() method.
* @param nodeIndex
* @param tensorIndex
* @param callArgs The keyword arguments passed to the __call__() method.
* @param name
* @param outputTensorIndex The index of this tensor in the list of outputs
* returned by apply().
*/
constructor(
readonly dtype: DataType, readonly shape: Shape,
public sourceLayer: Layer, readonly inputs: SymbolicTensor[],
readonly callArgs: Kwargs, name?: string,
readonly outputTensorIndex?: number) {
this.id = getNextUniqueTensorId();
if (name != null) {
this.originalName = getScopedTensorName(name);
this.name = getUniqueTensorName(this.originalName);
}
this.rank = shape.length;
}
}
/**
* Constructor arguments for Node.
*/
export interface NodeArgs {
/**
* The layer that takes `inputTensors` and turns them into `outputTensors`.
* (the node gets created when the `call` method of the layer is called).
*/
outboundLayer: Layer;
/**
* A list of layers, the same length as `inputTensors`, the layers from where
* `inputTensors` originate.
*/
inboundLayers: Layer[];
/**
* A list of integers, the same length as `inboundLayers`. `nodeIndices[i]` is
* the origin node of `inputTensors[i]` (necessary since each inbound layer
* might have several nodes, e.g. if the layer is being shared with a
* different data stream).
*/
nodeIndices: number[];
/**
* A list of integers, the same length as `inboundLayers`. `tensorIndices[i]`
* is the index of `inputTensors[i]` within the output of the inbound layer
* (necessary since each inbound layer might have multiple tensor outputs,
* with each one being independently manipulable).
*/
tensorIndices: number[];
/** List of input tensors. */
inputTensors: SymbolicTensor[];
/** List of output tensors. */
outputTensors: SymbolicTensor[];
/** List of input masks (a mask can be a tensor, or null). */
inputMasks: Tensor[];
/** List of output masks (a mask can be a tensor, or null). */
outputMasks: Tensor[];
/** List of input shape tuples. */
inputShapes: Shape|Shape[];
/** List of output shape tuples. */
outputShapes: Shape|Shape[];
}
/**
* The type of the return value of Layer.dispose() and Container.dispose().
*/
export interface DisposeResult {
/**
* Reference count after the dispose call.
*/
refCountAfterDispose: number;
/**
* Number of variables dispose in this dispose call.
*/
numDisposedVariables: number;
}
let _nextNodeID = 0;
/**
* A `Node` describes the connectivity between two layers.
*
* Each time a layer is connected to some new input,
* a node is added to `layer.inboundNodes`.
*
* Each time the output of a layer is used by another layer,
* a node is added to `layer.outboundNodes`.
*
* `nodeIndices` and `tensorIndices` are basically fine-grained coordinates
* describing the origin of the `inputTensors`, verifying the following:
*
* `inputTensors[i] ==
* inboundLayers[i].inboundNodes[nodeIndices[i]].outputTensors[
* tensorIndices[i]]`
*
* A node from layer A to layer B is added to:
* A.outboundNodes
* B.inboundNodes
*/
export class Node {
/**
* The layer that takes `inputTensors` and turns them into `outputTensors`
* (the node gets created when the `call` method of the layer is called).
*/
outboundLayer: Layer;
/**
* A list of layers, the same length as `inputTensors`, the layers from where
* `inputTensors` originate.
*/
inboundLayers: Layer[];
/**
* A list of integers, the same length as `inboundLayers`. `nodeIndices[i]` is
* the origin node of `inputTensors[i]` (necessary since each inbound layer
* might have several nodes, e.g. if the layer is being shared with a
* different data stream).
*/
nodeIndices: number[];
/**
* A list of integers, the same length as `inboundLayers`. `tensorIndices[i]`
* is the index of `inputTensors[i]` within the output of the inbound layer
* (necessary since each inbound layer might have multiple tensor outputs,
* with each one being independently manipulable).
*/
tensorIndices: number[];
/** List of input tensors. */
inputTensors: SymbolicTensor[];
/** List of output tensors. */
outputTensors: SymbolicTensor[];
/** List of input masks (a mask can be a tensor, or null). */
inputMasks: Tensor[];
/** List of output masks (a mask can be a tensor, or null). */
outputMasks: Tensor[];
/** List of input shape tuples. */
inputShapes: Shape|Shape[];
/** List of output shape tuples. */
outputShapes: Shape|Shape[];
readonly id: number;
constructor(
args: NodeArgs,
// TODO(michaelterry): Define actual type for this.
public callArgs?: Kwargs) {
this.id = _nextNodeID++;
/*
Layer instance (NOT a list).
this is the layer that takes a list of input tensors
and turns them into a list of output tensors.
the current node will be added to
the inboundNodes of outboundLayer.
*/
this.outboundLayer = args.outboundLayer;
/*
The following 3 properties describe where
the input tensors come from: which layers,
and for each layer, which node and which
tensor output of each node.
*/
// List of layer instances.
this.inboundLayers = args.inboundLayers;
// List of integers, 1:1 mapping with inboundLayers.
this.nodeIndices = args.nodeIndices;
// List of integers, 1:1 mapping with inboundLayers.
this.tensorIndices = args.tensorIndices;
/*
Following 2 properties:
tensor inputs and outputs of outboundLayer.
*/
// List of tensors. 1:1 mapping with inboundLayers.
this.inputTensors = args.inputTensors;
// List of tensors, created by outboundLayer.call().
this.outputTensors = args.outputTensors;
/*
Following 2 properties: input and output masks.
List of tensors, 1:1 mapping with inputTensor.
*/
this.inputMasks = args.inputMasks;
// List of tensors, created by outboundLayer.computeMask().
this.outputMasks = args.outputMasks;
// Following 2 properties: input and output shapes.
// List of shape tuples, shapes of inputTensors.
this.inputShapes = args.inputShapes;
// List of shape tuples, shapes of outputTensors.
this.outputShapes = args.outputShapes;
// Add nodes to all layers involved.
for (const layer of args.inboundLayers) {
if (layer != null) {
layer.outboundNodes.push(this);
}
}
args.outboundLayer.inboundNodes.push(this);
}
getConfig(): serialization.ConfigDict {
const inboundNames: string[] = [];
for (const layer of this.inboundLayers) {
if (layer != null) {
inboundNames.push(layer.name);
} else {
inboundNames.push(null);
}
}
return {
outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,
inboundLayers: inboundNames,
nodeIndices: this.nodeIndices,
tensorIndices: this.tensorIndices
};
}
}
/** Constructor arguments for Layer. */
export declare interface LayerArgs {
/**
* If defined, will be used to create an input layer to insert before this
* layer. If both `inputShape` and `batchInputShape` are defined,
* `batchInputShape` will be used. This argument is only applicable to input
* layers (the first layer of a model).
*/
inputShape?: Shape;
/**
* If defined, will be used to create an input layer to insert before this
* layer. If both `inputShape` and `batchInputShape` are defined,
* `batchInputShape` will be used. This argument is only applicable to input
* layers (the first layer of a model).
*/
batchInputShape?: Shape;
/**
* If `inputShape` is specified and `batchInputShape` is *not* specified,
* `batchSize` is used to construct the `batchInputShape`: `[batchSize,
* ...inputShape]`
*/
batchSize?: number;
/**
* The data-type for this layer. Defaults to 'float32'.
* This argument is only applicable to input layers (the first layer of a
* model).
*/
dtype?: DataType;
/** Name for this layer. */
name?: string;
/**
* Whether the weights of this layer are updatable by `fit`.
* Defaults to true.
*/
trainable?: boolean;
/**
* Initial weight values of the layer.
*/
weights?: Tensor[];
/** Legacy support. Do not use for new code. */
inputDType?: DataType;
}
// If necessary, add `output` arguments to the CallHook function.
// This is currently used for testing only, but may be used for debugger-related
// purposes in the future.
export type CallHook = (inputs: Tensor|Tensor[], kwargs: Kwargs) => void;
let _nextLayerID = 0;
/**
* A layer is a grouping of operations and weights that can be composed to
* create a `tf.LayersModel`.
*
* Layers are constructed by using the functions under the
* [tf.layers](#Layers-Basic) namespace.
*
* @doc {heading: 'Layers', subheading: 'Classes', namespace: 'layers'}
*/
export abstract class Layer extends serialization.Serializable {
/** Name for this layer. Must be unique within a model. */
name: string;
/**
* List of InputSpec class instances.
*
* Each entry describes one required input:
* - ndim
* - dtype
* A layer with `n` input tensors must have an `inputSpec` of length `n`.
*/
inputSpec: InputSpec[];
supportsMasking: boolean;
/** Whether the layer weights will be updated during training. */
protected trainable_: boolean;
batchInputShape: Shape;
dtype: DataType;
initialWeights: Tensor[];
inboundNodes: Node[];
outboundNodes: Node[];
activityRegularizer: Regularizer;
protected _trainableWeights: LayerVariable[];
private _nonTrainableWeights: LayerVariable[];
private _losses: RegularizerFn[];
// TODO(cais): _updates is currently unused.
private _updates: Tensor[];
private _built: boolean;
private _callHook: CallHook = null;
private _addedWeightNames: string[] = [];
readonly id: number;
// Porting Notes: PyKeras does not have this property in this base Layer
// class. Instead lets Layer subclass set it dynamically and checks the
// value with `hasattr`. In tfjs-layers, we let this be a member of this
// base class.
protected _stateful = false;
protected _refCount: number|null;
// A flag for whether fast (i.e., all-zero) weight initialization is to
// be used during `build()` call. This speeds up weight initialization
// by saving unnecessary calls to expensive initializers in cases where
// the initialized values will be overwritten by loaded weight values
// during model loading.
private fastWeightInitDuringBuild: boolean;
constructor(args: LayerArgs = {}) {
super();
this.id = _nextLayerID++;
this.activityRegularizer = null;
this.inputSpec = null;
this.supportsMasking = false;
// These properties will be set upon call of this.build()
this._trainableWeights = [];
this._nonTrainableWeights = [];
this._losses = [];
this._updates = [];
this._built = false;
/*
These lists will be filled via successive calls
to this.addInboundNode().
*/
this.inboundNodes = [];
this.outboundNodes = [];
let name = args.name;
if (!name) {
const prefix = this.getClassName();
name = generic_utils.toSnakeCase(prefix) + '_' + getUid(prefix);
}
this.name = name;
this.trainable_ = args.trainable == null ? true : args.trainable;
if (args.inputShape != null || args.batchInputShape != null) {
/*
In this case we will later create an input layer
to insert before the current layer
*/
let batchInputShape: Shape;
if (args.batchInputShape != null) {
batchInputShape = args.batchInputShape;
} else if (args.inputShape != null) {
let batchSize: number = null;
if (args.batchSize != null) {
batchSize = args.batchSize;
}
batchInputShape = [batchSize].concat(args.inputShape);
}
this.batchInputShape = batchInputShape;
// Set dtype.
let dtype = args.dtype;
if (dtype == null) {
dtype = args.inputDType;
}
if (dtype == null) {
dtype = 'float32';
}
this.dtype = dtype;
}
if (args.weights != null) {
this.initialWeights = args.weights;
} else {
this.initialWeights = null;
}
// The value of `_refCount` is initialized to null. When the layer is used
// in a symbolic way for the first time, it will be set to 1.
this._refCount = null;
this.fastWeightInitDuringBuild = false;
}
/**
* Converts a layer and its index to a unique (immutable type) name.
* This function is used internally with `this.containerNodes`.
* @param layer The layer.
* @param nodeIndex The layer's position (e.g. via enumerate) in a list of
* nodes.
*
* @returns The unique name.
*/
protected static nodeKey(layer: Layer, nodeIndex: number) {
return layer.name + '_ib-' + nodeIndex.toString();
}
/**
* Returns this.inboundNode at index nodeIndex.
*
* Porting note: This is a replacement for _get_node_attribute_at_index()
* @param nodeIndex
* @param attrName The name of the attribute related to request for this node.
*/
private getNodeAtIndex(nodeIndex: number, attrName: string): Node {
if (this.inboundNodes.length === 0) {
throw new RuntimeError(
'The layer has never been called ' +
`and thus has no defined ${attrName}.`);
}
if (this.inboundNodes.length <= nodeIndex) {
throw new ValueError(
`Asked to get ${attrName} at node ${nodeIndex}, ` +
`but the layer has only ${this.inboundNodes.length} inbound nodes.`);
}
return this.inboundNodes[nodeIndex];
}
/**
* Retrieves the input tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple inputs).
*/
getInputAt(nodeIndex: number): SymbolicTensor|SymbolicTensor[] {
return generic_utils.singletonOrArray(
this.getNodeAtIndex(nodeIndex, 'input').inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer at a given node.
*
* @param nodeIndex Integer, index of the node from which to retrieve the
* attribute. E.g. `nodeIndex=0` will correspond to the first time the layer
* was called.
*
* @return A tensor (or list of tensors if the layer has multiple outputs).
*/
getOutputAt(nodeIndex: number): SymbolicTensor|SymbolicTensor[] {
return generic_utils.singletonOrArray(
this.getNodeAtIndex(nodeIndex, 'output').outputTensors);
}
// Properties
/**
* Retrieves the input tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Input tensor or list of input tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get input(): SymbolicTensor|SymbolicTensor[] {
if (this.inboundNodes.length > 1) {
throw new AttributeError(
`Layer ${this.name}` +
' has multiple inbound nodes, ' +
'hence the notion of "layer input" ' +
'is ill-defined. ' +
'Use `getInputAt(nodeIndex)` instead.');
} else if (this.inboundNodes.length === 0) {
throw new AttributeError(
`Layer ${this.name}` +
' is not connected, no input to return.');
}
return generic_utils.singletonOrArray(
this.getNodeAtIndex(0, 'input').inputTensors);
}
/**
* Retrieves the output tensor(s) of a layer.
*
* Only applicable if the layer has exactly one inbound node,
* i.e. if it is connected to one incoming layer.
*
* @return Output tensor or list of output tensors.
*
* @exception AttributeError if the layer is connected to more than one
* incoming layers.
*/
get output(): SymbolicTensor|SymbolicTensor[] {
if (this.inboundNodes.length === 0) {
throw new AttributeError(
`Layer ${this.name}` +
' has no inbound nodes.');
}
if (this.inboundNodes.length > 1) {
throw new AttributeError(
`Layer ${this.name}` +
' has multiple inbound nodes, ' +
'hence the notion of "layer output" ' +
'is ill-defined. ' +
'Use `getOutputAt(nodeIndex)` instead.');
}
return generic_utils.singletonOrArray(
this.getNodeAtIndex(0, 'output').outputTensors);
}
get losses(): RegularizerFn[] {
return this._losses;
}
/**
* Retrieves the Layer's current loss values.
*
* Used for regularizers during training.
*/
calculateLosses(): Scalar[] {
// Porting Node: This is an augmentation to Layer.loss in PyKeras.
// In PyKeras, Layer.loss returns symbolic tensors. Here a concrete
// Tensor (specifically Scalar) values are returned. This is due to the
// imperative backend.
return this.losses.map(lossFn => lossFn());
}
get updates(): Tensor[] {
return this._updates;
}
get built(): boolean {
return this._built;
}
set built(built: boolean) {
this._built = built;
}
get trainable(): boolean {
return this.trainable_;
}
set trainable(trainable: boolean) {
this._trainableWeights.forEach(w => w.trainable = trainable);
this.trainable_ = trainable;
}
get trainableWeights(): LayerVariable[] {
if (this.trainable_) {
return this._trainableWeights.filter(w => w.trainable);
} else {
return [];
}
}
set trainableWeights(weights: LayerVariable[]) {
this._trainableWeights = weights;
}
get nonTrainableWeights(): LayerVariable[] {
if (this.trainable) {
return this._trainableWeights.filter(w => !w.trainable)
.concat(this._nonTrainableWeights);
} else {
return this._trainableWeights.concat(this._nonTrainableWeights);
}
}
set nonTrainableWeights(weights: LayerVariable[]) {
this._nonTrainableWeights = weights;
}
/**
* The concatenation of the lists trainableWeights and nonTrainableWeights
* (in this order).
*/
get weights(): LayerVariable[] {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
get stateful(): boolean {
return this._stateful;
}
/**
* Reset the states of the layer.
*
* This method of the base Layer class is essentially a no-op.
* Subclasses that are stateful (e.g., stateful RNNs) should override this
* method.
*/
resetStates(): void {
if (!this.stateful) {
throw new Error(
'Cannot call the resetStates() method of a non-stateful Layer ' +
'object.');
}
}
/**
* Checks compatibility between the layer and provided inputs.
*
* This checks that the tensor(s) `input`
* verify the input assumptions of the layer
* (if any). If not, exceptions are raised.
*
* @param inputs Input tensor or list of input tensors.
*
* @exception ValueError in case of mismatch between
* the provided inputs and the expectations of the layer.
*/
protected assertInputCompatibility(inputs: Tensor|Tensor[]|SymbolicTensor|
SymbolicTensor[]): void {
inputs = generic_utils.toList(inputs);
if (this.inputSpec == null || this.inputSpec.length === 0) {
return;
}
const inputSpec = generic_utils.toList(this.inputSpec);
if (inputs.length !== inputSpec.length) {
throw new ValueError(
`Layer ${this.name} expects ${inputSpec.length} inputs, ` +
`but it received ${inputs.length} input tensors. ` +
`Input received: ${inputs}`);
}
for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) {
const x = inputs[inputIndex];
const spec: InputSpec = inputSpec[inputIndex];
if (spec == null) {
continue;
}
// Check ndim.
const ndim = x.rank;
if (spec.ndim != null) {
if (ndim !== spec.ndim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}: ` +
`expected ndim=${spec.ndim}, found ndim=${ndim}`);
}
}
if (spec.maxNDim != null) {
if (ndim > spec.maxNDim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}` +
`: expected max_ndim=${spec.maxNDim}, found ndim=${ndim}`);
}
}
if (spec.minNDim != null) {
if (ndim < spec.minNDim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name}` +
`: expected min_ndim=${spec.minNDim}, found ndim=${ndim}.`);
}
}
// Check dtype.
if (spec.dtype != null) {
if (x.dtype !== spec.dtype) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ${this.name} ` +
`: expected dtype=${spec.dtype}, found dtype=${x.dtype}.`);
}
}
// Check specific shape axes.
if (spec.axes) {
const xShape = x.shape;
for (const key in spec.axes) {
const axis = Number(key);
const value = spec.axes[key];
// Perform Python-style slicing in case axis < 0;
// TODO(cais): Use https://github.com/alvivi/typescript-underscore to
// ensure type safety through Underscore calls.
const xShapeAtAxis =
axis >= 0 ? xShape[axis] : xShape[xShape.length + axis];
if (value != null && [value, null].indexOf(xShapeAtAxis) === -1) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ` +
`${this.name}: expected axis ${axis} of input shape to ` +
`have value ${value} but got shape ${xShape}.`);
}
}
}
// Check shape.
if (spec.shape != null) {
for (let i = 0; i < spec.shape.length; ++i) {
const specDim = spec.shape[i];
const dim = x.shape[i];
if (specDim != null && dim != null) {
if (specDim !== dim) {
throw new ValueError(
`Input ${inputIndex} is incompatible with layer ` +
`${this.name}: expected shape=${spec.shape}, ` +
`found shape=${x.shape}.`);
}
}
}
}
}
}
/**
* This is where the layer's logic lives.
*
* @param inputs Input tensor, or list/tuple of input tensors.
* @param kwargs Additional keyword arguments.
*
* @return A tensor or list/tuple of tensors.
*/
call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {
return inputs;
}
protected invokeCallHook(inputs: Tensor|Tensor[], kwargs: Kwargs) {
if (this._callHook != null) {
this._callHook(inputs, kwargs);
}
}
/**
* Set call hook.
* This is currently used for testing only.
* @param callHook
*/
setCallHook(callHook: CallHook) {
this._callHook = callHook;
}
/**
* Clear call hook.
* This is currently used for testing only.
*/
clearCallHook() {
this._callHook = null;
}
/**
* Builds or executes a `Layer's logic.
*
* When called with `tf.Tensor`(s), execute the `Layer`s computation and
* return Tensor(s). For example:
*
* ```js
* const denseLayer = tf.layers.dense({
* units: 1,
* kernelInitializer: 'zeros',
* useBias: false
* });
*
* // Invoke the layer's apply() method with a `tf.Tensor` (with concrete
* // numeric values).
* const input = tf.ones([2, 2]);
* const output = denseLayer.apply(input);
*
* // The output's value is expected to be [[0], [0]], due to the fact that
* // the dense layer has a kernel initialized to all-zeros and does not have
* // a bias.
* output.print();
* ```
*
* When called with `tf.SymbolicTensor`(s), this will prepare the layer for
* future execution. This entails internal book-keeping on shapes of
* expected Tensors, wiring layers together, and initializing weights.
*
* Calling `apply` with `tf.SymbolicTensor`s are typically used during the
* building of non-`tf.Sequential` models. For example:
*
* ```js
* const flattenLayer = tf.layers.flatten();
* const denseLayer = tf.layers.dense({units: 1});
*
* // Use tf.layers.input() to obtain a SymbolicTensor as input to apply().
* const input = tf.input({shape: [2, 2]});
* const output1 = flattenLayer.apply(input);
*
* // output1.shape is [null, 4]. The first dimension is the undetermined
* // batch size. The second dimension comes from flattening the [2, 2]
* // shape.
* console.log(JSON.stringify(output1.shape));
*
* // The output SymbolicTensor of the flatten layer can be used to call
* // the apply() of the dense layer:
* const output2 = denseLayer.apply(output1);
*
* // output2.shape is [null, 1]. The first dimension is the undetermined
* // batch size. The second dimension matches the number of units of the
* // dense layer.
* console.log(JSON.stringify(output2.shape));
*
* // The input and output and be used to construct a model that consists
* // of the flatten and dense layers.
* const model = tf.model({inputs: input, outputs: output2});
* ```
*
* @param inputs a `tf.Tensor` or `tf.SymbolicTensor` or an Array of them.
* @param kwargs Additional keyword arguments to be passed to `call()`.
*
* @return Output of the layer's `call` method.
*
* @exception ValueError error in case the layer is missing shape information
* for its `build` call.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
// Porting Note: This is a replacement for __call__() in Python.
apply(
inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],
kwargs?: Kwargs): Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[] {
kwargs = kwargs || {};
this.assertNotDisposed();
// Ensure inputs are all the same type.
const inputsList = generic_utils.toList(inputs);
let allAreSymbolic = true;
for (const input of inputsList) {
if (!(input instanceof SymbolicTensor)) {
allAreSymbolic = false;
break;
}
}
let noneAreSymbolic = true;
for (const input of inputsList) {
if (input instanceof SymbolicTensor) {
noneAreSymbolic = false;
break;
}
}
if (allAreSymbolic === noneAreSymbolic) {
throw new ValueError(
'Arguments to apply() must be all ' +
'SymbolicTensors or all Tensors');
}
// TODO(michaelterry): nameScope() may not be necessary.
return nameScope(this.name, () => {
// Handle laying building (weight creating, input spec locking).
if (!this.built) {
/*
Throw exceptions in case the input is not compatible
with the inputSpec specified in the layer constructor.
*/
this.assertInputCompatibility(inputs);
// Collect input shapes to build layer.
const inputShapes: Shape[] = [];
for (const xElem of generic_utils.toList(inputs)) {
inputShapes.push(xElem.shape);
}
this.build(generic_utils.singletonOrArray(inputShapes));
this.built = true;
// Load weights that were specified at layer instantiation.
if (this.initialWeights) {
this.setWeights(this.initialWeights);
}
if (this._refCount === null && noneAreSymbolic) {
// The first use of this layer is a non-symbolic call, set ref count
// to 1 so the Layer can be properly disposed if its dispose() method
// is called.
this._refCount = 1;
}
}
/*
Throw exceptions in case the input is not compatible
with the inputSpec set at build time.
*/
this.assertInputCompatibility(inputs);
// Handle mask propagation.
// TODO(michaelterry): Mask propagation not currently implemented.
// Actually call the layer, collecting output(s), mask(s), and shape(s).
if (noneAreSymbolic) {
let output = this.call(inputs as Tensor | Tensor[], kwargs);
// TODO(michaelterry): Compute the outputMask
// If the layer returns tensors from its inputs, unmodified,
// we copy them to avoid loss of tensor metadata.
const outputList: Tensor[] = generic_utils.toList(output);
const outputListCopy: Tensor[] = [];
// TODO(michaelterry): This copying may not be necessary given our eager
// backend.
for (let x of outputList) {
if (inputsList.indexOf(x) !== -1) {
x = x.clone();
}
outputListCopy.push(x);
}
output = generic_utils.singletonOrArray(outputListCopy);
if (this.activityRegularizer != null) {
throw new NotImplementedError(
'Layer invocation in the presence of activity ' +
'regularizer(s) is not supported yet.');
}
// TODO(michaelterry): Call addInboundNode()?
return output;
} else {
const inputShape = collectInputShape(inputs);
const outputShape = this.computeOutputShape(inputShape);
let output: SymbolicTensor|SymbolicTensor[];
const outputDType = guessOutputDType(inputs);
this.warnOnIncompatibleInputShape(
Array.isArray(inputs) ? inputShape[0] as Shape :
inputShape as Shape);
if (outputShape != null && outputShape.length > 0 &&
Array.isArray(outputShape[0])) {
// We have multiple output shapes. Create multiple output tensors.
output = (outputShape as Shape[])
.map(
(shape, index) => new SymbolicTensor(
outputDType, shape, this,
generic_utils.toList(inputs), kwargs, this.name,
index));
} else {
output = new SymbolicTensor(
outputDType, outputShape as Shape, this,
generic_utils.toList(inputs), kwargs, this.name);
}
/*
Add an inbound node to the layer, so that it keeps track
of the call and of all new variables created during the call.
This also updates the layer history of the output tensor(s).
If the input tensor(s) had no previous history,
this does nothing.
*/
this.addInboundNode(
inputs as SymbolicTensor | SymbolicTensor[], output, null, null,
inputShape, outputShape, kwargs);
this._refCount++;
if (this.activityRegularizer != null) {
throw new NotImplementedError(
'Layer invocation in the presence of activity ' +
'regularizer(s) is not supported yet.');
}
return output;
}
});
}
/**
* Check compatibility between input shape and this layer's batchInputShape.
*
* Print warning if any incompatibility is found.
*
* @param inputShape Input shape to be checked.
*/
protected warnOnIncompatibleInputShape(inputShape: Shape) {
if (this.batchInputShape == null) {
return;
} else if (inputShape.length !== this.batchInputShape.length) {
console.warn(
`The rank of the input tensor provided (shape: ` +
`${JSON.stringify(inputShape)}) does not match that of the ` +
`batchInputShape (${JSON.stringify(this.batchInputShape)}) ` +
`of the layer ${this.name}`);
} else {
let dimMismatch = false;
this.batchInputShape.forEach((dimension, i) => {
if (dimension != null && inputShape[i] != null &&
inputShape[i] !== dimension) {
dimMismatch = true;
}
});
if (dimMismatch) {
console.warn(
`The shape of the input tensor ` +
`(${JSON.stringify(inputShape)}) does not ` +
`match the expectation of layer ${this.name}: ` +
`${JSON.stringify(this.batchInputShape)}`);
}
}
}
/**
* Retrieves the output shape(s) of a layer.
*
* Only applicable if the layer has only one inbound node, or if all inbound
* nodes have the same output shape.
*
* @returns Output shape or shapes.
* @throws AttributeError: if the layer is connected to more than one incoming
* nodes.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
get outputShape(): Shape|Shape[] {
if (this.inboundNodes == null || this.inboundNodes.length === 0) {
throw new AttributeError(
`The layer ${this.name} has never been called and thus has no ` +
`defined output shape.`);
}
const allOutputShapes: string[] = [];
for (const node of this.inboundNodes) {
const shapeString = JSON.stringify(node.outputShapes);
if (allOutputShapes.indexOf(shapeString) === -1) {
allOutputShapes.push(shapeString);
}
}
if (allOutputShapes.length === 1) {
const outputShapes = this.inboundNodes[0].outputShapes;
if (Array.isArray(outputShapes) && Array.isArray(outputShapes[0]) &&
outputShapes.length === 1) {
return (outputShapes as Shape[])[0];
} else {
return outputShapes;
}
} else {
throw new AttributeError(
`The layer ${this.name} has multiple inbound nodes with different ` +
`output shapes. Hence the notion of "output shape" is ill-defined ` +
`for the layer.`);
// TODO(cais): Implement getOutputShapeAt().
}
}
/**
* Counts the total number of numbers (e.g., float32, int32) in the
* weights.
*
* @returns An integer count.
* @throws RuntimeError: If the layer is not built yet (in which case its
* weights are not defined yet.)
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
countParams(): number {
if (!this.built) {
throw new RuntimeError(
`You tried to call countParams() on ${this.name}, ` +
`but the layer is not built yet. Build it first by calling ` +
`build(batchInputShape).`);
}
return variable_utils.countParamsInWeights(this.weights);
}
/**
* Creates the layer weights.
*
* Must be implemented on all layers that have weights.
*
* Called when apply() is called to construct the weights.
*
* @param inputShape A `Shape` or array of `Shape` (unused).
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
build(inputShape: Shape|Shape[]) {
this.built = true;
}
/**
* Returns the current values of the weights of the layer.
*
* @param trainableOnly Whether to get the values of only trainable weights.
* @returns Weight values as an `Array` of `tf.Tensor`s.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
getWeights(trainableOnly = false): Tensor[] {
return batchGetValue(trainableOnly ? this.trainableWeights : this.weights);
}
/**
* Sets the weights of the layer, from Tensors.
*
* @param weights a list of Tensors. The number of arrays and their shape
* must match number of the dimensions of the weights of the layer (i.e.
* it should match the output of `getWeights`).
*
* @exception ValueError If the provided weights list does not match the
* layer's specifications.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
setWeights(weights: Tensor[]): void {
tidy(() => {
const params = this.weights;
if (params.length !== weights.length) {
// TODO(cais): Restore the following and use `providedWeights`, instead
// of `weights` in the error message, once the deeplearn.js bug is
// fixed: https://github.com/PAIR-code/deeplearnjs/issues/498 const
// providedWeights = JSON.stringify(weights).substr(0, 50);
throw new ValueError(
`You called setWeights(weights) on layer "${this.name}" ` +
`with a weight list of length ${weights.length}, ` +
`but the layer was expecting ${params.length} weights. ` +
`Provided weights: ${weights}...`);
}
if (params.length === 0) {
return;
}
const weightValueTuples: Array<[LayerVariable, Tensor]> = [];
const paramValues = batchGetValue(params);
for (let i = 0; i < paramValues.length; ++i) {
const pv = paramValues[i];
const p = params[i];
const w = weights[i];
if (!util.arraysEqual(pv.shape, w.shape)) {
throw new ValueError(
`Layer weight shape ${pv.shape} ` +
`not compatible with provided weight shape ${w.shape}`);
}
weightValueTuples.push([p, w]);
}
batchSetValue(weightValueTuples);
});
}
/**
* Adds a weight variable to the layer.
*
* @param name Name of the new weight variable.
* @param shape The shape of the weight.
* @param dtype The dtype of the weight.
* @param initializer An initializer instance.
* @param regularizer A regularizer instance.
* @param trainable Whether the weight should be trained via backprop or not
* (assuming that the layer itself is also trainable).
* @param constraint An optional trainable.
* @return The created weight variable.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
protected addWeight(
name: string, shape: Shape, dtype?: DataType, initializer?: Initializer,
regularizer?: Regularizer, trainable?: boolean, constraint?: Constraint,
getInitializerFunc?: Function): LayerVariable {
// Reject duplicate weight names.
if (this._addedWeightNames.indexOf(name) !== -1) {
throw new ValueError(
`Duplicate weight name ${name} for layer ${this.name}`);
}
this._addedWeightNames.push(name);
if (dtype == null) {
dtype = 'float32';
}
if (this.fastWeightInitDuringBuild) {
initializer = getInitializerFunc != null ? getInitializerFunc() :
getInitializer('zeros');
}
const initValue = initializer.apply(shape, dtype);
const weight =
new LayerVariable(initValue, dtype, name, trainable, constraint);
initValue.dispose();
// Request backend not to dispose the weights of the model on scope() exit.
if (regularizer != null) {
this.addLoss(() => regularizer.apply(weight.read()));
}
if (trainable == null) {
trainable = true;
}
if (trainable) {
this._trainableWeights.push(weight);
} else {
this._nonTrainableWeights.push(weight);
}
return weight;
}
/**
* Set the fast-weight-initialization flag.
*
* In cases where the initialized weight values will be immediately
* overwritten by loaded weight values during model loading, setting
* the flag to `true` saves unnecessary calls to potentially expensive
* initializers and speeds up the loading process.
*
* @param value Target value of the flag.
*/
setFastWeightInitDuringBuild(value: boolean) {
this.fastWeightInitDuringBuild = value;
}
/**
* Add losses to the layer.
*
* The loss may potentionally be conditional on some inputs tensors,
* for instance activity losses are conditional on the layer's inputs.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
addLoss(losses: RegularizerFn|RegularizerFn[]): void {
if (losses == null || Array.isArray(losses) && losses.length === 0) {
return;
}
// Update this.losses
losses = generic_utils.toList(losses);
if (this._losses !== undefined && this._losses !== null) {
this.losses.push(...losses);
}
}
/**
* Computes the output shape of the layer.
*
* Assumes that the layer will be built to match that input shape provided.
*
* @param inputShape A shape (tuple of integers) or a list of shape tuples
* (one per output tensor of the layer). Shape tuples can include null for
* free dimensions, instead of an integer.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {
return inputShape;
}
/**
* Computes an output mask tensor.
*
* @param inputs Tensor or list of tensors.
* @param mask Tensor or list of tensors.
*
* @return null or a tensor (or list of tensors, one per output tensor of the
* layer).
*/
computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor
|Tensor[] {
if (!this.supportsMasking) {
if (mask != null) {
if (Array.isArray(mask)) {
mask.forEach(maskElement => {
if (maskElement != null) {
throw new TypeError(
`Layer ${this.name} does not support masking, ` +
'but was passed an inputMask.');
}
});
} else {
throw new TypeError(
`Layer ${this.name} does not support masking, ` +
'but was passed an inputMask.');
}
}
// masking not explicitly supported: return null as mask
return null;
}
// if masking is explictly supported, by default
// carry over the input mask
return mask;
}
/**
* Internal method to create an inbound node for the layer.
*
* @param inputTensors List of input tensors.
* @param outputTensors List of output tensors.
* @param inputMasks List of input masks (a mask can be a tensor, or null).
* @param outputMasks List of output masks (a mask can be a tensor, or null).
* @param inputShapes List of input shape tuples.
* @param outputShapes List of output shape tuples.
* @param kwargs Dictionary of keyword arguments that were passed to the
* `call` method of the layer at the call that created the node.
*/
private addInboundNode(
inputTensors: SymbolicTensor|SymbolicTensor[],
outputTensors: SymbolicTensor|SymbolicTensor[],
inputMasks: Tensor|Tensor[], outputMasks: Tensor|Tensor[],
inputShapes: Shape|Shape[], outputShapes: Shape|Shape[],
kwargs: {} = null): void {
const inputTensorList: SymbolicTensor[] =
generic_utils.toList(inputTensors);
outputTensors = generic_utils.toList(outputTensors);
inputMasks = generic_utils.toList(inputMasks);
outputMasks = generic_utils.toList(outputMasks);
inputShapes = types_utils.normalizeShapeList(inputShapes);
outputShapes = types_utils.normalizeShapeList(outputShapes);
// Collect input tensor(s) coordinates.
const inboundLayers: Layer[] = [];
const nodeIndices: number[] = [];
const tensorIndices: number[] = [];
for (const x of inputTensorList) {
/*
* TODO(michaelterry): Keras adds this value to tensors; it's not
* clear whether we'll use this or not.
*/
inboundLayers.push(x.sourceLayer);
nodeIndices.push(x.nodeIndex);
tensorIndices.push(x.tensorIndex);
}
// Create node, add it to inbound nodes.
// (This call has side effects.)
// tslint:disable-next-line:no-unused-expression
new Node(
{
outboundLayer: this,
inboundLayers,
nodeIndices,
tensorIndices,
inputTensors: inputTensorList,
outputTensors,
inputMasks,
outputMasks,
inputShapes,
outputShapes
},
kwargs);
// Update tensor history
for (let i = 0; i < outputTensors.length; i++) {
// TODO(michaelterry: _uses_learning_phase not tracked.
outputTensors[i].sourceLayer = this;
outputTensors[i].nodeIndex = this.inboundNodes.length - 1;
outputTensors[i].tensorIndex = i;
}
}
/**
* Returns the config of the layer.
*
* A layer config is a TS dictionary (serializable)
* containing the configuration of a layer.
* The same layer can be reinstantiated later
* (without its trained weights) from this configuration.
*
* The config of a layer does not include connectivity
* information, nor the layer class name. These are handled
* by 'Container' (one layer of abstraction above).
*
* Porting Note: The TS dictionary follows TS naming standrds for
* keys, and uses tfjs-layers type-safe Enums. Serialization methods
* should use a helper function to convert to the pythonic storage
* standard. (see serialization_utils.convertTsToPythonic)
*
* @returns TS dictionary of configuration.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
getConfig(): serialization.ConfigDict {
const config:
serialization.ConfigDict = {name: this.name, trainable: this.trainable};
if (this.batchInputShape != null) {
config['batchInputShape'] = this.batchInputShape;
}
if (this.dtype != null) {
config['dtype'] = this.dtype;
}
return config;
}
/**
* Dispose the weight variables that this Layer instance holds.
*
* @returns {number} Number of disposed variables.
*/
protected disposeWeights(): number {
this.weights.forEach(weight => weight.dispose());
return this.weights.length;
}
protected assertNotDisposed() {
if (this._refCount === 0) {
throw new Error(`Layer '${this.name}' is already disposed.`);
}
}
/**
* Attempt to dispose layer's weights.
*
* This method decrease the reference count of the Layer object by 1.
*
* A Layer is reference-counted. Its reference count is incremented by 1
* the first item its `apply()` method is called and when it becomes a part
* of a new `Node` (through calling the `apply()`) method on a
* `tf.SymbolicTensor`).
*
* If the reference count of a Layer becomes 0, all the weights will be
* disposed and the underlying memory (e.g., the textures allocated in WebGL)
* will be freed.
*
* Note: If the reference count is greater than 0 after the decrement, the
* weights of the Layer will *not* be disposed.
*
* After a Layer is disposed, it cannot be used in calls such as `apply()`,
* `getWeights()` or `setWeights()` anymore.
*
* @returns A DisposeResult Object with the following fields:
* - refCountAfterDispose: The reference count of the Container after this
* `dispose()` call.
* - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed
* during this `dispose()` call.
* @throws {Error} If the layer is not built yet, or if the layer has already
* been disposed.
*
* @doc {heading: 'Models', 'subheading': 'Classes'}
*/
dispose(): DisposeResult {
if (!this.built) {
throw new Error(
`Cannot dispose Layer ${this.name} because it has not been ` +
`built yet.`);
}
if (this._refCount === null) {
throw new Error(
`Cannot dispose Layer ${this.name} because it has not been used ` +
`yet.`);
}
this.assertNotDisposed();
let numDisposedVariables = 0;
if (--this._refCount === 0) {
numDisposedVariables = this.disposeWeights();
}
return {refCountAfterDispose: this._refCount, numDisposedVariables};
}
}
/**
* Collects the input shape(s) of a list of `tf.Tensor`s or
* `tf.SymbolicTensor`s.
*
* TODO(michaelterry): Update PyKeras docs (backport).
*
* @param inputTensors List of input tensors (or single input tensor).
*
* @return List of shape tuples (or single tuple), one tuple per input.
*/
function collectInputShape(inputTensors: SymbolicTensor|SymbolicTensor[]|Tensor|
Tensor[]): Shape|Shape[] {
inputTensors =
generic_utils.toList(inputTensors) as SymbolicTensor[] | Tensor[];
const shapes: Shape[] = [];
for (const x of inputTensors) {
shapes.push(x.shape);
}
return generic_utils.singletonOrArray(shapes);
}
/**
* Guesses output dtype based on inputs.
*
* At present, just returns 'float32' for any input.
*
* @param inputTensors List of input tensors (or single input tensor).
*
* @return The guessed DType. At present, always returns 'float32'.
*/
function guessOutputDType(inputTensors: SymbolicTensor|SymbolicTensor[]|Tensor|
Tensor[]): DataType {
return 'float32';
}
/**
* Returns the list of input tensors necessary to compute `tensor`.
*
* Output will always be a list of tensors (potentially with 1 element).
*
* @param tensor The tensor to start from.
* @param layer Origin layer of the tensor.
* @param nodeIndex Origin node index of the tensor.
*
* @return Array of input tensors.
*/
export function getSourceInputs(
tensor: SymbolicTensor, layer?: Layer,
nodeIndex?: number): SymbolicTensor[] {
if (layer == null || (nodeIndex != null && nodeIndex > 0)) {
layer = tensor.sourceLayer;
nodeIndex = tensor.nodeIndex;
}
if (layer.inboundNodes.length === 0) {
return [tensor];
} else {
const node = layer.inboundNodes[nodeIndex];
if (node.inboundLayers.length === 0) {
return node.inputTensors;
} else {
const sourceTensors: SymbolicTensor[] = [];
for (let i = 0; i < node.inboundLayers.length; i++) {
const x = node.inputTensors[i];
const layer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const previousSources = getSourceInputs(x, layer, nodeIndex);
// Avoid input redundancy.
for (const x of previousSources) {
if (sourceTensors.indexOf(x) === -1) {
sourceTensors.push(x);
}
}
}
return sourceTensors;
}
}
} | the_stack |
import * as bip39 from 'bip39';
import * as fs from 'fs-extra';
// @ts-ignore
import * as hdkey from 'hdkey';
import * as path from 'path';
import { QuickPickItem, Uri, window } from 'vscode';
import { Constants, RequiredApps } from '../Constants';
import {
getWorkspaceRoot,
openZeppelinHelper,
outputCommandHelper,
required,
showConfirmPaidOperationDialog,
showIgnorableNotification,
showQuickPick,
telemetryHelper,
TruffleConfig,
TruffleConfiguration,
vscodeEnvironment,
} from '../helpers';
import { IDeployDestination, ItemType } from '../Models';
import { NetworkForContractItem } from '../Models/QuickPickItems/NetworkForContractItem';
import { AzureBlockchainProject, InfuraProject, LocalProject, LocalService } from '../Models/TreeItems';
import { Project } from '../Models/TreeItems';
import { Output } from '../Output';
import {
ContractDB,
ContractInstanceWithMetadata,
ContractService,
GanacheService,
MnemonicRepository,
OpenZeppelinService,
TreeManager,
} from '../services';
import { OZContractValidated } from '../services/openZeppelin/models';
import { Telemetry } from '../TelemetryClient';
import { NetworkNodeView } from '../ViewItems';
import { ServiceCommands } from './ServiceCommands';
interface IDeployDestinationItem {
cmd: () => Promise<void>;
cwd?: string;
description?: string;
detail?: string;
label: string;
networkId: string | number;
}
interface IExtendedQuickPickItem extends QuickPickItem {
/**
* Additional field for storing non-displayed information
*/
extended: string;
}
export namespace TruffleCommands {
export async function buildContracts(): Promise<void> {
Telemetry.sendEvent('TruffleCommands.buildContracts.commandStarted');
await showIgnorableNotification(
Constants.statusBarMessages.buildingContracts,
async () => {
if (!await required.checkAppsSilent(RequiredApps.truffle)) {
Telemetry.sendEvent('TruffleCommands.buildContracts.truffleInstallation');
await required.installTruffle(required.Scope.locally);
}
await outputCommandHelper.executeCommand(getWorkspaceRoot(), 'npx', RequiredApps.truffle, 'compile');
},
);
Telemetry.sendEvent('TruffleCommands.buildContracts.commandFinished');
}
export async function deployContracts(): Promise<void> {
Telemetry.sendEvent('TruffleCommands.deployContracts.commandStarted');
await checkOpenZeppelinIfUsed();
const truffleConfigsUri = TruffleConfiguration.getTruffleConfigUri();
const defaultDeployDestinations = getDefaultDeployDestinations(truffleConfigsUri);
const truffleDeployDestinations = await getTruffleDeployDestinations(truffleConfigsUri);
const treeDeployDestinations = await getTreeDeployDestinations(truffleConfigsUri);
const deployDestinations: IDeployDestinationItem[] = [];
deployDestinations.push(...defaultDeployDestinations);
deployDestinations.push(...truffleDeployDestinations);
deployDestinations.push(...treeDeployDestinations);
const uniqueDestinations = removeDuplicateNetworks(deployDestinations);
const command = await showQuickPick(
uniqueDestinations,
{
ignoreFocusOut: true,
placeHolder: Constants.placeholders.selectDeployDestination,
},
);
Telemetry.sendEvent(
'TruffleCommands.deployContracts.selectedDestination',
{ url: Telemetry.obfuscate(command.description || '') },
);
await command.cmd();
Telemetry.sendEvent('TruffleCommands.deployContracts.commandFinished');
}
export async function writeAbiToBuffer(uri: Uri): Promise<void> {
Telemetry.sendEvent('TruffleCommands.writeAbiToBuffer.commandStarted');
const contract = await readCompiledContract(uri);
await vscodeEnvironment.writeToClipboard(JSON.stringify(contract[Constants.contractProperties.abi]));
Telemetry.sendEvent('TruffleCommands.writeAbiToBuffer.commandFinished');
}
export async function writeBytecodeToBuffer(uri: Uri): Promise<void> {
Telemetry.sendEvent('TruffleCommands.writeBytecodeToBuffer.commandStarted');
const contract = await readCompiledContract(uri);
await vscodeEnvironment.writeToClipboard(contract[Constants.contractProperties.bytecode]);
Telemetry.sendEvent('TruffleCommands.writeBytecodeToBuffer.commandFinished');
}
export async function writeDeployedBytecodeToBuffer(uri: Uri): Promise<void> {
Telemetry.sendEvent('TruffleCommands.writeBytecodeToBuffer.commandStarted');
ensureFileIsContractJson(uri.fsPath);
const contractInstances = await ContractDB.getContractInstances(
path.basename(uri.fsPath, Constants.contractExtension.json)) as ContractInstanceWithMetadata[];
const contractInstancesWithNetworkInfo = contractInstances.filter((contractIns) => {
return contractIns.network.name !== undefined && !!contractIns.provider && !!contractIns.address;
});
if (!contractInstancesWithNetworkInfo.length) {
window.showInformationMessage(Constants.informationMessage.contractNotDeployed);
return;
}
const networkQuickPickItems = contractInstancesWithNetworkInfo.map((contractIns) =>
new NetworkForContractItem(contractIns.network.name!, contractIns.provider!.host, contractIns.address!));
const networkItem = await showQuickPick(
networkQuickPickItems,
{ placeHolder: 'Select a network', ignoreFocusOut: true },
);
try {
const deployedBytecode =
await ContractService.getDeployedBytecodeByAddress(networkItem.host, networkItem.contractAddress);
window.showInformationMessage(Constants.informationMessage.transactionBytecodeWasCopiedToClipboard);
await vscodeEnvironment.writeToClipboard(deployedBytecode);
} catch (ex) {
Telemetry.sendException(ex);
window.showErrorMessage(Constants.errorMessageStrings.FetchingDeployedBytecodeIsFailed);
}
Telemetry.sendEvent('TruffleCommands.writeBytecodeToBuffer.commandFinished');
}
export async function writeRPCEndpointAddressToBuffer(networkNodeView: NetworkNodeView): Promise<void> {
Telemetry.sendEvent('TruffleCommands.writeRPCEndpointAddressToBuffer.commandStarted');
try {
const rpcEndpointAddress = await networkNodeView.extensionItem.getRPCAddress();
Telemetry.sendEvent('TruffleCommands.writeRPCEndpointAddressToBuffer.getRPCAddress',
{ data: Telemetry.obfuscate(rpcEndpointAddress) },
);
if (rpcEndpointAddress) {
await vscodeEnvironment.writeToClipboard(rpcEndpointAddress);
window.showInformationMessage(Constants.informationMessage.rpcEndpointCopiedToClipboard);
} else {
window.showInformationMessage(
Constants.informationMessage.networkIsNotReady(networkNodeView.extensionItem.constructor.name));
}
} catch (error) {
Telemetry.sendException(error);
window.showErrorMessage(Constants.errorMessageStrings.BlockchainItemIsUnavailable(
networkNodeView.extensionItem.constructor.name));
}
}
export async function getPrivateKeyFromMnemonic(): Promise<void> {
Telemetry.sendEvent('TruffleCommands.getPrivateKeyFromMnemonic.commandStarted');
const mnemonicItems: IExtendedQuickPickItem[] = MnemonicRepository
.getExistedMnemonicPaths()
.map((mnemonicPath) => {
const savedMnemonic = MnemonicRepository.getMnemonic(mnemonicPath);
return {
detail: mnemonicPath,
extended: savedMnemonic,
label: MnemonicRepository.MaskMnemonic(savedMnemonic),
};
});
if (mnemonicItems.length === 0) {
Telemetry.sendEvent('TruffleCommands.getPrivateKeyFromMnemonic.thereAreNoMnemonics');
window.showErrorMessage(Constants.errorMessageStrings.ThereAreNoMnemonics);
return;
}
const mnemonicItem = await showQuickPick(
mnemonicItems,
{ placeHolder: Constants.placeholders.selectMnemonicExtractKey, ignoreFocusOut: true },
);
const mnemonic = mnemonicItem.extended;
if (!mnemonic) {
Telemetry.sendEvent('TruffleCommands.getPrivateKeyFromMnemonic.mnemonicFileHaveNoText');
window.showErrorMessage(Constants.errorMessageStrings.MnemonicFileHaveNoText);
return;
}
try {
const buffer = await bip39.mnemonicToSeed(mnemonic);
const key = hdkey.fromMasterSeed(buffer);
const childKey = key.derive('m/44\'/60\'/0\'/0/0');
const privateKey = childKey.privateKey.toString('hex');
await vscodeEnvironment.writeToClipboard(privateKey);
window.showInformationMessage(Constants.informationMessage.privateKeyWasCopiedToClipboard);
} catch (error) {
Telemetry.sendException(error);
window.showErrorMessage(Constants.errorMessageStrings.InvalidMnemonic);
}
Telemetry.sendEvent('TruffleCommands.getPrivateKeyFromMnemonic.commandFinished');
}
}
async function checkOpenZeppelinIfUsed(): Promise<void> {
if (OpenZeppelinService.projectJsonExists()) {
if (await openZeppelinHelper.shouldUpgradeOpenZeppelinAsync()) {
await openZeppelinHelper.upgradeOpenZeppelinContractsAsync();
await openZeppelinHelper.upgradeOpenZeppelinUserSettingsAsync();
}
await validateOpenZeppelinContracts();
await openZeppelinHelper.defineContractRequiredParameters();
}
}
function removeDuplicateNetworks(deployDestinations: IDeployDestinationItem[]): IDeployDestinationItem[] {
return deployDestinations.filter((destination, index, destinations) => {
return destinations.findIndex((dest) => dest.label === destination.label) === index;
});
}
async function installRequiredDependencies(): Promise<void> {
if (!await required.checkAppsSilent(RequiredApps.truffle)) {
Telemetry.sendEvent('TruffleCommands.installRequiredDependencies.installTruffle');
await required.installTruffle(required.Scope.locally);
}
if (await required.isHdWalletProviderRequired() && !(await required.checkHdWalletProviderVersion())) {
if (!await required.isDefaultProject()) {
const { cancelButton, installButton, requiresDependency } = Constants.informationMessage;
const answer = await window.showInformationMessage(requiresDependency, installButton, cancelButton);
if (answer !== installButton) {
return;
}
}
Telemetry.sendEvent('TruffleCommands.installRequiredDependencies.installTruffleHdWalletProvider');
await required.installTruffleHdWalletProvider();
}
}
async function validateOpenZeppelinContracts(): Promise<void> {
const validatedContracts = await OpenZeppelinService.validateContractsAsync();
validatedContracts.forEach((ozContract: OZContractValidated) => {
if (ozContract.isExistedOnDisk) {
Output.outputLine('', ozContract.isHashValid
? Constants.openZeppelin.validHashMessage(ozContract.contractPath)
: Constants.openZeppelin.invalidHashMessage(ozContract.contractPath));
} else {
Output.outputLine('', Constants.openZeppelin.contractNotExistedOnDisk(ozContract.contractPath));
}
});
const invalidContractsPaths = validatedContracts
.filter((ozContract: OZContractValidated) => !ozContract.isExistedOnDisk || !ozContract.isHashValid)
.map((ozContract: OZContractValidated) => ozContract.contractPath);
if (invalidContractsPaths.length !== 0) {
const errorMsg = Constants.validationMessages.openZeppelinFilesAreInvalid(invalidContractsPaths);
const error = new Error(errorMsg);
window.showErrorMessage(errorMsg);
const obfuscatedPaths = invalidContractsPaths.map((invalidContractsPath) =>
Telemetry.obfuscate(invalidContractsPath));
Telemetry.sendException(new Error(Constants.validationMessages.openZeppelinFilesAreInvalid(obfuscatedPaths)));
throw error;
}
}
function getDefaultDeployDestinations(truffleConfigPath: string): IDeployDestinationItem[] {
return [
{
cmd: createNewDeploymentService.bind(undefined, truffleConfigPath),
label: Constants.uiCommandStrings.createProject,
networkId: '*',
},
];
}
async function getTruffleDeployDestinations(truffleConfigPath: string): Promise<IDeployDestinationItem[]> {
const deployDestination: IDeployDestinationItem[] = [];
const truffleConfig = new TruffleConfig(truffleConfigPath);
const networksFromConfig = truffleConfig.getNetworks();
networksFromConfig.forEach(async (network: TruffleConfiguration.INetwork) => {
const options = network.options;
const url = `${options.provider ? options.provider.url : ''}` ||
`${options.host ? options.host : ''}${options.port ? ':' + options.port : ''}`;
deployDestination.push({
cmd: await getTruffleDeployFunction(
network.name,
truffleConfigPath,
network.options.network_id,
options.port),
cwd: path.dirname(truffleConfigPath),
description: url,
detail: 'From truffle-config.js',
label: network.name,
networkId: options.network_id,
});
});
return deployDestination;
}
async function getTreeDeployDestinations(truffleConfigPath: string): Promise<IDeployDestinationItem[]> {
const services = TreeManager.getItems();
const projects = services.reduce((res, service) => {
res.push(...service.getChildren() as Project[]);
return res;
}, [] as Project[]);
return getProjectDeployDestinationItems(projects, truffleConfigPath);
}
async function getProjectDeployDestinationItems(projects: Project[], truffleConfigPath: string)
: Promise<IDeployDestinationItem[]> {
const destinations: IDeployDestination[] = [];
const filteredProjects = projects.filter((project) =>
project instanceof AzureBlockchainProject ||
project instanceof InfuraProject ||
project instanceof LocalProject);
for (const project of filteredProjects) {
const projectDestinations = await project.getDeployDestinations();
destinations.push(...projectDestinations);
}
return destinations.map((destination) => {
const { description, detail, getTruffleNetwork, label, networkId, networkType, port } = destination;
return {
cmd: getServiceCreateFunction(networkType, getTruffleNetwork, truffleConfigPath, port),
description,
detail,
label,
networkId,
} as IDeployDestinationItem;
});
}
async function getTruffleDeployFunction(
name: string,
truffleConfigPath: string,
networkId: number | string,
port?: number)
: Promise<() => Promise<void>> {
const treeProjectNames = await getTreeProjectNames();
if (port !== undefined && (treeProjectNames.includes(name) || name === Constants.localhostName)) {
Telemetry.sendEvent('TruffleCommands.getTruffleDeployFunction.returnDeployToLocalGanache');
return deployToLocalGanache.bind(undefined, name, truffleConfigPath, port);
}
// 1 - is the marker of main network
if (networkId === 1 || networkId === '1') {
Telemetry.sendEvent('TruffleCommands.getTruffleDeployFunction.returnDeployToMainNetwork');
return deployToMainNetwork.bind(undefined, name, truffleConfigPath);
}
Telemetry.sendEvent('TruffleCommands.getTruffleDeployFunction.returnDeployToNetwork');
return deployToNetwork.bind(undefined, name, truffleConfigPath);
}
async function getTreeProjectNames(): Promise<string[]> {
const services = TreeManager.getItems();
const localService = services.find((service) => service instanceof LocalService);
const projects = (localService ? localService.getChildren() : []) as Project[];
const projectNames = [];
for (const project of projects) {
const projectDestinations = await project.getDeployDestinations();
projectNames.push(...projectDestinations);
}
return projectNames.map((destination) => destination.label);
}
function getServiceCreateFunction(
type: ItemType,
getTruffleNetwork: () => Promise<TruffleConfiguration.INetwork>,
truffleConfigPath: string,
port?: number,
): () => Promise<void> {
if (type === ItemType.LOCAL_NETWORK_NODE) {
Telemetry.sendEvent('TruffleCommands.getServiceCreateFunction.returnCreateLocalGanacheNetwork');
return createLocalGanacheNetwork.bind(undefined, getTruffleNetwork, truffleConfigPath, port!);
}
Telemetry.sendEvent('TruffleCommands.getServiceCreateFunction.returnCreateService');
return createNetwork.bind(undefined, getTruffleNetwork, truffleConfigPath);
}
async function createNewDeploymentService(truffleConfigPath: string): Promise<void> {
Telemetry.sendEvent('TruffleCommands.createNewDeploymentService.commandStarted');
const project = await ServiceCommands.createProject();
const deployDestination = await getProjectDeployDestinationItems([project], truffleConfigPath);
const command = await showQuickPick(
deployDestination,
{
ignoreFocusOut: true,
placeHolder: Constants.placeholders.selectDeployDestination,
},
);
Telemetry.sendEvent(
'TruffleCommands.deployContracts.createNewDeploymentService.selectedDestination',
{ url: Telemetry.obfuscate(command.description || '') },
);
await command.cmd();
}
async function createLocalGanacheNetwork(
getTruffleNetwork: () => Promise<TruffleConfiguration.INetwork>,
truffleConfigPath: string,
port: number,
): Promise<void> {
await GanacheService.startGanacheServer(port);
await createNetwork(getTruffleNetwork, truffleConfigPath);
}
async function createNetwork(getTruffleNetwork: () => Promise<TruffleConfiguration.INetwork>, truffleConfigPath: string)
: Promise<void> {
const network = await getTruffleNetwork();
const truffleConfig = new TruffleConfig(truffleConfigPath);
truffleConfig.setNetworks(network);
await deployToNetwork(network.name, truffleConfigPath);
}
async function deployToNetwork(networkName: string, truffleConfigPath: string): Promise<void> {
await showIgnorableNotification(
Constants.statusBarMessages.deployingContracts(networkName),
async () => {
const workspaceRoot = path.dirname(truffleConfigPath);
await fs.ensureDir(workspaceRoot);
try {
await installRequiredDependencies();
await outputCommandHelper.executeCommand(
workspaceRoot,
'npx',
RequiredApps.truffle, 'migrate', '--reset', '--network', networkName,
);
Output.outputLine(Constants.outputChannel.azureBlockchain, Constants.informationMessage.deploySucceeded);
Telemetry.sendEvent(
'TruffleCommands.deployToNetwork.deployedSuccessfully',
{
destination: telemetryHelper.mapNetworkName(networkName),
},
);
} catch (error) {
Output.outputLine(Constants.outputChannel.azureBlockchain, Constants.informationMessage.deployFailed);
Telemetry.sendEvent(
'TruffleCommands.deployToNetwork.deployedFailed',
{
destination: telemetryHelper.mapNetworkName(networkName),
},
);
throw error;
}
await ContractDB.updateContracts();
},
);
}
async function deployToLocalGanache(networkName: string, truffleConfigPath: string, port: number): Promise<void> {
await GanacheService.startGanacheServer(port);
await deployToNetwork(networkName, truffleConfigPath);
}
async function deployToMainNetwork(networkName: string, truffleConfigPath: string): Promise<void> {
await showConfirmPaidOperationDialog();
await deployToNetwork(networkName, truffleConfigPath);
}
async function readCompiledContract(uri: Uri): Promise<any> {
ensureFileIsContractJson(uri.fsPath);
const data = fs.readFileSync(uri.fsPath, null);
return JSON.parse(data.toString());
}
function ensureFileIsContractJson(filePath: string) {
if (path.extname(filePath) !== Constants.contractExtension.json) {
const error = new Error(Constants.errorMessageStrings.InvalidContract);
Telemetry.sendException(error);
throw error;
}
} | the_stack |
import { Injectable } from '@angular/core';
import { ExampleType } from '../example-viewer/example-viewer.component';
const STACKBLITZ_URL = 'https://run.stackblitz.com/api/angular/v1';
const COPYRIGHT = `Copyright 2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license`;
const TEMPLATE_FILES: { [id: string]: ExampleType['files'] } = {
core: [
{ file: 'polyfills.ts', filecontent: require('!!raw-loader!@assets/stackblitz/polyfills.ts') },
{ file: 'angular.json', filecontent: require('!!raw-loader!@assets/stackblitz/angular_json') },
{ file: 'main.ts', filecontent: require('!!raw-loader!@assets/stackblitz/main.ts') },
{ file: 'index.html', filecontent: require('!!raw-loader!@assets/stackblitz/index.html') },
],
bootstrap: [{ file: 'styles.scss', filecontent: { default: `@import '~bootstrap/scss/bootstrap.scss';` } }],
material: [
{
file: 'styles.scss',
filecontent: { default: `@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';` },
},
],
kendo: [{ file: 'styles.scss', filecontent: { default: `@import '~@progress/kendo-theme-default/dist/all.css';` } }],
primeng: [
{
file: 'styles.scss',
filecontent: {
default: `
@import '~primeng/resources/primeng.min.css';
@import '~primeng/resources/themes/bootstrap/theme.css';
`,
},
},
],
ionic: [
{
file: 'styles.scss',
filecontent: {
default: `
@import "~@ionic/angular/css/core.css";
@import "~@ionic/angular/css/normalize.css";
@import "~@ionic/angular/css/structure.css";
@import "~@ionic/angular/css/typography.css";
@import "~@ionic/angular/css/padding.css";
@import "~@ionic/angular/css/float-elements.css";
@import "~@ionic/angular/css/text-alignment.css";
@import "~@ionic/angular/css/flex-utils.css";
`,
},
},
],
'ng-zorro-antd': [
{
file: 'styles.scss',
filecontent: {
default: `
@import '~ng-zorro-antd/ng-zorro-antd.min.css';
`,
},
},
],
};
const TAGS: string[] = ['angular', 'formly', 'example'];
const angularVersion = '^7.0.0';
const materialVersion = '^7.0.0';
const formlyVersion = '^5.0.0';
const dependencies = {
core: {
'@angular/common': angularVersion,
'@angular/compiler': angularVersion,
'@angular/core': angularVersion,
'@angular/forms': angularVersion,
'@angular/platform-browser': angularVersion,
'@angular/platform-browser-dynamic': angularVersion,
'core-js': '^2.4.1',
rxjs: '^6.4.0',
'zone.js': '^0.9.0',
tslib: '^1.7.0',
'@ngx-formly/core': formlyVersion,
},
bootstrap: {
'@ngx-formly/bootstrap': formlyVersion,
bootstrap: '^4.2.1',
'popper.js': '^1.14',
jquery: '^3',
},
material: {
'@ngx-formly/material': formlyVersion,
},
kendo: {
'@ngx-formly/kendo': formlyVersion,
'@progress/kendo-theme-default': '^3.2.0',
'@progress/kendo-angular-dropdowns': '^4.0.0',
'@progress/kendo-angular-popup': '^3.0.0',
'@progress/kendo-angular-common': '^1.0.0',
'@progress/kendo-angular-l10n': '^1.0.0',
'rxjs-compat': '^6.4.0',
},
primeng: {
'@ngx-formly/primeng': formlyVersion,
primeng: '^7.0.5',
},
ionic: {
'@ngx-formly/ionic': formlyVersion,
'@ionic/angular': '4.0.0-beta.7', // workaround for https://github.com/ionic-team/ionic/issues/16354
'@angular-devkit/core': '*',
'@angular-devkit/schematics': '*',
'@angular/compiler-cli': '*',
'@angular/router': '*',
typescript: '*',
},
// non UI framework libraries
'ag-grid': {
'ag-grid-angular': '*',
'ag-grid-community': '*',
'@angular/compiler-cli': angularVersion,
typescript: '*',
},
'ngx-datatable': {
'@swimlane/ngx-datatable': '*',
},
'ngx-translate': {
'@ngx-translate/core': '*',
'@ngx-translate/http-loader': '*',
},
'ng-zorro-antd': {
'@ngx-formly/ng-zorro-antd': formlyVersion,
'ng-zorro-antd': '^8.0.0',
},
};
const ngModule = {
bootstrap: 'FormlyBootstrapModule',
material: 'FormlyMaterialModule',
kendo: 'FormlyKendoModule',
primeng: 'FormlyPrimeNGModule',
ionic: 'FormlyIonicModule',
'ng-zorro-antd': 'FormlyNgZorroAntdModule',
};
/**
* Stackblitz writer, write example files to stackblitz
*
* StackBlitz API
* URL: https://run.stackblitz.com/api/aio/v1/
* data: {
* // File name, directory and content of files
* files[file-name1]: file-content1,
* files[directory-name/file-name2]: file-content2,
* // Can add multiple tags
* tags[0]: tag-0,
* // Description of stackblitz
* description: description,
* // Private or not
* private: true
* // Dependencies
* dependencies: dependencies
* }
*/
@Injectable()
export class StackblitzWriter {
/**
* Returns an HTMLFormElement that will open a new stackblitz template with the example data when
* called with submit().
*/
constructStackblitzForm(type: string, exampleData: ExampleType): HTMLFormElement {
const indexFile = `src%2Fapp%2Fapp.component.ts`;
const form = this._createFormElement(indexFile);
TAGS.forEach((tag, i) => this._appendFormInput(form, `tags[${i}]`, tag));
this._appendFormInput(form, 'private', 'true');
this._appendFormInput(form, 'description', exampleData.title);
const appModuleContent = exampleData.files.find((f) => f.file === 'app.module.ts').filecontent.default;
exampleData.deps = exampleData.deps || [];
const options: any = { type };
if (['bootstrap', 'material', 'kendo', 'ionic', 'primeng', 'ng-zorro-antd'].indexOf(options.type) === -1) {
if (appModuleContent.indexOf('@ngx-formly/bootstrap') !== -1) {
options.type = 'bootstrap';
} else if (appModuleContent.indexOf('@ngx-formly/material') !== -1) {
options.type = 'material';
} else if (appModuleContent.indexOf('@ngx-formly/kendo') !== -1) {
options.type = 'kendo';
} else if (appModuleContent.indexOf('@ngx-formly/ionic') !== -1) {
options.type = 'ionic';
} else if (appModuleContent.indexOf('@ngx-formly/primeng') !== -1) {
options.type = 'primeng';
} else if (appModuleContent.indexOf('@ngx-formly/ng-zorro-antd') !== -1) {
options.type = 'ng-zorro-antd';
}
}
if ('material' === options.type || appModuleContent.indexOf('@angular/material') !== -1) {
options.includeMaterial = true;
}
if (
['material', 'kendo', 'material'].indexOf(options.type) !== -1 ||
options.includeMaterial ||
exampleData.files
.map((f) => f.filecontent.default)
.some((content) => content.indexOf('@angular/animations') !== -1)
) {
options.useAnimation = true;
}
if (appModuleContent.indexOf('ag-grid-angular') !== -1) {
options.includeAgGrid = true;
}
if (exampleData.deps.indexOf('fontawesome') !== -1) {
options.includeFontawesome = true;
}
if (appModuleContent.indexOf('@swimlane/ngx-datatable') !== -1) {
options.includeNgxDatable = true;
}
if (appModuleContent.indexOf('@ngx-translate/core') !== -1) {
options.includeNgxTranslate = true;
}
const deps = {
...dependencies.core,
...dependencies[options.type],
};
if (options.useAnimation) {
deps['@angular/animations'] = angularVersion;
}
if (options.includeMaterial) {
deps['@angular/cdk'] = materialVersion;
deps['@angular/material'] = materialVersion;
}
if (options.includeAgGrid) {
Object.assign(deps, dependencies['ag-grid']);
}
if (options.includeNgxDatable) {
Object.assign(deps, dependencies['ngx-datatable']);
}
if (options.includeNgxTranslate) {
Object.assign(deps, dependencies['ngx-translate']);
}
this._appendFormInput(form, 'dependencies', JSON.stringify(deps));
[...TEMPLATE_FILES.core, ...TEMPLATE_FILES[options.type]].forEach((data) => {
this._addFileToForm(
form,
this._replaceExamplePlaceholderNames(data.file, data.filecontent.default, options),
data.file,
false,
);
});
exampleData.files.forEach((data) => {
this._addFileToForm(
form,
this._replaceExamplePlaceholderNames(data.file, data.filecontent.default, options),
data.file,
data.file.indexOf('assets') !== 0,
);
});
return form;
}
/** Constructs a new form element that will navigate to the stackblitz url. */
_createFormElement(indexFile: string): HTMLFormElement {
const form = document.createElement('form');
form.action = `${STACKBLITZ_URL}?file=${indexFile}`;
form.method = 'post';
form.target = '_blank';
return form;
}
/** Appends the name and value as an input to the form. */
_appendFormInput(form: HTMLFormElement, name: string, value: string): void {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
form.appendChild(input);
}
/**
* Adds the file text to the form.
* @param form the html form you are appending to
* @param data example metadata about the example
* @param content file contents
* @param filename file name of the example
* @param path path to the src
* @param prependApp whether to prepend the 'app' prefix to the path
*/
_addFileToForm(form: HTMLFormElement, content: string, filename: string, prependApp = true) {
if (prependApp) {
filename = 'app/' + filename;
}
if (filename !== 'angular.json') {
filename = 'src/' + filename;
}
this._appendFormInput(form, `files[${filename}]`, this._appendCopyright(filename, content));
}
_replaceExamplePlaceholderNames(fileName: string, filecontent: string, options): string {
if (fileName === 'app.module.ts') {
if (options.type === 'ionic') {
filecontent = filecontent.replace(
`'@angular/common';`,
`'@angular/common';\nimport { IonicModule } from '@ionic/angular';`,
);
filecontent = filecontent.replace(`FormlyModule.forRoot`, `IonicModule.forRoot(),\n FormlyModule.forRoot`);
}
if (filecontent.indexOf(`@ngx-formly/${options.type}'`) === -1) {
filecontent = filecontent.replace(
`'@ngx-formly/core';`,
`'@ngx-formly/core';\nimport { ${ngModule[options.type]} } from '@ngx-formly/${options.type}';`,
);
filecontent = filecontent.replace(
`FormlyModule.forRoot`,
`${ngModule[options.type]},\n FormlyModule.forRoot`,
);
}
if (options.useAnimation) {
filecontent = filecontent.replace('@angular/common', '@angular/platform-browser/animations');
filecontent = filecontent.replace(/CommonModule/g, 'BrowserAnimationsModule');
} else {
filecontent = filecontent.replace('@angular/common', '@angular/platform-browser');
filecontent = filecontent.replace(/CommonModule/g, 'BrowserModule');
}
filecontent = filecontent.replace('declarations: [', `bootstrap: [AppComponent],\n declarations: [`);
} else if (fileName === 'styles.scss') {
filecontent = `${filecontent}\nbody { padding: 10px; }`;
if (options.type !== 'material' && options.includeMaterial) {
filecontent = `${filecontent}\n@import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; `;
}
if (options.includeAgGrid) {
filecontent = `${filecontent}\n@import '~ag-grid-community/dist/styles/ag-grid.css'; `;
filecontent = `${filecontent}\n@import '~ag-grid-community/dist/styles/ag-theme-balham.css'; `;
}
}
if (fileName === 'index.html' && options.includeFontawesome) {
filecontent = `<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">\n${filecontent}`;
}
filecontent = filecontent.replace(/_json/g, '.json');
return filecontent;
}
_appendCopyright(filename: string, content: string) {
if (filename.indexOf('.ts') > -1 || filename.indexOf('.scss') > -1) {
content = `${content}\n\n/** ${COPYRIGHT} */`;
} else if (filename.indexOf('.html') > -1) {
content = `${content}\n\n<!-- ${COPYRIGHT} -->`;
}
return content;
}
} | the_stack |
// This code adopted from our existing jobs code
import cache from 'memory-cache';
import axios, { AxiosError } from 'axios';
import querystring from 'querystring';
import { IGraphProvider, IGraphEntry, IGraphEntryWithManager, IGraphGroupMember, IGraphGroup, GraphUserType } from '.';
import { ErrorHelper, CreateError } from '../../transitional';
import { ICacheHelper } from '../caching';
export interface IMicrosoftGraphProviderOptions {
tokenCacheSeconds?: string | number;
clientId: string;
clientSecret: string;
tokenEndpoint?: string;
tenantId?: string;
cacheProvider?: ICacheHelper;
}
const graphBaseUrl = 'https://graph.microsoft.com/v1.0/';
const odataNextLink = '@odata.nextLink';
const defaultCachePeriodMinutes = 60;
interface IGraphOptions {
selectValues?: string;
filterValues?: string;
orderBy?: string;
body?: any;
count?: boolean;
consistencyLevel?: 'eventual',
}
export class MicrosoftGraphProvider implements IGraphProvider {
#_tokenCacheMilliseconds: number;
#_clientSecret: string;
#_staticManagerEntryCacheById: Map<string, IGraphEntryWithManager>;
#_tenantId: string;
#_tokenEndpoint: string;
#_cache: ICacheHelper;
public clientId: string;
constructor(graphOptions: IMicrosoftGraphProviderOptions) {
this.#_staticManagerEntryCacheById = new Map();
const secondsString = (graphOptions.tokenCacheSeconds || '60').toString();
this.#_tokenCacheMilliseconds = parseInt(secondsString, 10) * 1000;
this.clientId = graphOptions.clientId;
this.#_clientSecret = graphOptions.clientSecret;
this.#_tenantId = graphOptions.tenantId;
this.#_tokenEndpoint = graphOptions.tokenEndpoint;
this.#_cache = graphOptions.cacheProvider;
if (!this.clientId) {
throw new Error('MicrosoftGraphProvider: clientId required');
}
if (!this.#_clientSecret) {
throw new Error('MicrosoftGraphProvider: clientSecret required');
}
}
async isUserInGroup(corporateId: string, securityGroupId: string): Promise<boolean> {
// TODO: refactor for efficient use of Microsoft Graph's checkMemberObjects https://docs.microsoft.com/en-us/graph/api/group-checkmemberobjects?view=graph-rest-1.0&tabs=http
const members = await this.getGroupMembers(securityGroupId);
return members.filter(m => m.id === corporateId).length > 0;
}
private async getTokenThenEntity(aadId: string, resource: string): Promise<unknown> {
const accessToken = await this.getToken();
return await this.getUserByIdLookup(aadId, accessToken, resource);
}
async getManagerById(aadId: string) {
const entity = await this.getTokenThenEntity(aadId, 'manager') as IGraphEntry;
return entity;
}
async getUserAndManagerById(aadId: string): Promise<IGraphEntryWithManager> {
const entity = await this.getTokenThenEntity(aadId, null) as IGraphEntryWithManager;
try {
const manager = await this.getTokenThenEntity(aadId, 'manager') as IGraphEntry;
if (manager) {
entity.manager = manager;
}
} catch (warning) {
if (ErrorHelper.IsNotFound(warning)) {
console.warn(`User not found with AAD ID ${aadId}`);
} else {
console.warn(warning);
}
}
return entity;
}
async getManagementChain(corporateId: string): Promise<IGraphEntryWithManager[]> {
let chain = [];
try {
let entry = await this.getCachedEntryWithManagerById(corporateId);
while (entry) {
const clone = { ...entry };
delete clone.manager;
chain.push(clone);
entry = entry.manager && entry.manager.id ? await this.getCachedEntryWithManagerById(entry.manager.id) : null;
}
} catch (getError) {
if (ErrorHelper.IsNotFound(getError)) {
return null;
} else {
console.dir(getError);
throw getError;
}
}
return chain;
}
async getCachedEntryWithManagerById(corporateId: string): Promise<IGraphEntryWithManager> {
let entry = this.#_staticManagerEntryCacheById.get(corporateId);
if (entry) {
return entry;
}
entry = await this.getUserAndManagerById(corporateId);
this.#_staticManagerEntryCacheById.set(corporateId, entry);
return entry;
}
async getUserById(id: string): Promise<IGraphEntry> {
try {
const info = await this.getTokenThenEntity(id, null);
return info as IGraphEntry;
} catch (error) {
if (ErrorHelper.IsNotFound(error)) {
return null;
}
throw error;
}
}
async getGroup(corporateGroupId: string): Promise<IGraphGroup> {
const response = await this.lookupInGraph([
'groups',
corporateGroupId,
], {
selectValues: 'description,displayName,id,mail,mailNickname',
});
return response;
}
async getGroupsByNickname(nickname: string): Promise<string[]> {
const response = await this.lookupInGraph([
'groups',
], {
filterValues: `mailNickname eq '${encodeURIComponent(nickname)}'`,
selectValues: 'id',
}) as any[];
if (response?.map) {
return response.map(entry => entry.id);
}
const values = (response as any).value as any[];
return values.map(entry => entry.id);
}
async getMailAddressByUsername(corporateUsername: string): Promise<string> {
const response = await this.lookupInGraph([
'users',
corporateUsername,
], {
selectValues: 'mail',
});
return response && response.mail ? response.mail : null;
}
async getUserIdByUsername(corporateUsername: string): Promise<string> {
const response = await this.lookupInGraph([
'users',
corporateUsername,
], {
selectValues: 'id',
});
return response?.id;
}
async getUserIdByNickname(nickname: string): Promise<string> {
const response = await this.lookupInGraph([
'users',
], {
filterValues: `mailNickname eq '${encodeURIComponent(nickname)}'`,
selectValues: 'id',
}) as any[];
if (!response || response.length === 0) {
return null;
}
if (Array.isArray(response)) {
return response.map(entry => entry.id)[0];
}
const subResponse = (response as any).value ? (response as any).value : [];
return subResponse.map(entry => entry.id)[0];
}
async getUserIdByMail(mail: string): Promise<string> {
const response = await this.lookupInGraph([
'users',
], {
filterValues: `mail eq '${mail}'`, // encodeURIComponent(
selectValues: 'id',
count: true,
consistencyLevel: 'eventual',
}) as any[];
if (!response || response.length === 0) {
return null;
}
if (Array.isArray(response)) {
return response.map(entry => entry.id)[0];
}
const subResponse = (response as any).value ? (response as any).value : [];
return subResponse.map(entry => entry.id)[0];
}
async getUsersByIds(userIds: string[]): Promise<IGraphEntry[]> {
if (!userIds || userIds.length === 0) {
return [];
}
let response = await this.lookupInGraph([
'users',
], {
filterValues: userIds.map(id => `id eq '${id.trim()}'`).join(' or '),
selectValues: 'id,displayName,mailNickname,mail,userPrincipalName,userType,jobTitle',
}) as any[];
// caching issues...
if (!response.filter && (response as any).value?.filter) {
response = (response as any).value;
}
return response.filter(e => e.userType !== GraphUserType.Guest).map(entry => {
return {
id: entry.id,
mailNickname: entry.mailNickname,
displayName: entry.displayName,
mail: entry.mail,
givenName: entry.givenName,
userPrincipalName: entry.userPrincipalName,
jobTitle: entry.jobTitle,
};
});
}
async getDirectReports(corporateIdOrUpn: string): Promise<IGraphEntry[]> {
let response = await this.lookupInGraph([
'users',
corporateIdOrUpn,
'directReports',
], {
selectValues: 'id,displayName,mailNickname,mail,userPrincipalName,userType,jobTitle',
}) as any[];
if (!response.filter && (response as any).value?.filter) {
response = (response as any).value;
}
return response.filter(e => e.userType !== GraphUserType.Guest).map(entry => {
return {
id: entry.id,
mailNickname: entry.mailNickname,
displayName: entry.displayName,
mail: entry.mail,
givenName: entry.givenName,
userPrincipalName: entry.userPrincipalName,
jobTitle: entry.jobTitle,
};
});
}
async getUsersByMailNicknames(mailNicknames: string[]): Promise<IGraphEntry[]> {
let response = await this.lookupInGraph([
'users',
], {
filterValues: mailNicknames.map(alias => `mailNickname eq '${alias.trim()}'`).join(' or '),
selectValues: 'id,displayName,mailNickname,mail,userPrincipalName,userType,jobTitle',
}) as any[];
if (!response.filter && (response as any).value?.filter) {
response = (response as any).value;
}
return response.filter(e => e.userType !== GraphUserType.Guest).map(entry => {
return {
id: entry.id,
mailNickname: entry.mailNickname,
displayName: entry.displayName,
mail: entry.mail,
givenName: entry.givenName,
userPrincipalName: entry.userPrincipalName,
jobTitle: entry.jobTitle,
};
});
}
async getUsersBySearch(minimum3Characters: string): Promise<IGraphEntry[]> {
if (!minimum3Characters || minimum3Characters.length < 3) {
throw new Error(`Minimum 3 characters required: ${minimum3Characters}`);
}
minimum3Characters = minimum3Characters.replace(/'/g, '\'\'');
let response = await this.lookupInGraph([
'users',
], {
filterValues: `startswith(givenName, '${minimum3Characters}') or startswith(surname, '${minimum3Characters}') or startswith(displayName, '${minimum3Characters}') or startswith(mailNickname, '${minimum3Characters}') or startswith(mail, '${minimum3Characters}')`,
selectValues: 'id,displayName,mailNickname,mail,userPrincipalName,userType,jobTitle',
}) as any[];
if (!response.filter && (response as any).value?.filter) {
response = (response as any).value;
}
return response.filter(e => e.userType !== GraphUserType.Guest).map(entry => {
return {
id: entry.id,
mailNickname: entry.mailNickname,
displayName: entry.displayName,
mail: entry.mail,
givenName: entry.givenName,
userPrincipalName: entry.userPrincipalName,
jobTitle: entry.jobTitle,
};
});
}
async getGroupMembers(corporateGroupId: string): Promise<IGraphGroupMember[]> {
const response = await this.lookupInGraph([
'groups',
corporateGroupId,
'transitiveMembers', // transitiveMembers or members
], {
selectValues: 'id,userPrincipalName',
}) as any[];
// may be a caching bug:
if (Array.isArray(response)) {
return response.map(entry => { return { id: entry.id, userPrincipalName: entry.userPrincipalName }; });
}
const subResponse = (response as any).value ? (response as any).value : [];
return subResponse.map(entry => { return { id: entry.id, userPrincipalName: entry.userPrincipalName }; });
}
async getGroupsStartingWith(minimum3Characters: string): Promise<IGraphGroup[]> {
if (!minimum3Characters || minimum3Characters.length < 3) {
throw new Error(`Minimum 3 characters required: ${minimum3Characters}`);
}
// NOTE: this is currently explicitly looking for Security Groups only
let response = await this.lookupInGraph([
'groups',
], {
filterValues: `securityEnabled eq true and (startswith(displayName, '${minimum3Characters}') or startswith(mailNickname, '${minimum3Characters}'))`,
selectValues: 'id,displayName,mailNickname',
}) as any[];
if (!response.filter && (response as any).value?.filter) {
response = (response as any).value;
}
return response.map(entry => { return { id: entry.id, mailNickname: entry.mailNickname, displayName: entry.displayName }; });
}
async getGroupsByMail(groupMailAddress: string): Promise<string[]> {
let response = await this.lookupInGraph([
'groups',
], {
filterValues: `mail eq '${groupMailAddress}'`,
selectValues: 'id',
}) as any[];
if (!response.filter && (response as any).value?.filter) {
response = (response as any).value;
}
return response.map(entry => entry.id);
}
async getGroupsById(corporateId: string): Promise<string[]> {
const response = await this.lookupInGraph([
'users',
corporateId,
'getMemberGroups',
], {
// selectValues: '',
body: {
securityEnabledOnly: true,
},
}) as string[];
return response;
}
private async getUserByIdLookup(aadId: string, token: string, subResource: string): Promise<any> {
if (!aadId) {
throw CreateError.InvalidParameters('No user ID provided to lookup');
}
const extraPath = subResource ? `/${subResource}` : '';
const url = `https://graph.microsoft.com/v1.0/users/${aadId}${extraPath}?$select=id,mailNickname,userType,displayName,givenName,mail,userPrincipalName,jobTitle`;
if (this.#_cache) {
try {
const cached = await this.#_cache.getObject(url);
if (cached?.value) {
return cached.value;
}
} catch (error) {
if (!ErrorHelper.IsNotFound(error)) {
console.warn(error);
}
}
}
try {
const response = await axios({
url,
method: 'get',
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.data) {
throw CreateError.NotFound(`${subResource || 'user'} not in directory for ${aadId}`);
}
if ((response.data as any).error?.message) { // axios returns unknown now
throw CreateError.InvalidParameters((response.data as any).error.message);
}
if (this.#_cache) {
this.#_cache.setObjectWithExpire(url, { value: response.data }, defaultCachePeriodMinutes).then(ok => { }).catch(err => { });
}
return response.data;
} catch (error) {
const axiosError = error as AxiosError;
if (axiosError?.response) {
if (axiosError.response?.status === 404) {
throw CreateError.NotFound(`${subResource || 'user'} not in the directory for '${aadId}'`, axiosError);
} else if (axiosError.response?.status >= 500) {
throw CreateError.ServerError('Graph server error', axiosError);
} else if (axiosError.response?.status >= 400) {
throw CreateError.InvalidParameters('Incorrect graph parameters', axiosError);
}
}
throw error;
}
}
private async lookupInGraph(entityPath: string[], options: IGraphOptions): Promise<any> {
// initial hacking on top of the API
const subUrl = entityPath.map(item => encodeURIComponent(item)).join('/');
const queries = {};
if (options.filterValues) {
queries['$filter'] = options.filterValues;
}
if (options.selectValues) {
queries['$select'] = options.selectValues;
}
if (options.orderBy) {
queries['$orderby'] = options.orderBy;
}
let hasArray = false;
let value = null;
let url = `${graphBaseUrl}${subUrl}?${querystring.stringify(queries)}`;
let originalUrl = url;
try {
if (this.#_cache) {
value = await this.#_cache.getObject(url);
if (value?.cache) {
if (Array.isArray(value.cache) && value.cache.length === 0) {
// live lookup still
} else {
return value.cache as any;
}
}
}
} catch (error) {
console.warn(error);
}
let pages = 0;
do {
const consistencyLevel = options.consistencyLevel;
const body = await this.request(url, options.body, consistencyLevel);
if (body.value && pages === 0) {
hasArray = body && body.value && Array.isArray(body.value);
if (hasArray) {
value = body.value as any[];
} else {
value = body.value;
}
} else if (hasArray && body.value) {
value = value.concat(body.value as any[]);
} else if (!body.value) {
value = body;
} else {
throw new Error(`Page ${pages} in response is not an array type but had a link: ${url}`);
}
++pages;
url = body && body[odataNextLink] ? body[odataNextLink] : null;
} while (url);
if (this.#_cache) {
try {
this.#_cache.setObjectWithExpire(originalUrl, { cache: value }, defaultCachePeriodMinutes).then(ok => { }).catch(err => {
console.warn(err);
});
} catch (error) {
console.warn(error);
}
}
return value;
}
private async request(url: string, body?: any, eventualConsistency?: string): Promise<any> {
const token = await this.getToken();
const method = body ? 'post' : 'get';
if (this.#_cache && method === 'get') {
try {
const value = await this.#_cache.getObject(url);
if (value?.cache) {
if (Array.isArray(value.cache) && value.cache.length === 0) {
// live lookup still
} else {
return value.cache as any;
}
}
} catch (error) {
console.warn(error);
}
}
try {
const headers = {
Authorization: `Bearer ${token}`,
// ConsistencyLevel: undefined,
};
if (eventualConsistency) {
// headers.ConsistencyLevel = eventualConsistency;
}
const response = await axios({
url,
method,
data: method === 'post' ? body : undefined,
headers,
});
if (!response.data) {
throw CreateError.ServerError('Empty response');
}
if ((response.data as any).error?.message) { // axios returns unknown now
throw CreateError.InvalidParameters((response.data as any).error.message); // axios returns unknown now
}
if (this.#_cache && method === 'get') {
this.#_cache.setObjectWithExpire(url, { cache: response.data }, defaultCachePeriodMinutes).then(ok => { }).catch(err => { });
}
return response.data;
} catch (error) {
const axiosError = error as AxiosError;
if (axiosError?.response) {
if (axiosError.response?.status === 404) {
const err = CreateError.NotFound('Not found', axiosError);
err['url'] = url;
throw error;
} else if (axiosError.response?.status >= 500) {
const err = CreateError.ServerError('Graph server error', axiosError);
err['url'] = url;
throw err;
} else if (axiosError.response?.status >= 400) {
throw CreateError.InvalidParameters('Incorrect graph parameters', axiosError);
}
}
error['url'] = url;
throw error;
}
}
async getToken() {
const clientId = this.clientId;
const clientSecret = this.#_clientSecret;
if (!clientId || !clientSecret) {
throw new Error('The graph provider requires an AAD clientId and clientSecret.');
}
const tokenKey = this.clientId;
const token = cache.get(tokenKey) as string;
if (token) {
return token;
}
const tokenEndpoint = this.#_tokenEndpoint || `https://login.microsoftonline.com/${this.#_tenantId}/oauth2/token`;
// These are the parameters necessary for the OAuth 2.0 Client Credentials Grant Flow.
// For more information, see Service to Service Calls Using Client Credentials (https://msdn.microsoft.com/library/azure/dn645543.aspx).
try {
const qs = {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
resource: 'https://graph.microsoft.com',
};
const response = await axios.post(tokenEndpoint, querystring.stringify(qs), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
if (!response.data) {
throw CreateError.ServerError('Empty response');
}
const data = response.data as any; // axios returns unknown now
if (!data.access_token) {
throw CreateError.InvalidParameters('No access token');
}
if (data.error?.message) {
throw CreateError.InvalidParameters(data.error.message);
}
const accessToken = data.access_token as string;
cache.put(tokenKey, accessToken, this.#_tokenCacheMilliseconds);
return accessToken;
} catch (error) {
const axiosError = error as AxiosError;
if (axiosError?.response) {
if (axiosError.response?.status === 404) {
throw CreateError.NotFound('Not found', axiosError);
} else if (axiosError.response?.status >= 500) {
throw CreateError.ServerError('Graph server error', axiosError);
} else if (axiosError.response?.status === 401) {
throw CreateError.NotAuthenticated('Invalid authorization to access to the graph');
} else if (axiosError.response?.status === 403) {
throw CreateError.NotAuthorized('Not authorized to access the graph');
} else if (axiosError.response?.status >= 400) {
throw CreateError.InvalidParameters('Incorrect graph parameters', axiosError);
}
}
throw error;
}
}
} | the_stack |
import { filterMap, toStringLiteral } from './utils';
import { TypeContent, makeTypeContentRoot, makeTypeContentChild, Settings, JsDoc } from './types';
import {
AlternativesDescribe,
ArrayDescribe,
BaseDescribe,
BasicDescribe,
Describe,
ObjectDescribe,
StringDescribe
} from './joiDescribeTypes';
import { getInterfaceOrTypeName, getMetadataFromDetails } from './joiUtils';
// see __tests__/joiTypes.ts for more information
export const supportedJoiTypes = ['array', 'object', 'alternatives', 'any', 'boolean', 'date', 'number', 'string'];
// @TODO - Temporarily used prevent 'map' and 'set' from being used by cast
// Remove once support for 'map' and 'set' is added
const validCastTo = ['string', 'number'];
function getCommonDetails(
details: Describe,
settings: Settings
): { interfaceOrTypeName?: string; jsDoc: JsDoc; required: boolean } {
const interfaceOrTypeName = getInterfaceOrTypeName(settings, details);
const description = details.flags?.description;
const presence = details.flags?.presence;
const example = details.examples?.[0];
let required;
if (presence === 'optional') {
required = false;
} else if (presence === 'required') {
required = true;
} else {
required = settings.defaultToRequired;
}
return { interfaceOrTypeName, jsDoc: { description, example }, required };
}
export function getAllCustomTypes(parsedSchema: TypeContent): string[] {
if (parsedSchema.__isRoot) {
return parsedSchema.children.flatMap(child => getAllCustomTypes(child));
} else {
return parsedSchema.customTypes || [];
}
}
/**
* Get all indent characters for this indent level
* @param settings includes what the indent characters are
* @param indentLevel how many indent levels
*/
function getIndentStr(settings: Settings, indentLevel: number): string {
return settings.indentationChacters.repeat(indentLevel);
}
/**
* Get Interface jsDoc
*/
function getDescriptionStr(settings: Settings, name: string, jsDoc?: JsDoc, indentLevel = 0): string {
if (!settings.commentEverything && !jsDoc?.description && !jsDoc?.example) {
return '';
}
const lines = ['/**'];
if (settings.commentEverything || (jsDoc && jsDoc.description)) {
lines.push(` * ${jsDoc?.description ?? name}`);
}
if (jsDoc?.example) {
lines.push(` * @example ${jsDoc.example}`);
}
lines.push(' */');
return lines.map(line => `${getIndentStr(settings, indentLevel)}${line}`).join('\n') + '\n';
}
function typeContentToTsHelper(
settings: Settings,
parsedSchema: TypeContent,
indentLevel: number,
doExport = false
): { tsContent: string; jsDoc?: JsDoc } {
if (!parsedSchema.__isRoot) {
return {
tsContent: parsedSchema.content,
jsDoc: parsedSchema.jsDoc
};
}
const children = parsedSchema.children;
if (doExport && !parsedSchema.interfaceOrTypeName) {
throw new Error(`Type ${JSON.stringify(parsedSchema)} needs a name to be exported`);
}
switch (parsedSchema.joinOperation) {
case 'list': {
const childrenContent = children.map(child => typeContentToTsHelper(settings, child, indentLevel));
if (childrenContent.length > 1) {
throw new Error('Multiple array item types not supported');
}
let content = childrenContent[0].tsContent;
if (content.includes('|')) {
// TODO: might need a better way to add the parens for union
content = `(${content})`;
}
const arrayStr = `${content}[]`;
if (doExport) {
return {
tsContent: `export type ${parsedSchema.interfaceOrTypeName} = ${arrayStr};`,
jsDoc: parsedSchema.jsDoc
};
}
return { tsContent: arrayStr, jsDoc: parsedSchema.jsDoc };
}
case 'union': {
const childrenContent = children.map(child => typeContentToTsHelper(settings, child, indentLevel).tsContent);
const unionStr = childrenContent.join(' | ');
if (doExport) {
return {
tsContent: `export type ${parsedSchema.interfaceOrTypeName} = ${unionStr};`,
jsDoc: parsedSchema.jsDoc
};
}
return { tsContent: unionStr, jsDoc: parsedSchema.jsDoc };
}
case 'object': {
if (!children.length && !doExport) {
return { tsContent: 'object', jsDoc: parsedSchema.jsDoc };
}
// interface can have no properties {} if the joi object has none defined
let objectStr = '{}';
if (children.length !== 0) {
const childrenContent = children.map(child => {
const childInfo = typeContentToTsHelper(settings, child, indentLevel + 1, false);
// forcing name to be defined here, might need a runtime check but it should be set if we are here
const descriptionStr = getDescriptionStr(
settings,
child.interfaceOrTypeName as string,
childInfo.jsDoc,
indentLevel
);
const optionalStr = child.required ? '' : '?';
const indentString = getIndentStr(settings, indentLevel);
return `${descriptionStr}${indentString}${child.interfaceOrTypeName}${optionalStr}: ${childInfo.tsContent};`;
});
objectStr = `{\n${childrenContent.join('\n')}\n${getIndentStr(settings, indentLevel - 1)}}`;
}
if (doExport) {
return {
tsContent: `export interface ${parsedSchema.interfaceOrTypeName} ${objectStr}`,
jsDoc: parsedSchema.jsDoc
};
}
return { tsContent: objectStr, jsDoc: parsedSchema.jsDoc };
}
default:
throw new Error(`Unsupported join operation ${parsedSchema.joinOperation}`);
}
}
export function typeContentToTs(settings: Settings, parsedSchema: TypeContent, doExport = false): string {
const { tsContent, jsDoc } = typeContentToTsHelper(settings, parsedSchema, 1, doExport);
// forcing name to be defined here, might need a runtime check but it should be set if we are here
const descriptionStr = getDescriptionStr(settings, parsedSchema.interfaceOrTypeName as string, jsDoc);
return `${descriptionStr}${tsContent}`;
}
// TODO: will be issues with useLabels if a nested schema has a label but is not exported on its own
// TODO: will need to pass around ignoreLabels more
/**
* Parses a joi schema into a TypeContent
* @param details: the joi schema
* @param settings: settings used for parsing
* @param useLabels if true and if a schema has a label we won't parse it and instead just reference the label in the outputted type
* @param ignoreLabels a list a label to ignore if found. Sometimes nested joi schemas will inherit the parents label so we want to ignore that
* @param rootSchema
*/
export function parseSchema(
details: Describe,
settings: Settings,
useLabels = true,
ignoreLabels: string[] = [],
rootSchema?: boolean
): TypeContent | undefined {
function parseHelper(): TypeContent | undefined {
// Convert type if a valid cast type is present
if (details.flags?.cast && validCastTo.includes(details.flags?.cast as 'number' | 'string')) {
// @NOTE - if additional values are added beyond 'string' and 'number' further transformation will
// be needed on the details object to support those types
details.type = details.flags?.cast as 'string' | 'number';
}
switch (details.type) {
case 'array':
return parseArray(details, settings);
case 'string':
return parseStringSchema(details, settings, rootSchema ?? false);
case 'alternatives':
return parseAlternatives(details, settings);
case 'object':
return parseObjects(details, settings);
default:
return parseBasicSchema(details, settings, rootSchema ?? false);
}
}
const { interfaceOrTypeName, jsDoc, required } = getCommonDetails(details, settings);
if (interfaceOrTypeName && useLabels && !ignoreLabels.includes(interfaceOrTypeName)) {
// skip parsing and just reference the label since we assumed we parsed the schema that the label references
// TODO: do we want to use the labels description if we reference it?
const child = makeTypeContentChild({
content: interfaceOrTypeName,
customTypes: [interfaceOrTypeName],
jsDoc,
required
});
const allowedValues = createAllowTypes(details);
if (allowedValues.length !== 0) {
allowedValues.unshift(child);
return makeTypeContentRoot({
joinOperation: 'union',
interfaceOrTypeName: '',
children: allowedValues,
jsDoc,
required
});
}
return child;
}
if (!supportedJoiTypes.includes(details.type)) {
// See if we can find a base type for this type in the details.
let typeToUse;
const baseTypes: string[] = getMetadataFromDetails('baseType', details);
if (baseTypes.length > 0) {
// If there are multiple base types then the deepest one will be at the
// end of the list which is most likely the one to use.
typeToUse = baseTypes.pop() as string;
}
// If we could not get the base type from the metadata then see if we can
// map it to something sensible. If not, then set it to 'unknown'.
if (typeToUse === undefined) {
switch (details.type as string) {
case 'function':
typeToUse = '(...args: any[]) => any';
break;
case 'symbol':
typeToUse = 'symbol';
break;
case 'binary':
typeToUse = 'Buffer';
break;
default:
typeToUse = 'unknown';
break;
}
}
if (settings.debug) {
console.debug(`Using '${typeToUse}' for unsupported type '${details.type}'`);
}
return makeTypeContentChild({ content: typeToUse, interfaceOrTypeName, jsDoc, required });
}
const parsedSchema = parseHelper();
if (!parsedSchema) {
return undefined;
}
parsedSchema.interfaceOrTypeName = interfaceOrTypeName;
parsedSchema.jsDoc = jsDoc;
parsedSchema.required = required;
return parsedSchema;
}
function parseBasicSchema(details: BasicDescribe, settings: Settings, rootSchema: boolean): TypeContent | undefined {
const { interfaceOrTypeName, jsDoc } = getCommonDetails(details, settings);
const joiType = details.type;
let content = joiType as string;
if (joiType === 'date') {
content = 'Date';
}
const values = details.allow;
// at least one value
if (values && values.length !== 0) {
const allowedValues = createAllowTypes(details);
if (values[0] === null) {
allowedValues.unshift(makeTypeContentChild({ content }));
}
return makeTypeContentRoot({ joinOperation: 'union', children: allowedValues, interfaceOrTypeName, jsDoc });
}
if (rootSchema) {
return makeTypeContentRoot({
joinOperation: 'union',
children: [makeTypeContentChild({ content, interfaceOrTypeName, jsDoc })],
interfaceOrTypeName,
jsDoc
});
} else {
return makeTypeContentChild({ content, interfaceOrTypeName, jsDoc });
}
}
function createAllowTypes(details: BaseDescribe): TypeContent[] {
const values = details.allow;
// at least one value
if (values && values.length !== 0) {
const allowedValues = values.map((value: unknown) =>
makeTypeContentChild({ content: typeof value === 'string' ? toStringLiteral(value) : `${value}` })
);
return allowedValues;
}
return [];
}
/**
* `undefined` is not part of this list as that would make the field optional instead
*/
const stringAllowValues = [null, ''];
function parseStringSchema(details: StringDescribe, settings: Settings, rootSchema: boolean): TypeContent | undefined {
const { interfaceOrTypeName, jsDoc } = getCommonDetails(details, settings);
const values = details.allow;
// at least one value
if (values && values.length !== 0) {
if (values.length === 1 && values[0] === '') {
// special case of empty string sometimes used in Joi to allow just empty string
} else {
const allowedValues = values.map(value =>
stringAllowValues.includes(value) && value !== ''
? makeTypeContentChild({ content: `${value}` })
: makeTypeContentChild({ content: toStringLiteral(value) })
);
if (values.filter(value => stringAllowValues.includes(value)).length == values.length) {
allowedValues.unshift(makeTypeContentChild({ content: 'string' }));
}
return makeTypeContentRoot({ joinOperation: 'union', children: allowedValues, interfaceOrTypeName, jsDoc });
}
}
if (rootSchema) {
return makeTypeContentRoot({
joinOperation: 'union',
children: [makeTypeContentChild({ content: 'string', interfaceOrTypeName, jsDoc })],
interfaceOrTypeName,
jsDoc
});
} else {
return makeTypeContentChild({ content: 'string', interfaceOrTypeName, jsDoc });
}
}
function parseArray(details: ArrayDescribe, settings: Settings): TypeContent | undefined {
// TODO: handle multiple things in the items arr
const item = details.items ? details.items[0] : ({ type: 'any' } as Describe);
const { interfaceOrTypeName, jsDoc } = getCommonDetails(details, settings);
const child = parseSchema(item, settings);
if (!child) {
return undefined;
}
const allowedValues = createAllowTypes(details);
// at least one value
if (allowedValues.length !== 0) {
allowedValues.unshift(
makeTypeContentRoot({ joinOperation: 'list', children: [child], interfaceOrTypeName, jsDoc })
);
return makeTypeContentRoot({ joinOperation: 'union', children: allowedValues, interfaceOrTypeName, jsDoc });
}
return makeTypeContentRoot({ joinOperation: 'list', children: [child], interfaceOrTypeName, jsDoc });
}
function parseAlternatives(details: AlternativesDescribe, settings: Settings): TypeContent | undefined {
const { interfaceOrTypeName, jsDoc } = getCommonDetails(details, settings);
const ignoreLabels = interfaceOrTypeName ? [interfaceOrTypeName] : [];
const children = filterMap(details.matches, match => {
return parseSchema(match.schema, settings, true, ignoreLabels);
});
// This is an check that cannot be tested as Joi throws an error before this package
// can be called, there is test for it in alternatives
if (children.length === 0) {
/* istanbul ignore next */
return undefined;
}
return makeTypeContentRoot({ joinOperation: 'union', children, interfaceOrTypeName, jsDoc });
}
function parseObjects(details: ObjectDescribe, settings: Settings): TypeContent | undefined {
let children = filterMap(Object.entries(details.keys || {}), ([key, value]) => {
const parsedSchema = parseSchema(value, settings);
// The only type that could return this is alternatives
// see parseAlternatives for why this is ignored
if (!parsedSchema) {
return undefined;
}
parsedSchema.interfaceOrTypeName = /^[$A-Z_][0-9A-Z_$]*$/i.test(key || '') ? key : `'${key}'`;
return parsedSchema;
});
const isMap = details.patterns?.length === 1 && details.patterns[0].schema.type === 'string';
if (details?.flags?.unknown === true || isMap) {
let unknownType = 'unknown';
const unknownTypes: string[] = getMetadataFromDetails('unknownType', details);
if (unknownTypes.length > 0) {
// If there are multiple base types then the deepest one will be at the
// end of the list which is most likely the one to use.
unknownType = unknownTypes.pop() as string;
}
const unknownProperty = {
content: unknownType,
interfaceOrTypeName: '[x: string]',
required: true,
jsDoc: { description: `${unknownType && unknownType[0].toUpperCase() + unknownType.slice(1)} Property` }
} as TypeContent;
children.push(unknownProperty);
}
if (settings.sortPropertiesByName) {
children = children.sort((a, b) => {
// interfaceOrTypeName should never be null at this point
if (!a.interfaceOrTypeName || !b.interfaceOrTypeName) {
return 0;
} else if (a.interfaceOrTypeName > b.interfaceOrTypeName) {
return 1;
} else if (a.interfaceOrTypeName < b.interfaceOrTypeName) {
return -1;
}
// this next line can never happen as the object is totally invalid as the object is invalid
// the code would not build so ignoring this
/* istanbul ignore next */
return 0;
});
}
const { interfaceOrTypeName, jsDoc } = getCommonDetails(details, settings);
const allowedValues = createAllowTypes(details);
// at least one value
if (allowedValues.length !== 0) {
allowedValues.unshift(makeTypeContentRoot({ joinOperation: 'object', children, interfaceOrTypeName, jsDoc }));
return makeTypeContentRoot({ joinOperation: 'union', children: allowedValues, interfaceOrTypeName, jsDoc });
}
return makeTypeContentRoot({ joinOperation: 'object', children, interfaceOrTypeName, jsDoc });
} | the_stack |
import pRetry from 'p-retry';
import { ApiGranule, GranuleId, GranuleStatus } from '@cumulus/types/api/granules';
import Logger from '@cumulus/logger';
import { invokeApi } from './cumulusApiClient';
import { ApiGatewayLambdaHttpProxyResponse, InvokeApiFunction } from './types';
const logger = new Logger({ sender: '@api-client/granules' });
type AssociateExecutionRequest = {
granuleId: string
collectionId: string
executionArn: string
};
/**
* GET raw response from /granules/{granuleName}
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {Object} [params.query] - query to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the granule fetched by the API
*/
export const getGranuleResponse = async (params: {
prefix: string,
granuleId: GranuleId,
query?: { [key: string]: string },
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const {
prefix,
granuleId,
query,
callback = invokeApi,
} = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'GET',
resource: '/{proxy+}',
path: `/granules/${granuleId}`,
...(query && { queryStringParameters: query }),
},
});
};
/**
* GET granule record from /granules/{granuleName}
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {Object} [params.query] - query to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the granule fetched by the API
*/
export const getGranule = async (params: {
prefix: string,
granuleId: GranuleId,
query?: { [key: string]: string },
callback?: InvokeApiFunction
}): Promise<ApiGranule> => {
const response = await getGranuleResponse(params);
return JSON.parse(response.body);
};
/**
* Wait for a granule to be present in the database (using pRetry)
*
* @param {Object} params - params
* @param {string} params.granuleId - granuleId to wait for
* @param {number} params.retries - number of times to retry
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
*/
export const waitForGranule = async (params: {
prefix: string,
granuleId: GranuleId,
status?: GranuleStatus,
retries?: number,
pRetryOptions?: pRetry.Options,
callback?: InvokeApiFunction
}) => {
const {
prefix,
granuleId,
status,
retries = 10,
pRetryOptions = {},
callback = invokeApi,
} = params;
await pRetry(
async () => {
const apiResult = await getGranuleResponse({ prefix, granuleId, callback });
if (apiResult.statusCode === 500) {
throw new pRetry.AbortError('API misconfigured/down/etc, failing test');
}
if (apiResult.statusCode !== 200) {
throw new Error(`granule ${granuleId} not in database yet, status ${apiResult.statusCode} retrying....`);
}
if (status) {
const granuleStatus = JSON.parse(apiResult.body).status;
if (status !== granuleStatus) {
throw new Error(`Granule status ${granuleStatus} does not match requested status, retrying...`);
}
}
logger.info(`Granule ${granuleId} in database, proceeding...`); // TODO fix logging
},
{
retries,
onFailedAttempt: (e) => {
logger.error(e.message);
},
...pRetryOptions,
}
);
};
/**
* Reingest a granule from the Cumulus API
* PUT /granules/{}
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {string} params.workflowName - Optional WorkflowName
* @param {string} params.executionArn - Optional executionArn
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the granule fetched by the API
*/
export const reingestGranule = async (params: {
prefix: string,
granuleId: GranuleId,
workflowName?: string | undefined,
executionArn?: string | undefined,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, granuleId, workflowName, executionArn, callback = invokeApi } = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'PUT',
resource: '/{proxy+}',
path: `/granules/${granuleId}`,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'reingest',
workflowName,
executionArn,
}),
},
});
};
/**
* Removes a granule from CMR via the Cumulus API
* PUT /granules/{granuleId}
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the granule fetched by the API
*/
export const removeFromCMR = async (params: {
prefix: string,
granuleId: GranuleId,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, granuleId, callback = invokeApi } = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'PUT',
resource: '/{proxy+}',
path: `/granules/${granuleId}`,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'removeFromCmr' }),
},
});
};
/**
* Run a workflow with the given granule as the payload
* PUT /granules/{granuleId}
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {string} params.workflow - workflow to be run with given granule
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the granule fetched by the API
*/
export const applyWorkflow = async (params: {
prefix: string,
granuleId: GranuleId,
workflow: string,
meta?: object,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const {
prefix,
granuleId,
workflow,
meta,
callback = invokeApi,
} = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'PUT',
resource: '/{proxy+}',
headers: {
'Content-Type': 'application/json',
},
path: `/granules/${granuleId}`,
body: JSON.stringify({ action: 'applyWorkflow', workflow, meta }),
},
});
};
/**
* Delete a granule from Cumulus via the API lambda
* DELETE /granules/${granuleId}
*
* @param {Object} params - params
* @param {pRetry.Options} params.pRetryObject - pRetry options object
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the delete confirmation from the API
*/
export const deleteGranule = async (params: {
prefix: string,
granuleId: GranuleId,
pRetryOptions?: pRetry.Options,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const {
pRetryOptions,
prefix,
granuleId,
callback = invokeApi,
} = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'DELETE',
resource: '/{proxy+}',
path: `/granules/${granuleId}`,
},
pRetryOptions,
});
};
/**
* Move a granule via the API
* PUT /granules/{granuleId}
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {Array<Object>} params.destinations - move granule destinations
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke
* the api lambda
* @returns {Promise<Object>} - the move response from the API
*/
export const moveGranule = async (params: {
prefix: string,
granuleId: GranuleId,
destinations: unknown[],
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const {
prefix,
granuleId,
destinations,
callback = invokeApi,
} = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'PUT',
resource: '/{proxy+}',
headers: {
'Content-Type': 'application/json',
},
path: `/granules/${granuleId}`,
body: JSON.stringify({ action: 'move', destinations }),
},
});
};
/**
* Removed a granule from CMR and delete from Cumulus via the API
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {string} params.granuleId - a granule ID
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the delete confirmation from the API
*/
export const removePublishedGranule = async (params: {
prefix: string,
granuleId: GranuleId,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, granuleId, callback = invokeApi } = params;
// pre-delete: Remove the granule from CMR
await removeFromCMR({ prefix, granuleId, callback });
return deleteGranule({ prefix, granuleId, callback });
};
/**
* Query granules stored in cumulus
* GET /granules
* @param {Object} params - params
* @param {Object} [params.query] - query to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the response from the callback
*/
export const listGranules = async (params: {
prefix: string,
query?: {
fields?: string[],
[key: string]: string | string[] | undefined
},
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, query, callback = invokeApi } = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'GET',
resource: '/{proxy+}',
path: '/granules',
queryStringParameters: query,
},
});
};
/**
* Create granule into cumulus.
* POST /granules
* @param {Object} params - params
* @param {Object} [params.body] - granule to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the response from the callback
*/
export const createGranule = async (params: {
prefix: string,
body: ApiGranule,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, body, callback = invokeApi } = params;
return await callback({
prefix,
payload: {
httpMethod: 'POST',
resource: '/{proxy+}',
path: '/granules',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
});
};
/**
* Update granule in cumulus.
* PUT /granules/{granuleId}
* @param {Object} params - params
* @param {Object} [params.body] - granule to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the response from the callback
*/
export const updateGranule = async (params: {
prefix: string,
body: ApiGranule,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, body, callback = invokeApi } = params;
return await callback({
prefix,
payload: {
httpMethod: 'PUT',
resource: '/{proxy+}',
path: `/granules/${body.granuleId}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
expectedStatusCodes: [200, 201],
});
};
/**
* Associate an execution with a granule in cumulus.
* POST /granules/{granuleId}/execution
* @param {Object} params - params
* @param {Object} [params.body] - granule and execution info to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the response from the callback
*/
export const associateExecutionWithGranule = async (params: {
prefix: string,
body: AssociateExecutionRequest,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, body, callback = invokeApi } = params;
return await callback({
prefix,
payload: {
httpMethod: 'POST',
resource: '/{proxy+}',
path: `/granules/${body.granuleId}/executions`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
});
};
/**
* Bulk operations on granules stored in cumulus
* POST /granules/bulk
* @param {Object} params - params
* @param {Object} params.body - body to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the response from the callback
*/
export const bulkGranules = async (params: {
prefix: string,
body: object,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, body, callback = invokeApi } = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'POST',
resource: '/{proxy+}',
headers: {
'Content-Type': 'application/json',
},
path: '/granules/bulk',
body: JSON.stringify(body),
},
expectedStatusCodes: 202,
});
};
/**
* Bulk delete granules stored in cumulus
* POST /granules/bulkDelete
* @param {Object} params - params
* @param {Object} params.body - body to pass the API lambda
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the response from the callback
*/
export const bulkDeleteGranules = async (params: {
prefix: string,
body: unknown,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, body, callback = invokeApi } = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'POST',
resource: '/{proxy+}',
headers: {
'Content-Type': 'application/json',
},
path: '/granules/bulkDelete',
body: JSON.stringify(body),
},
expectedStatusCodes: 202,
});
};
export const bulkReingestGranules = async (params: {
prefix: string,
body: unknown,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, body, callback = invokeApi } = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'POST',
resource: '/{proxy+}',
headers: {
'Content-Type': 'application/json',
},
path: '/granules/bulkReingest',
body: JSON.stringify(body),
},
expectedStatusCodes: 202,
});
};
/**
* Bulk Granule Operations
* POST /granules/bulk
*
* @param {Object} params - params
* @param {string} params.prefix - the prefix configured for the stack
* @param {Array<string>} params.ids - the granules to have bulk operation on
* @param {string} params.workflowName - workflowName for the bulk operation execution
* @param {Function} params.callback - async function to invoke the api lambda
* that takes a prefix / user payload. Defaults
* to cumulusApiClient.invokeApifunction to invoke the
* api lambda
* @returns {Promise<Object>} - the response from the callback
*/
export const bulkOperation = async (params: {
prefix: string,
ids: string[],
workflowName: string,
callback?: InvokeApiFunction
}): Promise<ApiGatewayLambdaHttpProxyResponse> => {
const { prefix, ids, workflowName, callback = invokeApi } = params;
return await callback({
prefix: prefix,
payload: {
httpMethod: 'POST',
resource: '/{proxy+}',
path: '/granules/bulk/',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ ids, workflowName }),
},
expectedStatusCodes: 202,
});
}; | the_stack |
export const description = `
Test vertex attributes behave correctly (no crash / data leak) when accessed out of bounds
Test coverage:
The following is parameterized (all combinations tested):
1) Draw call type? (drawIndexed, drawIndirect, drawIndexedIndirect)
- Run the draw call using an index buffer and/or an indirect buffer.
- Doesn't test direct draw, as vertex buffer OOB are CPU validated and treated as validation errors.
- Also the instance step mode vertex buffer OOB are CPU validated for drawIndexed, so we only test
robustness access for vertex step mode vertex buffers.
2) Draw call parameter (vertexCount, firstVertex, indexCount, firstIndex, baseVertex, instanceCount,
vertexCountInIndexBuffer)
- The parameter which goes out of bounds. Filtered depending on the draw call type.
- vertexCount, firstVertex: used for drawIndirect only, test for vertex step mode buffer OOB
- instanceCount: used for both drawIndirect and drawIndexedIndirect, test for instance step mode buffer OOB
- baseVertex, vertexCountInIndexBuffer: used for both drawIndexed and drawIndexedIndirect, test
for vertex step mode buffer OOB. vertexCountInIndexBuffer indicates how many vertices are used
within the index buffer, i.e. [0, 1, ..., vertexCountInIndexBuffer-1].
- indexCount, firstIndex: used for drawIndexedIndirect only, validate the vertex buffer access
when the vertex itself is OOB in index buffer. This never happens in drawIndexed as we have index
buffer OOB CPU validation for it.
3) Attribute type (float32, float32x2, float32x3, float32x4)
- The input attribute type in the vertex shader
4) Error scale (0, 1, 4, 10^2, 10^4, 10^6)
- Offset to add to the correct draw call parameter
- 0 For control case
5) Additional vertex buffers (0, +4)
- Tests that no OOB occurs if more vertex buffers are used
6) Partial last number and offset vertex buffer (false, true)
- Tricky cases that make vertex buffer OOB.
- With partial last number enabled, vertex buffer size will be 1 byte less than enough, making the
last vertex OOB with 1 byte.
- Offset vertex buffer will bind the vertex buffer to render pass with 4 bytes offset, causing OOB
- For drawIndexed, these two flags are suppressed for instance step mode vertex buffer to make sure
it pass the CPU validation.
The tests have one instance step mode vertex buffer bound for instanced attributes, to make sure
instanceCount / firstInstance are tested.
The tests include multiple attributes per vertex buffer.
The vertex buffers are filled by repeating a few values randomly chosen for each test until the
end of the buffer.
The tests run a render pipeline which verifies the following:
1) All vertex attribute values occur in the buffer or are 0 (for control case it can't be 0)
2) All gl_VertexIndex values are within the index buffer or 0
TODO:
Currently firstInstance is not tested, as for drawIndexed it is CPU validated, and for drawIndirect
and drawIndexedIndirect it should always be 0. Once there is an extension to allow making them non-zero,
it should be added into drawCallTestParameter list.
`;
import { makeTestGroup } from '../../../common/framework/test_group.js';
import { assert } from '../../../common/util/util.js';
import { GPUTest } from '../../gpu_test.js';
// Encapsulates a draw call (either indexed or non-indexed)
class DrawCall {
private test: GPUTest;
private vertexBuffers: GPUBuffer[];
// Add a float offset when binding vertex buffer
private offsetVertexBuffer: boolean;
// Keep instance step mode vertex buffer in range, in order to test vertex step
// mode buffer OOB in drawIndexed. Setting true will suppress partialLastNumber
// and offsetVertexBuffer for instance step mode vertex buffer.
private keepInstanceStepModeBufferInRange: boolean;
// Draw
public vertexCount: number;
public firstVertex: number;
// DrawIndexed
public vertexCountInIndexBuffer: number; // For generating index buffer in drawIndexed and drawIndexedIndirect
public indexCount: number; // For accessing index buffer in drawIndexed and drawIndexedIndirect
public firstIndex: number;
public baseVertex: number;
// Both Draw and DrawIndexed
public instanceCount: number;
public firstInstance: number;
constructor({
test,
vertexArrays,
vertexCount,
partialLastNumber,
offsetVertexBuffer,
keepInstanceStepModeBufferInRange,
}: {
test: GPUTest;
vertexArrays: Float32Array[];
vertexCount: number;
partialLastNumber: boolean;
offsetVertexBuffer: boolean;
keepInstanceStepModeBufferInRange: boolean;
}) {
this.test = test;
// Default arguments (valid call)
this.vertexCount = vertexCount;
this.firstVertex = 0;
this.vertexCountInIndexBuffer = vertexCount;
this.indexCount = vertexCount;
this.firstIndex = 0;
this.baseVertex = 0;
this.instanceCount = vertexCount;
this.firstInstance = 0;
this.offsetVertexBuffer = offsetVertexBuffer;
this.keepInstanceStepModeBufferInRange = keepInstanceStepModeBufferInRange;
// Since vertexInIndexBuffer is mutable, generation of the index buffer should be deferred to right before calling draw
// Generate vertex buffer
this.vertexBuffers = vertexArrays.map((v, i) => {
if (i === 0 && keepInstanceStepModeBufferInRange) {
// Suppress partialLastNumber for the first vertex buffer, aka the instance step mode buffer
return this.generateVertexBuffer(v, false);
} else {
return this.generateVertexBuffer(v, partialLastNumber);
}
});
}
// Insert a draw call into |pass| with specified type
public insertInto(pass: GPURenderPassEncoder, indexed: boolean, indirect: boolean) {
if (indexed) {
if (indirect) {
this.drawIndexedIndirect(pass);
} else {
this.drawIndexed(pass);
}
} else {
if (indirect) {
this.drawIndirect(pass);
} else {
this.draw(pass);
}
}
}
// Insert a draw call into |pass|
public draw(pass: GPURenderPassEncoder) {
this.bindVertexBuffers(pass);
pass.draw(this.vertexCount, this.instanceCount, this.firstVertex, this.firstInstance);
}
// Insert an indexed draw call into |pass|
public drawIndexed(pass: GPURenderPassEncoder) {
// Generate index buffer
const indexArray = new Uint32Array(this.vertexCountInIndexBuffer).map((_, i) => i);
const indexBuffer = this.test.makeBufferWithContents(indexArray, GPUBufferUsage.INDEX);
this.bindVertexBuffers(pass);
pass.setIndexBuffer(indexBuffer, 'uint32');
pass.drawIndexed(
this.indexCount,
this.instanceCount,
this.firstIndex,
this.baseVertex,
this.firstInstance
);
}
// Insert an indirect draw call into |pass|
public drawIndirect(pass: GPURenderPassEncoder) {
this.bindVertexBuffers(pass);
pass.drawIndirect(this.generateIndirectBuffer(), 0);
}
// Insert an indexed indirect draw call into |pass|
public drawIndexedIndirect(pass: GPURenderPassEncoder) {
// Generate index buffer
const indexArray = new Uint32Array(this.vertexCountInIndexBuffer).map((_, i) => i);
const indexBuffer = this.test.makeBufferWithContents(indexArray, GPUBufferUsage.INDEX);
this.bindVertexBuffers(pass);
pass.setIndexBuffer(indexBuffer, 'uint32');
pass.drawIndexedIndirect(this.generateIndexedIndirectBuffer(), 0);
}
// Bind all vertex buffers generated
private bindVertexBuffers(pass: GPURenderPassEncoder) {
let currSlot = 0;
for (let i = 0; i < this.vertexBuffers.length; i++) {
if (i === 0 && this.keepInstanceStepModeBufferInRange) {
// Keep the instance step mode buffer in range
pass.setVertexBuffer(currSlot++, this.vertexBuffers[i], 0);
} else {
pass.setVertexBuffer(currSlot++, this.vertexBuffers[i], this.offsetVertexBuffer ? 4 : 0);
}
}
}
// Create a vertex buffer from |vertexArray|
// If |partialLastNumber| is true, delete one byte off the end
private generateVertexBuffer(vertexArray: Float32Array, partialLastNumber: boolean): GPUBuffer {
let size = vertexArray.byteLength;
let length = vertexArray.length;
if (partialLastNumber) {
size -= 1; // Shave off one byte from the buffer size.
length -= 1; // And one whole element from the writeBuffer.
}
const buffer = this.test.device.createBuffer({
size,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, // Ensure that buffer can be used by writeBuffer
});
this.test.device.queue.writeBuffer(buffer, 0, vertexArray.slice(0, length));
return buffer;
}
// Create an indirect buffer containing draw call values
private generateIndirectBuffer(): GPUBuffer {
const indirectArray = new Int32Array([
this.vertexCount,
this.instanceCount,
this.firstVertex,
this.firstInstance,
]);
return this.test.makeBufferWithContents(indirectArray, GPUBufferUsage.INDIRECT);
}
// Create an indirect buffer containing indexed draw call values
private generateIndexedIndirectBuffer(): GPUBuffer {
const indirectArray = new Int32Array([
this.indexCount,
this.instanceCount,
this.firstIndex,
this.baseVertex,
this.firstInstance,
]);
return this.test.makeBufferWithContents(indirectArray, GPUBufferUsage.INDIRECT);
}
}
// Parameterize different sized types
interface VertexInfo {
wgslType: string;
sizeInBytes: number;
validationFunc: string;
}
const typeInfoMap: { [k: string]: VertexInfo } = {
float32: {
wgslType: 'f32',
sizeInBytes: 4,
validationFunc: 'return valid(v);',
},
float32x2: {
wgslType: 'vec2<f32>',
sizeInBytes: 8,
validationFunc: 'return valid(v.x) && valid(v.y);',
},
float32x3: {
wgslType: 'vec3<f32>',
sizeInBytes: 12,
validationFunc: 'return valid(v.x) && valid(v.y) && valid(v.z);',
},
float32x4: {
wgslType: 'vec4<f32>',
sizeInBytes: 16,
validationFunc: `return valid(v.x) && valid(v.y) && valid(v.z) && valid(v.w) ||
v.x == 0.0 && v.y == 0.0 && v.z == 0.0 && (v.w == 0.0 || v.w == 1.0);`,
},
};
class F extends GPUTest {
generateBufferContents(
numVertices: number,
attributesPerBuffer: number,
typeInfo: VertexInfo,
arbitraryValues: number[],
bufferCount: number
): Float32Array[] {
// Make an array big enough for the vertices, attributes, and size of each element
const vertexArray = new Float32Array(
numVertices * attributesPerBuffer * (typeInfo.sizeInBytes / 4)
);
for (let i = 0; i < vertexArray.length; ++i) {
vertexArray[i] = arbitraryValues[i % arbitraryValues.length];
}
// Only the first buffer is instance step mode, all others are vertex step mode buffer
assert(bufferCount >= 2);
const bufferContents: Float32Array[] = [];
for (let i = 0; i < bufferCount; i++) {
bufferContents.push(vertexArray);
}
return bufferContents;
}
generateVertexBufferDescriptors(
bufferCount: number,
attributesPerBuffer: number,
type: GPUVertexFormat
) {
const typeInfo = typeInfoMap[type];
// Vertex buffer descriptors
const buffers: GPUVertexBufferLayout[] = [];
{
let currAttribute = 0;
for (let i = 0; i < bufferCount; i++) {
buffers.push({
arrayStride: attributesPerBuffer * typeInfo.sizeInBytes,
stepMode: i === 0 ? 'instance' : 'vertex',
attributes: Array(attributesPerBuffer)
.fill(0)
.map((_, i) => ({
shaderLocation: currAttribute++,
offset: i * typeInfo.sizeInBytes,
format: type as GPUVertexFormat,
})),
});
}
}
return buffers;
}
generateVertexShaderCode({
bufferCount,
attributesPerBuffer,
validValues,
typeInfo,
vertexIndexOffset,
numVertices,
isIndexed,
}: {
bufferCount: number;
attributesPerBuffer: number;
validValues: number[];
typeInfo: VertexInfo;
vertexIndexOffset: number;
numVertices: number;
isIndexed: boolean;
}): string {
// Create layout and attributes listing
let layoutStr = 'struct Attributes {';
const attributeNames = [];
{
let currAttribute = 0;
for (let i = 0; i < bufferCount; i++) {
for (let j = 0; j < attributesPerBuffer; j++) {
layoutStr += `[[location(${currAttribute})]] a_${currAttribute} : ${typeInfo.wgslType};\n`;
attributeNames.push(`a_${currAttribute}`);
currAttribute++;
}
}
}
layoutStr += '};';
const vertexShaderCode: string = `
${layoutStr}
fn valid(f : f32) -> bool {
return ${validValues.map(v => `f == ${v}.0`).join(' || ')};
}
fn validationFunc(v : ${typeInfo.wgslType}) -> bool {
${typeInfo.validationFunc}
}
[[stage(vertex)]] fn main(
[[builtin(vertex_index)]] VertexIndex : u32,
attributes : Attributes
) -> [[builtin(position)]] vec4<f32> {
var attributesInBounds = ${attributeNames
.map(a => `validationFunc(attributes.${a})`)
.join(' && ')};
var indexInBoundsCountFromBaseVertex =
(VertexIndex >= ${vertexIndexOffset}u &&
VertexIndex < ${vertexIndexOffset + numVertices}u);
var indexInBounds = VertexIndex == 0u || indexInBoundsCountFromBaseVertex;
var Position : vec4<f32>;
if (attributesInBounds && (${!isIndexed} || indexInBounds)) {
// Success case, move the vertex to the right of the viewport to show that at least one case succeed
Position = vec4<f32>(0.5, 0.0, 0.0, 1.0);
} else {
// Failure case, move the vertex to the left of the viewport
Position = vec4<f32>(-0.5, 0.0, 0.0, 1.0);
}
return Position;
}`;
return vertexShaderCode;
}
createRenderPipeline({
bufferCount,
attributesPerBuffer,
validValues,
typeInfo,
vertexIndexOffset,
numVertices,
isIndexed,
buffers,
}: {
bufferCount: number;
attributesPerBuffer: number;
validValues: number[];
typeInfo: VertexInfo;
vertexIndexOffset: number;
numVertices: number;
isIndexed: boolean;
buffers: GPUVertexBufferLayout[];
}): GPURenderPipeline {
const pipeline = this.device.createRenderPipeline({
vertex: {
module: this.device.createShaderModule({
code: this.generateVertexShaderCode({
bufferCount,
attributesPerBuffer,
validValues,
typeInfo,
vertexIndexOffset,
numVertices,
isIndexed,
}),
}),
entryPoint: 'main',
buffers,
},
fragment: {
module: this.device.createShaderModule({
code: `
[[stage(fragment)]] fn main() -> [[location(0)]] vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}`,
}),
entryPoint: 'main',
targets: [{ format: 'rgba8unorm' }],
},
primitive: { topology: 'point-list' },
});
return pipeline;
}
doTest({
bufferCount,
attributesPerBuffer,
dataType,
validValues,
vertexIndexOffset,
numVertices,
isIndexed,
isIndirect,
drawCall,
}: {
bufferCount: number;
attributesPerBuffer: number;
dataType: GPUVertexFormat;
validValues: number[];
vertexIndexOffset: number;
numVertices: number;
isIndexed: boolean;
isIndirect: boolean;
drawCall: DrawCall;
}): void {
// Vertex buffer descriptors
const buffers: GPUVertexBufferLayout[] = this.generateVertexBufferDescriptors(
bufferCount,
attributesPerBuffer,
dataType
);
// Pipeline setup, texture setup
const pipeline = this.createRenderPipeline({
bufferCount,
attributesPerBuffer,
validValues,
typeInfo: typeInfoMap[dataType],
vertexIndexOffset,
numVertices,
isIndexed,
buffers,
});
const colorAttachment = this.device.createTexture({
format: 'rgba8unorm',
size: { width: 2, height: 1, depthOrArrayLayers: 1 },
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
});
const colorAttachmentView = colorAttachment.createView();
const encoder = this.device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: colorAttachmentView,
storeOp: 'store',
loadValue: { r: 0.0, g: 1.0, b: 0.0, a: 1.0 },
},
],
});
pass.setPipeline(pipeline);
// Run the draw variant
drawCall.insertInto(pass, isIndexed, isIndirect);
pass.endPass();
this.device.queue.submit([encoder.finish()]);
// Validate we see green on the left pixel, showing that no failure case is detected
this.expectSinglePixelIn2DTexture(
colorAttachment,
'rgba8unorm',
{ x: 0, y: 0 },
{ exp: new Uint8Array([0x00, 0xff, 0x00, 0xff]), layout: { mipLevel: 0 } }
);
}
}
export const g = makeTestGroup(F);
g.test('vertex_buffer_access')
.params(
u =>
u
.combineWithParams([
{ indexed: false, indirect: true },
{ indexed: true, indirect: false },
{ indexed: true, indirect: true },
])
.expand('drawCallTestParameter', function* (p) {
if (p.indexed) {
yield* ['baseVertex', 'vertexCountInIndexBuffer'] as const;
if (p.indirect) {
yield* ['indexCount', 'instanceCount', 'firstIndex'] as const;
}
} else if (p.indirect) {
yield* ['vertexCount', 'instanceCount', 'firstVertex'] as const;
}
})
.combine('type', Object.keys(typeInfoMap) as GPUVertexFormat[])
.combine('additionalBuffers', [0, 4])
.combine('partialLastNumber', [false, true])
.combine('offsetVertexBuffer', [false, true])
.combine('errorScale', [0, 1, 4, 10 ** 2, 10 ** 4, 10 ** 6])
.unless(p => p.drawCallTestParameter === 'instanceCount' && p.errorScale > 10 ** 4) // To avoid timeout
)
.fn(async t => {
const p = t.params;
const typeInfo = typeInfoMap[p.type];
// Number of vertices to draw
const numVertices = 4;
// Each buffer is bound to this many attributes (2 would mean 2 attributes per buffer)
const attributesPerBuffer = 2;
// Some arbitrary values to fill our buffer with to avoid collisions with other tests
const arbitraryValues = [990, 685, 446, 175];
// A valid value is 0 or one in the buffer
const validValues =
p.errorScale === 0 && !p.offsetVertexBuffer && !p.partialLastNumber
? arbitraryValues // Control case with no OOB access, must read back valid values in buffer
: [0, ...arbitraryValues]; // Testing case with OOB access, can be 0 for OOB data
// Generate vertex buffer contents. Only the first buffer is instance step mode, all others are vertex step mode
const bufferCount = p.additionalBuffers + 2; // At least one instance step mode and one vertex step mode buffer
const bufferContents = t.generateBufferContents(
numVertices,
attributesPerBuffer,
typeInfo,
arbitraryValues,
bufferCount
);
// Mutable draw call
const draw = new DrawCall({
test: t,
vertexArrays: bufferContents,
vertexCount: numVertices,
partialLastNumber: p.partialLastNumber,
offsetVertexBuffer: p.offsetVertexBuffer,
keepInstanceStepModeBufferInRange: p.indexed && !p.indirect, // keep instance step mode buffer in range for drawIndexed
});
// Offset the draw call parameter we are testing by |errorScale|
draw[p.drawCallTestParameter] += p.errorScale;
// Offset the range checks for gl_VertexIndex in the shader if we use BaseVertex
let vertexIndexOffset = 0;
if (p.drawCallTestParameter === 'baseVertex') {
vertexIndexOffset += p.errorScale;
}
t.doTest({
bufferCount,
attributesPerBuffer,
dataType: p.type,
validValues,
vertexIndexOffset,
numVertices,
isIndexed: p.indexed,
isIndirect: p.indirect,
drawCall: draw,
});
}); | the_stack |
import { AfterContentInit, Directive, ElementRef, HostBinding, Input, OnDestroy, OnInit, Optional, Renderer2,
Self, forwardRef, HostListener, Output, EventEmitter, ContentChildren, QueryList, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { NgControl } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { MDCCheckboxFoundation, MDCCheckboxAdapter } from '@material/checkbox';
import { AbstractMdcInput } from '../abstract/abstract.mdc.input';
import { asBoolean } from '../../utils/value.utils';
import { MdcEventRegistry } from '../../utils/mdc.event.registry';
import { AbstractMdcRipple } from '../ripple/abstract.mdc.ripple';
/**
* Directive for the input element of an <code>MdcCheckboxDirective</code>.
*/
@Directive({
selector: 'input[mdcCheckboxInput][type=checkbox]',
providers: [{provide: AbstractMdcInput, useExisting: forwardRef(() => MdcCheckboxInputDirective) }]
})
export class MdcCheckboxInputDirective extends AbstractMdcInput implements OnInit, OnDestroy {
/** @internal */
@HostBinding('class.mdc-checkbox__native-control') readonly _cls = true;
private onDestroy$: Subject<any> = new Subject();
private _id: string | null = null;
private _disabled = false;
private _checked = false;
private _indeterminate = false;
/** @internal */
@Output() readonly _checkedChange: EventEmitter<boolean> = new EventEmitter<boolean>();
/** @internal */
@Output() readonly _indeterminateChange: EventEmitter<boolean> = new EventEmitter<boolean>();
/** @internal */
@Output() readonly _disabledChange: EventEmitter<boolean> = new EventEmitter<boolean>();
constructor(public _elm: ElementRef, @Optional() @Self() public _cntr: NgControl) {
super();
}
ngOnInit() {
this._cntr?.valueChanges!.pipe(takeUntil(this.onDestroy$)).subscribe((value) => {
this.updateValue(value, true);
});
}
ngOnDestroy() {
this.onDestroy$.next();
this.onDestroy$.complete();
}
/** @docs-private */
@HostBinding()
@Input() get id() {
return this._id;
}
set id(value: string | null) {
this._id = value;
}
/** @docs-private */
@HostBinding()
@Input() get disabled() {
return this._cntr ? !!this._cntr.disabled : this._disabled;
}
set disabled(value: boolean) {
const newVal = asBoolean(value);
if (newVal != this._disabled) {
this._disabled = asBoolean(newVal);
this._disabledChange.emit(newVal);
}
}
static ngAcceptInputType_disabled: boolean | '';
/** @docs-private */
@HostBinding()
@Input() get checked(): boolean {
return this._checked;
}
set checked(value: boolean) {
this.updateValue(value, false);
}
static ngAcceptInputType_checked: boolean | '';
private updateValue(value: any, fromControl: boolean) {
// When the 'checked' property is the source of the change, we want to coerce boolean
// values using asBoolean, so that initializing with an attribute with no value works
// as expected.
// When the NgControl is the source of the change we don't want that. The value should
// be interpreted like NgControl/NgForms handles non-boolean values when binding.
const newVal = fromControl ? !!value : asBoolean(value);
if (newVal !== this._checked) {
this._checked = newVal;
this._checkedChange.emit(newVal);
}
if (!fromControl && this._cntr && newVal !== this._cntr.value) {
this._cntr.control!.setValue(newVal);
}
}
/** @docs-private */
@HostBinding()
@Input() get indeterminate() {
return this._indeterminate;
}
set indeterminate(value: boolean) {
const newVal = asBoolean(value);
if (newVal !== this._indeterminate) {
this._indeterminate = newVal;
Promise.resolve().then(() => this._indeterminateChange.emit(newVal));
}
}
static ngAcceptInputType_indeterminate: boolean | '';
// We listen to click-event instead of change-event, because IE doesn't fire the
// change-event when an indeterminate checkbox is clicked. There's no need to
// also listen to change-events.
@HostListener('click') _onChange() {
// only update the checked state from click if there is no control for which we already
// listen to value changes:
if (!this._cntr)
this.checked = this._elm.nativeElement.checked;
this.indeterminate = this._elm.nativeElement.indeterminate;
}
}
/**
* Directive for creating a Material Design checkbox. The checkbox is driven by an
* underlying native checkbox input, which must use the <code>MdcCheckboxInputDirective</code>
* directive.
* The current implementation will add all other required DOM elements (such as the
* background and ripple).
* Future implementations will also support supplying (customized) background
* elements.
*
* This directive can be used together with an <code>mdcFormField</code> to
* easily position checkboxes and their labels, see
* <a href="/components/form-field">mdcFormField</a>.
*/
@Directive({
selector: '[mdcCheckbox]'
})
export class MdcCheckboxDirective extends AbstractMdcRipple implements AfterContentInit, OnDestroy {
/** @internal */
@HostBinding('class.mdc-checkbox') readonly _cls = true;
private onDestroy$: Subject<any> = new Subject();
private onInputChange$: Subject<any> = new Subject();
/** @internal */
@ContentChildren(MdcCheckboxInputDirective) _inputs?: QueryList<MdcCheckboxInputDirective>;
private mdcAdapter: MDCCheckboxAdapter = {
addClass: (className: string) => this._renderer.addClass(this.root.nativeElement, className),
removeClass: (className: string) => this._renderer.removeClass(this.root.nativeElement, className),
setNativeControlAttr: (attr: string, value: string) => this._renderer.setAttribute(this._input!._elm.nativeElement, attr, value),
removeNativeControlAttr: (attr: string) => this._renderer.removeAttribute(this._input!._elm.nativeElement, attr),
forceLayout: () => this.root.nativeElement.offsetWidth, // force layout
isAttachedToDOM: () => !!this._input,
hasNativeControl: () => !!this._input,
isChecked: () => this._input!._elm.nativeElement.checked,
isIndeterminate: () => this._input!._elm.nativeElement.indeterminate,
setNativeControlDisabled: (disabled: boolean) => this._input!.disabled = disabled
};
/** @internal */
_foundation: MDCCheckboxFoundation | null = null;
constructor(renderer: Renderer2, private root: ElementRef, registry: MdcEventRegistry, @Inject(DOCUMENT) doc: any) {
super(root, renderer, registry, doc as Document);
this.addRippleSurface('mdc-checkbox__ripple');
}
ngAfterContentInit() {
MdcCheckboxDirective.addBackground(this._rippleElm, this._renderer);
this.initRipple(true);
if (this._input) {
this._foundation = new MDCCheckboxFoundation(this.mdcAdapter);
this._foundation.init();
}
this._inputs!.changes.pipe(takeUntil(this.onDestroy$)).subscribe(() => {
this.reinitRipple();
if (this._foundation)
this._foundation.destroy();
if (this._input) {
this._foundation = new MDCCheckboxFoundation(this.mdcAdapter);
this._foundation.init();
} else
this._foundation = null;
this.subscribeInputChanges();
});
this.subscribeInputChanges();
}
ngOnDestroy() {
this.onInputChange$.next(); this.onInputChange$.complete();
this.onDestroy$.next(); this.onDestroy$.complete();
if (this._foundation) {
this._foundation.destroy();
this._foundation = null;
}
this.destroyRipple();
}
private subscribeInputChanges() {
this.onInputChange$.next();
this._input?._indeterminateChange.asObservable().pipe(takeUntil(this.onInputChange$)).subscribe(() => this._foundation?.handleChange());
this._input?._checkedChange.asObservable().pipe(takeUntil(this.onInputChange$)).subscribe(() => this._foundation?.handleChange());
this._input?._disabledChange.asObservable().pipe(takeUntil(this.onInputChange$)).subscribe(val => this._foundation?.setDisabled(val));
}
private static addBackground(elm: ElementRef, renderer: Renderer2) {
let path = renderer.createElement('path', 'svg');
renderer.addClass(path, 'mdc-checkbox__checkmark-path');
renderer.setAttribute(path, 'fill', 'none');
renderer.setAttribute(path, 'd', 'M1.73,12.91 8.1,19.28 22.79,4.59');
let svg = renderer.createElement('svg', 'svg');
renderer.appendChild(svg, path);
renderer.addClass(svg, 'mdc-checkbox__checkmark');
renderer.setAttribute(svg, 'viewBox', '0 0 24 24');
let mixedmark = renderer.createElement('div');
renderer.addClass(mixedmark, 'mdc-checkbox__mixedmark');
let bg = renderer.createElement('div');
renderer.appendChild(bg, svg);
renderer.appendChild(bg, mixedmark);
renderer.addClass(bg, 'mdc-checkbox__background');
renderer.appendChild(elm.nativeElement, bg);
}
/** @internal */
protected getRippleInteractionElement() {
return this._input?._elm;
}
/** @internal */
@HostListener('animationend')
onAnimationEnd() {
this._foundation?.handleAnimationEnd();
}
/** @internal */
get _input() {
return this._inputs && this._inputs.length > 0 ? this._inputs.first : null;
}
}
export const CHECKBOX_DIRECTIVES = [
MdcCheckboxInputDirective,
MdcCheckboxDirective
]; | the_stack |
declare module "util" {
interface InspectOptions extends NodeJS.InspectOptions { }
type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module';
type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string;
interface InspectOptionsStylized extends InspectOptions {
stylize(text: string, styleType: Style): string;
}
function format(format: any, ...param: any[]): string;
function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string;
/** @deprecated since v0.11.3 - use a third party module instead. */
function log(string: string): void;
function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string;
function inspect(object: any, options: InspectOptions): string;
namespace inspect {
let colors: NodeJS.Dict<[number, number]>;
let styles: {
[K in Style]: string
};
let defaultOptions: InspectOptions;
/**
* Allows changing inspect settings from the repl.
*/
let replDefaults: InspectOptions;
const custom: unique symbol;
}
/** @deprecated since v4.0.0 - use `Array.isArray()` instead. */
function isArray(object: any): object is any[];
/** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */
function isRegExp(object: any): object is RegExp;
/** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */
function isDate(object: any): object is Date;
/** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */
function isError(object: any): object is Error;
function inherits(constructor: any, superConstructor: any): void;
function debuglog(key: string): (msg: string, ...param: any[]) => void;
/** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */
function isBoolean(object: any): object is boolean;
/** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */
function isBuffer(object: any): object is Buffer;
/** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */
function isFunction(object: any): boolean;
/** @deprecated since v4.0.0 - use `value === null` instead. */
function isNull(object: any): object is null;
/** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */
function isNullOrUndefined(object: any): object is null | undefined;
/** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */
function isNumber(object: any): object is number;
/** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */
function isObject(object: any): boolean;
/** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */
function isPrimitive(object: any): boolean;
/** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */
function isString(object: any): object is string;
/** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */
function isSymbol(object: any): object is symbol;
/** @deprecated since v4.0.0 - use `value === undefined` instead. */
function isUndefined(object: any): object is undefined;
function deprecate<T extends Function>(fn: T, message: string, code?: string): T;
function isDeepStrictEqual(val1: any, val2: any): boolean;
function callbackify(fn: () => Promise<void>): (callback: (err: NodeJS.ErrnoException) => void) => void;
function callbackify<TResult>(fn: () => Promise<TResult>): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
function callbackify<T1>(fn: (arg1: T1) => Promise<void>): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void;
function callbackify<T1, TResult>(fn: (arg1: T1) => Promise<TResult>): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void;
function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void;
function callbackify<T1, T2, T3, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
function callbackify<T1, T2, T3, T4>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void;
function callbackify<T1, T2, T3, T4, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
function callbackify<T1, T2, T3, T4, T5>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void;
function callbackify<T1, T2, T3, T4, T5, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
function callbackify<T1, T2, T3, T4, T5, T6>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void;
function callbackify<T1, T2, T3, T4, T5, T6, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
interface CustomPromisifyLegacy<TCustom extends Function> extends Function {
__promisify__: TCustom;
}
interface CustomPromisifySymbol<TCustom extends Function> extends Function {
[promisify.custom]: TCustom;
}
type CustomPromisify<TCustom extends Function> = CustomPromisifySymbol<TCustom> | CustomPromisifyLegacy<TCustom>;
function promisify<TCustom extends Function>(fn: CustomPromisify<TCustom>): TCustom;
function promisify<TResult>(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise<TResult>;
function promisify(fn: (callback: (err?: any) => void) => void): () => Promise<void>;
function promisify<T1, TResult>(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise<TResult>;
function promisify<T1>(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise<void>;
function promisify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise<TResult>;
function promisify<T1, T2>(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise<void>;
function promisify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void):
(arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>;
function promisify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>;
function promisify<T1, T2, T3, T4, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>;
function promisify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void):
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>;
function promisify<T1, T2, T3, T4, T5, TResult>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>;
function promisify<T1, T2, T3, T4, T5>(
fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void,
): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>;
function promisify(fn: Function): Function;
namespace promisify {
const custom: unique symbol;
}
namespace types {
function isAnyArrayBuffer(object: any): object is ArrayBufferLike;
function isArgumentsObject(object: any): object is IArguments;
function isArrayBuffer(object: any): object is ArrayBuffer;
function isArrayBufferView(object: any): object is NodeJS.ArrayBufferView;
function isAsyncFunction(object: any): boolean;
function isBigInt64Array(value: any): value is BigInt64Array;
function isBigUint64Array(value: any): value is BigUint64Array;
function isBooleanObject(object: any): object is Boolean;
function isBoxedPrimitive(object: any): object is String | Number | BigInt | Boolean | Symbol;
function isDataView(object: any): object is DataView;
function isDate(object: any): object is Date;
function isExternal(object: any): boolean;
function isFloat32Array(object: any): object is Float32Array;
function isFloat64Array(object: any): object is Float64Array;
function isGeneratorFunction(object: any): object is GeneratorFunction;
function isGeneratorObject(object: any): object is Generator;
function isInt8Array(object: any): object is Int8Array;
function isInt16Array(object: any): object is Int16Array;
function isInt32Array(object: any): object is Int32Array;
function isMap<T>(
object: T | {},
): object is T extends ReadonlyMap<any, any>
? unknown extends T
? never
: ReadonlyMap<any, any>
: Map<any, any>;
function isMapIterator(object: any): boolean;
function isModuleNamespaceObject(value: any): boolean;
function isNativeError(object: any): object is Error;
function isNumberObject(object: any): object is Number;
function isPromise(object: any): object is Promise<any>;
function isProxy(object: any): boolean;
function isRegExp(object: any): object is RegExp;
function isSet<T>(
object: T | {},
): object is T extends ReadonlySet<any>
? unknown extends T
? never
: ReadonlySet<any>
: Set<any>;
function isSetIterator(object: any): boolean;
function isSharedArrayBuffer(object: any): object is SharedArrayBuffer;
function isStringObject(object: any): object is String;
function isSymbolObject(object: any): object is Symbol;
function isTypedArray(object: any): object is NodeJS.TypedArray;
function isUint8Array(object: any): object is Uint8Array;
function isUint8ClampedArray(object: any): object is Uint8ClampedArray;
function isUint16Array(object: any): object is Uint16Array;
function isUint32Array(object: any): object is Uint32Array;
function isWeakMap(object: any): object is WeakMap<any, any>;
function isWeakSet(object: any): object is WeakSet<any>;
}
class TextDecoder {
readonly encoding: string;
readonly fatal: boolean;
readonly ignoreBOM: boolean;
constructor(
encoding?: string,
options?: { fatal?: boolean; ignoreBOM?: boolean }
);
decode(
input?: NodeJS.ArrayBufferView | ArrayBuffer | null,
options?: { stream?: boolean }
): string;
}
interface EncodeIntoResult {
/**
* The read Unicode code units of input.
*/
read: number;
/**
* The written UTF-8 bytes of output.
*/
written: number;
}
class TextEncoder {
readonly encoding: string;
encode(input?: string): Uint8Array;
encodeInto(input: string, output: Uint8Array): EncodeIntoResult;
}
} | the_stack |
const { compile, match } = require("path-to-regexp");
import { getQueryParamsObject } from "utils/helpers";
export const BASE_URL = "/";
export const ORG_URL = "/org";
export const PAGE_NOT_FOUND_URL = "/404";
export const SERVER_ERROR_URL = "/500";
export const APPLICATIONS_URL = `/applications`;
export const USER_AUTH_URL = "/user";
export const PROFILE = "/profile";
export const USERS_URL = "/users";
export const UNSUBSCRIBE_EMAIL_URL = "/unsubscribe/discussion/:threadId";
export const SETUP = "/setup/welcome";
export const FORGOT_PASSWORD_URL = `${USER_AUTH_URL}/forgotPassword`;
export const RESET_PASSWORD_URL = `${USER_AUTH_URL}/resetPassword`;
export const BASE_SIGNUP_URL = `/signup`;
export const SIGN_UP_URL = `${USER_AUTH_URL}/signup`;
export const BASE_LOGIN_URL = `/login`;
export const AUTH_LOGIN_URL = `${USER_AUTH_URL}/login`;
export const SIGNUP_SUCCESS_URL = `/signup-success`;
export const ORG_INVITE_USERS_PAGE_URL = `${ORG_URL}/invite`;
export const ORG_SETTINGS_PAGE_URL = `${ORG_URL}/settings`;
export const BUILDER_URL = `/applications/:applicationId/(pages)?/:pageId?/edit`;
export const VIEWER_URL = `/applications/:applicationId/(pages)?/:pageId?`;
export const VIEWER_FORK_PATH = `${VIEWER_URL}/fork`;
export const INTEGRATION_EDITOR_PATH = `${BUILDER_URL}/datasources/:selectedTab`;
export const API_EDITOR_BASE_PATH = `${BUILDER_URL}/api`;
export const API_EDITOR_ID_PATH = `${API_EDITOR_BASE_PATH}/:apiId`;
export const QUERIES_EDITOR_BASE_PATH = `${BUILDER_URL}/queries`;
export const QUERIES_EDITOR_ID_PATH = `${QUERIES_EDITOR_BASE_PATH}/:queryId`;
export const JS_COLLECTION_EDITOR_PATH = `${BUILDER_URL}/jsObjects`;
export const JS_COLLECTION_ID_PATH = `${JS_COLLECTION_EDITOR_PATH}/:collectionId`;
export const CURL_IMPORT_PAGE_PATH = `${BUILDER_URL}/api/curl/curl-import`;
export const PAGE_LIST_EDITOR_PATH = `${BUILDER_URL}/pages`;
export const DATA_SOURCES_EDITOR_ID_PATH = `${BUILDER_URL}/datasource/:datasourceId`;
export const PROVIDER_TEMPLATE_PATH = `${BUILDER_URL}/provider/:providerId`;
export const GEN_TEMPLATE_URL = "generate-page";
export const GENERATE_TEMPLATE_PATH = `${BUILDER_URL}/${GEN_TEMPLATE_URL}`;
export const GEN_TEMPLATE_FORM_ROUTE = "/form";
export const GENERATE_TEMPLATE_FORM_PATH = `${GENERATE_TEMPLATE_PATH}${GEN_TEMPLATE_FORM_ROUTE}`;
export const BUILDER_CHECKLIST_URL = `${BUILDER_URL}/checklist`;
export const matchApiBasePath = match(API_EDITOR_BASE_PATH);
export const matchApiPath = match(API_EDITOR_ID_PATH);
export const matchDatasourcePath = match(DATA_SOURCES_EDITOR_ID_PATH);
export const matchQueryBasePath = match(QUERIES_EDITOR_BASE_PATH);
export const matchQueryPath = match(QUERIES_EDITOR_ID_PATH);
export const matchBuilderPath = match(BUILDER_URL);
export const matchJSObjectPath = match(JS_COLLECTION_ID_PATH);
export const matchViewerPath = match(VIEWER_URL);
export const matchViewerForkPath = match(VIEWER_FORK_PATH);
export const BUILDER_URL_REGEX = /\/applications\/(.[^\/]*)\/pages\/(.[^\/]*)\//;
export const extractAppIdAndPageIdFromUrl = (url = "") => {
const matched = url.match(BUILDER_URL_REGEX);
if (matched) {
return {
applicationId: matched[1],
pageId: matched[2],
};
}
return {
applicationId: "",
pageId: "",
};
};
export const compileBuilderUrl = compile(BUILDER_URL);
export const addBranchParam = (branch: string) => {
const url = new URL(window.location.href);
url.searchParams.set(GIT_BRANCH_QUERY_KEY, encodeURIComponent(branch));
return url.toString().slice(url.origin.length);
};
export type BuilderRouteParams = {
pageId: string;
applicationId: string;
};
export type AppViewerRouteParams = {
pageId?: string;
};
export type APIEditorRouteParams = {
pageId: string;
apiId?: string;
};
export type ProviderViewerRouteParams = {
pageId: string;
providerId: string;
};
export type QueryEditorRouteParams = {
pageId: string;
queryId: string;
};
export type JSEditorRouteParams = {
pageId: string;
collectionId?: string;
};
export const BUILDER_BASE_URL = (applicationId = ":applicationId"): string =>
`/applications/${applicationId}`;
export const GIT_BRANCH_QUERY_KEY = "branch";
export const BUILDER_PAGE_URL = (props: {
branch?: string;
applicationId?: string;
hash?: string;
pageId?: string; // TODO make pageId mandatory
params?: Record<string, string>;
suffix?: string;
}): string => {
const {
branch,
applicationId,
hash = "",
pageId,
params = {},
suffix,
} = props;
// todo (rishabh s) check when this is applicable
if (!pageId) return APPLICATIONS_URL;
const existingParams = getQueryParamsObject() || {};
// not persisting the entire query currently, since that's the current behaviour
const { branch: branchQuery } = existingParams;
let modifiedParams = { ...params };
const derivedBranch = branch || branchQuery;
if (derivedBranch) {
modifiedParams = { branch: derivedBranch, ...params };
}
// test param to make sure a query param is present in the URL during dev and tests
if ((window as any).Cypress || process.env?.NODE_ENV === "development") {
modifiedParams = { a: "b", ...modifiedParams };
}
const queryString = convertToQueryParams(modifiedParams);
const suffixPath = suffix ? `/${suffix}` : "";
const hashPath = hash ? `#${hash}` : "";
return `/applications/${applicationId}/pages/${pageId}/edit${suffixPath}${hashPath}${queryString}`;
};
export const API_EDITOR_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "api",
});
export const PAGE_LIST_EDITOR_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "pages",
});
export const DATA_SOURCES_EDITOR_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "datasource",
});
export const DATA_SOURCES_EDITOR_ID_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
datasourceId = ":datasourceId",
params = {},
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: `datasource/${datasourceId}`,
params,
});
export const QUERIES_EDITOR_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "queries",
});
export const JS_COLLECTION_EDITOR_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "jsObjects",
});
export const INTEGRATION_TABS = {
ACTIVE: "ACTIVE",
NEW: "NEW",
};
export const INTEGRATION_EDITOR_MODES = {
AUTO: "auto",
MOCK: "mock",
};
export const INTEGRATION_EDITOR_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
selectedTab = ":selectedTab",
mode = "",
params = {},
suffix = "",
): string => {
if (mode) {
(params as any).mode = mode;
}
const suffixPath = suffix ? `/${suffix}` : "";
return BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: `datasources/${selectedTab}${suffixPath}`,
params,
});
};
export const QUERIES_EDITOR_ID_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
queryId = ":queryId",
params = {},
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: `queries/${queryId}`,
params,
});
export const API_EDITOR_ID_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
apiId = ":apiId",
params = {},
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: `api/${apiId}`,
params,
});
export const API_EDITOR_URL_WITH_SELECTED_PAGE_ID = (
applicationId = ":applicationId",
pageId = ":pageId",
selectedPageId = ":importTo",
): string => {
return BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "api",
params: {
importTo: selectedPageId,
},
});
};
export const JS_COLLECTION_ID_URL = (
applicationId = ":applicationId",
pageId = ":pageId",
collectionId = ":collectionId",
params = {},
): string => {
return BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: `jsObjects/${collectionId}`,
params,
});
};
export const getApplicationViewerPageURL = (props: {
applicationId?: string;
pageId?: string; // TODO make pageId this mandatory
params?: Record<string, string>;
suffix?: string;
}): string => {
const {
applicationId = ":applicationId",
pageId = ":pageId",
params = {},
suffix,
} = props;
const url = `/applications/${applicationId}/pages/${pageId}`;
const existingParams = getQueryParamsObject() || {};
// not persisting the entire query currently, since that's the current behaviour
const { branch } = existingParams;
let modifiedParams = { ...params };
if (branch) {
modifiedParams = { branch, ...params };
}
const queryString = convertToQueryParams(modifiedParams);
const suffixPath = suffix ? `/${suffix}` : "";
return url + suffixPath + queryString;
};
export function convertToQueryParams(
params: Record<string, string> = {},
): string {
const paramKeys = Object.keys(params);
const queryParams: string[] = [];
if (paramKeys) {
paramKeys.forEach((paramKey: string) => {
const value = params[paramKey];
if (paramKey && value) {
queryParams.push(`${paramKey}=${value}`);
}
});
}
return queryParams.length ? "?" + queryParams.join("&") : "";
}
export const getCurlImportPageURL = (
applicationId = ":applicationId",
pageId = ":pageId",
params = {},
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "api/curl/curl-import",
params,
});
export const getProviderTemplatesURL = (
applicationId = ":applicationId",
pageId = ":pageId",
providerId = ":providerId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: `api/provider/${providerId}`,
});
export const QUERY_EDITOR_URL_WITH_SELECTED_PAGE_ID = (
applicationId = ":applicationId",
pageId = ":pageId",
selectedPageId = ":importTo",
): string => {
const params = {
importTo: selectedPageId,
};
return BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "queries",
params,
});
};
export const getGenerateTemplateURL = (
applicationId = ":applicationId",
pageId = ":pageId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: GEN_TEMPLATE_URL,
});
export const getGenerateTemplateFormURL = (
applicationId = ":applicationId",
pageId = ":pageId",
params = {},
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: `${GEN_TEMPLATE_URL}${GEN_TEMPLATE_FORM_ROUTE}`,
params,
});
export const getOnboardingCheckListUrl = (
applicationId = ":applicationId",
pageId = ":pageId",
): string =>
BUILDER_PAGE_URL({
applicationId,
pageId,
suffix: "checklist",
});
export const ADMIN_SETTINGS_URL = "/settings";
export const ADMIN_SETTINGS_CATEGORY_DEFAULT_URL = "/settings/general";
export const ADMIN_SETTINGS_CATEGORY_URL = "/settings/:category";
export function getAdminSettingsCategoryUrl(category: string) {
return `${ADMIN_SETTINGS_URL}/${category}`;
} | the_stack |
"strict mode";
import { applyThemeToNetwork, Node, Edge, getElementByIdOrThrow, setIsInset, vscode, expandInset, closeInset, ThemeChangedEvent, addWindowEventListener, CommandMessage } from "./baseView";
import { CustomViewData, GraphViewData } from "model";
import { DomainInfo, Plan, ProblemInfo, VariableValue } from "pddl-workspace";
/** Declared in baseWebview.js */
declare function onLoad(): void;
/**
* This must be declared in the same file, where it is used : (.
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
declare namespace vis {
type IdType = number | string;
class DataSet<T> {
constructor(content: T[]);
length: number;
add(node: T): void;
add(nodes: T[]): void;
get(id: number): T;
get(filter: { filter: (edge: Edge) => boolean }): T[];
clear(): void;
update(nodes: Node[]): void;
update(node: Node): void;
}
type Direction = 'DU' | 'UD' | 'RL' | 'LR';
interface Options {
layout?: { hierarchical: { direction: Direction } };
edges?: { font: { color: string | undefined; strokeColor: string | undefined } };
configure?: boolean;
}
export class Network {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(container: HTMLElement, treeData: { nodes: DataSet<Node>; edges: DataSet<Edge> }, options: any);
fit(options?: { animation: boolean }): void;
getSelectedNodes(): number[];
releaseNode(): void;
focus(nodeId: number, arg1: { animation: boolean; locked: boolean }): void;
selectNodes(arg0: number[]): void;
on(arg0: string, event: (nodeEvent: { nodes: number[] }) => void): void;
setOptions(options: Options): void;
setSize(width: string, height: string): void;
}
}
const nodes = new vis.DataSet<Node>([]);
const edges = new vis.DataSet<Edge>([]);
const networkData = {
nodes: nodes,
edges: edges
};
let network: vis.Network | null;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function initialize(): void {
// create a network
const container = getElementByIdOrThrow("network");
const options = {
clickToUse: true,
nodes: {
font: { size: 12 }
},
edges: {
font: { align: 'top', size: 8 },
arrows: { to: { enabled: true, scaleFactor: 0.5 } }
},
physics: {
stabilization: false
},
configure: false
};
network = new vis.Network(container, networkData, options);
network.on("configChange", function () {
// this will immediately fix the height of the configuration
// wrapper to prevent unnecessary scrolls in chrome.
// see https://github.com/almende/vis/issues/1568
const div = container.getElementsByClassName("vis-configuration-wrapper")[0] as HTMLElement;
div.style["height"] = div.getBoundingClientRect().height + "px";
});
document.body.addEventListener("themeChanged", event => {
network && applyThemeToNetwork(network, (event as ThemeChangedEvent).detail.newTheme);
});
if (!vscode) { populateWithTestData(); }
onLoad();
}
type Value = boolean | number | undefined;
/** Schema for data being passed to the view for display. */
interface ProblemInitViewData {
symmetricRelationshipGraph: GraphViewData;
typeProperties: never; // serialized Map<string, TypeProperties>;
typeRelationships: TypesRelationship[];
scalarValues: never; // serialized Map<string, Value>;
customVisualization: CustomViewData | undefined;
}
interface TypeProperties {
propertyNames: string[];
objects: never;
}
interface TypesRelationship {
types: never; // serializable Map<string, string[]>;
relationships: never; // serializable Map<string, RelationshipValue[]>;
}
interface RelationshipValue {
parameters: never; // serializable Map<string, string>;
value?: Value;
}
function handleMessage(message: CommandMessage): void {
switch (message.command) {
case 'updateContent':
const data = message.data as ProblemInitViewData;
updateScalarValues(data.scalarValues);
updateGraph(data.symmetricRelationshipGraph);
updateObjectProperties(data.typeProperties);
updateObjectRelationships(data.typeRelationships);
updateCustomView(data.customVisualization);
break;
default:
console.log("Unexpected message: " + message.command);
}
}
addWindowEventListener(handleMessage);
function populateWithTestData(): void {
// for testing only
updateCustomView({
plan: new Plan([]),
state: [
new VariableValue("predicate1", true),
new VariableValue("function1", 3.14),
],
customVisualizationScript: `function visualizePlanHtml(plan, width) {
return "PLAN VISUALIZATION";
}
module.exports = {
// define one of the following functions:
visualizePlanHtml: visualizePlanHtml,
visualizePlanInDiv: undefined, // function (hostDiv, plan, width)
visualizePlanSvg: undefined // function (plan, width)
};
`,
displayWidth: 500
});
updateGraph({
nodes: [{ id: 1, label: 'City' }, { id: 2, label: 'Town' }, { id: 3, label: 'Village' }],
relationships: [{ from: 1, to: 2, label: 'connected' }, { from: 2, to: 3, label: 'connected' }]
});
const truckProperties: TypeProperties = {
propertyNames: [
"size", "available"
],
objects: {
"red": {
"size": 1,
"available": true
},
"blue": {
"size": 2,
"available": false
},
"green": {
"size": undefined
}
} as never
};
updateObjectProperties({
"truck": truckProperties
} as never);
updateObjectRelationships([
{
types: {
"driver": ["Peter", "Paul"],
"truck": ["red", "blue", "green"]
} as never,
relationships: {
"driving": [
{
"parameters": {
"driver": "Peter",
"truck": "red"
}
},
{
"parameters": {
"driver": "Paul",
"truck": "green"
},
"value": false
}
],
"milage": [
{
"parameters": {
"driver": "Peter",
"truck": "red"
},
"value": 14
},
{
"parameters": {
"driver": "Paul",
"truck": "green"
},
"value": 17
}
]
} as never
},
{
relationships: {
"same": [
{
"parameters": {
"t1": "red",
"t2": "blue"
},
"value": true
},
{
"parameters": {
"t1": "blue",
"t2": "green"
},
"value": true,
}
]
} as never,
types: {
"truck": [
"red",
"green",
"blue"
]
} as never
}
]);
setIsInset(true);
}
function clearNetwork(): void {
nodes.clear();
edges.clear();
}
function updateGraph(data: GraphViewData): void {
clearNetwork();
nodes.add(data.nodes);
edges.add(data.relationships);
network?.fit();
const container = getElementByIdOrThrow("networkSection");
container.style.display = data.nodes.length > 0 ? 'initial' : 'none';
}
function updateScalarValues(data: never): void {
const container = getElementByIdOrThrow("scalarValues");
const header = `<table class="objectValues">
<tr><th></th><th>value</th></tr>`;
const footer = `</table>`;
container.innerHTML = header +
Object.keys(data)
.sort((a, b) => a.localeCompare(b))
.map(variableName => createScalarValuesTableRow(variableName, data[variableName] as Value))
.join('\n') +
footer;
}
function createScalarValuesTableRow(variableName: string, value: Value): string {
return `<tr><th>${variableName}</th><td>${value}</td></tr>`;
}
/**
* Renders object properties as HTML tables per type.
* @param data object properties
*/
function updateObjectProperties(data: never): void {
const container = getElementByIdOrThrow("objectProperties");
container.innerHTML = Object.keys(data).map(type => createTypePropertiesTable(type, data[type])).join('\n');
}
function createTypePropertiesTable(type: string, objectProperties: TypeProperties): string {
const headerCells = [th(type)].concat(objectProperties.propertyNames.map(n => th(n)));
const objectRows = Object.keys(objectProperties.objects).map(objName => createObjectPropertiesRow(objName, objectProperties.objects[objName] as never, objectProperties.propertyNames));
return '<table class="objectValues">' +
tr(headerCells) +
objectRows.join('\n') +
"\n</table>";
}
/**
* Create object property table row
* @param objectName object name
* @param objectValues object values
* @param propertyNames property names
*/
function createObjectPropertiesRow(objectName: string, objectValues: never, propertyNames: string[]): string {
const valueCells = propertyNames.map(p => td(createObjectPropertyValue(objectValues,p, objectName)));
const cells = [th(objectName)].concat(valueCells);
return tr(cells);
}
/**
* Create object property table row
* @param objectValues object values
* @param propertyName property name
* @param objectName name of the object for the tooltip
*/
function createObjectPropertyValue(objectValues: never, propertyName: string, objectName: string): string {
const value = objectValues[propertyName];
const fullVariableName = `(${propertyName} ${objectName})`;
return createValueSnap(fullVariableName, value);
}
function createValueSnap(fullVariableName: string, value: Value): string {
if (value !== undefined) {
let tooltip = fullVariableName;
if (typeof(value) === 'number') {
tooltip = toPddlFunctionInit(tooltip, value);
}
else if (typeof (value) === 'boolean' && value === false) {
tooltip = `(not ${tooltip})`;
}
return toSnap(value, tooltip);
} else {
return " ";
}
}
function updateObjectRelationships(data: TypesRelationship[]): void {
const container = getElementByIdOrThrow("relationships");
container.innerHTML = data.map(relationship => createTypeRelationshipsTable(relationship)).join('\n');
}
function createTypeRelationshipsTable(relationship: TypesRelationship): string {
const types = Object.keys(relationship.types);
if (types.length > 2) { return ""; }
const objectType = types[0];
const subjectType = types.length === 2 ? types[1] : types[0]; // if relationship is symmetric
const headerCells = [th(types.join(' \\ '))].concat((relationship.types[subjectType] as string[]).map(n => th(n)));
const objectRows = (relationship.types[objectType] as string[])
.map(rowObject => createObjectRelationshipRow(rowObject, relationship, subjectType));
return '<table class="objectValues">' +
tr(headerCells) +
objectRows.join('\n') +
"\n</table>";
}
/**
* Create object relationship table row
* @param rowObject name of the object described by this row
* @param relationship type relationship
* @param subjectType name of the type in the columns
*/
function createObjectRelationshipRow(rowObject: string, relationship: TypesRelationship, subjectType: string): string {
const valueCells = (relationship.types[subjectType] as string[])
.map(subject => createRelationshipsValue(rowObject, subject, relationship.relationships))
.map(value => td(value));
const cells = [th(rowObject)].concat(valueCells);
return tr(cells);
}
/**
* Creates relationship table cell
* @param rowObject object name (row)
* @param subject subject name (column)
* @param relationships list of relationship values (as serialized Map<string, RelationshipValue[]>)
*/
function createRelationshipsValue(rowObject: string, subject: string, relationships: never): string {
const relevantRelationshipsValues = Object.keys(relationships)
.map(relationshipName => createRelationshipValue(relationshipName, relationships[relationshipName] as RelationshipValue[], [rowObject, subject]))
.filter(r => !!r); // filter out nulls
return relevantRelationshipsValues.join("<br>");
}
/**
* Creates relationship-value tuple, if the relationship is relevant to the given objects
* @param relationshipName relationship name
* @param relationship structure (array of RelationshipValue)
* @param objectNames object names
*/
function createRelationshipValue(relationshipName: string, relationship: RelationshipValue[], objectNames: string[]): string | null {
const relevantGrounding = relationship.find(relationshipGrounding => relationshipDescribes(relationshipGrounding, objectNames));
if (relevantGrounding) {
let cellText = relationshipName;
let tooltip = `(${relationshipName} ${objectNames.join(' ')})`;
if (relevantGrounding.value !== undefined) {
if (typeof (relevantGrounding.value) === 'number') {
cellText += ":=" + relevantGrounding.value;
tooltip = toPddlFunctionInit(tooltip, relevantGrounding.value);
}
else if (typeof (relevantGrounding.value) === 'boolean' && relevantGrounding.value === false) {
cellText = `<i>not</i> ${cellText}`;
tooltip = `(not ${tooltip})`;
}
}
return toSnap(cellText, tooltip);
}
else {
return null;
}
}
/**
* @typedef CustomViewData Custom state visualization data and view logic.
* @property {Plan} plan In this case, it is a dummy plan, which serves as a container for the domain and problem objects.
* @property {VariableValue[]} state
* @property {string} customVisualizationScript Javascript, which exports the `CustomVisualization` interface.
* @property {number} displayWidth
*/
/**
* Renders the custom state view.
* @param data data
*/
function updateCustomView(data: CustomViewData | undefined): void {
const customViewDiv = getElementByIdOrThrow("customView");
if (data && data.customVisualizationScript) {
try {
const customVisualization = eval(data.customVisualizationScript);
const plan = new Plan(data.plan.steps,
data.plan.domain && DomainInfo.clone(data.plan.domain),
data.plan.problem && ProblemInfo.clone(data.plan.problem));
customViewDiv.innerHTML = '';
if (customVisualization.visualizePlanHtml) {
const vizHtml = customVisualization.visualizePlanHtml(plan, data.displayWidth);
customViewDiv.innerHTML = vizHtml;
} else if (customVisualization.visualizePlanInDiv) {
customVisualization.visualizePlanInDiv(customViewDiv, plan, data.displayWidth);
} else if (customVisualization.visualizePlanSvg) {
const vizSvg = customVisualization.visualizePlanSvg(plan, data.displayWidth);
customViewDiv.appendChild(vizSvg);
} else if (customVisualization.visualizeStateHtml) {
const vizHtml = customVisualization.visualizeStateHtml(plan, data.state, data.displayWidth);
customViewDiv.innerHTML = vizHtml;
} else if (customVisualization.visualizeStateInDiv) {
customVisualization.visualizeStateInDiv(customViewDiv, plan, data.state, data.displayWidth);
} else if (customVisualization.visualizeStateSvg) {
const vizSvg = customVisualization.visualizeStateSvg(plan, data.state, data.displayWidth);
customViewDiv.appendChild(vizSvg);
}
}
catch (err) {
console.error(err);
}
}
}
function toPddlFunctionInit(functionName: string, value: number | boolean): string {
return `(= ${functionName} ${value})`;
}
function toSnap(htmlText: string | Value, tooltip: string): string {
return `<snap title="${tooltip}">${htmlText}</snap>`;
}
/**
* True if the relationship describes given objects.
* @param relationship structure
* @param objectNames object names
*/
function relationshipDescribes(relationship: RelationshipValue, objectNames: string[]): boolean {
return Object.values(relationship.parameters).join(',') === objectNames.join(',');
}
/**
* Wraps table cells to table row
* @param cells cell(s) html
*/
function tr(cells: string[]): string {
return "<tr>" + cells.join('') + "</tr>";
}
/**
* Wraps header cell
* @param cell cell html
*/
function th(cell: string): string {
return "<th>" + cell + "</th>";
}
/**
* Wraps cell
* @param cell cell html
*/
function td(cell: string): string {
return "<td>" + cell + "</td>";
}
function fit(): void {
network?.fit();
}
// subscribe to view events
document.body.onload = initialize;
getElementByIdOrThrow("fit").onclick = fit;
getElementByIdOrThrow("expandInset").onclick = expandInset;
getElementByIdOrThrow("closeInset").onclick = closeInset; | the_stack |
import { Component, OnInit, OnDestroy, Input, ComponentFactoryResolver, Injector, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Subject, forkJoin, of, merge, EMPTY } from 'rxjs';
import { filter, tap, switchMap, pluck, map, catchError, withLatestFrom, takeUntil } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { PrimitiveArray, Data, DataItem, bar } from 'billboard.js';
import {
WebAppSettingDataService,
AnalyticsService,
TRACKED_EVENT_LIST,
DynamicPopupService,
AgentHistogramDataService,
StoreHelperService,
MessageQueueService,
NewUrlStateNotificationService,
MESSAGE_TO
} from 'app/shared/services';
import { ServerMapData } from 'app/core/components/server-map/class/server-map-data.class';
import { getMaxTickValue } from 'app/core/utils/chart-util';
import { Actions } from 'app/shared/store/reducers';
import { SourceType } from 'app/core/components/response-summary-chart/response-summary-chart-container.component';
import { Layer } from 'app/core/components/response-summary-chart/response-summary-chart-container.component';
import { filterObj } from 'app/core/utils/util';
import { ServerErrorPopupContainerComponent } from 'app/core/components/server-error-popup/server-error-popup-container.component';
@Component({
selector: 'pp-response-avg-max-chart-container',
templateUrl: './response-avg-max-chart-container.component.html',
styleUrls: ['./response-avg-max-chart-container.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ResponseAvgMaxChartContainerComponent implements OnInit, OnDestroy {
@Input() sourceType: string;
private unsubscribe = new Subject<void>();
private serverMapData: ServerMapData;
private isOriginalNode: boolean;
private selectedAgent = '';
private chartColors: string[];
private defaultYMax = 10;
private originalTarget: ISelectedTarget; // from serverMap
private targetFromList: INodeInfo; // from targetList
dataFetchFailedText: string;
dataEmptyText: string;
chartConfig: IChartConfig;
showLoading: boolean;
showRetry: boolean;
retryMessage: string;
chartVisibility = {};
previousRange: number[];
constructor(
private storeHelperService: StoreHelperService,
private messageQueueService: MessageQueueService,
private agentHistogramDataService: AgentHistogramDataService,
private newUrlStateNotificationService: NewUrlStateNotificationService,
private translateService: TranslateService,
private webAppSettingDataService: WebAppSettingDataService,
private analyticsService: AnalyticsService,
private dynamicPopupService: DynamicPopupService,
private injector: Injector,
private componentFactoryResolver: ComponentFactoryResolver,
private cd: ChangeDetectorRef,
) {}
ngOnInit() {
this.initChartColors();
this.initI18nText();
this.listenToEmitter();
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
set activeLayer(layer: Layer) {
this.showLoading = layer === Layer.LOADING;
this.showRetry = layer === Layer.RETRY;
this.setChartVisibility(layer === Layer.CHART);
this.cd.markForCheck();
}
onRendered(): void {
this.activeLayer = Layer.CHART;
}
private setChartVisibility(showChart: boolean): void {
this.chartVisibility = {
'show-chart': showChart,
'shady-chart': !showChart && this.chartConfig !== undefined,
};
}
onRetry(): void {
this.activeLayer = Layer.LOADING;
const target = this.getTargetInfo();
this.agentHistogramDataService.getData(this.serverMapData, this.previousRange, target).pipe(
// map((data: any) => this.isAllAgent() ? data['responseStatistics'] : data['agentResponseStatistics'][this.selectedAgent]),
pluck('agentResponseStatistics', this.selectedAgent),
catchError((error: IServerErrorFormat) => {
this.activeLayer = Layer.RETRY;
this.dynamicPopupService.openPopup({
data: {
title: 'Error',
contents: error
},
component: ServerErrorPopupContainerComponent
}, {
resolver: this.componentFactoryResolver,
injector: this.injector
});
return EMPTY;
})
).pipe(
map((data: IResponseStatistics) => this.cleanIntermediateChartData(data)),
map((data: IResponseStatistics) => this.makeChartData(data)),
withLatestFrom(this.storeHelperService.getResponseAvgMaxChartYMax(this.unsubscribe))
).subscribe(([chartData, yMax]: [PrimitiveArray[], number]) => {
this.chartConfig = {
dataConfig: this.makeDataOption(chartData),
elseConfig: this.makeElseOption(yMax)
};
this.cd.markForCheck();
});
}
private initChartColors(): void {
this.chartColors = this.webAppSettingDataService.getColorByResponseStatistics();
}
private initI18nText(): void {
forkJoin(
this.translateService.get('COMMON.FAILED_TO_FETCH_DATA'),
this.translateService.get('COMMON.NO_DATA'),
).subscribe(([dataFetchFailedText, dataEmptyText]: string[]) => {
this.dataFetchFailedText = dataFetchFailedText;
this.dataEmptyText = dataEmptyText;
});
}
private listenToEmitter(): void {
this.newUrlStateNotificationService.onUrlStateChange$.pipe(
takeUntil((this.unsubscribe)),
).subscribe(() => {
this.serverMapData = null;
this.originalTarget = null;
this.targetFromList = null;
});
merge(
this.messageQueueService.receiveMessage(this.unsubscribe, MESSAGE_TO.SERVER_MAP_TARGET_SELECT).pipe(
filter(() => this.sourceType !== SourceType.INFO_PER_SERVER),
filter((target: ISelectedTarget) => {
this.isOriginalNode = true;
this.selectedAgent = '';
this.originalTarget = target;
this.targetFromList = null;
return !target.isMerged;
}),
map(() => this.getTargetInfo().responseStatistics),
),
this.storeHelperService.getAgentSelection(this.unsubscribe).pipe(
filter(() => this.sourceType !== SourceType.INFO_PER_SERVER),
filter((agent: string) => this.selectedAgent !== agent),
tap((agent: string) => this.selectedAgent = agent),
filter(() => !!this.originalTarget),
map(() => this.getTargetInfo()),
switchMap((target: INodeInfo) => {
if (this.isAllAgent()) {
return of(target.responseStatistics);
} else {
let data;
if (this.sourceType === SourceType.MAIN) {
const range = this.previousRange = this.newUrlStateNotificationService.isRealTimeMode()
? this.previousRange ? this.previousRange : [this.newUrlStateNotificationService.getStartTimeToNumber(), this.newUrlStateNotificationService.getEndTimeToNumber()]
: [this.newUrlStateNotificationService.getStartTimeToNumber(), this.newUrlStateNotificationService.getEndTimeToNumber()];
data = this.agentHistogramDataService.getData(this.serverMapData, range, target).pipe(
catchError(() => of(null)),
filter((res: any) => res === null ? (this.activeLayer = Layer.RETRY, false) : true)
);
} else {
data = of(target);
}
return data.pipe(
pluck('agentResponseStatistics', this.selectedAgent)
);
}
}),
),
this.messageQueueService.receiveMessage(this.unsubscribe, MESSAGE_TO.SERVER_MAP_TARGET_SELECT_BY_LIST).pipe(
filter(() => this.sourceType !== SourceType.INFO_PER_SERVER),
tap((target: any) => {
this.selectedAgent = '';
this.targetFromList = target;
if (this.originalTarget.isNode) {
this.isOriginalNode = true;
} else {
this.isOriginalNode = true;
}
}),
map((target: any) => target.responseStatistics),
),
this.messageQueueService.receiveMessage(this.unsubscribe, MESSAGE_TO.AGENT_SELECT_FOR_SERVER_LIST).pipe(
filter(() => this.sourceType === SourceType.INFO_PER_SERVER),
tap(({agent}: IAgentSelection) => this.selectedAgent = agent),
pluck('responseStatistics'),
),
this.messageQueueService.receiveMessage(this.unsubscribe, MESSAGE_TO.SERVER_MAP_DATA_UPDATE).pipe(
tap(({serverMapData, range}: {serverMapData: ServerMapData, range: number[]}) => {
this.serverMapData = serverMapData;
this.previousRange = range;
}),
filter(() => !!this.originalTarget),
filter(() => this.sourceType === SourceType.MAIN),
filter(() => !this.originalTarget.isMerged || !!this.targetFromList),
switchMap(({serverMapData, range}: {serverMapData: ServerMapData, range: number[]}) => {
const target = this.originalTarget.isMerged || this.targetFromList ? serverMapData.getNodeData(this.targetFromList.key) || serverMapData.getLinkData(this.targetFromList.key)
: this.getTargetInfo();
return !target ? of(null)
: this.selectedAgent ? this.agentHistogramDataService.getData(serverMapData, range, target).pipe(
catchError(() => of(null)),
filter((res: any) => !!res),
pluck('agentResponseStatistics', this.selectedAgent)
)
: of (target.responseStatistics);
}),
)
).pipe(
map((data: IResponseStatistics) => this.cleanIntermediateChartData(data)),
map((data) => this.makeChartData(data)),
switchMap((data: PrimitiveArray[]) => {
if (this.shouldUpdateYMax()) {
const maxTickValue = getMaxTickValue(data, 1);
const yMax = maxTickValue === 0 ? this.defaultYMax : maxTickValue;
this.storeHelperService.dispatch(new Actions.UpdateResponseAvgMaxChartYMax(yMax));
return of([data, yMax]);
} else {
return of(data).pipe(
withLatestFrom(this.storeHelperService.getResponseAvgMaxChartYMax(this.unsubscribe))
);
}
}),
).subscribe(([chartData, yMax]: [PrimitiveArray[], number]) => {
this.chartConfig = {
dataConfig: this.makeDataOption(chartData),
elseConfig: this.makeElseOption(yMax),
};
this.cd.markForCheck();
});
}
private shouldUpdateYMax(): boolean {
return this.isAllAgent() && this.isOriginalNode;
}
private isAllAgent(): boolean {
return this.selectedAgent === '';
}
private getTargetInfo(): any {
return this.originalTarget.isNode
? this.serverMapData.getNodeData(this.originalTarget.node[0])
: this.serverMapData.getLinkData(this.originalTarget.link[0]);
}
private cleanIntermediateChartData(data: IResponseStatistics): IResponseStatistics {
return data ? filterObj((key: string) => key === 'Max' || key === 'Avg', data) : data;
}
private makeChartData(data: IResponseStatistics): PrimitiveArray[] {
return data
? [['x', ...Object.keys(data)], ['rs', ...Object.values(data)]]
: [];
}
private makeDataOption(columns: PrimitiveArray[]): Data {
return {
x: 'x',
columns,
empty: {
label: {
text: this.dataEmptyText
}
},
type: bar(),
color: (_, {index}: DataItem): string => this.chartColors[index],
labels: {
colors: getComputedStyle(document.body).getPropertyValue('--text-primary'),
format: {
rs: (v: number) => this.convertWithUnit(v)
}
}
};
}
private makeElseOption(yMax: number): {[key: string]: any} {
return {
padding: {
top: 20,
right: 20 // (or 25)
},
legend: {
show: false
},
axis: {
rotated: true,
x: {
type: 'category'
},
y: {
tick: {
count: 3,
format: (v: number): string => this.convertWithUnit(v)
},
padding: {
top: 0,
bottom: 0
},
min: 0,
max: yMax,
default: [0, this.defaultYMax]
}
},
grid: {
y: {
show: true
}
},
tooltip: {
show: false
},
transition: {
duration: 0
}
};
}
private convertWithUnit(value: number): string {
const unitList = ['ms', 'sec'];
return [...unitList].reduce((acc: string, curr: string, i: number, arr: string[]) => {
const v = Number(acc);
return v >= 1000
? (v / 1000).toString()
: (arr.splice(i + 1), Number.isInteger(v) ? `${v}${curr}` : `${v.toFixed(2)}${curr}`);
}, value.toString());
}
onClickColumn(columnName: string): void {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.CLICK_RESPONSE_AVG_MAX_GRAPH);
}
} | the_stack |
import * as fetch from "isomorphic-fetch";
import * as jwt from "jsonwebtoken";
import { APIError, APIResultError, HTTPError } from "./errors";
import {
Assigned,
Config,
ErrorNonJson,
LoginResponse,
Mutation,
Operation,
Options,
Payload,
Request,
Response,
TxnContext,
UiKeywords,
} from "./types";
// milliseconds before doing automatic token refresh
const AUTO_REFRESH_PREFETCH_TIME = 5000;
const ACL_TOKEN_HEADER = "X-Dgraph-AccessToken";
const ALPHA_AUTH_TOKEN_HEADER = "X-Dgraph-AuthToken";
const DGRAPHCLOUD_API_KEY_HEADER = "X-Auth-Token";
/**
* Stub is a stub/client connecting to a single dgraph server instance.
*/
export class DgraphClientStub {
private readonly addr: string;
private readonly options: Options;
// tslint:disable-next-line no-any
private readonly jsonParser: (text: string) => any;
private legacyApi: boolean;
private accessToken: string;
private refreshToken: string;
private autoRefresh: boolean;
private autoRefreshTimer?: number;
constructor(
addr?: string,
stubConfig: {
legacyApi?: boolean;
// tslint:disable-next-line no-any
jsonParser?(text: string): any;
} = {},
options: Options = {},
) {
if (addr === undefined) {
// tslint:disable-next-line no-http-string
this.addr = "http://localhost:8080";
} else {
this.addr = addr;
}
this.options = options;
this.legacyApi = !!stubConfig.legacyApi;
this.jsonParser =
stubConfig.jsonParser !== undefined
? stubConfig.jsonParser
: // tslint:disable-next-line no-unsafe-any
JSON.parse.bind(JSON);
}
public async detectApiVersion(): Promise<string> {
const health = await this.getHealth();
// tslint:disable-next-line no-unsafe-any no-string-literal
let version: string = health["version"] || health[0].version;
if (version === undefined) {
version = "1.0.x";
}
this.legacyApi = version.startsWith("1.0.");
return version;
}
public alter(op: Operation): Promise<Payload> {
let body: string;
if (op.schema !== undefined) {
body = op.schema;
} else if (op.dropAttr !== undefined) {
body = JSON.stringify({ drop_attr: op.dropAttr });
} else if (op.dropAll) {
body = JSON.stringify({ drop_all: true });
} else {
return Promise.reject("Invalid op argument in alter");
}
return this.callAPI("alter", {
...this.options,
method: "POST",
body,
});
}
public query(req: Request): Promise<Response> {
const headers =
this.options.headers !== undefined
? { ...this.options.headers }
: {};
if (req.vars !== undefined) {
if (this.legacyApi) {
headers["X-Dgraph-Vars"] = JSON.stringify(req.vars);
} else {
headers["Content-Type"] = "application/json";
req.query = JSON.stringify({
query: req.query,
variables: req.vars,
});
}
}
if (headers["Content-Type"] === undefined && !this.legacyApi) {
headers["Content-Type"] = "application/graphql+-";
}
let url = "query";
if (this.legacyApi) {
if (req.startTs !== 0) {
url += `/${req.startTs}`;
}
if (req.debug) {
url += "?debug=true";
}
} else {
const params: { key: string; value: string }[] = [];
if (req.startTs !== 0) {
params.push({
key: "startTs",
value: `${req.startTs}`,
});
}
if (req.timeout > 0) {
params.push({
key: "timeout",
value: `${req.timeout}s`,
});
}
if (req.debug) {
params.push({
key: "debug",
value: "true",
});
}
if (req.readOnly) {
params.push({
key: "ro",
value: "true",
});
}
if (req.bestEffort) {
params.push({
key: "be",
value: "true",
});
}
if (req?.hash?.length > 0) {
params.push({
key: "hash",
value: `${req.hash}`,
});
}
if (params.length > 0) {
url += "?";
url += params
.map(
({
key,
value,
}: {
key: string;
value: string;
}): string => `${key}=${value}`,
)
.join("&");
}
}
return this.callAPI(url, {
...this.options,
method: "POST",
body: req.query,
headers,
});
}
public mutate(mu: Mutation): Promise<Assigned> {
let body: string;
let usingJSON: boolean = false;
if (mu.setJson !== undefined || mu.deleteJson !== undefined) {
usingJSON = true;
const obj: { [k: string]: object } = {};
if (mu.setJson !== undefined) {
obj.set = mu.setJson;
}
if (mu.deleteJson !== undefined) {
obj.delete = mu.deleteJson;
}
body = JSON.stringify(obj);
} else if (
mu.setNquads !== undefined ||
mu.deleteNquads !== undefined
) {
body = `{
${
mu.setNquads === undefined
? ""
: `set {
${mu.setNquads}
}`
}
${
mu.deleteNquads === undefined
? ""
: `delete {
${mu.deleteNquads}
}`
}
}`;
} else if (mu.mutation !== undefined) {
body = mu.mutation;
if (mu.isJsonString !== undefined) {
// Caller has specified mutation type
usingJSON = mu.isJsonString;
} else {
// Detect content-type
try {
JSON.parse(mu.mutation);
usingJSON = true;
} catch (e) {
usingJSON = false;
}
}
} else {
return Promise.reject("Mutation has no data");
}
const headers = {
...(this.options.headers !== undefined ? this.options.headers : {}),
"Content-Type": `application/${usingJSON ? "json" : "rdf"}`,
};
if (usingJSON && this.legacyApi) {
headers["X-Dgraph-MutationType"] = "json";
}
let url = "mutate";
let nextDelim = "?";
if (mu.startTs > 0) {
url +=
(!this.legacyApi ? `?startTs=` : `/`) + mu.startTs.toString();
nextDelim = "&";
}
if (mu?.hash?.length > 0) {
if (!this.legacyApi) {
url += `${nextDelim}hash=${mu.hash}`;
}
}
if (mu.commitNow) {
if (!this.legacyApi) {
url += `${nextDelim}commitNow=true`;
} else {
headers["X-Dgraph-CommitNow"] = "true";
}
}
return this.callAPI(url, {
...this.options,
method: "POST",
body,
headers,
});
}
public commit(ctx: TxnContext): Promise<TxnContext> {
let body: string;
if (ctx.keys === undefined) {
body = "[]";
} else {
body = JSON.stringify(ctx.keys);
}
let url = !this.legacyApi
? `commit?startTs=${ctx.start_ts}`
: `commit/${ctx.start_ts}`;
if (ctx?.hash?.length > 0) {
if (!this.legacyApi) {
url += `&hash=${ctx.hash}`;
}
}
return this.callAPI(url, {
...this.options,
method: "POST",
body,
});
}
public abort(ctx: TxnContext): Promise<TxnContext> {
let url = !this.legacyApi
? `commit?startTs=${ctx.start_ts}&abort=true`
: `abort/${ctx.start_ts}`;
if (ctx?.hash?.length > 0) {
if (!this.legacyApi) {
url += `&hash=${ctx.hash}`;
}
}
return this.callAPI(url, { ...this.options, method: "POST" });
}
public async login(
userid?: string,
password?: string,
refreshToken?: string,
): Promise<boolean> {
if (this.legacyApi) {
throw new Error("Pre v1.1 clients do not support Login methods");
}
const body: { [k: string]: string } = {};
if (
userid === undefined &&
refreshToken === undefined &&
this.refreshToken === undefined
) {
throw new Error(
"Cannot find login details: neither userid/password nor refresh token are specified",
);
}
if (userid === undefined) {
body.refresh_token =
refreshToken !== undefined ? refreshToken : this.refreshToken;
} else {
body.userid = userid;
body.password = password;
}
const res: LoginResponse = await this.callAPI("login", {
...this.options,
method: "POST",
body: JSON.stringify(body),
});
this.accessToken = res.data.accessJWT;
this.refreshToken = res.data.refreshJWT;
this.maybeStartRefreshTimer(this.accessToken);
return true;
}
public async loginIntoNamespace(
userid?: string,
password?: string,
namespace?: number,
refreshToken?: string,
): Promise<boolean> {
if (this.legacyApi) {
throw new Error("Pre v1.1 clients do not support Login methods");
}
const body: { [k: string]: string | number } = {};
if (
userid === undefined &&
refreshToken === undefined &&
this.refreshToken === undefined
) {
throw new Error(
"Cannot find login details: neither userid/password nor refresh token are specified",
);
}
if (userid === undefined) {
body.refresh_token =
refreshToken !== undefined ? refreshToken : this.refreshToken;
} else {
body.userid = userid;
body.password = password;
body.namespace = namespace;
}
const res: LoginResponse = await this.callAPI("login", {
...this.options,
method: "POST",
body: JSON.stringify(body),
});
this.accessToken = res.data.accessJWT;
this.refreshToken = res.data.refreshJWT;
this.maybeStartRefreshTimer(this.accessToken);
return true;
}
public logout(): void {
this.accessToken = undefined;
this.refreshToken = undefined;
}
public getAuthTokens(): { accessToken?: string; refreshToken?: string } {
return {
accessToken: this.accessToken,
refreshToken: this.refreshToken,
};
}
public async fetchUiKeywords(): Promise<UiKeywords> {
return this.callAPI("ui/keywords", this.options);
}
/**
* Gets instance or cluster health, based on the all param
*/
public async getHealth(all: boolean = false): Promise<Response> {
return this.callAPI(`health${all ? "?all" : ""}`, {
...this.options,
acceptRawText: true,
});
}
/**
* Gets the state of the cluster
*/
public async getState(): Promise<Response> {
return this.callAPI("state", this.options);
}
public setAutoRefresh(val: boolean) {
if (!val) {
this.cancelRefreshTimer();
}
this.autoRefresh = val;
this.maybeStartRefreshTimer(this.accessToken);
}
public setAlphaAuthToken(authToken: string) {
if (this.options.headers === undefined) {
this.options.headers = {};
}
this.options.headers[ALPHA_AUTH_TOKEN_HEADER] = authToken;
}
/**
* @deprecated since v21.3 and will be removed in v21.07 release.
* Please use {@link setCloudApiKey} instead.
*/
public setSlashApiKey(apiKey: string) {
this.setCloudApiKey(apiKey);
}
public setCloudApiKey(apiKey: string) {
if (this.options.headers === undefined) {
this.options.headers = {};
}
this.options.headers[DGRAPHCLOUD_API_KEY_HEADER] = apiKey;
}
private cancelRefreshTimer() {
if (this.autoRefreshTimer !== undefined) {
// tslint:disable-next-line
clearTimeout(<any>this.autoRefreshTimer);
this.autoRefreshTimer = undefined;
}
}
private maybeStartRefreshTimer(accessToken?: string) {
if (accessToken === undefined || !this.autoRefresh) {
return;
}
this.cancelRefreshTimer();
const timeToWait = Math.max(
2000,
// tslint:disable-next-line no-unsafe-any
(<{ exp: number }>jwt.decode(accessToken)).exp * 1000 -
Date.now() -
AUTO_REFRESH_PREFETCH_TIME,
);
// tslint:disable-next-line no-unsafe-any no-any
this.autoRefreshTimer = <number>(
(<unknown>(
setTimeout(
() => (this.refreshToken !== undefined ? this.login() : 0),
timeToWait,
)
))
);
}
private async callAPI<T>(path: string, config: Config): Promise<T> {
const url = this.getURL(path);
config.headers = config.headers !== undefined ? config.headers : {};
if (this.accessToken !== undefined && path !== "login") {
config.headers[ACL_TOKEN_HEADER] = this.accessToken;
}
// tslint:disable-next-line no-unsafe-any
const response = await fetch(url, config);
// tslint:disable-next-line no-unsafe-any
if (response.status >= 300 || response.status < 200) {
// tslint:disable-next-line no-unsafe-any
throw new HTTPError(response);
}
let json;
// tslint:disable-next-line no-unsafe-any
const responseText: string = await response.text();
try {
// tslint:disable-next-line no-unsafe-any
json = this.jsonParser(responseText);
} catch (e) {
if (config.acceptRawText) {
return <T>(<unknown>responseText);
}
const err: ErrorNonJson = <ErrorNonJson>(
new Error("Response is not JSON")
);
err.responseText = responseText;
throw err;
}
// tslint:disable-next-line no-unsafe-any
const errors = (<{ errors: APIResultError[] }>json).errors;
if (errors !== undefined) {
throw new APIError(url, errors);
}
return <T>json;
}
private getURL(path: string): string {
return `${this.addr}${this.addr.endsWith("/") ? "" : "/"}${path}`;
}
} | the_stack |
import { DiscordRESTError, Member, User, VoiceChannel } from 'eris';
import { Command, CommandMessage, Subcommand } from '../../../structures';
import { PunishmentType } from '../../../entities/PunishmentsEntity';
import PunishmentService from '../../../services/PunishmentService';
import { Categories, CHANNEL_REGEX } from '../../../util/Constants';
import Permissions from '../../../util/Permissions';
import { Inject } from '@augu/lilith';
import Discord from '../../../components/Discord';
import ms = require('ms');
const condition = (discord: Discord, member: Member) =>
member.user.id !== discord.client.user.id && // If it's not Nino
member.guild.ownerID === member.user.id && // If the owner is in the voice channel
member.permissions.has('voiceMuteMembers'); // If the member is a voice moderator
const botCondition = (discord: Discord, member: Member) =>
member.user.id !== discord.client.user.id && // If it's not Nino
member.bot === true; // If it's a bot
export default class VoiceKickCommand extends Command {
@Inject
private readonly discord!: Discord;
constructor() {
super({
userPermissions: 'voiceMoveMembers',
description: 'descriptions.voice_kick',
category: Categories.Moderation,
examples: [
'vckick | Kick all members in your voice channel',
'vckick <#521254554543485646> | Kick all members in a specific channel',
'vckick bots | Kick all bots in your voice channel',
'vckick bots <#521254554543485646> | Kick all bots in a specific channel',
],
aliases: ['kickvc'],
name: 'vckick',
});
}
async run(msg: CommandMessage, [channelOrAmount]: [string?]) {
if (!channelOrAmount) {
const message = await msg.reply('Kicking all members...');
if (!msg.member.voiceState.channelID) return msg.reply('You must be in a voice channel.');
const id = msg.member.voiceState.channelID; // cache it if they decide to leave
const voiceChan = await this.discord.getChannel<VoiceChannel>(id);
if (voiceChan === null) return msg.error("Unknown voice channel you're in.");
if (
!voiceChan.permissionsOf(this.discord.client.user.id).has('voiceConnect') ||
!voiceChan.permissionsOf(this.discord.client.user.id).has('voiceMoveMembers')
)
return msg.reply('I do not have permissions to **Connect** or **Move Members**.');
const members = voiceChan.voiceMembers.filter((c) => condition(this.discord, c));
if (members.length === 0)
return msg.error(
'No users were in this channel. (excluding myself, the owner, and people with **`Voice Mute Members`** permission)'
);
if (members.length === 1) {
await this.discord.client.joinVoiceChannel(id);
try {
await members[0].edit(
{ channelID: null },
encodeURIComponent(
`[Voice Kick] Told to kick ${members[0].username}#${members[0].discriminator} (${members[0].id})`
)
);
} catch {
return msg.error(`Unable to kick **${members[0].username}#${members[0].discriminator}**.`);
}
}
await this.discord.client.joinVoiceChannel(id);
await message.edit(`ℹ️ **Removing ${members.length} members...**`);
let success = 0;
let errored = 0;
for (const member of members) {
try {
success++;
await member.edit(
{ channelID: null },
encodeURIComponent(`[Voice Kick] Told to kick ${member.username}#${member.discriminator} (${member.id})`)
);
} catch {
errored++;
}
}
const errorRate = ((errored / members.length) * 100).toFixed(2);
const successRate = ((success / members.length) * 100).toFixed(2);
this.discord.client.leaveVoiceChannel(id);
await message.delete();
return msg.reply(
[
`Successfully kicked **${success}/${members.length}** members.`,
'',
`> ${msg.successEmote} **Success Rate**: ${successRate}%`,
`> ${msg.errorEmote} **Error Rate**: ${errorRate}%`,
].join('\n')
);
}
const channel = await this.discord.getChannel<VoiceChannel>(channelOrAmount);
// if I can recall correctly, IDs are around 15-21 but I could be wrong.
// ~ Noel
if (channel === null) return msg.reply(`Channel with ID **${channelOrAmount}** was not found.`);
if (channel.type !== 2) return msg.reply('Channel was not a voice channel.');
if (
!channel.permissionsOf(this.discord.client.user.id).has('voiceConnect') ||
!channel.permissionsOf(this.discord.client.user.id).has('voiceMoveMembers')
)
return msg.reply('I do not have permissions to **Connect** or **Move Members**.');
const members = channel.voiceMembers.filter((c) => condition(this.discord, c));
if (members.length === 0)
return msg.error(
'No users were in this channel. (excluding myself, the owner, and people with **`Voice Mute Members`** permission)'
);
if (members.length === 1) {
await this.discord.client.joinVoiceChannel(channel.id);
try {
await members[0].edit(
{ channelID: null },
encodeURIComponent(
`[Voice Kick] Told to kick ${members[0].username}#${members[0].discriminator} (${members[0].id})`
)
);
} catch {
return msg.error(`Unable to kick **${members[0].username}#${members[0].discriminator}**.`);
}
}
const message = await msg.reply(`ℹ️ Kicking all members in <#${channel.id}> (${members.length} members)`);
await this.discord.client.joinVoiceChannel(channel.id);
let success = 0;
let errored = 0;
for (const member of members) {
try {
success++;
await member.edit(
{ channelID: null },
encodeURIComponent(`[Voice Kick] Told to kick ${member.username}#${member.discriminator} (${member.id})`)
);
} catch {
errored++;
}
}
const errorRate = ((errored / members.length) * 100).toFixed(2);
const successRate = ((success / members.length) * 100).toFixed(2);
this.discord.client.leaveVoiceChannel(channel.id);
await message.delete();
return msg.reply(
[
`Successfully kicked **${success}/${members.length}** members.`,
'',
`> ${msg.successEmote} **Success Rate**: ${successRate}%`,
`> ${msg.errorEmote} **Error Rate**: ${errorRate}%`,
].join('\n')
);
}
@Subcommand('<channel | amount>')
async bots(msg: CommandMessage, [channelOrAmount]: [string?]) {
if (!channelOrAmount) {
const message = await msg.reply('Kicking all bots...');
if (!msg.member.voiceState.channelID) return msg.reply('You must be in a voice channel.');
const id = msg.member.voiceState.channelID; // cache it if they decide to leave
const voiceChan = await this.discord.getChannel<VoiceChannel>(id);
if (voiceChan === null) return msg.error("Unknown voice channel you're in.");
if (
!voiceChan.permissionsOf(this.discord.client.user.id).has('voiceConnect') ||
!voiceChan.permissionsOf(this.discord.client.user.id).has('voiceMoveMembers')
)
return msg.reply('I do not have permissions to **Connect** or **Move Members**.');
const members = voiceChan.voiceMembers.filter((c) => botCondition(this.discord, c));
if (members.length === 0) return msg.error('No bots were in this channel. (excluding myself)');
if (members.length === 1) {
await this.discord.client.joinVoiceChannel(id);
try {
await members[0].edit(
{ channelID: null },
encodeURIComponent(
`[Voice Kick] Told to kick ${members[0].username}#${members[0].discriminator} (${members[0].id})`
)
);
} catch {
return msg.error(`Unable to kick bot **${members[0].username}#${members[0].discriminator}**.`);
}
}
await this.discord.client.joinVoiceChannel(id);
await message.edit(`ℹ️ **Removing ${members.length} bots...**`);
let success = 0;
let errored = 0;
for (const member of members) {
try {
success++;
await member.edit(
{ channelID: null },
encodeURIComponent(`[Voice Kick] Told to kick ${member.username}#${member.discriminator} (${member.id})`)
);
} catch {
errored++;
}
}
const errorRate = ((errored / members.length) * 100).toFixed(2);
const successRate = ((success / members.length) * 100).toFixed(2);
this.discord.client.leaveVoiceChannel(id);
await message.delete();
return msg.reply(
[
`Successfully kicked **${success}/${members.length}** bots.`,
'',
`> ${msg.successEmote} **Success Rate**: ${successRate}%`,
`> ${msg.errorEmote} **Error Rate**: ${errorRate}%`,
].join('\n')
);
}
const channel = await this.discord.getChannel<VoiceChannel>(channelOrAmount);
// if I can recall correctly, IDs are around 15-21 but I could be wrong.
// ~ Noel
if (channel === null) return msg.reply(`Channel with ID **${channelOrAmount}** was not found.`);
if (channel.type !== 2) return msg.reply('Channel was not a voice channel.');
if (
!channel.permissionsOf(this.discord.client.user.id).has('voiceConnect') ||
!channel.permissionsOf(this.discord.client.user.id).has('voiceMoveMembers')
)
return msg.reply('I do not have permissions to **Connect** or **Move Members**.');
const members = channel.voiceMembers.filter((c) => botCondition(this.discord, c));
if (members.length === 0)
return msg.error(
'No users were in this channel. (excluding myself, the owner, and people with **`Voice Mute Members`** permission)'
);
if (members.length === 1) {
await this.discord.client.joinVoiceChannel(channel.id);
try {
await members[0].edit(
{ channelID: null },
encodeURIComponent(
`[Voice Kick] Told to kick ${members[0].username}#${members[0].discriminator} (${members[0].id})`
)
);
} catch {
return msg.error(`Unable to kick **${members[0].username}#${members[0].discriminator}**.`);
}
}
const message = await msg.reply(`ℹ️ Kicking all members in <#${channel.id}> (${members.length} members)`);
await this.discord.client.joinVoiceChannel(channel.id);
let success = 0;
let errored = 0;
for (const member of members) {
try {
success++;
await member.edit(
{ channelID: null },
encodeURIComponent(`[Voice Kick] Told to kick ${member.username}#${member.discriminator} (${member.id})`)
);
} catch {
errored++;
}
}
const errorRate = ((errored / members.length) * 100).toFixed(2);
const successRate = ((success / members.length) * 100).toFixed(2);
this.discord.client.leaveVoiceChannel(channel.id);
await message.delete();
return msg.reply(
[
`Successfully kicked **${success}/${members.length}** members.`,
'',
`> ${msg.successEmote} **Success Rate**: ${successRate}%`,
`> ${msg.errorEmote} **Error Rate**: ${errorRate}%`,
].join('\n')
);
}
} | the_stack |
import { PlainTextElement, View } from '@slack/types'
import {
Blocks,
Call,
Escape,
File,
Home,
Input,
JSXSlack,
Modal,
Option,
Section,
Select,
} from '../../src/index'
beforeEach(() => JSXSlack.exactMode(false))
describe('Container components', () => {
const falseyStr = ''
const falseyNum = 0
describe('<Blocks>', () => {
it('accepts input layout block and input components', () => {
const [input]: any = (
<Blocks>
<Input label="Select">
<Select>
<Option value="test">test</Option>
</Select>
</Input>
</Blocks>
)
expect(input.type).toBe('input')
const [inputComponent]: any = (
<Blocks>
<Select label="Select">
<Option value="test">test</Option>
</Select>
</Blocks>
)
expect(inputComponent.type).toBe('input')
})
it('throws error when <Blocks> has unexpected element', () => {
expect(() => (
<Blocks>
<b>unexpected</b>
</Blocks>
)).toThrow()
expect(() => (
<Blocks>
<Escape>unexpected</Escape>
</Blocks>
)).toThrow()
// <Input type="hidden"> cannot use in message
expect(() => (
<Blocks>
<Input type="hidden" name="foo" value="bar" />
</Blocks>
)).toThrow()
// <input type="submit"> cannot use in message
expect(() => (
<Blocks>
<input type="submit" value="bar" />
</Blocks>
)).toThrow()
// Incompatible accessory for section block
expect(() => (
<Blocks>
{
{
type: 'section',
accessory: { type: 'incompatible' },
} as any
}
</Blocks>
)).toThrow(/incompatible/)
// Incompatible interactive element for actions block
expect(() => (
<Blocks>
{
{
type: 'actions',
elements: [{ type: 'incompatible' }],
} as any
}
</Blocks>
)).toThrow(/incompatible/)
})
it('ignores invalid literal values to keep compatibillity with v1', () => {
let blocks: any
expect(() => {
blocks = (
// @ts-expect-error
<Blocks>
Hello
{falseyStr && <Section>test</Section>}
{falseyNum && <Section>test</Section>}
</Blocks>
)
}).not.toThrow()
expect(blocks).toStrictEqual([])
})
})
describe('<Modal>', () => {
it('generates view payload JSON', () => {
const simpleView: View = {
type: 'modal',
title: { type: 'plain_text', text: 'test', emoji: true },
blocks: [{ type: 'section', text: expect.any(Object) }],
}
expect(
JSXSlack(
<Modal title="test">
<Section>Hello!</Section>
</Modal>
)
).toStrictEqual(simpleView)
// Optional attributes
const viewWithOptions: View & Record<string, any> = {
type: 'modal',
title: expect.any(Object),
blocks: expect.any(Array),
callback_id: 'callback_id',
external_id: 'external_id',
submit: { type: 'plain_text', text: 'Submit', emoji: true },
close: { type: 'plain_text', text: 'Close', emoji: true },
private_metadata: 'private_metadata',
clear_on_close: true,
notify_on_close: false,
}
expect(
JSXSlack(
<Modal
callbackId="callback_id"
clearOnClose
close="Close"
externalId="external_id"
notifyOnClose={false}
privateMetadata="private_metadata"
submit="Submit"
title="test"
>
<Section>Hello!</Section>
</Modal>
)
).toStrictEqual(viewWithOptions)
})
it('throws error when <Modal> has unexpected element', () => {
expect(() =>
JSXSlack(
<Modal title="test">
<File externalId="external_id" />
</Modal>
)
).toThrow()
expect(() =>
JSXSlack(
<Modal title="test">
<Call callId="R01234567" />
</Modal>
)
).toThrow()
})
it('ignores invalid literal values to keep compatibillity with v1', () => {
let modal: any
expect(() => {
modal = (
// @ts-expect-error
<Modal title="title">
Hello
{falseyStr && <Section>test</Section>}
{falseyNum && <Section>test</Section>}
</Modal>
)
}).not.toThrow()
expect(modal.blocks).toStrictEqual([])
})
it('has default submit field when using input block with omitted submit prop', () => {
const submit: PlainTextElement = expect.objectContaining({
type: 'plain_text',
text: 'Submit',
})
expect(
<Modal title="title">
<Input label="test" />
</Modal>
).toStrictEqual(expect.objectContaining({ submit }))
// <input> alias
expect(
<Modal title="title">
<input label="test" />
</Modal>
).toStrictEqual(expect.objectContaining({ submit }))
// Input layout block
expect(
<Modal title="title">
<Input label="test">
<Select>
<Option selected>a</Option>
</Select>
</Input>
</Modal>
).toStrictEqual(expect.objectContaining({ submit }))
// Input component
expect(
<Modal title="title">
<Select label="test">
<Option selected>a</Option>
</Select>
</Modal>
).toStrictEqual(expect.objectContaining({ submit }))
// No input layout block
expect(
<Modal title="title">
<Section>test</Section>
</Modal>
).not.toStrictEqual(expect.objectContaining({ submit }))
// <Input type="hidden" />
expect(
<Modal title="title">
<Input type="hidden" name="foo" value="bar" />
</Modal>
).not.toStrictEqual(expect.objectContaining({ submit }))
})
describe('`workflow_step` type', () => {
it('ignores some props about for around of the modal content', () => {
const workflowStep = (
<Modal type="workflow_step">
<Input type="submit" value="submit" />
</Modal>
)
expect(workflowStep).toStrictEqual({
type: 'workflow_step',
blocks: [],
})
expect(workflowStep).not.toHaveProperty('submit_disabled')
const workflowStepFull = (
// @ts-expect-error
<Modal
callbackId="callback_id"
clearOnClose
close="Close"
externalId="external_id"
notifyOnClose={false}
privateMetadata="private_metadata"
submit="Submit"
title="test"
type="workflow_step"
>
<Section>Hello!</Section>
</Modal>
)
expect(workflowStepFull['type']).toBe('workflow_step')
expect(workflowStepFull).not.toHaveProperty('title')
expect(workflowStepFull).not.toHaveProperty('submit')
expect(workflowStepFull).not.toHaveProperty('close')
expect(workflowStepFull).not.toHaveProperty('clear_on_close')
expect(workflowStepFull).not.toHaveProperty('notify_on_close')
})
describe('submit prop', () => {
it('assigns submit_disabled field as true if defined submit as false', () => {
expect(
<Modal type="workflow_step" submit={false}>
{}
</Modal>
).toStrictEqual({
type: 'workflow_step',
submit_disabled: true,
blocks: [],
})
})
it('assigns submit_disabled field as false if defined truthy value', () => {
expect(
<Modal type="workflow_step" submit>
{}
</Modal>
).toStrictEqual({
type: 'workflow_step',
submit_disabled: false,
blocks: [],
})
})
it('does not assign submit_disabled field to the regular modal even if defined as false', () => {
expect(
// @ts-expect-error
<Modal type="modal" submit={false}>
{}
</Modal>
).not.toHaveProperty('submit_disabled')
})
})
})
})
describe('<Home>', () => {
it('generates view payload JSON', () => {
const view = {
type: 'home',
blocks: [{ type: 'section', text: expect.any(Object) }],
}
expect(
JSXSlack(
<Home>
<Section>Hello!</Section>
</Home>
)
).toStrictEqual(view)
const viewWithOptions = {
type: 'home',
callback_id: 'callback_id',
external_id: 'external_id',
private_metadata: 'private_metadata',
blocks: [{ type: 'section', text: expect.any(Object) }],
}
expect(
JSXSlack(
<Home
callbackId="callback_id"
externalId="external_id"
privateMetadata="private_metadata"
>
<Section>Hello!</Section>
</Home>
)
).toStrictEqual(viewWithOptions)
})
it('accepts input layout block and input components', () => {
const inputLayout: any = (
<Home>
<Input label="Select">
<Select>
<Option value="test">test</Option>
</Select>
</Input>
</Home>
)
expect(inputLayout.blocks[0].type).toBe('input')
const inputComponent: any = (
<Home>
<Select label="Select">
<Option value="test">test</Option>
</Select>
</Home>
)
expect(inputComponent.blocks[0].type).toBe('input')
})
it('accepts <Input type="hidden"> to store private metadata', () => {
expect(
JSXSlack(
<Home>
<Input type="hidden" name="foo" value="bar" />
<input type="hidden" name="abc" value="def" />
</Home>
).private_metadata
).toBe(JSON.stringify({ foo: 'bar', abc: 'def' }))
expect(
JSXSlack(
<Home privateMetadata="override">
<Input type="hidden" name="foo" value="bar" />
<input type="hidden" name="abc" value="def" />
</Home>
).private_metadata
).toBe('override')
// Custom transformer
expect(
JSXSlack(
<Home
privateMetadata={(meta: any) =>
meta && new URLSearchParams(meta).toString()
}
>
<Input type="hidden" name="foo" value="bar" />
<input type="hidden" name="abc" value="def" />
</Home>
).private_metadata
).toBe('foo=bar&abc=def')
})
it('ignores <Input type="modal">', () => {
expect(
<Home>
<Input type="submit" value="test" />
</Home>
).toStrictEqual({ type: 'home', blocks: [] })
})
it('throws error when <Home> has unexpected element', () => {
expect(() =>
JSXSlack(
<Home>
<b>unexpected</b>
</Home>
)
).toThrow()
expect(() =>
JSXSlack(
<Home>
<File externalId="external_id" />
</Home>
)
).toThrow()
expect(() =>
JSXSlack(
<Home>
<Call callId="R01234567" />
</Home>
)
).toThrow()
})
it('ignores invalid literal values to keep compatibillity with v1', () => {
let home: any
expect(() => {
home = (
// @ts-expect-error
<Home>
Hello
{falseyStr && <Section>test</Section>}
{falseyNum && <Section>test</Section>}
</Home>
)
}).not.toThrow()
expect(home.blocks).toStrictEqual([])
})
})
}) | the_stack |
import { Link, useHistory, useLocation } from 'react-router-dom'
import React, { useEffect, useMemo, useState } from 'react'
import { Badge, Button, ButtonGroup, Col, Container, Row, Spinner } from 'react-bootstrap'
import {
Configuration,
Objective,
ObjectivesApi,
ObjectiveStatus,
ObjectiveStatusAvailability,
ObjectiveStatusBudget
} from '../client'
import { formatDuration, parseDuration, PATH_PREFIX } from '../App'
import Navbar from '../components/Navbar'
import { parseLabels } from "../labels";
import ErrorBudgetGraph from "../components/graphs/ErrorBudgetGraph";
import RequestsGraph from "../components/graphs/RequestsGraph";
import ErrorsGraph from "../components/graphs/ErrorsGraph";
import AlertsTable from "../components/AlertsTable";
const Detail = () => {
const history = useHistory()
const query = new URLSearchParams(useLocation().search)
const api = useMemo(() => {
return new ObjectivesApi(new Configuration({ basePath: `./api/v1` }))
}, [])
const queryExpr = query.get('expr')
const expr = queryExpr == null ? '' : queryExpr
const labels = parseLabels(expr)
const groupingExpr = query.get('grouping')
const grouping = groupingExpr == null ? '' : groupingExpr
const groupingLabels = parseLabels(grouping)
const name: string = labels['__name__']
const timeRangeQuery = query.get('timerange')
const timeRangeParsed = timeRangeQuery != null ? parseDuration(timeRangeQuery) : null
const timeRange: number = timeRangeParsed != null ? timeRangeParsed : 3600 * 1000
const [objective, setObjective] = useState<Objective | null>(null);
const [objectiveError, setObjectiveError] = useState<string>('');
enum StatusState {
Unknown,
Error,
NoData,
Success,
}
const [statusState, setStatusState] = useState<StatusState>(StatusState.Unknown);
const [availability, setAvailability] = useState<ObjectiveStatusAvailability | null>(null);
const [errorBudget, setErrorBudget] = useState<ObjectiveStatusBudget | null>(null);
useEffect(() => {
// const controller = new AbortController()
document.title = `${name} - Pyrra`
api.listObjectives({ expr: expr })
.then((os: Objective[]) => os.length === 1 ? setObjective(os[0]) : setObjective(null))
.catch((resp) => {
if (resp.status !== undefined) {
resp.text().then((err: string) => (setObjectiveError(err)))
} else {
setObjectiveError(resp.message)
}
})
api.getObjectiveStatus({ expr: expr, grouping: grouping })
.then((s: ObjectiveStatus[]) => {
if (s.length === 0) {
setStatusState(StatusState.NoData)
} else if (s.length === 1) {
setAvailability(s[0].availability)
setErrorBudget(s[0].budget)
setStatusState(StatusState.Success)
} else {
setStatusState(StatusState.Error)
}
})
.catch((resp) => {
if (resp.status === 404) {
setStatusState(StatusState.NoData)
} else {
setStatusState(StatusState.Error)
}
})
// return () => {
// // cancel any pending requests.
// controller.abort()
// }
}, [api, name, expr, grouping, timeRange, StatusState.Error, StatusState.NoData, StatusState.Success])
if (objectiveError !== '') {
return (
<>
<Navbar/>
<Container>
<div style={{ margin: '50px 0' }}>
<h3>{objectiveError}</h3>
<br/>
<Link to="/" className="btn btn-light">
Go Back
</Link>
</div>
</Container>
</>
)
}
if (objective == null) {
return (
<div style={{ marginTop: '50px', textAlign: 'center' }}>
<Spinner animation="border" role="status">
<span className="sr-only">Loading...</span>
</Spinner>
</div>
)
}
if (objective.labels === undefined) {
return (
<></>
)
}
const timeRanges = [
28 * 24 * 3600 * 1000, // 4w
7 * 24 * 3600 * 1000, // 1w
24 * 3600 * 1000, // 1d
12 * 3600 * 1000, // 12h
3600 * 1000 // 1h
]
const handleTimeRangeClick = (t: number) => () => {
history.push(`/objectives?expr=${expr}&grouping=${groupingExpr}&timerange=${formatDuration(t)}`)
}
const renderAvailability = () => {
const headline = (<h6>Availability</h6>)
switch (statusState) {
case StatusState.Unknown:
return (
<div>
{headline}
<Spinner animation={'border'} style={{
width: 50,
height: 50,
padding: 0,
borderRadius: 50,
borderWidth: 2,
opacity: 0.25
}}/>
</div>
)
case StatusState.Error:
return (
<div>
{headline}
<h2 className="error">Error</h2>
</div>
)
case StatusState.NoData:
return (
<div>
{headline}
<h2>No data</h2>
</div>
)
case StatusState.Success:
if (availability === null) {
return <></>
}
return (
<div className={availability.percentage > objective.target ? 'good' : 'bad'}>
{headline}
<h2>{(100 * availability.percentage).toFixed(3)}%</h2>
</div>
)
}
}
const renderErrorBudget = () => {
const headline = (<h6>Error Budget</h6>)
switch (statusState) {
case StatusState.Unknown:
return (
<div>
{headline}
<Spinner animation={'border'} style={{
width: 50,
height: 50,
padding: 0,
borderRadius: 50,
borderWidth: 2,
opacity: 0.25
}}/>
</div>
)
case StatusState.Error:
return (
<div>
{headline}
<h2 className="error">Error</h2>
</div>
)
case StatusState.NoData:
return (
<div>
{headline}
<h2>No data</h2>
</div>
)
case StatusState.Success:
if (errorBudget === null) {
return <></>
}
return (
<div className={errorBudget.remaining > 0 ? 'good' : 'bad'}>
{headline}
<h2>{(100 * errorBudget.remaining).toFixed(3)}%</h2>
</div>
)
}
}
const labelBadges = Object.entries({ ...objective.labels, ...groupingLabels })
.filter((l: [string, string]) => l[0] !== '__name__')
.map((l: [string, string]) => (
<Badge key={l[1]} variant={"light"}>{l[0]}={l[1]}</Badge>
))
const uPlotCursor = {
lock: true,
sync: {
key: 'detail'
}
};
return (
<>
<Navbar>
<div>
<Link to="/">Objectives</Link> > <span>{name}</span>
</div>
</Navbar>
<div className="content detail">
<Container>
<Row>
<Col xs={12}>
<h3>{name}</h3>
{labelBadges}
</Col>
{objective.description !== undefined && objective.description !== '' ? (
<Col xs={12} md={6}>
<p>{objective.description}</p>
</Col>
)
: (<></>)}
</Row>
<Row>
<div className="metrics">
<div>
<h6>Objective in <strong>{formatDuration(objective.window)}</strong></h6>
<h2>{(100 * objective.target).toFixed(3)}%</h2>
</div>
{renderAvailability()}
{renderErrorBudget()}
</div>
</Row>
<Row>
<Col className="text-center timerange">
<div className="inner">
<ButtonGroup aria-label="Time Range">
{timeRanges.map((t: number) => (
<Button
key={t}
variant="light"
onClick={handleTimeRangeClick(t)}
active={timeRange === t}
>{formatDuration(t)}</Button>
))}
</ButtonGroup>
</div>
</Col>
</Row>
<Row style={{ marginBottom: 0 }}>
<Col>
<ErrorBudgetGraph
api={api}
labels={labels}
grouping={groupingLabels}
timeRange={timeRange}
uPlotCursor={uPlotCursor}
/>
</Col>
</Row>
<Row>
<Col style={{ textAlign: 'right' }}>
{availability != null ? (
<>
<small>Errors: {Math.floor(availability.errors).toLocaleString()}</small>
<small>Total: {Math.floor(availability.total).toLocaleString()}</small>
</>
) : (
<></>
)}
</Col>
</Row>
<Row>
<Col xs={12} sm={6}>
<RequestsGraph
api={api}
labels={labels}
grouping={groupingLabels}
timeRange={timeRange}
uPlotCursor={uPlotCursor}
/>
</Col>
<Col xs={12} sm={6}>
<ErrorsGraph
api={api}
labels={labels}
grouping={groupingLabels}
timeRange={timeRange}
uPlotCursor={uPlotCursor}
/>
</Col>
</Row>
<Row>
<Col>
<h4>Multi Burn Rate Alerts</h4>
<AlertsTable
objective={objective}
grouping={groupingLabels}
/>
</Col>
</Row>
<Row>
<Col>
<h4>Config</h4>
<pre style={{ padding: 20, borderRadius: 4 }}>
<code>{objective.config}</code>
</pre>
</Col>
</Row>
</Container>
</div>
</>
);
};
export default Detail | the_stack |
* GeoPoint represents a specific coordinate on earth. We support
* a number of different variants of geopoints being specified.
*
* @category Full Text Search
*/
export type GeoPoint =
| [longitude: number, latitude: number]
| { lon: number; lat: number }
| { longitude: number; latitude: number }
function _parseGeoPoint(v: GeoPoint): [number, number] {
if (Array.isArray(v)) {
return v
} else if (v instanceof Object) {
const latLonObj = v as any
if (latLonObj.lon || latLonObj.lat) {
return [latLonObj.lon, latLonObj.lat]
} else if (latLonObj.longitude || latLonObj.latitude) {
return [latLonObj.longitude, latLonObj.latitude]
}
}
throw new Error('invalid geopoint specified')
}
/**
* @internal
*/
function _unpackListArgs<T>(args: T[] | T[][]): T[] {
if (Array.isArray(args[0])) {
return (args[0] as any) as T[]
}
return (args as any) as T[]
}
/**
* Provides the ability to specify the query for a search query.
*
* @category Full Text Search
*/
export class SearchQuery {
protected _data: any
constructor(data: any) {
if (!data) {
data = {}
}
this._data = data
}
toJSON(): any {
return this._data
}
/**
* @internal
*/
static toJSON(query: SearchQuery | any): any {
if (query.toJSON) {
return query.toJSON()
}
return query
}
/**
* @internal
*/
static hasProp(query: SearchQuery | any, prop: string): boolean {
const json = this.toJSON(query)
return json[prop] !== undefined
}
static match(match: string): MatchSearchQuery {
return new MatchSearchQuery(match)
}
static matchPhrase(phrase: string): MatchPhraseSearchQuery {
return new MatchPhraseSearchQuery(phrase)
}
static regexp(regexp: string): RegexpSearchQuery {
return new RegexpSearchQuery(regexp)
}
static queryString(query: string): QueryStringSearchQuery {
return new QueryStringSearchQuery(query)
}
static numericRange(): NumericRangeSearchQuery {
return new NumericRangeSearchQuery()
}
static dateRange(): DateRangeSearchQuery {
return new DateRangeSearchQuery()
}
/**
* Creates a ConjunctionSearchQuery from a set of other SearchQuery's.
*
* @deprecated Use the multi-argument overload instead.
*/
static conjuncts(queries: SearchQuery[]): ConjunctionSearchQuery
/**
* Creates a ConjunctionSearchQuery from a set of other SearchQuery's.
*/
static conjuncts(...queries: SearchQuery[]): ConjunctionSearchQuery
/**
* @internal
*/
static conjuncts(
...args: SearchQuery[] | SearchQuery[][]
): ConjunctionSearchQuery {
const queries = _unpackListArgs(args)
return new ConjunctionSearchQuery(...queries)
}
/**
* Creates a DisjunctionSearchQuery from a set of other SearchQuery's.
*
* @deprecated Use the multi-argument overload instead.
*/
static disjuncts(queries: SearchQuery[]): DisjunctionSearchQuery
/**
* Creates a DisjunctionSearchQuery from a set of other SearchQuery's.
*/
static disjuncts(...queries: SearchQuery[]): DisjunctionSearchQuery
/**
* @internal
*/
static disjuncts(
...args: SearchQuery[] | SearchQuery[][]
): DisjunctionSearchQuery {
const queries = _unpackListArgs(args)
return new DisjunctionSearchQuery(...queries)
}
static boolean(): BooleanSearchQuery {
return new BooleanSearchQuery()
}
static wildcard(wildcard: string): WildcardSearchQuery {
return new WildcardSearchQuery(wildcard)
}
/**
* Creates a DocIdSearchQuery from a set of document-ids.
*
* @deprecated Use the multi-argument overload instead.
*/
static docIds(queries: string[]): DocIdSearchQuery
/**
* Creates a DocIdSearchQuery from a set of document-ids.
*/
static docIds(...queries: string[]): DocIdSearchQuery
/**
* @internal
*/
static docIds(...args: string[] | string[][]): DocIdSearchQuery {
const queries = _unpackListArgs(args)
return new DocIdSearchQuery(...queries)
}
static booleanField(val: boolean): BooleanFieldSearchQuery {
return new BooleanFieldSearchQuery(val)
}
static term(term: string): TermSearchQuery {
return new TermSearchQuery(term)
}
static phrase(terms: string[]): PhraseSearchQuery {
return new PhraseSearchQuery(terms)
}
static prefix(prefix: string): PrefixSearchQuery {
return new PrefixSearchQuery(prefix)
}
static matchAll(): MatchAllSearchQuery {
return new MatchAllSearchQuery()
}
static matchNone(): MatchNoneSearchQuery {
return new MatchNoneSearchQuery()
}
static geoDistance(
lon: number,
lat: number,
distance: number
): GeoDistanceSearchQuery {
return new GeoDistanceSearchQuery(lon, lat, distance)
}
static geoBoundingBox(
tl_lon: number,
tl_lat: number,
br_lon: number,
br_lat: number
): GeoBoundingBoxSearchQuery {
return new GeoBoundingBoxSearchQuery(tl_lon, tl_lat, br_lon, br_lat)
}
static geoPolygon(points: GeoPoint[]): GeoPolygonSearchQuery {
return new GeoPolygonSearchQuery(points)
}
}
/**
* Represents a match search query.
*
* @category Full Text Search
*/
export class MatchSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(match: string) {
super({
match: match,
})
}
field(field: string): MatchSearchQuery {
this._data.field = field
return this
}
analyzer(analyzer: string): MatchSearchQuery {
this._data.analyzer = analyzer
return this
}
prefixLength(prefixLength: number): MatchSearchQuery {
this._data.prefix_length = prefixLength
return this
}
fuzziness(fuzziness: number): MatchSearchQuery {
this._data.fuzziness = fuzziness
return this
}
boost(boost: number): MatchSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a match-phrase search query.
*
* @category Full Text Search
*/
export class MatchPhraseSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(phrase: string) {
super({
match_phrase: phrase,
})
}
field(field: string): MatchPhraseSearchQuery {
this._data.field = field
return this
}
analyzer(analyzer: string): MatchPhraseSearchQuery {
this._data.analyzer = analyzer
return this
}
boost(boost: number): MatchPhraseSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a regexp search query.
*
* @category Full Text Search
*/
export class RegexpSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(regexp: string) {
super({
regexp: regexp,
})
}
field(field: string): RegexpSearchQuery {
this._data.field = field
return this
}
boost(boost: number): RegexpSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a query-string search query.
*
* @category Full Text Search
*/
export class QueryStringSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(query: string) {
super({
query: query,
})
}
boost(boost: number): QueryStringSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a numeric-range search query.
*
* @category Full Text Search
*/
export class NumericRangeSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor() {
super({})
}
min(min: number, inclusive?: boolean): NumericRangeSearchQuery {
if (inclusive === undefined) {
inclusive = true
}
this._data.min = min
this._data.inclusive_min = inclusive
return this
}
max(max: number, inclusive?: boolean): NumericRangeSearchQuery {
if (inclusive === undefined) {
inclusive = false
}
this._data.max = max
this._data.inclusive_max = inclusive
return this
}
field(field: string): NumericRangeSearchQuery {
this._data.field = field
return this
}
boost(boost: number): NumericRangeSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a date-range search query.
*
* @category Full Text Search
*/
export class DateRangeSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor() {
super({})
}
start(start: Date | string, inclusive?: boolean): DateRangeSearchQuery {
if (inclusive === undefined) {
inclusive = true
}
if (start instanceof Date) {
this._data.start = start.toISOString()
} else {
this._data.start = start
}
this._data.inclusive_start = inclusive
return this
}
end(end: Date | string, inclusive?: boolean): DateRangeSearchQuery {
if (inclusive === undefined) {
inclusive = false
}
if (end instanceof Date) {
this._data.end = end.toISOString()
} else {
this._data.end = end
}
this._data.inclusive_end = inclusive
return this
}
field(field: string): DateRangeSearchQuery {
this._data.field = field
return this
}
dateTimeParser(parser: string): DateRangeSearchQuery {
this._data.datetime_parser = parser
return this
}
boost(boost: number): DateRangeSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a conjunction search query.
*
* @category Full Text Search
*/
export class ConjunctionSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(...queries: SearchQuery[]) {
super({
conjuncts: [],
})
this.and(...queries)
}
/**
* Adds additional queries to this conjunction query.
*
* @deprecated Use the multi-argument overload instead.
*/
and(queries: SearchQuery[]): ConjunctionSearchQuery
/**
* Adds additional queries to this conjunction query.
*/
and(...queries: SearchQuery[]): ConjunctionSearchQuery
/**
* @internal
*/
and(...args: SearchQuery[] | SearchQuery[][]): ConjunctionSearchQuery {
const queries = _unpackListArgs(args)
for (let i = 0; i < queries.length; ++i) {
this._data.conjuncts.push(queries[i])
}
return this
}
boost(boost: number): ConjunctionSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a disjunction search query.
*
* @category Full Text Search
*/
export class DisjunctionSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(...queries: SearchQuery[]) {
super({
disjuncts: [],
})
this.or(...queries)
}
/**
* Adds additional queries to this disjunction query.
*
* @deprecated Use the multi-argument overload instead.
*/
or(queries: SearchQuery[]): DisjunctionSearchQuery
/**
* Adds additional queries to this disjunction query.
*/
or(...queries: SearchQuery[]): DisjunctionSearchQuery
/**
* @internal
*/
or(...args: SearchQuery[] | SearchQuery[][]): DisjunctionSearchQuery {
const queries = _unpackListArgs(args)
for (let i = 0; i < queries.length; ++i) {
this._data.disjuncts.push(queries[i])
}
return this
}
boost(boost: number): DisjunctionSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a boolean search query.
*
* @category Full Text Search
*/
export class BooleanSearchQuery extends SearchQuery {
private _shouldMin: number | undefined
/**
* @internal
*/
constructor() {
super({})
this._shouldMin = undefined
}
must(query: ConjunctionSearchQuery): BooleanSearchQuery {
if (!SearchQuery.hasProp(query, 'conjuncts')) {
query = new ConjunctionSearchQuery(query)
}
this._data.must = query
return this
}
should(query: DisjunctionSearchQuery): BooleanSearchQuery {
if (!SearchQuery.hasProp(query, 'disjuncts')) {
query = new DisjunctionSearchQuery(query)
}
this._data.should = query
return this
}
mustNot(query: DisjunctionSearchQuery): BooleanSearchQuery {
if (!SearchQuery.hasProp(query, 'disjuncts')) {
query = new DisjunctionSearchQuery(query)
}
this._data.must_not = query
return this
}
shouldMin(shouldMin: number): BooleanSearchQuery {
this._shouldMin = shouldMin
return this
}
boost(boost: number): BooleanSearchQuery {
this._data.boost = boost
return this
}
toJSON(): any {
const out: any = {}
if (this._data.must) {
out.must = SearchQuery.toJSON(this._data.must)
}
if (this._data.should) {
out.should = SearchQuery.toJSON(this._data.should)
if (this._shouldMin) {
out.should.min = this._shouldMin
}
}
if (this._data.must_not) {
out.must_not = SearchQuery.toJSON(this._data.must_not)
}
return out
}
}
/**
* Represents a wildcard search query.
*
* @category Full Text Search
*/
export class WildcardSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(wildcard: string) {
super({
wildcard: wildcard,
})
}
field(field: string): WildcardSearchQuery {
this._data.field = field
return this
}
boost(boost: number): WildcardSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a document-id search query.
*
* @category Full Text Search
*/
export class DocIdSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(...ids: string[]) {
super({
ids: [],
})
this.addDocIds(...ids)
}
/**
* Adds additional document-id's to this query.
*
* @deprecated Use the multi-argument overload instead.
*/
addDocIds(ids: string[]): DocIdSearchQuery
/**
* Adds additional document-id's to this query.
*/
addDocIds(...ids: string[]): DocIdSearchQuery
/**
* @internal
*/
addDocIds(...args: string[] | string[][]): DocIdSearchQuery {
const ids = _unpackListArgs(args)
for (let i = 0; i < ids.length; ++i) {
this._data.ids.push(ids[i])
}
return this
}
field(field: string): DocIdSearchQuery {
this._data.field = field
return this
}
boost(boost: number): DocIdSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a boolean-field search query.
*
* @category Full Text Search
*/
export class BooleanFieldSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(val: boolean) {
super({
bool: val,
})
}
field(field: string): BooleanFieldSearchQuery {
this._data.field = field
return this
}
boost(boost: number): BooleanFieldSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a term search query.
*
* @category Full Text Search
*/
export class TermSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(term: string) {
super({
term: term,
})
}
field(field: string): TermSearchQuery {
this._data.field = field
return this
}
prefixLength(prefixLength: number): TermSearchQuery {
this._data.prefix_length = prefixLength
return this
}
fuzziness(fuzziness: number): TermSearchQuery {
this._data.fuzziness = fuzziness
return this
}
boost(boost: number): TermSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a phrase search query.
*
* @category Full Text Search
*/
export class PhraseSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(terms: string[]) {
super({
terms: terms,
})
}
field(field: string): PhraseSearchQuery {
this._data.field = field
return this
}
boost(boost: number): PhraseSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a prefix search query.
*
* @category Full Text Search
*/
export class PrefixSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(prefix: string) {
super({
prefix: prefix,
})
}
field(field: string): PrefixSearchQuery {
this._data.field = field
return this
}
boost(boost: number): PrefixSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a match-all search query.
*
* @category Full Text Search
*/
export class MatchAllSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor() {
super({
match_all: null,
})
}
}
/**
* Represents a match-none search query.
*
* @category Full Text Search
*/
export class MatchNoneSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor() {
super({
match_none: true,
})
}
}
/**
* Represents a geo-distance search query.
*
* @category Full Text Search
*/
export class GeoDistanceSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(lon: number, lat: number, distance: number) {
super({
location: [lon, lat],
distance: distance,
})
}
field(field: string): GeoDistanceSearchQuery {
this._data.field = field
return this
}
boost(boost: number): GeoDistanceSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a geo-bounding-box search query.
*
* @category Full Text Search
*/
export class GeoBoundingBoxSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(tl_lon: number, tl_lat: number, br_lon: number, br_lat: number) {
super({
top_left: [tl_lon, tl_lat],
bottom_right: [br_lon, br_lat],
})
}
field(field: string): GeoBoundingBoxSearchQuery {
this._data.field = field
return this
}
boost(boost: number): GeoBoundingBoxSearchQuery {
this._data.boost = boost
return this
}
}
/**
* Represents a geo-polygon search query.
*
* @category Full Text Search
*/
export class GeoPolygonSearchQuery extends SearchQuery {
/**
* @internal
*/
constructor(points: GeoPoint[]) {
const mappedPoints = points.map((v) => _parseGeoPoint(v))
super({
polygon_points: mappedPoints,
})
}
field(field: string): GeoPolygonSearchQuery {
this._data.field = field
return this
}
boost(boost: number): GeoPolygonSearchQuery {
this._data.boost = boost
return this
}
} | the_stack |
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import { assert, expect } from "chai";
import { BigNumber, BigNumberish, ethers } from "ethers";
import {
AuctionAlreadyStartedError,
ListingNotFoundError,
WrongListingTypeError,
} from "../src/common/error";
import { NATIVE_TOKEN_ADDRESS } from "../src/constants/currency";
import { ListingType } from "../src/enums/marketplace";
import { Edition, Marketplace, NFTCollection, Token } from "../src/contracts";
import { AuctionListing, DirectListing, Offer } from "../src/types/marketplace";
import {
expectError,
fastForwardTime,
jsonProvider,
sdk,
signers,
} from "./before-setup";
import { isWinningBid } from "../src/common/marketplace";
import { ethers as hardhatEthers } from "hardhat";
global.fetch = require("cross-fetch");
let tokenAddress = NATIVE_TOKEN_ADDRESS;
/**
* Throughout these tests, the admin wallet will be the deployer
* and lister of all listings.
*
* Bog and Sam and Abby wallets will be used for direct listings and auctions.
*/
describe("Marketplace Contract", async () => {
let marketplaceContract: Marketplace;
let dummyNftContract: NFTCollection;
let dummyBundleContract: Edition;
let customTokenContract: Token;
let adminWallet: SignerWithAddress,
samWallet: SignerWithAddress,
abbyWallet: SignerWithAddress,
bobWallet: SignerWithAddress,
w1: SignerWithAddress,
w2: SignerWithAddress,
w3: SignerWithAddress,
w4: SignerWithAddress;
beforeEach(async () => {
await jsonProvider.send("hardhat_reset", []);
[adminWallet, samWallet, bobWallet, abbyWallet, w1, w2, w3, w4] = signers;
await sdk.updateSignerOrProvider(adminWallet);
marketplaceContract = sdk.getMarketplace(
await sdk.deployer.deployBuiltInContract(Marketplace.contractType, {
name: "Test Marketplace",
seller_fee_basis_points: 0,
}),
);
dummyNftContract = sdk.getNFTCollection(
await sdk.deployer.deployBuiltInContract(NFTCollection.contractType, {
name: "TEST NFT",
seller_fee_basis_points: 200,
fee_recipient: adminWallet.address,
primary_sale_recipient: adminWallet.address,
}),
);
await dummyNftContract.mintBatch([
{
name: "Test 0",
},
{
name: "Test 2",
},
{
name: "Test 3",
},
{
name: "Test 4",
},
]);
dummyBundleContract = sdk.getEdition(
await sdk.deployer.deployBuiltInContract(Edition.contractType, {
name: "TEST BUNDLE",
seller_fee_basis_points: 100,
primary_sale_recipient: adminWallet.address,
}),
);
await dummyBundleContract.mintBatch([
{
metadata: {
name: "Test 0",
},
supply: 100000,
},
{
metadata: {
name: "Test 1",
},
supply: 100000,
},
]);
customTokenContract = sdk.getToken(
await sdk.deployer.deployBuiltInContract(Token.contractType, {
name: "Test",
symbol: "TEST",
primary_sale_recipient: adminWallet.address,
}),
);
await customTokenContract.mintBatchTo([
{
toAddress: bobWallet.address,
amount: 1000,
},
{
toAddress: samWallet.address,
amount: 1000,
},
{
toAddress: adminWallet.address,
amount: 1000,
},
]);
tokenAddress = customTokenContract.getAddress();
});
const createDirectListing = async (
contractAddress: string,
tokenId: BigNumberish,
quantity: BigNumberish = 1,
): Promise<BigNumber> => {
return (
await marketplaceContract.direct.createListing({
assetContractAddress: contractAddress,
buyoutPricePerToken: 0.1,
currencyContractAddress: tokenAddress,
startTimestamp: new Date(0), // start date can be in the past
listingDurationInSeconds: 60 * 60 * 24,
tokenId,
quantity,
})
).id;
};
const createAuctionListing = async (
contractAddress: string,
tokenId: BigNumberish,
quantity: BigNumberish = 1,
startTime: Date = new Date(),
): Promise<BigNumber> => {
return (
await marketplaceContract.auction.createListing({
assetContractAddress: contractAddress,
buyoutPricePerToken: 0.1,
currencyContractAddress: tokenAddress,
startTimestamp: startTime,
listingDurationInSeconds: 60 * 60 * 24,
tokenId,
quantity,
reservePricePerToken: 0.05,
})
).id;
};
describe("Listing", () => {
it("should list direct listings with 721s", async () => {
const listingId = await createDirectListing(
dummyNftContract.getAddress(),
0,
);
assert.isDefined(listingId);
});
// TODO deploy WETH on hardhat
it.skip("should list acuction with native token", async () => {
const tx = await marketplaceContract.auction.createListing({
assetContractAddress: dummyNftContract.getAddress(),
buyoutPricePerToken: 1,
currencyContractAddress: NATIVE_TOKEN_ADDRESS,
startTimestamp: new Date(),
listingDurationInSeconds: 60 * 60 * 24,
tokenId: 0,
quantity: 1,
reservePricePerToken: 0.0001,
});
const id = tx.id;
sdk.updateSignerOrProvider(samWallet);
await marketplaceContract.auction.makeBid(id, 0.1);
});
it("should list direct listings with 1155s", async () => {
const listingId = await createDirectListing(
dummyBundleContract.getAddress(),
0,
10,
);
assert.isDefined(listingId);
});
it("should list auction listings with 721s", async () => {
const listingId = await createAuctionListing(
dummyNftContract.getAddress(),
0,
);
assert.isDefined(listingId);
});
it("should list auction listings with 1155s", async () => {
const listingId = await createAuctionListing(
dummyNftContract.getAddress(),
0,
10,
);
assert.isDefined(listingId);
});
it("should be able to restrict listing", async () => {
await marketplaceContract.allowListingFromSpecificAssetOnly(
dummyBundleContract.getAddress(),
);
const listingId = await createDirectListing(
dummyBundleContract.getAddress(),
0,
10,
);
assert.isDefined(listingId);
try {
await createDirectListing(dummyNftContract.getAddress(), 0, 10);
} catch (e) {
expectError(e, "!ASSET");
}
});
});
describe("Listing Filters", () => {
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
await createDirectListing(dummyNftContract.getAddress(), 0);
await createAuctionListing(dummyNftContract.getAddress(), 1);
await createDirectListing(dummyBundleContract.getAddress(), 0, 10);
await createAuctionListing(dummyBundleContract.getAddress(), 0, 10);
await dummyBundleContract.transfer(samWallet.address, "0", 10);
await dummyBundleContract.transfer(samWallet.address, "1", 10);
await sdk.updateSignerOrProvider(samWallet);
await createDirectListing(dummyBundleContract.getAddress(), 0, 10);
await createAuctionListing(dummyBundleContract.getAddress(), 1, 10);
});
it("should paginate properly", async () => {
const listings = await marketplaceContract.getAllListings({
start: 0,
count: 1,
});
assert.equal(listings.length, 1, "pagination doesn't work");
});
it("should filter sellers properly", async () => {
const listings = await marketplaceContract.getAllListings({
seller: adminWallet.address,
});
assert.equal(listings.length, 4, "filter doesn't work");
});
it("should filter asset contract properly", async () => {
const listings = await marketplaceContract.getAllListings({
tokenContract: dummyBundleContract.getAddress(),
});
assert.equal(listings.length, 4, "filter doesn't work");
});
it("should filter asset contract with token contract address properly", async () => {
const listings = await marketplaceContract.getAllListings({
tokenContract: dummyNftContract.getAddress(),
});
assert.equal(listings.length, 2, "filter doesn't work");
});
it("should filter asset contract with token id properly", async () => {
const listings0 = await marketplaceContract.getAllListings({
tokenId: 0,
});
assert.equal(listings0.length, 4, "filter doesn't work");
const listings1 = await marketplaceContract.getAllListings({
tokenId: 1,
});
assert.equal(listings1.length, 2, "filter doesn't work");
});
it("should filter asset contract with token contract and id properly", async () => {
const listings = await marketplaceContract.getAllListings({
tokenContract: dummyNftContract.getAddress(),
tokenId: 1,
});
assert.equal(listings.length, 1, "filter doesn't work");
});
});
describe("Get Listing", () => {
let directListingId: BigNumber;
let auctionListingId: BigNumber;
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
directListingId = await createDirectListing(
dummyNftContract.getAddress(),
0,
);
auctionListingId = await createAuctionListing(
dummyNftContract.getAddress(),
1,
);
});
it("should return only active listings", async () => {
const before = await marketplaceContract.getActiveListings();
expect(before.length).to.eq(1);
await sdk.updateSignerOrProvider(samWallet);
await marketplaceContract.buyoutListing(directListingId, 1);
const afterDirectBuyout = await marketplaceContract.getActiveListings();
expect(afterDirectBuyout.length).to.eq(0);
// TODO add test for buying out auctions too (needs time control)
});
it("should return an auction listing", async () => {
const listing = (await marketplaceContract.getListing(
auctionListingId,
)) as AuctionListing;
assert.equal(listing.type.toString(), ListingType.Auction.toString());
assert.equal(listing.tokenId.toString(), "1");
assert.equal(listing.asset.id.toString(), "1");
assert.equal(listing.asset.name, "Test 2");
});
it("should return an auction listing", async () => {
const listings = await marketplaceContract.getAllListings();
assert(listings.length > 0);
});
it("should return a direct listing", async () => {
const listing = (await marketplaceContract.getListing(
directListingId,
)) as DirectListing;
assert.equal(listing.type.toString(), ListingType.Direct.toString());
assert.equal(listing.tokenId.toString(), "0");
assert.equal(listing.asset.id.toString(), "0");
assert.equal(listing.asset.name, "Test 0");
});
it("should return a direct listing using getDirectListing", async () => {
const listing = await marketplaceContract.direct.getListing(
directListingId,
);
assert.equal(listing.type.toString(), ListingType.Direct.toString());
assert.equal(listing.tokenId.toString(), "0");
});
it("should return a direct listing using getAuctionListing", async () => {
const listing = await marketplaceContract.auction.getListing(
auctionListingId,
);
assert.equal(listing.type.toString(), ListingType.Auction.toString());
assert.equal(listing.tokenId.toString(), "1");
});
});
describe("Offers", () => {
let directListingId: BigNumber;
let auctionListingId: BigNumber;
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
directListingId = await createDirectListing(
dummyNftContract.getAddress(),
0,
10,
);
auctionListingId = await createAuctionListing(
dummyNftContract.getAddress(),
1,
);
});
it("should allow the seller to accept an offer", async () => {
await sdk.updateSignerOrProvider(bobWallet);
const currentBalance = await dummyNftContract.balanceOf(
bobWallet.address,
);
assert.equal(
currentBalance.toString(),
"0",
"The buyer should start with no tokens",
);
await marketplaceContract.direct.makeOffer(
directListingId,
10,
tokenAddress,
0.034,
new Date(Date.now() + 60 * 60 * 24 * 10 * 1000),
);
await sdk.updateSignerOrProvider(adminWallet);
await marketplaceContract.direct.acceptOffer(
directListingId,
bobWallet.address,
);
const balance = await dummyNftContract.balanceOf(bobWallet.address);
assert.equal(
balance.toString(),
"1",
"The buyer should have been awarded token",
);
});
it("should allow a buyer to buyout a direct listing", async () => {
await sdk.updateSignerOrProvider(bobWallet);
const currentBalance = await dummyNftContract.balanceOf(
bobWallet.address,
);
assert.equal(
currentBalance.toString(),
"0",
"The buyer should start with no tokens",
);
await marketplaceContract.buyoutListing(directListingId, 1);
const balance = await dummyNftContract.balanceOf(bobWallet.address);
assert.equal(
balance.toString(),
"1",
"The buyer should have been awarded token",
);
});
it("should allow a buyer to buyout a direct listing after making an offer", async () => {
await sdk.updateSignerOrProvider(bobWallet);
const currentBalance = await dummyNftContract.balanceOf(
bobWallet.address,
);
assert.equal(
currentBalance.toString(),
"0",
"The buyer should start with no tokens",
);
await marketplaceContract.direct.makeOffer(
directListingId,
1,
customTokenContract.getAddress(),
0.05,
);
await marketplaceContract.buyoutListing(directListingId, 1);
const balance = await dummyNftContract.balanceOf(bobWallet.address);
assert.equal(
balance.toString(),
"1",
"The buyer should have been awarded token",
);
});
it("should allow a buyer to buyout a direct listing for someone else", async () => {
await sdk.updateSignerOrProvider(bobWallet);
const currentBalance = await dummyNftContract.balanceOf(w4.address);
assert.equal(
currentBalance.toString(),
"0",
"The buyer should start with no tokens",
);
await marketplaceContract.buyoutListing(directListingId, 1, w4.address);
const balance = await dummyNftContract.balanceOf(w4.address);
assert.equal(
balance.toString(),
"1",
"The buyer should have been awarded token",
);
});
it("should allow offers to be made on direct listings", async () => {
sdk.updateSignerOrProvider(bobWallet);
await marketplaceContract.direct.makeOffer(
directListingId,
1,
tokenAddress,
"1",
);
const offer = (await marketplaceContract.direct.getActiveOffer(
directListingId,
bobWallet.address,
)) as Offer;
assert.equal(offer.buyerAddress, bobWallet.address);
assert.equal(
offer.pricePerToken.toString(),
ethers.utils.parseUnits("1").toString(),
);
assert.equal(offer.listingId.toString(), directListingId.toString());
sdk.updateSignerOrProvider(samWallet);
await marketplaceContract.direct.makeOffer(
directListingId,
1,
tokenAddress,
"1",
);
const secondOffer = (await marketplaceContract.direct.getActiveOffer(
directListingId,
samWallet.address,
)) as Offer;
assert.equal(secondOffer.buyerAddress, samWallet.address);
assert.equal(
offer.pricePerToken.toString(),
ethers.utils.parseUnits("1").toString(),
);
assert.equal(offer.listingId.toString(), directListingId.toString());
});
it("should return undefined when checking offers on an address that hasn't made any", async () => {
const offer = await marketplaceContract.direct.getActiveOffer(
directListingId,
adminWallet.address,
);
assert.isUndefined(offer);
});
it("should allow bids by the same person", async () => {
await sdk.updateSignerOrProvider(bobWallet);
await marketplaceContract.auction.makeBid(auctionListingId, 0.06);
await marketplaceContract.auction.makeBid(auctionListingId, 0.08);
const winningBid = (await marketplaceContract.auction.getWinningBid(
auctionListingId,
)) as Offer;
assert.equal(winningBid.buyerAddress, bobWallet.address);
assert.equal(
winningBid.pricePerToken.toString(),
ethers.utils.parseUnits("0.08").toString(),
);
});
it("should allow bids to be made on auction listings", async () => {
await sdk.updateSignerOrProvider(bobWallet);
await marketplaceContract.auction.makeBid(auctionListingId, 0.06);
let winningBid = (await marketplaceContract.auction.getWinningBid(
auctionListingId,
)) as Offer;
assert.equal(winningBid.buyerAddress, bobWallet.address);
assert.equal(
winningBid.pricePerToken.toString(),
ethers.utils.parseUnits("0.06").toString(),
);
assert.equal(
winningBid.listingId.toString(),
auctionListingId.toString(),
);
// Make a higher winning bid
await sdk.updateSignerOrProvider(samWallet);
await marketplaceContract.auction.makeBid(auctionListingId, 0.09);
winningBid = (await marketplaceContract.auction.getWinningBid(
auctionListingId,
)) as Offer;
assert.equal(winningBid.buyerAddress, samWallet.address);
assert.equal(
winningBid.pricePerToken.toString(),
ethers.utils.parseUnits("0.09").toString(),
);
assert.equal(
winningBid.listingId.toString(),
auctionListingId.toString(),
);
});
});
describe("Validators", () => {
let directListingId: BigNumber;
let auctionListingId: BigNumber;
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
directListingId = await createDirectListing(
dummyNftContract.getAddress(),
0,
);
auctionListingId = await createAuctionListing(
dummyNftContract.getAddress(),
1,
);
});
it("should throw an error trying to fetch a listing of the wrong type", async () => {
try {
await marketplaceContract.direct.getListing(auctionListingId);
assert.fail("Should have thrown an error");
} catch (err) {
if (!(err instanceof WrongListingTypeError)) {
throw err;
}
}
try {
await marketplaceContract.auction.getListing(directListingId);
assert.fail("Should have thrown an error");
} catch (err) {
if (!(err instanceof WrongListingTypeError)) {
throw err;
}
}
});
});
describe("Bidding", () => {
let auctionListingId: BigNumber;
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
auctionListingId = await createAuctionListing(
dummyNftContract.getAddress(),
1,
);
});
it("should automatically award a buyout", async () => {
await sdk.updateSignerOrProvider(bobWallet);
const currentBalance = await dummyNftContract.balanceOf(
bobWallet.address,
);
assert.equal(
currentBalance.toString(),
"0",
"The buyer should start with no tokens",
);
await marketplaceContract.auction.makeBid(auctionListingId, "20");
const balance = await dummyNftContract.balanceOf(bobWallet.address);
assert.equal(
balance.toString(),
"1",
"The buyer should have been awarded token",
);
});
// TODO: idk if a seller can close out an auction before the auction
// has ended and so the call to `acceptWinningBid` is failing on this
// test because the listing is still active.
it.skip("should allow the seller to accept the winning bid", async () => {
await sdk.updateSignerOrProvider(bobWallet);
const currentBalance = await dummyNftContract.balanceOf(
bobWallet.address,
);
assert.equal(
currentBalance.toString(),
"0",
"The buyer should start with no tokens",
);
await marketplaceContract.auction.makeBid(auctionListingId, "2");
const winningBid = (await marketplaceContract.auction.getWinningBid(
auctionListingId,
)) as Offer;
assert.equal(
winningBid.buyerAddress,
bobWallet.address,
"Bob should be the winning bidder",
);
await sdk.updateSignerOrProvider(bobWallet);
await marketplaceContract.auction.closeListing(auctionListingId);
const balance = await dummyNftContract.balanceOf(bobWallet.address);
assert.equal(
balance.toString(),
"1",
"The buyer should have been awarded token",
);
// TODO: write test for calling closeAuctionListing with sellers wallet
});
it("should throw an error if a bid being placed is not a winning bid", async () => {
await sdk.updateSignerOrProvider(bobWallet);
const currentBalance = await dummyNftContract.balanceOf(
bobWallet.address,
);
assert.equal(
currentBalance.toString(),
"0",
"The buyer should start with no tokens",
);
await marketplaceContract.auction.makeBid(auctionListingId, "2");
try {
await marketplaceContract.auction.makeBid(auctionListingId, "2.01");
// eslint-disable-next-line no-empty
} catch (err) {}
});
it("should allow an auction buyout", async () => {
const id = (
await marketplaceContract.auction.createListing({
assetContractAddress: dummyBundleContract.getAddress(),
buyoutPricePerToken: 0.8,
currencyContractAddress: tokenAddress,
// to start tomorrow so we can update it
startTimestamp: new Date(),
listingDurationInSeconds: 60 * 60 * 24,
tokenId: "1",
quantity: 2,
reservePricePerToken: 0.2,
})
).id;
await sdk.updateSignerOrProvider(bobWallet);
await marketplaceContract.buyoutListing(id);
const balance = await dummyBundleContract.balanceOf(
bobWallet.address,
"1",
);
assert.equal(balance.toString(), "2", "The buyer should have 2 tokens");
});
});
describe("Closing listings", () => {
let directListingId: BigNumber;
let auctionListingId: BigNumber;
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
directListingId = await createDirectListing(
dummyNftContract.getAddress(),
0,
);
auctionListingId = await createAuctionListing(
dummyNftContract.getAddress(),
1,
);
});
it("should allow a seller to close an auction that hasn't started yet", async () => {
const id = (
await marketplaceContract.auction.createListing({
assetContractAddress: dummyNftContract.getAddress(),
buyoutPricePerToken: 0.1,
currencyContractAddress: tokenAddress,
// to start tomorrow so we can update it
startTimestamp: new Date(),
listingDurationInSeconds: 60 * 60 * 24,
tokenId: "0",
quantity: 1,
reservePricePerToken: 0.05,
})
).id;
await marketplaceContract.auction.cancelListing(id);
try {
await marketplaceContract.auction.getListing(id);
} catch (err) {
if (!(err instanceof ListingNotFoundError)) {
throw err;
}
}
});
it("should not throw an error when trying to close an auction that already started (no bids)", async () => {
await marketplaceContract.auction.cancelListing(auctionListingId);
});
it("should throw an error when trying to close an auction that already started (with bids)", async () => {
await marketplaceContract.auction.makeBid(auctionListingId, 0.06);
try {
await marketplaceContract.auction.cancelListing(auctionListingId);
assert.fail("should have thrown an error");
} catch (err: any) {
if (
!(err instanceof AuctionAlreadyStartedError) &&
!(err.message as string).includes(
"cannot close auction before it has ended",
)
) {
throw err;
}
}
});
it("should correctly close a direct listing", async () => {
const listing = await marketplaceContract.direct.getListing(
directListingId,
);
assert.equal(listing.quantity.toString(), "1");
await marketplaceContract.direct.cancelListing(directListingId);
try {
await marketplaceContract.direct.getListing(directListingId);
} catch (e) {
if (!(e instanceof ListingNotFoundError)) {
throw e;
}
}
});
// Skipping until decision is made on this:
// https://github.com/nftlabs/nftlabs-sdk-ts/issues/119#issuecomment-1003199128
it.skip("should allow the seller to cancel an auction that has started as long as there are no active bids", async () => {
const startTime = new Date();
const listingId = await createAuctionListing(
dummyNftContract.getAddress(),
2,
1,
startTime,
);
await marketplaceContract.auction.getListing(listingId);
await marketplaceContract.auction.getWinningBid(listingId);
try {
await marketplaceContract.auction.cancelListing(auctionListingId);
// eslint-disable-next-line no-empty
} catch (err) {
console.error("failed to cancel listing", err);
assert.fail(
"The seller should be able to cancel the auction if there are no active bids",
);
}
});
it("should distribute the tokens when a listing closes", async () => {
await sdk.updateSignerOrProvider(adminWallet);
const listingId = (
await marketplaceContract.auction.createListing({
assetContractAddress: dummyNftContract.getAddress(),
buyoutPricePerToken: 10,
currencyContractAddress: tokenAddress,
startTimestamp: new Date(),
listingDurationInSeconds: 60 * 60,
tokenId: "2",
quantity: "1",
reservePricePerToken: 1,
})
).id;
await sdk.updateSignerOrProvider(bobWallet);
await marketplaceContract.auction.makeBid(listingId, 2);
await fastForwardTime(60 * 60 * 24);
/**
* Buyer
*/
const oldBalance = await dummyNftContract.balanceOf(bobWallet.address);
assert.equal(
oldBalance.toString(),
"0",
"The buyer should have no tokens to start",
);
await marketplaceContract.auction.closeListing(listingId);
const balance = await dummyNftContract.balanceOf(bobWallet.address);
assert.equal(
balance.toString(),
"1",
"The buyer should have been awarded token",
);
/**
* Seller
*/
await sdk.updateSignerOrProvider(adminWallet);
const oldTokenBalance = await customTokenContract.balanceOf(
adminWallet.address,
);
assert.deepEqual(
oldTokenBalance.value,
ethers.utils.parseUnits("1000"),
"The buyer should have 1000 tokens to start",
);
await marketplaceContract.auction.closeListing(listingId);
const newTokenBalance = await customTokenContract.balanceOf(
adminWallet.address,
);
assert.deepEqual(
newTokenBalance.value,
ethers.utils
.parseUnits("1000")
// eslint-disable-next-line line-comment-position
.add(ethers.utils.parseUnits("2.00")), // 2% taken out for royalties
// TODO read the fee from the TWFee contract
"The buyer should have two additional tokens after the listing closes",
);
});
});
describe("Updating listings", () => {
let directListingId: BigNumber;
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
directListingId = await createDirectListing(
dummyNftContract.getAddress(),
0,
);
});
it("should allow you to update a direct listing", async () => {
const buyoutPrice = ethers.utils.parseUnits("0.1");
const directListing = await marketplaceContract.direct.getListing(
directListingId,
);
assert.equal(
directListing.buyoutPrice.toString(),
buyoutPrice.toString(),
);
directListing.buyoutPrice = ethers.utils.parseUnits("20");
const block = await hardhatEthers.provider.getBlock("latest");
directListing.startTimeInSeconds = block.timestamp;
await marketplaceContract.direct.updateListing(directListing);
const updatedListing = await marketplaceContract.direct.getListing(
directListingId,
);
assert.equal(
updatedListing.buyoutPrice.toString(),
ethers.utils.parseUnits("20").toString(),
);
});
it("should allow you to update an auction listing", async () => {
const buyoutPrice = ethers.utils.parseUnits("10");
const id = (
await marketplaceContract.auction.createListing({
assetContractAddress: dummyNftContract.getAddress(),
buyoutPricePerToken: 10,
currencyContractAddress: tokenAddress,
// to start tomorrow so we can update it
startTimestamp: new Date(Date.now() + 24 * 60 * 60 * 100000),
listingDurationInSeconds: 60 * 60 * 24,
tokenId: "0",
quantity: 1,
reservePricePerToken: 1,
})
).id;
const auctionListing = await marketplaceContract.auction.getListing(id);
assert.equal(
auctionListing.buyoutPrice.toString(),
buyoutPrice.toString(),
);
auctionListing.buyoutPrice = ethers.utils.parseUnits("9");
await marketplaceContract.auction.updateListing(auctionListing);
const updatedListing = await marketplaceContract.auction.getListing(id);
assert.equal(
updatedListing.buyoutPrice.toString(),
ethers.utils.parseUnits("9").toString(),
);
});
});
describe("Utils", async () => {
// TODO rewrite this test to actually try to place bids
it("should return the correct bid buffer rules", async () => {
const testCases: {
winningBid: BigNumberish;
newBid: BigNumberish;
buffer: BigNumberish;
valid: boolean;
}[] = [
{
winningBid: 10,
newBid: 12,
buffer: 500,
valid: true,
},
{
winningBid: 100,
newBid: 101,
buffer: 500,
valid: false,
},
{
winningBid: 10,
newBid: 12,
buffer: 1000,
valid: true,
},
{
winningBid: 10,
newBid: 15,
buffer: 5001,
valid: false,
},
{
winningBid: 10,
newBid: 15,
buffer: 4999,
valid: true,
},
{
winningBid: 10,
newBid: 9,
buffer: 1000,
valid: false,
},
];
for (const testCase of testCases) {
const result = isWinningBid(
testCase.winningBid,
testCase.newBid,
testCase.buffer,
);
assert.equal(
result,
testCase.valid,
`should be valid: ${JSON.stringify(testCase)}`,
);
}
});
});
describe("Buffers", () => {
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
});
it("should set the correct bid buffer default of 15 minutes", async () => {
const buffer = await marketplaceContract.getTimeBufferInSeconds();
assert.equal(buffer.toNumber(), 15 * 60);
});
it("should set the correct time buffer default of 500 bps", async () => {
const buffer = await marketplaceContract.getBidBufferBps();
assert.equal(buffer.toNumber(), 500);
});
it("should allow you to set the bid buffer", async () => {
await marketplaceContract.setBidBufferBps(1000);
const buffer = await marketplaceContract.getBidBufferBps();
assert.equal(buffer.toNumber(), 1000);
});
it("should allow you to set the time buffer", async () => {
await marketplaceContract.setTimeBufferInSeconds(1000);
const buffer = await marketplaceContract.getTimeBufferInSeconds();
assert.equal(buffer.toNumber(), 1000);
});
});
describe("Invalid Listings", () => {
let directListingId: BigNumber;
beforeEach(async () => {
await sdk.updateSignerOrProvider(adminWallet);
directListingId = await createDirectListing(
dummyNftContract.getAddress(),
0,
);
});
it("should throw an error when trying to buyout an invalid direct listing", async () => {
await sdk.updateSignerOrProvider(adminWallet);
await dummyNftContract.transfer(samWallet.address, "0");
await sdk.updateSignerOrProvider(bobWallet);
try {
await marketplaceContract.direct.buyoutListing(directListingId, 1);
assert.fail("should have thrown");
} catch (err: any) {
console.error(err);
}
});
it("should not return invalid direct listings", async () => {
await sdk.updateSignerOrProvider(adminWallet);
await dummyNftContract.transfer(samWallet.address, "0");
const allListings = await marketplaceContract.getAllListings();
const found = allListings.find(
(l) => l.id.toString() === directListingId.toString(),
);
assert.isUndefined(
found,
"should not have found the listing becuase it is invalid",
);
});
});
}); | the_stack |
import { FocusMonitor } from '@angular/cdk/a11y';
import { DOWN_ARROW, ESCAPE, LEFT_ARROW, RIGHT_ARROW, TAB } from '@angular/cdk/keycodes';
import { OverlayContainer } from '@angular/cdk/overlay';
import { Component, ElementRef, QueryList, Type, ViewChild, ViewChildren } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import {
createKeyboardEvent,
createMouseEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
fastTestSetup,
patchElementFocus,
} from '../../../../test/helpers';
import { MenuItemComponent } from './menu-item.component';
import { MenuTriggerDirective } from './menu-trigger.directive';
import { MenuComponent } from './menu.component';
import { MenuModule } from './menu.module';
describe('browser.ui.menu', () => {
let overlayContainer: OverlayContainer;
let overlayContainerElement: HTMLElement;
let focusMonitor: FocusMonitor;
function createFixture<T>(component: Type<T>): ComponentFixture<T> {
return TestBed.createComponent(component);
}
fastTestSetup();
beforeAll(async () => {
await TestBed
.configureTestingModule({
imports: [
MenuModule,
NoopAnimationsModule,
],
declarations: [
SimpleMenuComponent,
NestedMenuComponent,
],
})
.compileComponents();
});
beforeEach(() => {
overlayContainer = TestBed.get(OverlayContainer);
overlayContainerElement = overlayContainer.getContainerElement();
focusMonitor = TestBed.get(FocusMonitor);
});
afterEach(() => {
const currentOverlayContainer = TestBed.get(OverlayContainer);
// Since we're resetting the testing module in some of the tests,
// we can potentially have multiple overlay containers.
currentOverlayContainer.ngOnDestroy();
overlayContainer.ngOnDestroy();
});
it('should open the menu as an idempotent operation', () => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
expect(() => {
fixture.componentInstance.trigger.openMenu();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('Item');
expect(overlayContainerElement.textContent).toContain('Disabled');
}).not.toThrowError();
});
it('should close the menu when a click occurs outside the menu', fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
const backdrop = <HTMLElement>overlayContainerElement.querySelector('.cdk-overlay-backdrop');
backdrop.click();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should restore focus to the trigger when the menu was opened by keyboard', fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
// A click without a mousedown before it is considered a keyboard open.
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.Menu')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(triggerEl);
}));
it('should restore focus to the root trigger when the menu was opened by mouse', fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.Menu')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(triggerEl);
}));
it('should scroll the panel to the top on open, when it is scrollable', fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
// Add 50 items to make the menu scrollable
fixture.componentInstance.extraItems = new Array(50).fill('Hello there');
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
// Flush due to the additional tick that is necessary for the FocusMonitor.
flush();
expect(overlayContainerElement.querySelector('.Menu').scrollTop).toBe(0);
}));
it(
'should set the proper focus origin when restoring focus after opening by keyboard',
fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
triggerEl.click(); // A click without a mousedown before it is considered a keyboard open.
fixture.detectChanges();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-program-focused');
focusMonitor.stopMonitoring(triggerEl);
}),
);
it(
'should set the proper focus origin when restoring focus after opening by mouse',
fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchMouseEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-mouse-focused');
focusMonitor.stopMonitoring(triggerEl);
}),
);
it(
'should set proper focus origin when right clicking on trigger, before opening by keyboard',
fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
// Trigger a fake right click.
dispatchEvent(triggerEl, createMouseEvent('mousedown', 50, 100, 2));
// A click without a left button mousedown before it is considered a keyboard open.
triggerEl.click();
fixture.detectChanges();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-program-focused');
focusMonitor.stopMonitoring(triggerEl);
}),
);
it('should close the menu when pressing ESCAPE', fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
const panel = overlayContainerElement.querySelector('.Menu');
const event = createKeyboardEvent('keydown', ESCAPE);
dispatchEvent(panel, event);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should transfer any custom classes from the host to the overlay', () => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const menuEl = fixture.debugElement.query(By.css('gd-menu')).nativeElement;
const panel = overlayContainerElement.querySelector('.Menu');
expect(menuEl.classList).not.toContain('custom-one');
expect(menuEl.classList).not.toContain('custom-two');
expect(panel.classList).toContain('custom-one');
expect(panel.classList).toContain('custom-two');
});
it('should set the "menu" role on the overlay panel', () => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const menuPanel = overlayContainerElement.querySelector('.Menu');
expect(menuPanel).toBeTruthy('Expected to find a menu panel.');
const role = menuPanel ? menuPanel.getAttribute('role') : '';
expect(role).toBe('menu', 'Expected panel to have the "menu" role.');
});
it('should not throw an error on destroy', () => {
const fixture = createFixture(SimpleMenuComponent);
expect(fixture.destroy.bind(fixture)).not.toThrow();
});
it('should be able to extract the menu item text', () => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
expect(fixture.componentInstance.items.first.getLabel()).toBe('Item');
});
it('should filter out non-text nodes when figuring out the label', () => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
expect(fixture.componentInstance.items.last.getLabel()).toBe('Item with an icon');
});
it('should set the proper focus origin when opening by mouse', fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
spyOn(fixture.componentInstance.items.first, 'focus').and.callThrough();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchMouseEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.items.first.focus).toHaveBeenCalledWith('mouse');
}));
it(
'should switch to keyboard focus when using the keyboard after opening using the mouse',
fakeAsync(() => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
fixture.componentInstance.triggerEl.nativeElement.click();
fixture.detectChanges();
const panel = document.querySelector('.Menu') as HTMLElement;
const items: HTMLElement[] = Array.from(panel.querySelectorAll('.Menu [gd-menu-item]'));
items.forEach(item => patchElementFocus(item));
tick(500);
tick();
fixture.detectChanges();
expect(items.some(item => item.classList.contains('cdk-keyboard-focused'))).toBe(false);
dispatchKeyboardEvent(panel, 'keydown', DOWN_ARROW);
fixture.detectChanges();
// Flush due to the additional tick that is necessary for the FocusMonitor.
flush();
// We skip to the third item, because the second one is disabled.
expect(items[2].classList).toContain('cdk-focused');
expect(items[2].classList).toContain('cdk-keyboard-focused');
}),
);
it('should toggle the aria-expanded attribute on the trigger', () => {
const fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
expect(triggerEl.hasAttribute('aria-expanded')).toBe(false);
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
expect(triggerEl.getAttribute('aria-expanded')).toBe('true');
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
expect(triggerEl.hasAttribute('aria-expanded')).toBe(false);
});
describe('close event', () => {
let fixture: ComponentFixture<SimpleMenuComponent>;
beforeEach(() => {
fixture = createFixture(SimpleMenuComponent);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
});
it('should emit an event when a menu item is clicked', () => {
const menuItem = overlayContainerElement.querySelector('[gd-menu-item]') as HTMLElement;
menuItem.click();
fixture.detectChanges();
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('click');
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
});
it('should emit a close event when the backdrop is clicked', () => {
const backdrop = overlayContainerElement
.querySelector('.cdk-overlay-backdrop') as HTMLElement;
backdrop.click();
fixture.detectChanges();
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith(undefined);
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
});
it('should emit an event when pressing ESCAPE', () => {
const menu = overlayContainerElement.querySelector('.Menu') as HTMLElement;
dispatchKeyboardEvent(menu, 'keydown', ESCAPE);
fixture.detectChanges();
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('keydown');
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
});
it('should complete the callback when the menu is destroyed', () => {
const emitCallback = jasmine.createSpy('emit callback');
const completeCallback = jasmine.createSpy('complete callback');
fixture.componentInstance.menu.closed.subscribe(emitCallback, null, completeCallback);
fixture.destroy();
expect(emitCallback).toHaveBeenCalledWith(undefined);
expect(emitCallback).toHaveBeenCalledTimes(1);
expect(completeCallback).toHaveBeenCalled();
});
});
describe('nested menu', () => {
let fixture: ComponentFixture<NestedMenuComponent>;
let instance: NestedMenuComponent;
let overlay: HTMLElement;
const compileTestComponent = () => {
fixture = createFixture(NestedMenuComponent);
fixture.detectChanges();
instance = fixture.componentInstance;
overlay = overlayContainerElement;
};
it('should set the `triggersSubmenu` flags on the triggers', () => {
compileTestComponent();
expect(instance.rootTrigger.triggersSubmenu()).toBe(false);
expect(instance.levelOneTrigger.triggersSubmenu()).toBe(true);
expect(instance.levelTwoTrigger.triggersSubmenu()).toBe(true);
});
it('should set the `parentMenu` on the sub-menu instances', () => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
expect(instance.rootMenu.parentMenu).toBeFalsy();
expect(instance.levelOneMenu.parentMenu).toBe(instance.rootMenu);
expect(instance.levelTwoMenu.parentMenu).toBe(instance.levelOneMenu);
});
it('should emit an event when the hover state of the menu items changes', () => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
const spy = jasmine.createSpy('hover spy');
const subscription = instance.rootMenu._hovered().subscribe(spy);
const menuItems = overlay.querySelectorAll('[gd-menu-item]');
dispatchMouseEvent(menuItems[0], 'mouseenter');
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
dispatchMouseEvent(menuItems[1], 'mouseenter');
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(2);
subscription.unsubscribe();
});
it('should toggle a nested menu when its trigger is hovered', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length).toBe(1, 'Expected one open menu');
const items = Array.from(overlay.querySelectorAll('.Menu [gd-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger');
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(levelOneTrigger.classList)
.toContain('MenuItem--highlighted', 'Expected the trigger to be highlighted');
expect(overlay.querySelectorAll('.Menu').length).toBe(2, 'Expected two open menus');
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length).toBe(1, 'Expected one open menu');
expect(levelOneTrigger.classList)
.not.toContain('mat-menu-item-highlighted', 'Expected the trigger to not be highlighted');
}));
it(
'should close all the open sub-menus when the hover state is changed at the root',
fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
const items = Array.from(overlay.querySelectorAll('.Menu [gd-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger');
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
tick();
const levelTwoTrigger = overlay.querySelector('#level-two-trigger') as HTMLElement;
dispatchMouseEvent(levelTwoTrigger, 'mouseenter');
fixture.detectChanges();
tick();
expect(overlay.querySelectorAll('.Menu').length)
.toBe(3, 'Expected three open menus');
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length)
.toBe(1, 'Expected one open menu');
}),
);
it('should close submenu when hovering over disabled sibling item', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
const items = fixture.debugElement.queryAll(By.directive(MenuItemComponent));
dispatchFakeEvent(items[0].nativeElement, 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length)
.toBe(2, 'Expected two open menus');
items[1].componentInstance.disabled = true;
fixture.detectChanges();
// Invoke the handler directly since the fake events are flaky on disabled elements.
items[1].componentInstance._handleMouseEnter();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length)
.toBe(1, 'Expected one open menu');
}));
it('should not open submenu when hovering over disabled trigger', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length)
.toBe(1, 'Expected one open menu');
const item = fixture.debugElement.query(By.directive(MenuItemComponent));
item.componentInstance.disabled = true;
fixture.detectChanges();
// Invoke the handler directly since the fake events are flaky on disabled elements.
item.componentInstance._handleMouseEnter();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length)
.toBe(1, 'Expected to remain at one open menu');
}));
it('should open a nested menu when its trigger is clicked', () => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length).toBe(1, 'Expected one open menu');
const levelOneTrigger = overlay.querySelector('#level-one-trigger') as HTMLElement;
levelOneTrigger.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length).toBe(2, 'Expected two open menus');
levelOneTrigger.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length)
.toBe(2, 'Expected repeat clicks not to close the menu.');
});
it('should open and close a nested menu with arrow keys in ltr', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length).toBe(1, 'Expected one open menu');
const levelOneTrigger = overlay.querySelector('#level-one-trigger') as HTMLElement;
dispatchKeyboardEvent(levelOneTrigger, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
const panels = overlay.querySelectorAll('.Menu');
expect(panels.length).toBe(2, 'Expected two open menus');
dispatchKeyboardEvent(panels[1], 'keydown', LEFT_ARROW);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length).toBe(1);
}));
it('should not do anything with the arrow keys for a top-level menu', () => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
const menu = overlay.querySelector('.Menu');
dispatchKeyboardEvent(menu, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length)
.toBe(1, 'Expected one menu to remain open');
dispatchKeyboardEvent(menu, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length)
.toBe(1, 'Expected one menu to remain open');
});
it('should close all of the menus when the backdrop is clicked', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu').length)
.toBe(3, 'Expected three open menus');
expect(overlay.querySelectorAll('.cdk-overlay-backdrop').length)
.toBe(1, 'Expected one backdrop element');
expect(overlay.querySelectorAll('.Menu, .cdk-overlay-backdrop')[0].classList)
.toContain('cdk-overlay-backdrop', 'Expected backdrop to be beneath all of the menus');
(overlay.querySelector('.cdk-overlay-backdrop') as HTMLElement).click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length).toBe(0, 'Expected no open menus');
}));
it('should shift focus between the sub-menus', () => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
expect(overlay.querySelector('.Menu').contains(document.activeElement))
.toBe(true, 'Expected focus to be inside the root menu');
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu')[1].contains(document.activeElement))
.toBe(true, 'Expected focus to be inside the first nested menu');
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu')[2].contains(document.activeElement))
.toBe(true, 'Expected focus to be inside the second nested menu');
instance.levelTwoTrigger.closeMenu();
fixture.detectChanges();
expect(overlay.querySelectorAll('.Menu')[1].contains(document.activeElement))
.toBe(true, 'Expected focus to be back inside the first nested menu');
instance.levelOneTrigger.closeMenu();
fixture.detectChanges();
expect(overlay.querySelector('.Menu').contains(document.activeElement))
.toBe(true, 'Expected focus to be back inside the root menu');
});
it('should close all of the menus when an item is clicked', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
const menus = overlay.querySelectorAll('.Menu');
expect(menus.length).toBe(3, 'Expected three open menus');
(menus[2].querySelector('.MenuItem') as HTMLElement).click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length).toBe(0, 'Expected no open menus');
}));
it('should close all of the menus when the user tabs away', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
const menus = overlay.querySelectorAll('.Menu');
expect(menus.length).toBe(3, 'Expected three open menus');
dispatchKeyboardEvent(menus[menus.length - 1], 'keydown', TAB);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length).toBe(0, 'Expected no open menus');
}));
it('should set a class on the menu items that trigger a sub-menu', () => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
const menuItems = overlay.querySelectorAll('[gd-menu-item]');
expect(menuItems[0].classList).toContain('MenuItem--submenuTrigger');
expect(menuItems[1].classList).not.toContain('MenuItem--submenuTrigger');
});
it('should close all of the menus when the root is closed programmatically', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
const menus = overlay.querySelectorAll('.Menu');
expect(menus.length).toBe(3, 'Expected three open menus');
instance.rootTrigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.Menu').length).toBe(0, 'Expected no open menus');
}));
it('should prevent the default mousedown action if the menu item opens a sub-menu', () => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
const event = createMouseEvent('mousedown');
Object.defineProperty(event, 'buttons', { get: () => 1 });
event.preventDefault = jasmine.createSpy('preventDefault spy');
dispatchMouseEvent(overlay.querySelector('[gd-menu-item]'), 'mousedown', 0, 0, event);
expect(event.preventDefault).toHaveBeenCalled();
});
it('should not re-focus a child menu trigger when hovering another trigger', fakeAsync(() => {
compileTestComponent();
dispatchFakeEvent(instance.rootTriggerEl.nativeElement, 'mousedown');
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
const items = Array.from(overlay.querySelectorAll('.Menu [gd-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger');
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
tick();
expect(overlay.querySelectorAll('.Menu').length).toBe(2, 'Expected two open menus');
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(document.activeElement)
.not.toBe(levelOneTrigger, 'Expected focus not to be returned to the initial trigger.');
}));
});
});
@Component({
template: `
<button [gdMenuTrigger]="menu" #triggerEl>Toggle menu</button>
<gd-menu
#menu="gdMenu"
class="custom-one custom-two"
(closed)="closeCallback($event)">
<button gd-menu-item> Item</button>
<button gd-menu-item disabled> Disabled</button>
<button gd-menu-item>
Item with an icon
</button>
<button *ngFor="let item of extraItems" gd-menu-item>{{item}}</button>
</gd-menu>
`,
})
class SimpleMenuComponent {
@ViewChild(MenuTriggerDirective) trigger: MenuTriggerDirective;
@ViewChild('triggerEl') triggerEl: ElementRef<HTMLElement>;
@ViewChild(MenuComponent) menu: MenuComponent;
@ViewChildren(MenuItemComponent) items: QueryList<MenuItemComponent>;
extraItems: string[] = [];
closeCallback = jasmine.createSpy('menu closed callback');
}
@Component({
template: `
<button
[gdMenuTrigger]="root"
#rootTrigger="gdMenuTrigger"
#rootTriggerEl>
Toggle menu
</button>
<button
[gdMenuTrigger]="levelTwo"
#alternateTrigger="gdMenuTrigger">
Toggle alternate menu
</button>
<gd-menu #root="gdMenu" (closed)="rootCloseCallback($event)">
<button gd-menu-item
id="level-one-trigger"
[gdMenuTrigger]="levelOne"
#levelOneTrigger="gdMenuTrigger">
One
</button>
<button gd-menu-item>Two</button>
</gd-menu>
<gd-menu #levelOne="gdMenu" (closed)="levelOneCloseCallback($event)">
<button gd-menu-item>Four</button>
<button gd-menu-item
id="level-two-trigger"
[gdMenuTrigger]="levelTwo"
#levelTwoTrigger="gdMenuTrigger">
Five
</button>
<button gd-menu-item>Six</button>
</gd-menu>
<gd-menu #levelTwo="gdMenu" (closed)="levelTwoCloseCallback($event)">
<button gd-menu-item>Seven</button>
<button gd-menu-item>Eight</button>
<button gd-menu-item>Nine</button>
</gd-menu>
`,
})
class NestedMenuComponent {
@ViewChild('root') rootMenu: MenuComponent;
@ViewChild('rootTrigger') rootTrigger: MenuTriggerDirective;
@ViewChild('rootTriggerEl') rootTriggerEl: ElementRef<HTMLElement>;
@ViewChild('alternateTrigger') alternateTrigger: MenuTriggerDirective;
readonly rootCloseCallback = jasmine.createSpy('root menu closed callback');
@ViewChild('levelOne') levelOneMenu: MenuComponent;
@ViewChild('levelOneTrigger') levelOneTrigger: MenuTriggerDirective;
readonly levelOneCloseCallback = jasmine.createSpy('level one menu closed callback');
@ViewChild('levelTwo') levelTwoMenu: MenuComponent;
@ViewChild('levelTwoTrigger') levelTwoTrigger: MenuTriggerDirective;
readonly levelTwoCloseCallback = jasmine.createSpy('level one menu closed callback');
} | the_stack |
import { h, render } from 'preact';
import cx from 'classnames';
import RefinementList from '../../components/RefinementList/RefinementList';
import type {
HierarchicalMenuItem,
HierarchicalMenuConnectorParams,
HierarchicalMenuRenderState,
HierarchicalMenuWidgetDescription,
} from '../../connectors/hierarchical-menu/connectHierarchicalMenu';
import connectHierarchicalMenu from '../../connectors/hierarchical-menu/connectHierarchicalMenu';
import defaultTemplates from './defaultTemplates';
import type { PreparedTemplateProps } from '../../lib/utils/prepareTemplateProps';
import {
prepareTemplateProps,
getContainerNode,
createDocumentationMessageGenerator,
} from '../../lib/utils';
import type {
TransformItems,
Template,
WidgetFactory,
RendererOptions,
SortBy,
ComponentCSSClasses,
} from '../../types';
import { component } from '../../lib/suit';
const withUsage = createDocumentationMessageGenerator({
name: 'hierarchical-menu',
});
const suit = component('HierarchicalMenu');
type HierarchicalMenuTemplates = Partial<{
/**
* Item template, provided with `name`, `count`, `isRefined`, `url` data properties.
*/
item: Template<{
name: string;
count: number;
isRefined: boolean;
url: string;
}>;
/**
* Template used for the show more text, provided with `isShowingMore` data property.
*/
showMoreText: Template<{ isShowingMore: boolean }>;
}>;
export type HierarchicalMenuCSSClasses = Partial<{
/**
* CSS class to add to the root element.
*/
root: string | string[];
/**
* CSS class to add to the root element when no refinements.
*/
noRefinementRoot: string | string[];
/**
* CSS class to add to the list element.
*/
list: string | string[];
/**
* CSS class to add to the child list element.
*/
childList: string | string[];
/**
* CSS class to add to each item element.
*/
item: string | string[];
/**
* CSS class to add to each selected item element.
*/
selectedItem: string | string[];
/**
* CSS class to add to each parent item element.
*/
parentItem: string | string[];
/**
* CSS class to add to each link (when using the default template).
*/
link: string | string[];
/**
* CSS class to add to each label (when using the default template).
*/
label: string | string[];
/**
* CSS class to add to each count element (when using the default template).
*/
count: string | string[];
/**
* CSS class to add to the show more element.
*/
showMore: string | string[];
/**
* CSS class to add to the disabled show more element.
*/
disabledShowMore: string | string[];
}>;
export type HierarchicalMenuComponentCSSClasses =
ComponentCSSClasses<HierarchicalMenuCSSClasses>;
export type HierarchicalMenuComponentTemplates =
Required<HierarchicalMenuTemplates>;
export type HierarchicalMenuWidgetParams = {
/**
* CSS Selector or HTMLElement to insert the widget.
*/
container: string | HTMLElement;
/**
* Array of attributes to use to generate the hierarchy of the menu.
*/
attributes: string[];
/**
* Separator used in the attributes to separate level values.
*/
separator?: string;
/**
* Prefix path to use if the first level is not the root level.
*/
rootPath?: string;
/**
* Show the siblings of the selected parent level of the current refined value.
*
* With `showParentLevel` set to `true` (default):
* - Parent lvl0
* - **lvl1**
* - **lvl2**
* - lvl2
* - lvl2
* - lvl 1
* - lvl 1
* - Parent lvl0
* - Parent lvl0
*
* With `showParentLevel` set to `false`:
* - Parent lvl0
* - **lvl1**
* - **lvl2**
* - Parent lvl0
* - Parent lvl0
*/
showParentLevel?: boolean;
/**
* Max number of values to display.
*/
limit?: number;
/**
* Whether to display the "show more" button.
*/
showMore?: boolean;
/**
* Max number of values to display when showing more.
* does not impact the root level.
*/
showMoreLimit?: number;
/**
* How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`.
* You can also use a sort function that behaves like the standard Javascript [compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax).
*/
sortBy?: SortBy<HierarchicalMenuItem>;
/**
* Function to transform the items passed to the templates.
*/
transformItems?: TransformItems<HierarchicalMenuItem>;
/**
* Templates to use for the widget.
*/
templates?: HierarchicalMenuTemplates;
/**
* CSS classes to add to the wrapping elements.
*/
cssClasses?: HierarchicalMenuCSSClasses;
};
const renderer =
({
cssClasses,
containerNode,
showMore,
templates,
renderState,
}: {
cssClasses: HierarchicalMenuComponentCSSClasses;
containerNode: HTMLElement;
showMore: boolean;
templates: HierarchicalMenuTemplates;
renderState: {
templateProps?: PreparedTemplateProps<HierarchicalMenuComponentTemplates>;
};
}) =>
(
{
createURL,
items,
refine,
instantSearchInstance,
isShowingMore,
toggleShowMore,
canToggleShowMore,
}: HierarchicalMenuRenderState &
RendererOptions<HierarchicalMenuConnectorParams>,
isFirstRendering: boolean
) => {
if (isFirstRendering) {
renderState.templateProps = prepareTemplateProps({
defaultTemplates,
templatesConfig: instantSearchInstance.templatesConfig,
templates,
});
return;
}
render(
<RefinementList
createURL={createURL}
cssClasses={cssClasses}
facetValues={items}
templateProps={renderState.templateProps!}
toggleRefinement={refine}
showMore={showMore}
toggleShowMore={toggleShowMore}
isShowingMore={isShowingMore}
canToggleShowMore={canToggleShowMore}
/>,
containerNode
);
};
/**
* The hierarchical menu widget is used to create a navigation based on a hierarchy of facet attributes.
*
* It is commonly used for categories with subcategories.
*
* All attributes (lvl0, lvl1 here) must be declared as [attributes for faceting](https://www.algolia.com/doc/guides/searching/faceting/#declaring-attributes-for-faceting) in your
* Algolia settings.
*
* By default, the separator we expect is ` > ` (with spaces) but you can use
* a different one by using the `separator` option.
* @requirements
* Your objects must be formatted in a specific way to be
* able to display hierarchical menus. Here's an example:
*
* ```javascript
* {
* "objectID": "123",
* "name": "orange",
* "categories": {
* "lvl0": "fruits",
* "lvl1": "fruits > citrus"
* }
* }
* ```
*
* Every level must be specified entirely.
* It's also possible to have multiple values per level, for example:
*
* ```javascript
* {
* "objectID": "123",
* "name": "orange",
* "categories": {
* "lvl0": ["fruits", "vitamins"],
* "lvl1": ["fruits > citrus", "vitamins > C"]
* }
* }
* ```
* @type {WidgetFactory}
* @devNovel HierarchicalMenu
* @category filter
* @param {HierarchicalMenuWidgetParams} widgetParams The HierarchicalMenu widget options.
* @return {Widget} A new HierarchicalMenu widget instance.
* @example
* search.addWidgets([
* instantsearch.widgets.hierarchicalMenu({
* container: '#hierarchical-categories',
* attributes: ['hierarchicalCategories.lvl0', 'hierarchicalCategories.lvl1', 'hierarchicalCategories.lvl2'],
* })
* ]);
*/
export type HierarchicalMenuWidget = WidgetFactory<
HierarchicalMenuWidgetDescription & { $$widgetType: 'ais.hierarchicalMenu' },
HierarchicalMenuConnectorParams,
HierarchicalMenuWidgetParams
>;
const hierarchicalMenu: HierarchicalMenuWidget = function hierarchicalMenu(
widgetParams
) {
const {
container,
attributes,
separator,
rootPath,
showParentLevel,
limit,
showMore = false,
showMoreLimit,
sortBy,
transformItems,
templates = {},
cssClasses: userCssClasses = {},
} = widgetParams || {};
if (!container) {
throw new Error(withUsage('The `container` option is required.'));
}
const containerNode = getContainerNode(container);
const cssClasses = {
root: cx(suit(), userCssClasses.root),
noRefinementRoot: cx(
suit({ modifierName: 'noRefinement' }),
userCssClasses.noRefinementRoot
),
list: cx(suit({ descendantName: 'list' }), userCssClasses.list),
childList: cx(
suit({ descendantName: 'list', modifierName: 'child' }),
userCssClasses.childList
),
item: cx(suit({ descendantName: 'item' }), userCssClasses.item),
selectedItem: cx(
suit({ descendantName: 'item', modifierName: 'selected' }),
userCssClasses.selectedItem
),
parentItem: cx(
suit({ descendantName: 'item', modifierName: 'parent' }),
userCssClasses.parentItem
),
link: cx(suit({ descendantName: 'link' }), userCssClasses.link),
label: cx(suit({ descendantName: 'label' }), userCssClasses.label),
count: cx(suit({ descendantName: 'count' }), userCssClasses.count),
showMore: cx(suit({ descendantName: 'showMore' }), userCssClasses.showMore),
disabledShowMore: cx(
suit({ descendantName: 'showMore', modifierName: 'disabled' }),
userCssClasses.disabledShowMore
),
};
const specializedRenderer = renderer({
cssClasses,
containerNode,
templates,
showMore,
renderState: {},
});
const makeWidget = connectHierarchicalMenu(specializedRenderer, () =>
render(null, containerNode)
);
return {
...makeWidget({
attributes,
separator,
rootPath,
showParentLevel,
limit,
showMore,
showMoreLimit,
sortBy,
transformItems,
}),
$$widgetType: 'ais.hierarchicalMenu',
};
};
export default hierarchicalMenu; | the_stack |
import fs from 'fs';
import path from 'path';
import {utils, providers} from 'ethers';
import {Config, Reporter} from '@jest/reporters';
import linker from 'solc/linker';
import easyTable from 'easy-table';
interface MethodCalls {
[methodName: string]: {
gasData: number[];
calls: number;
};
}
interface ContractCalls {
[contractName: string]: {
interface: utils.Interface;
address?: string;
code: string;
methodCalls: MethodCalls;
deploy?: {
gasData: number[];
calls: number;
};
};
}
interface Options {
contractArtifactFolder: string;
}
interface ParsedArtifact {
abi: (string | utils.FunctionFragment | utils.EventFragment)[];
// eslint-disable-next-line @typescript-eslint/ban-types
deployedBytecode: object;
contractName: string;
networks: {[networkName: string]: {address: string}};
}
interface GasConsumed {
[contract: string]: ContractStats;
}
interface ContractStats {
deployment: number;
methods: {[method: string]: Stats};
}
interface Stats {
calls: number;
min: number;
max: number;
avg: number;
}
const gasConsumed: GasConsumed = {};
/* TODO:
- Handle failures gracefully
- Organize and clean up
*/
export class GasReporter implements Reporter {
options: Options;
provider: providers.JsonRpcProvider;
globalConfig: Config.GlobalConfig;
startBlockNum = 0;
constructor(globalConfig: Config.GlobalConfig, options: Options) {
this.globalConfig = globalConfig;
this.options = options;
this.provider = new providers.JsonRpcProvider(
`http://localhost:${process.env.GANACHE_PORT || 8545}`
);
}
onTestStart(): void {
/* empty */
}
getLastError(): void {
/* empty */
}
onTestResult(): void {
/* empty */
}
onRunStart(): void {
if (!this.options.contractArtifactFolder) {
console.log(
"The contractArtifactFolder was not set in options, assuming a default folder of '/build/contracts/'"
);
this.options.contractArtifactFolder = 'build/contracts';
}
}
onRunComplete(): Promise<void> {
return new Promise((resolve, reject) => {
this.generateFinalResults()
.then(() => {
resolve();
})
.catch(e => {
reject(e);
});
});
}
async generateFinalResults(): Promise<void> {
const endBlockNum = await this.provider.getBlockNumber();
const contractCalls = await this.parseContractCalls(
this.startBlockNum,
endBlockNum,
this.options.contractArtifactFolder
);
this.outputGasInfo(contractCalls);
await this.saveResultsToFile(process.env.CIRCLE_SHA1);
}
async parseContractCalls(
startBlockNum: number,
endBlockNum: number,
contractFolder: string
): Promise<ContractCalls> {
const networkId = (await this.provider.getNetwork()).chainId;
const contractCalls = await this.parseContractArtifactFolder(contractFolder, networkId);
for (let i = startBlockNum; i <= endBlockNum; i++) {
await this.parseBlock(i, contractCalls);
}
return contractCalls;
}
parseContractArtifactFolder(contractFolder: string, networkId: number): ContractCalls {
const contractCalls: ContractCalls = {};
const contractArtifacts = fs.readdirSync(contractFolder);
contractArtifacts.forEach((artifact: string) => {
const fileLocation = path.join(contractFolder, artifact);
const fileContent = fs.readFileSync(fileLocation, 'utf8');
const parsedArtifact = JSON.parse(fileContent);
this.parseInterfaceAndAddress(parsedArtifact, networkId, contractCalls);
this.parseCode(parsedArtifact, contractCalls);
});
return contractCalls;
}
parseCode(parsedArtifact: ParsedArtifact, contractCalls: ContractCalls): void {
const lookup = {};
for (const contractName of Object.keys(contractCalls)) {
if (contractCalls[contractName].address) {
lookup[contractName] = contractCalls[contractName].address;
}
}
if (parsedArtifact.deployedBytecode) {
const linkedCode = linker.linkBytecode(parsedArtifact.deployedBytecode, lookup);
contractCalls[parsedArtifact.contractName].code = linkedCode;
}
}
parseInterfaceAndAddress(
parsedArtifact: ParsedArtifact,
networkId: number,
contractCalls: ContractCalls
): void {
// Only attempt to parse as a contract if we have a defined ABI and contractName
if (parsedArtifact.abi && parsedArtifact.contractName) {
const contractInterface = new utils.Interface(parsedArtifact.abi);
contractCalls[parsedArtifact.contractName] = {
methodCalls: {},
code: '',
interface: contractInterface
};
if (parsedArtifact.networks[networkId]) {
contractCalls[parsedArtifact.contractName].address =
parsedArtifact.networks[networkId].address;
}
}
}
outputGasInfo(contractCalls: ContractCalls): void {
for (const contractName of Object.keys(contractCalls)) {
const contractStats: ContractStats = {
deployment: 0,
methods: {}
};
if (contractCalls[contractName].deploy) {
const deployGas = contractCalls[contractName].deploy.gasData;
if (deployGas[1] && deployGas[1] !== deployGas[0]) {
throw new Error('Multiple deployments with differing gas costs detected!');
// This shouldn't happen with our current workflow where contracts are deployed exactly once before tests are run.
}
contractStats.deployment = deployGas[0];
}
const methodCalls = contractCalls[contractName].methodCalls;
Object.keys(methodCalls).forEach(methodName => {
const method = methodCalls[methodName];
const total = method.gasData.reduce((acc, datum) => acc + datum, 0);
const average = Math.round(total / method.gasData.length);
const min = Math.min(...method.gasData);
const max = Math.max(...method.gasData);
const stats: Stats = {calls: method.calls, min: min, max: max, avg: average};
contractStats.methods[methodName] = stats;
});
if (contractStats.deployment > 0) {
gasConsumed[contractName] = contractStats;
}
}
console.log(this.objectToEasyTable(gasConsumed, false).toString());
}
objectToEasyTable(gasConsumed: GasConsumed, markdown: boolean): easyTable {
function addCell(table: easyTable, column: string, entry: string | number): void {
if (!markdown) {
table.cell(column, entry.toString());
} else {
table.cell(column + ' |', entry.toString() + ' |');
}
}
const table = new easyTable();
if (markdown) {
addCell(table, 'Contract', 'Contract');
addCell(table, 'Deployment', 'Deployment');
addCell(table, 'Method', 'Method');
addCell(table, 'Calls', 'Calls');
addCell(table, 'Min', 'Min');
addCell(table, 'Avg', 'Avg');
addCell(table, 'Max', 'Max');
table.newRow();
addCell(table, 'Contract', '---');
addCell(table, 'Deployment', '---');
addCell(table, 'Method', '---');
addCell(table, 'Calls', '---');
addCell(table, 'Min', '---');
addCell(table, 'Avg', '---');
addCell(table, 'Max', '---');
table.newRow();
}
Object.keys(gasConsumed).forEach(contract => {
const contractStats = gasConsumed[contract];
addCell(table, 'Contract', contract);
addCell(table, 'Deployment', contractStats.deployment);
addCell(table, 'Method', '*');
addCell(table, 'Calls', '*');
addCell(table, 'Min', '*');
addCell(table, 'Avg', '*');
addCell(table, 'Max', '*');
table.newRow();
Object.keys(contractStats.methods).forEach(method => {
addCell(table, 'Contract', '*');
addCell(table, 'Deployment', '*');
addCell(table, 'Method', method);
const methodStats = contractStats.methods[method];
addCell(table, 'Calls', methodStats.calls);
addCell(table, 'Min', methodStats.min);
addCell(table, 'Avg', methodStats.avg);
addCell(table, 'Max', methodStats.max);
table.newRow();
});
});
return table;
}
async parseBlock(blockNum: number, contractCalls: ContractCalls): Promise<void> {
const block = await this.provider.getBlock(blockNum);
for (const transHash of block.transactions) {
const transaction = await this.provider.getTransaction(transHash);
const transactionReceipt = await this.provider.getTransactionReceipt(transHash);
if (transaction.to) {
const code = await this.provider.getCode(transaction.to);
for (const contractName of Object.keys(contractCalls)) {
const contractCall = contractCalls[contractName];
if (contractCall.code.localeCompare(code, undefined, {sensitivity: 'base'}) === 0) {
const details = contractCall.interface.parseTransaction(transaction);
if (details != null) {
if (!contractCall.methodCalls[details.name]) {
contractCall.methodCalls[details.name] = {
gasData: [],
calls: 0
};
}
contractCall.methodCalls[details.name].gasData.push(
transactionReceipt.gasUsed.toNumber()
);
contractCall.methodCalls[details.name].calls++;
}
}
}
} else if (transactionReceipt.contractAddress) {
const code = await this.provider.getCode(transactionReceipt.contractAddress);
for (const contractName of Object.keys(contractCalls)) {
const contractCall = contractCalls[contractName];
if (contractCall.code.localeCompare(code, undefined, {sensitivity: 'base'}) === 0) {
if (!contractCall.deploy) {
contractCall.deploy = {calls: 0, gasData: []};
}
contractCall.deploy.calls++;
contractCall.deploy.gasData.push(transactionReceipt.gasUsed.toNumber());
}
}
}
}
}
async saveResultsToFile(hash: string): Promise<void> {
const results = {
date: Date.now(),
networkName: this.provider.network.name,
revision: hash,
gasConsumed
};
const resultsString = JSON.stringify(results, null, 4) + '\n';
await fs.appendFile('./gas.json', resultsString, err => {
if (err) throw err;
console.log('Wrote json to gas.json');
});
const date = new Date(Date.now());
await fs.appendFile(
'./gas.md',
'\n\n\n# date: ' +
date.toUTCString() +
'\nnetworkName: ' +
this.provider.network.name +
'\nrevision: ' +
hash +
'\n' +
this.objectToEasyTable(gasConsumed, true).print().toString(),
err => {
if (err) throw err;
console.log('Wrote table to gas.md');
}
);
}
}
module.exports = GasReporter; | the_stack |
'use strict';
import * as assert from 'assert';
import {VerticalObjects} from 'vs/editor/common/viewLayout/verticalObjects';
suite('Editor ViewLayout - VerticalObjects', () => {
test('VerticalObjects 1', () => {
var verticalObjects = new VerticalObjects();
// Start off with 10 lines
verticalObjects.replaceLines(10);
// lines: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
// whitespace: -
assert.equal(verticalObjects.getTotalHeight(10), 100);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 10), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 10), 10);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 10), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 10), 30);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 10), 40);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 10), 50);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 10), 60);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 10), 70);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 10), 80);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 10), 90);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 0, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 1, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 5, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 9, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(10, 10), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(11, 10), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(15, 10), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(19, 10), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(20, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(21, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(29, 10), 3);
// Add whitespace of height 5px after 2nd line
verticalObjects.insertWhitespace(2, 0, 5);
// lines: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
// whitespace: a(2,5)
assert.equal(verticalObjects.getTotalHeight(10), 105);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 10), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 10), 10);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 10), 25);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 10), 35);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 10), 45);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 0, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 1, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 9, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 10, 10), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 20, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 21, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 24, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 25, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 35, 10), 4);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 45, 10), 5);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(104, 10), 10);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(105, 10), 10);
// Add two more whitespaces of height 5px
verticalObjects.insertWhitespace(3, 0, 5);
verticalObjects.insertWhitespace(4, 0, 5);
// lines: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
// whitespace: a(2,5), b(3, 5), c(4, 5)
assert.equal(verticalObjects.getTotalHeight(10), 115);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 10), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 10), 10);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 10), 25);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 10), 40);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 10), 55);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 10), 65);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 0, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 1, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 9, 10), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 10, 10), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 19, 10), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 20, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 34, 10), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 35, 10), 4);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 49, 10), 4);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 50, 10), 5);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 64, 10), 5);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 65, 10), 6);
assert.equal(verticalObjects.getVerticalOffsetForWhitespaceIndex(0, 10), 20); // 20 -> 25
assert.equal(verticalObjects.getVerticalOffsetForWhitespaceIndex(1, 10), 35); // 35 -> 40
assert.equal(verticalObjects.getVerticalOffsetForWhitespaceIndex(2, 10), 50);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(0, 10), 0);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(19, 10), 0);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(20, 10), 0);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(21, 10), 0);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(22, 10), 0);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(23, 10), 0);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(24, 10), 0);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(25, 10), 1);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(26, 10), 1);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(34, 10), 1);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(35, 10), 1);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(36, 10), 1);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(39, 10), 1);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(40, 10), 2);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(41, 10), 2);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(49, 10), 2);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(50, 10), 2);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(51, 10), 2);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(54, 10), 2);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(55, 10), -1);
assert.equal(verticalObjects.getWhitespaceIndexAtOrAfterVerticallOffset(1000, 10), -1);
});
test('VerticalObjects 2', () => {
var verticalObjects = new VerticalObjects();
// Start off with 10 lines and one whitespace after line 2, of height 5
verticalObjects.replaceLines(10);
var a = verticalObjects.insertWhitespace(2, 0, 5);
// 10 lines
// whitespace: - a(2,5)
assert.equal(verticalObjects.getTotalHeight(1), 15);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 7);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 8);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 9);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 10);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 11);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 12);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 1), 13);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 1), 14);
// Change whitespace height
// 10 lines
// whitespace: - a(2,10)
verticalObjects.changeWhitespace(a, 2, 10);
assert.equal(verticalObjects.getTotalHeight(1), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 12);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 13);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 14);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 15);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 16);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 17);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 1), 18);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 1), 19);
// Change whitespace position
// 10 lines
// whitespace: - a(5,10)
verticalObjects.changeWhitespace(a, 5, 10);
assert.equal(verticalObjects.getTotalHeight(1), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 2);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 3);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 4);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 15);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 16);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 17);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 1), 18);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 1), 19);
// Pretend that lines 5 and 6 were deleted
// 8 lines
// whitespace: - a(4,10)
verticalObjects.onModelLinesDeleted(5, 6);
assert.equal(verticalObjects.getTotalHeight(1), 18);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 2);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 3);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 14);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 15);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 16);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 17);
// Insert two lines at the beginning
// 10 lines
// whitespace: - a(6,10)
verticalObjects.onModelLinesInserted(1, 2);
assert.equal(verticalObjects.getTotalHeight(1), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 2);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 3);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 4);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 5);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 16);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 17);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 1), 18);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 1), 19);
// Remove whitespace
// 10 lines
verticalObjects.removeWhitespace(a);
assert.equal(verticalObjects.getTotalHeight(1), 10);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 2);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 3);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 4);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 5);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 6);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 7);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 1), 8);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 1), 9);
});
test('VerticalObjects getLineNumberAtOrAfterVerticalOffset', () => {
var verticalObjects = new VerticalObjects();
verticalObjects.replaceLines(10);
verticalObjects.insertWhitespace(6, 0, 10);
// 10 lines
// whitespace: - a(6,10)
assert.equal(verticalObjects.getTotalHeight(1), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 2);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 3);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 4);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 5);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 16);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 17);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 1), 18);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 1), 19);
// Do some hit testing
// line [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// vertical: [0, 1, 2, 3, 4, 5, 16, 17, 18, 19]
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset(-100, 1), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( -1, 1), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 0, 1), 1);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 1, 1), 2);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 2, 1), 3);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 3, 1), 4);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 4, 1), 5);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 5, 1), 6);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 6, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 7, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 8, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 9, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 10, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 11, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 12, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 13, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 14, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 15, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 16, 1), 7);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 17, 1), 8);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 18, 1), 9);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 19, 1), 10);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 20, 1), 10);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 21, 1), 10);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 22, 1), 10);
assert.equal(verticalObjects.getLineNumberAtOrAfterVerticalOffset( 23, 1), 10);
});
test('VerticalObjects getCenteredLineInViewport', () => {
var verticalObjects = new VerticalObjects();
verticalObjects.replaceLines(10);
verticalObjects.insertWhitespace(6, 0, 10);
// 10 lines
// whitespace: - a(6,10)
assert.equal(verticalObjects.getTotalHeight(1), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 1), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 1), 1);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 1), 2);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 1), 3);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 1), 4);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 1), 5);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 1), 16);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 1), 17);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 1), 18);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 1), 19);
// Find centered line in viewport 1
// line [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// vertical: [0, 1, 2, 3, 4, 5, 16, 17, 18, 19]
assert.equal(verticalObjects.getCenteredLineInViewport(0, 1, 1), 1);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 2, 1), 2);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 3, 1), 2);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 4, 1), 3);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 5, 1), 3);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 6, 1), 4);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 7, 1), 4);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 8, 1), 5);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 9, 1), 5);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 10, 1), 6);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 11, 1), 6);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 12, 1), 6);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 13, 1), 6);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 14, 1), 6);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 15, 1), 6);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 16, 1), 6);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 17, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 18, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 19, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 21, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 22, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 23, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 24, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 25, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 26, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 27, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 28, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 29, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 30, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 31, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 32, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(0, 33, 1), 7);
// Find centered line in viewport 2
// line [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// vertical: [0, 1, 2, 3, 4, 5, 16, 17, 18, 19]
assert.equal(verticalObjects.getCenteredLineInViewport( 0, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 1, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 2, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 3, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 4, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 5, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 6, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 7, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 8, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport( 9, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(10, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(11, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(12, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(13, 20, 1), 7);
assert.equal(verticalObjects.getCenteredLineInViewport(14, 20, 1), 8);
assert.equal(verticalObjects.getCenteredLineInViewport(15, 20, 1), 8);
assert.equal(verticalObjects.getCenteredLineInViewport(16, 20, 1), 9);
assert.equal(verticalObjects.getCenteredLineInViewport(17, 20, 1), 9);
assert.equal(verticalObjects.getCenteredLineInViewport(18, 20, 1), 10);
assert.equal(verticalObjects.getCenteredLineInViewport(19, 20, 1), 10);
assert.equal(verticalObjects.getCenteredLineInViewport(20, 23, 1), 10);
assert.equal(verticalObjects.getCenteredLineInViewport(21, 23, 1), 10);
assert.equal(verticalObjects.getCenteredLineInViewport(22, 23, 1), 10);
});
test('VerticalObjects getLinesViewportData 1', () => {
var verticalObjects = new VerticalObjects();
verticalObjects.replaceLines(10);
verticalObjects.insertWhitespace(6, 0, 100);
// 10 lines
// whitespace: - a(6,100)
assert.equal(verticalObjects.getTotalHeight(10), 200);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 10), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 10), 10);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 10), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 10), 30);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 10), 40);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 10), 50);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 10), 160);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 10), 170);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 10), 180);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 10), 190);
// viewport 0->50
var viewportData = verticalObjects.getLinesViewportData(0,50,10);
assert.equal(viewportData.startLineNumber, 1);
assert.equal(viewportData.endLineNumber, 5);
assert.deepEqual(viewportData.relativeVerticalOffset, [0, 10, 20, 30, 40]);
assert.equal(viewportData.visibleRangesDeltaTop, 0);
// viewport 1->51
viewportData = verticalObjects.getLinesViewportData(1,51,10);
assert.equal(viewportData.startLineNumber, 1);
assert.equal(viewportData.endLineNumber, 6);
assert.deepEqual(viewportData.relativeVerticalOffset, [0, 10, 20, 30, 40, 50]);
assert.equal(viewportData.visibleRangesDeltaTop, -1);
// viewport 5->55
viewportData = verticalObjects.getLinesViewportData(5,55,10);
assert.equal(viewportData.startLineNumber, 1);
assert.equal(viewportData.endLineNumber, 6);
assert.deepEqual(viewportData.relativeVerticalOffset, [0, 10, 20, 30, 40, 50]);
assert.equal(viewportData.visibleRangesDeltaTop, -5);
// viewport 10->60
viewportData = verticalObjects.getLinesViewportData(10,60,10);
assert.equal(viewportData.startLineNumber, 2);
assert.equal(viewportData.endLineNumber, 6);
assert.deepEqual(viewportData.relativeVerticalOffset, [10, 20, 30, 40, 50]);
assert.equal(viewportData.visibleRangesDeltaTop, -10);
// viewport 50->100
viewportData = verticalObjects.getLinesViewportData(50,100,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 6);
assert.deepEqual(viewportData.relativeVerticalOffset, [50]);
assert.equal(viewportData.visibleRangesDeltaTop, -50);
// viewport 60->110
viewportData = verticalObjects.getLinesViewportData(60,110,10);
assert.equal(viewportData.startLineNumber, 7);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [160]);
assert.equal(viewportData.visibleRangesDeltaTop, -60);
// viewport 65->115
viewportData = verticalObjects.getLinesViewportData(65,115,10);
assert.equal(viewportData.startLineNumber, 7);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [160]);
assert.equal(viewportData.visibleRangesDeltaTop, -65);
// viewport 50->159
viewportData = verticalObjects.getLinesViewportData(50,159,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 6);
assert.deepEqual(viewportData.relativeVerticalOffset, [50]);
assert.equal(viewportData.visibleRangesDeltaTop, -50);
// viewport 50->160
viewportData = verticalObjects.getLinesViewportData(50,160,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 6);
assert.deepEqual(viewportData.relativeVerticalOffset, [50]);
assert.equal(viewportData.visibleRangesDeltaTop, -50);
// viewport 51->161
viewportData = verticalObjects.getLinesViewportData(51,161,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [50, 160]);
assert.equal(viewportData.visibleRangesDeltaTop, -51);
// viewport 150->169
viewportData = verticalObjects.getLinesViewportData(150,169,10);
assert.equal(viewportData.startLineNumber, 7);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [160]);
assert.equal(viewportData.visibleRangesDeltaTop, -150);
// viewport 159->169
viewportData = verticalObjects.getLinesViewportData(159,169,10);
assert.equal(viewportData.startLineNumber, 7);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [160]);
assert.equal(viewportData.visibleRangesDeltaTop, -159);
// viewport 160->169
viewportData = verticalObjects.getLinesViewportData(160,169,10);
assert.equal(viewportData.startLineNumber, 7);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [160]);
assert.equal(viewportData.visibleRangesDeltaTop, -160);
// viewport 160->1000
viewportData = verticalObjects.getLinesViewportData(160,1000,10);
assert.equal(viewportData.startLineNumber, 7);
assert.equal(viewportData.endLineNumber, 10);
assert.deepEqual(viewportData.relativeVerticalOffset, [160, 170, 180, 190]);
assert.equal(viewportData.visibleRangesDeltaTop, -160);
});
test('VerticalObjects getLinesViewportData 2 & getWhitespaceViewportData', () => {
var verticalObjects = new VerticalObjects();
verticalObjects.replaceLines(10);
var a = verticalObjects.insertWhitespace(6, 0, 100);
var b = verticalObjects.insertWhitespace(7, 0, 50);
// 10 lines
// whitespace: - a(6,100), b(7, 50)
assert.equal(verticalObjects.getTotalHeight(10), 250);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 1, 10), 0);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 2, 10), 10);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 3, 10), 20);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 4, 10), 30);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 5, 10), 40);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 6, 10), 50);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 7, 10), 160);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 8, 10), 220);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber( 9, 10), 230);
assert.equal(verticalObjects.getVerticalOffsetForLineNumber(10, 10), 240);
// viewport 50->160
var viewportData = verticalObjects.getLinesViewportData(50,160,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 6);
assert.deepEqual(viewportData.relativeVerticalOffset, [50]);
assert.equal(viewportData.visibleRangesDeltaTop, -50);
var whitespaceData = verticalObjects.getWhitespaceViewportData(50,160,10);
assert.deepEqual(whitespaceData, [{
id: a,
afterLineNumber: 6,
verticalOffset: 60,
height: 100
}]);
// viewport 50->219
viewportData = verticalObjects.getLinesViewportData(50,219,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [50, 160]);
assert.equal(viewportData.visibleRangesDeltaTop, -50);
whitespaceData = verticalObjects.getWhitespaceViewportData(50,219,10);
assert.deepEqual(whitespaceData, [{
id: a,
afterLineNumber: 6,
verticalOffset: 60,
height: 100
}, {
id: b,
afterLineNumber: 7,
verticalOffset: 170,
height: 50
}]);
// viewport 50->220
viewportData = verticalObjects.getLinesViewportData(50,220,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 7);
assert.deepEqual(viewportData.relativeVerticalOffset, [50, 160]);
assert.equal(viewportData.visibleRangesDeltaTop, -50);
// viewport 50->250
viewportData = verticalObjects.getLinesViewportData(50,250,10);
assert.equal(viewportData.startLineNumber, 6);
assert.equal(viewportData.endLineNumber, 10);
assert.deepEqual(viewportData.relativeVerticalOffset, [50, 160, 220, 230, 240]);
assert.equal(viewportData.visibleRangesDeltaTop, -50);
});
test('VerticalObjects getWhitespaceAtVerticalOffset', () => {
var verticalObjects = new VerticalObjects();
verticalObjects.replaceLines(10);
var a = verticalObjects.insertWhitespace(6, 0, 100);
var b = verticalObjects.insertWhitespace(7, 0, 50);
var whitespace = verticalObjects.getWhitespaceAtVerticalOffset(0, 10);
assert.equal(whitespace, null);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(59, 10);
assert.equal(whitespace, null);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(60, 10);
assert.equal(whitespace.id, a);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(61, 10);
assert.equal(whitespace.id, a);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(159, 10);
assert.equal(whitespace.id, a);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(160, 10);
assert.equal(whitespace, null);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(161, 10);
assert.equal(whitespace, null);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(169, 10);
assert.equal(whitespace, null);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(170, 10);
assert.equal(whitespace.id, b);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(171, 10);
assert.equal(whitespace.id, b);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(219, 10);
assert.equal(whitespace.id, b);
whitespace = verticalObjects.getWhitespaceAtVerticalOffset(220, 10);
assert.equal(whitespace, null);
});
}); | the_stack |
import {
arrayForEach
} from '@tko/utils'
import {
isSubscribable, isObservable, observable, unwrap, dependencyDetection,
isWritableObservable, isWriteableObservable, observableArray, subscribable
} from '@tko/observable'
import {
computed, isPureComputed, isComputed
} from '../dist'
describe('Dependent Observable', function () {
it('Should be subscribable', function () {
var instance = computed(function () { })
expect(isSubscribable(instance)).toEqual(true)
})
it('Should not advertise that ko.computed is observable', function () {
expect(isObservable(computed)).toEqual(false)
})
it('Should advertise that instances are observable', function () {
var instance = computed(function () { })
expect(isObservable(instance)).toEqual(true)
})
it('Should unwrap the underlying value of observables', function () {
var someObject = { abc: 123 },
observablePrimitiveValue = observable(123),
observableObjectValue = observable(someObject),
observableNullValue = observable(null),
observableUndefinedValue = observable(undefined),
computedValue = computed(function () { return observablePrimitiveValue() + 1 })
expect(unwrap(observablePrimitiveValue)).toBe(123)
expect(unwrap(observableObjectValue)).toBe(someObject)
expect(unwrap(observableNullValue)).toBe(null)
expect(unwrap(observableUndefinedValue)).toBe(undefined)
expect(unwrap(computedValue)).toBe(124)
})
it('Should advertise that instances are computed', function () {
var instance = computed(function () { })
expect(isComputed(instance)).toEqual(true)
})
it('Should advertise that instances are not pure computed', function () {
var instance = computed(function () { })
expect(isPureComputed(instance)).toEqual(false)
})
it('Should advertise that instances cannot have values written to them', function () {
var instance = computed(function () { })
expect(isWriteableObservable(instance)).toEqual(false)
expect(isWritableObservable(instance)).toEqual(false)
})
it('ko.isComputed should return false for non-computed values', function () {
arrayForEach([
undefined,
null,
'x',
{},
function () {},
observable(),
(function () { var x = computed(function () {}); x.__ko_proto__ = {}; return x }())
], value => expect(isComputed(value)).toEqual(false))
})
it('Should require an evaluator function as constructor param', function () {
expect(function () { computed() }).toThrow()
})
it('Should be able to read the current value of the evaluator function', function () {
var instance = computed(function () { return 123 })
expect(instance()).toEqual(123)
})
it('Should not be able to write a value to it if there is no "write" callback', function () {
var instance = computed(function () { return 123 })
expect(function () { instance(456) }).toThrow()
expect(instance()).toEqual(123)
})
it('Should invoke the "write" callback, where present, if you attempt to write a value to it', function () {
var invokedWriteWithValue, invokedWriteWithThis
var instance = computed({
read: function () {},
write: function (value) { invokedWriteWithValue = value; invokedWriteWithThis = this }
})
var someContainer = { depObs: instance }
someContainer.depObs('some value')
expect(invokedWriteWithValue).toEqual('some value')
expect(invokedWriteWithThis).toEqual(function () { return this }.call()) // Since no owner was specified
})
it('Should be able to write to multiple computed properties on a model object using chaining syntax', function () {
var model = {
prop1: computed({
read: function () {},
write: function (value) {
expect(value).toEqual('prop1')
} }),
prop2: computed({
read: function () {},
write: function (value) {
expect(value).toEqual('prop2')
} })
}
model.prop1('prop1').prop2('prop2')
})
it('Should be able to use Function.prototype methods to access/update', function () {
var instance = computed({read: function () { return 'A' }, write: function (/* value */) {}})
var obj = {}
expect(instance.call(null)).toEqual('A')
expect(instance.apply(null, [])).toBe('A')
expect(instance.call(obj, 'B')).toBe(obj)
})
it('Should use options.owner as "this" when invoking the "write" callback, and can pass multiple parameters', function () {
var invokedWriteWithArgs, invokedWriteWithThis
var someOwner = {}
var obs = observable()
var instance = computed({
read: function () { return obs() },
write: function () { obs(null); invokedWriteWithArgs = Array.prototype.slice.call(arguments, 0); invokedWriteWithThis = this },
owner: someOwner
})
instance('first', 2, ['third1', 'third2'])
expect(invokedWriteWithArgs.length).toEqual(3)
expect(invokedWriteWithArgs[0]).toEqual('first')
expect(invokedWriteWithArgs[1]).toEqual(2)
expect(invokedWriteWithArgs[2]).toEqual(['third1', 'third2'])
expect(invokedWriteWithThis).toEqual(someOwner)
})
it('Should use the second arg (evaluatorFunctionTarget) for "this" when calling read/write if no options.owner was given', function () {
var expectedThis = {}, actualReadThis, actualWriteThis
var obs = observable()
var instance = computed({
read: function () { actualReadThis = this; return obs() },
write: function () { actualWriteThis = this; obs(null) }
}, expectedThis)
instance('force invocation of write')
expect(actualReadThis).toEqual(expectedThis)
expect(actualWriteThis).toEqual(expectedThis)
})
it('Should be able to pass evaluator function using "options" parameter called "read"', function () {
var instance = computed({
read: function () { return 123 }
})
expect(instance()).toEqual(123)
})
it('Should cache result of evaluator function and not call it again until dependencies change', function () {
var timesEvaluated = 0
var instance = computed(function () { timesEvaluated++; return 123 })
expect(instance()).toEqual(123)
expect(instance()).toEqual(123)
expect(timesEvaluated).toEqual(1)
})
it('Should automatically update value when a dependency changes', function () {
var observableInstance = new observable(1)
var dependantObservable = computed(function () { return observableInstance() + 1 })
expect(dependantObservable()).toEqual(2)
observableInstance(50)
expect(dependantObservable()).toEqual(51)
})
it('Should be able to use \'peek\' on an observable to avoid a dependency', function () {
var observableInstance = observable(1),
computedInstance = computed(function () { return observableInstance.peek() + 1 })
expect(computedInstance()).toEqual(2)
observableInstance(50)
expect(computedInstance()).toEqual(2) // value wasn't changed
})
it('Should be able to use \'ko.ignoreDependencies\' within a computed to avoid dependencies', function () {
var observableInstance = observable(1),
computedInstance = computed(function () {
return dependencyDetection.ignoreDependencies(function () { return observableInstance() + 1 })
})
expect(computedInstance()).toEqual(2)
observableInstance(50)
expect(computedInstance()).toEqual(2) // value wasn't changed
})
it('Should unsubscribe from previous dependencies each time a dependency changes', function () {
var observableA = new observable('A')
var observableB = new observable('B')
var observableToUse = 'A'
var timesEvaluated = 0
var dependantObservable = computed(function () {
timesEvaluated++
return observableToUse == 'A' ? observableA() : observableB()
})
expect(dependantObservable()).toEqual('A')
expect(timesEvaluated).toEqual(1)
// Changing an unrelated observable doesn't trigger evaluation
observableB('B2')
expect(timesEvaluated).toEqual(1)
// Switch to other observable
observableToUse = 'B'
observableA('A2')
expect(dependantObservable()).toEqual('B2')
expect(timesEvaluated).toEqual(2)
// Now changing the first observable doesn't trigger evaluation
observableA('A3')
expect(timesEvaluated).toEqual(2)
})
it('Should notify subscribers of changes', function () {
var notifiedValue
var observableInstance = new observable(1)
var dependantObservable = computed(function () { return observableInstance() + 1 })
dependantObservable.subscribe(function (value) { notifiedValue = value })
expect(notifiedValue).toEqual(undefined)
observableInstance(2)
expect(notifiedValue).toEqual(3)
})
it('Should notify "spectator" subscribers about changes', function () {
var obs = new observable()
var comp = computed(() => obs())
var notifiedValues = []
comp.subscribe(function (value) {
notifiedValues.push(value)
}, null, 'spectate')
obs('A')
obs('B')
expect(notifiedValues).toEqual([ 'A', 'B' ])
})
it('Should notify "beforeChange" subscribers before changes', function () {
var notifiedValue
var observableInstance = new observable(1)
var dependantObservable = computed(function () { return observableInstance() + 1 })
dependantObservable.subscribe(function (value) { notifiedValue = value }, null, 'beforeChange')
expect(notifiedValue).toEqual(undefined)
observableInstance(2)
expect(notifiedValue).toEqual(2)
expect(dependantObservable()).toEqual(3)
})
it('Should only update once when each dependency changes, even if evaluation calls the dependency multiple times', function () {
var notifiedValues = []
var observableInstance = new observable()
var dependantObservable = computed(function () { return observableInstance() * observableInstance() })
dependantObservable.subscribe(function (value) { notifiedValues.push(value) })
observableInstance(2)
expect(notifiedValues.length).toEqual(1)
expect(notifiedValues[0]).toEqual(4)
})
it('Should be able to chain computed observables', function () {
var underlyingObservable = new observable(1)
var computed1 = computed(function () { return underlyingObservable() + 1 })
var computed2 = computed(function () { return computed1() + 1 })
expect(computed2()).toEqual(3)
underlyingObservable(11)
expect(computed2()).toEqual(13)
})
it('Should be able to use \'peek\' on a computed observable to avoid a dependency', function () {
var underlyingObservable = new observable(1)
var computed1 = computed(function () { return underlyingObservable() + 1 })
var computed2 = computed(function () { return computed1.peek() + 1 })
expect(computed2()).toEqual(3)
expect(computed2.isActive()).toEqual(false)
underlyingObservable(11)
expect(computed2()).toEqual(3) // value wasn't changed
})
it('Should accept "owner" parameter to define the object on which the evaluator function should be called', function () {
var model = new function () {
this.greeting = 'hello'
this.fullMessageWithoutOwner = computed(function () { return (this || {}).greeting + ' world' })
this.fullMessageWithOwner = computed(function () { return this.greeting + ' world' }, this)
}()
expect(model.fullMessageWithoutOwner()).toEqual('undefined world')
expect(model.fullMessageWithOwner()).toEqual('hello world')
})
it('Should dispose and not call its evaluator function when the disposeWhen function returns true', function () {
var underlyingObservable = new observable(100)
var timeToDispose = false
var timesEvaluated = 0
var computedInstance = computed(
function () { timesEvaluated++; return underlyingObservable() + 1 },
null,
{ disposeWhen: function () { return timeToDispose } }
)
expect(timesEvaluated).toEqual(1)
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([ underlyingObservable ])
expect(computedInstance.isActive()).toEqual(true)
timeToDispose = true
underlyingObservable(101)
expect(timesEvaluated).toEqual(1)
expect(computedInstance.getDependenciesCount()).toEqual(0)
expect(computedInstance.getDependencies()).toEqual([])
expect(computedInstance.isActive()).toEqual(false)
})
it('Should dispose itself as soon as disposeWhen returns true, as long as it isn\'t waiting for a DOM node to be removed', function () {
var underlyingObservable = observable(100),
computedInstance = computed(
underlyingObservable,
null,
{ disposeWhen: function () { return true } }
)
expect(underlyingObservable.getSubscriptionsCount()).toEqual(0)
expect(computedInstance.isActive()).toEqual(false)
})
it('Should delay disposal until after disposeWhen returns false if it is waiting for a DOM node to be removed', function () {
var underlyingObservable = observable(100),
shouldDispose = true,
computedInstance = computed(
underlyingObservable,
null,
{ disposeWhen: function () { return shouldDispose }, disposeWhenNodeIsRemoved: true }
)
// Even though disposeWhen returns true, it doesn't dispose yet, because it's
// expecting an initial 'false' result to indicate the DOM node is still in the document
expect(underlyingObservable.getSubscriptionsCount()).toEqual(1)
expect(computedInstance.isActive()).toEqual(true)
// Trigger the false result. Of course it still doesn't dispose yet, because
// disposeWhen says false.
shouldDispose = false
underlyingObservable(101)
expect(underlyingObservable.getSubscriptionsCount()).toEqual(1)
expect(computedInstance.isActive()).toEqual(true)
// Now trigger a true result. This time it will dispose.
shouldDispose = true
underlyingObservable(102)
expect(underlyingObservable.getSubscriptionsCount()).toEqual(0)
expect(computedInstance.isActive()).toEqual(false)
})
it('Should describe itself as active if the evaluator has dependencies on its first run', function () {
var someObservable = observable('initial'),
computedInstance = computed(function () { return someObservable() })
expect(computedInstance.isActive()).toEqual(true)
})
it('Should describe itself as inactive if the evaluator has no dependencies on its first run', function () {
var computedInstance = computed(function () { return 123 })
expect(computedInstance.isActive()).toEqual(false)
})
it('Should describe itself as inactive if subsequent runs of the evaluator result in there being no dependencies', function () {
var someObservable = observable('initial'),
shouldHaveDependency = true,
computedInstance = computed(function () { shouldHaveDependency && someObservable() })
expect(computedInstance.isActive()).toEqual(true)
// Trigger a refresh
shouldHaveDependency = false
someObservable('modified')
expect(computedInstance.isActive()).toEqual(false)
})
it('Should be inactive if it depends on an inactive computed', function () {
var someObservable = observable('initial'),
shouldHaveDependency = true,
computed1 = computed(function () { shouldHaveDependency && someObservable() }),
computed2 = computed(computed1)
expect(computed2.isActive()).toEqual(true)
// Trigger a refresh
shouldHaveDependency = false
someObservable('modified')
expect(computed2.isActive()).toEqual(false)
})
it('Should advertise that instances *can* have values written to them if you supply a "write" callback', function () {
var instance = computed({
read: function () {},
write: function () {}
})
expect(isWriteableObservable(instance)).toEqual(true)
expect(isWritableObservable(instance)).toEqual(true)
})
it('Should allow deferring of evaluation (and hence dependency detection)', function () {
var timesEvaluated = 0
var instance = computed({
read: function () { timesEvaluated++; return 123 },
deferEvaluation: true
})
expect(timesEvaluated).toEqual(0)
expect(instance()).toEqual(123)
expect(timesEvaluated).toEqual(1)
})
it('Should perform dependency detection when subscribed to when constructed with "deferEvaluation"', function () {
var data = observable(1),
computedInstance = computed({ read: data, deferEvaluation: true }),
result = observable()
// initially computed has no dependencies since it has not been evaluated
expect(computedInstance.getDependenciesCount()).toEqual(0)
expect(computedInstance.getDependencies()).toEqual([])
// Now subscribe to computed
computedInstance.subscribe(result)
// The dependency should now be tracked
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([ data ])
// But the subscription should not have sent down the initial value
expect(result()).toEqual(undefined)
// Updating data should trigger the subscription
data(42)
expect(result()).toEqual(42)
})
it('Should fire "awake" event when deferred computed is first evaluated', function () {
var data = observable('A'),
computedInstance = computed({ read: data, deferEvaluation: true })
var notifySpy = jasmine.createSpy('notifySpy')
computedInstance.subscribe(notifySpy, null, 'awake')
expect(notifySpy).not.toHaveBeenCalled()
expect(computedInstance()).toEqual('A')
expect(notifySpy).toHaveBeenCalledWith('A')
expect(notifySpy.calls.length).toBe(1)
// Subscribing or updating data shouldn't trigger any more notifications
notifySpy.reset()
computedInstance.subscribe(function () {})
data('B')
computedInstance()
expect(notifySpy).not.toHaveBeenCalled()
})
it('Should prevent recursive calling of read function', function () {
var observableInstance = observable(0)
computed(function () {
// this both reads and writes to the observable
// will result in errors like "Maximum call stack size exceeded" (chrome)
// or "Out of stack space" (IE) or "too much recursion" (Firefox) if recursion
// isn't prevented
observableInstance(observableInstance() + 1)
})
})
it('Should not subscribe to observables accessed through change notifications of a computed', function () {
// See https://github.com/SteveSanderson/knockout/issues/341
var observableDependent = observable(),
observableIndependent = observable(),
computedInstance = computed(function () { return observableDependent() })
// initially there is only one dependency
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([observableDependent])
// create a change subscription that also accesses an observable
computedInstance.subscribe(function () { observableIndependent() })
// now trigger evaluation of the computed by updating its dependency
observableDependent(1)
// there should still only be one dependency
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([observableDependent])
// also test with a beforeChange subscription
computedInstance.subscribe(function () { observableIndependent() }, null, 'beforeChange')
observableDependent(2)
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([observableDependent])
})
it('Should not subscribe to observables accessed through change notifications of a modified observable', function () {
// See https://github.com/SteveSanderson/knockout/issues/341
var observableDependent = observable(),
observableIndependent = observable(),
observableModified = observable(),
computedInstance = computed(function () { observableModified(observableDependent()) })
// initially there is only one dependency
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([observableDependent])
// create a change subscription that also accesses an observable
observableModified.subscribe(function () { observableIndependent() })
// now trigger evaluation of the computed by updating its dependency
observableDependent(1)
// there should still only be one dependency
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([observableDependent])
// also test with a beforeChange subscription
observableModified.subscribe(function () { observableIndependent() }, null, 'beforeChange')
observableDependent(2)
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([observableDependent])
})
it('Should be able to re-evaluate a computed that previously threw an exception', function () {
var observableSwitch = observable(true), observableValue = observable(1),
computedInstance = computed(function () {
if (!observableSwitch()) {
throw Error('Error during computed evaluation')
} else {
return observableValue()
}
})
// Initially the computed evaluated successfully
expect(computedInstance()).toEqual(1)
expect(function () {
// Update observable to cause computed to throw an exception
observableSwitch(false)
}).toThrow('Error during computed evaluation')
// The value of the computed is now undefined, although currently it keeps the previous value
expect(computedInstance()).toEqual(1)
// The computed should not be dependent on the second observable
expect(computedInstance.getDependenciesCount()).toEqual(1)
expect(computedInstance.getDependencies()).toEqual([observableSwitch])
// Updating the second observable shouldn't re-evaluate computed
observableValue(2)
expect(computedInstance()).toEqual(1)
// Update the first observable to cause computed to re-evaluate
observableSwitch(1)
expect(computedInstance()).toEqual(2)
})
it('Should expose a "notify" extender that can configure a computed to notify on all changes', function () {
var notifiedValues = []
var observableInstance = observable(1)
var computedInstance = computed(function () { return observableInstance() })
computedInstance.subscribe(function (value) { notifiedValues.push(value) })
expect(notifiedValues).toEqual([])
// Trigger update without changing value; the computed will not notify the change (default behavior)
observableInstance.valueHasMutated()
expect(notifiedValues).toEqual([])
// Set the computed to notify always
computedInstance.extend({ notify: 'always' })
observableInstance.valueHasMutated()
expect(notifiedValues).toEqual([1])
})
it('Should support array tracking using extender', function () {
var myArray = observable(['Alpha', 'Beta', 'Gamma']),
myComputed = computed(function () {
return myArray().slice(-2)
}).extend({trackArrayChanges: true}),
changelist
expect(myComputed()).toEqual(['Beta', 'Gamma'])
var arrayChange = myComputed.subscribe(function (changes) {
changelist = changes
}, null, 'arrayChange')
myArray(['Alpha', 'Beta', 'Gamma', 'Delta'])
expect(myComputed()).toEqual(['Gamma', 'Delta'])
expect(changelist).toEqual([
{ status: 'deleted', value: 'Beta', index: 0 },
{ status: 'added', value: 'Delta', index: 1 }
])
// Should clean up all subscriptions when arrayChange subscription is disposed
arrayChange.dispose()
expect(myComputed.getSubscriptionsCount()).toBe(0)
})
// Borrowed from haberman/knockout (see knockout/knockout#359)
it('Should allow long chains without overflowing the stack', function () {
// maximum with previous code (when running this test only): Chrome 28: 1310, IE 10: 2200; FF 23: 103
// maximum with changed code: Chrome 28: 2620, +100%, IE 10: 4900, +122%; FF 23: 267, +160%
// (per #1622 and #1905, max depth reduced to pass tests in older FF)
var depth = 100
var first = observable(0)
var last = first
for (var i = 0; i < depth; i++) {
(function () {
var l = last
last = computed(function () { return l() + 1 })
})()
}
var all = computed(function () { return last() + first() })
first(1)
expect(all()).toEqual(depth + 2)
})
it('Should inherit any properties defined on ko.subscribable.fn or computed.fn', function () {
this.after(function () {
delete subscribable.fn.customProp // Will be able to reach this
delete subscribable.fn.customFunc // Overridden on computed.fn
delete computed.fn.customFunc // Will be able to reach this
})
subscribable.fn.customProp = 'subscribable value'
subscribable.fn.customFunc = function () { throw new Error('Shouldn\'t be reachable') }
computed.fn.customFunc = function () { return this() }
var instance = computed(function () { return 123 })
expect(instance.customProp).toEqual('subscribable value')
expect(instance.customFunc()).toEqual(123)
})
it('Should have access to functions added to "fn" on existing instances on supported browsers', function () {
// On unsupported browsers, there's nothing to test
if (!jasmine.browserSupportsProtoAssignment) {
return
}
this.after(function () {
delete subscribable.fn.customFunction1
delete computed.fn.customFunction2
})
var computedInstance = computed(function () {})
var customFunction1 = function () {}
var customFunction2 = function () {}
subscribable.fn.customFunction1 = customFunction1
computed.fn.customFunction2 = customFunction2
expect(computedInstance.customFunction1).toBe(customFunction1)
expect(computedInstance.customFunction2).toBe(customFunction2)
})
it('Should not evaluate (or add dependencies) after it has been disposed', function () {
var evaluateCount = 0,
observableInstance = observable(0),
computedInstance = computed(function () {
return ++evaluateCount + observableInstance()
})
expect(evaluateCount).toEqual(1)
computedInstance.dispose()
// This should not cause a new evaluation
observableInstance(1)
expect(evaluateCount).toEqual(1)
expect(computedInstance()).toEqual(1)
expect(computedInstance.getDependenciesCount()).toEqual(0)
expect(computedInstance.getDependencies()).toEqual([])
})
it('Should not evaluate (or add dependencies) after it has been disposed if created with "deferEvaluation"', function () {
var evaluateCount = 0,
observableInstance = observable(0),
computedInstance = computed({
read: function () {
return ++evaluateCount + observable()
},
deferEvaluation: true
})
expect(evaluateCount).toEqual(0)
computedInstance.dispose()
// This should not cause a new evaluation
observableInstance(1)
expect(evaluateCount).toEqual(0)
expect(computedInstance()).toEqual(undefined)
expect(computedInstance.getDependenciesCount()).toEqual(0)
expect(computedInstance.getDependencies()).toEqual([])
})
it('Should not add dependencies if disposed during evaluation', function () {
// This is a bit of a contrived example and likely won't occur in any actual applications.
// A more likely scenario might involve a binding that removes a node connected to the binding,
// causing the binding's computed observable to dispose.
// See https://github.com/knockout/knockout/issues/1041
var evaluateCount = 0,
observableToTriggerDisposal = observable(false),
observableGivingValue = observable(0),
computedInstance = computed(function () {
if (observableToTriggerDisposal()) { computedInstance.dispose() }
return ++evaluateCount + observableGivingValue()
})
// Check initial state
expect(evaluateCount).toEqual(1)
expect(computedInstance()).toEqual(1)
expect(computedInstance.getDependenciesCount()).toEqual(2)
expect(computedInstance.getDependencies()).toEqual([observableToTriggerDisposal, observableGivingValue])
expect(observableGivingValue.getSubscriptionsCount()).toEqual(1)
// Now cause a disposal during evaluation
observableToTriggerDisposal(true)
expect(evaluateCount).toEqual(2)
expect(computedInstance()).toEqual(2)
expect(computedInstance.getDependenciesCount()).toEqual(0)
expect(computedInstance.getDependencies()).toEqual([])
expect(observableGivingValue.getSubscriptionsCount()).toEqual(0)
})
describe('Context', function () {
it('Should accurately report initial evaluation', function () {
var observableInstance = observable(1),
evaluationCount = 0,
computedInstance = computed(function () {
++evaluationCount
observableInstance() // for dependency
return dependencyDetection.isInitial()
})
expect(evaluationCount).toEqual(1) // single evaluation
expect(computedInstance()).toEqual(true) // value of isInitial was true
observableInstance(2)
expect(evaluationCount).toEqual(2) // second evaluation
expect(computedInstance()).toEqual(false) // value of isInitial was false
// value outside of computed is undefined
expect(dependencyDetection.isInitial()).toBeUndefined()
})
it('Should accurately report initial evaluation when deferEvaluation is true', function () {
var observableInstance = observable(1),
evaluationCount = 0,
computedInstance = computed(function () {
++evaluationCount
observableInstance() // for dependency
return dependencyDetection.isInitial()
}, null, {deferEvaluation: true})
expect(evaluationCount).toEqual(0) // no evaluation yet
expect(computedInstance()).toEqual(true) // first access causes evaluation; value of isInitial was true
expect(evaluationCount).toEqual(1) // single evaluation
observableInstance(2)
expect(evaluationCount).toEqual(2) // second evaluation
expect(computedInstance()).toEqual(false) // value of isInitial was false
})
it('Should accurately report the number of dependencies', function () {
var observable1 = observable(1),
observable2 = observable(1),
evaluationCount = 0,
computedInstance = computed(function () {
++evaluationCount
// no dependencies at first
expect(dependencyDetection.getDependenciesCount()).toEqual(0)
expect(dependencyDetection.getDependencies()).toEqual([])
// add a single dependency
observable1()
expect(dependencyDetection.getDependenciesCount()).toEqual(1)
expect(dependencyDetection.getDependencies()).toEqual([observable1])
// add a second one
observable2()
expect(dependencyDetection.getDependenciesCount()).toEqual(2)
expect(dependencyDetection.getDependencies()).toEqual([observable1, observable2])
// accessing observable again doesn't affect count
observable1()
expect(dependencyDetection.getDependenciesCount()).toEqual(2)
expect(dependencyDetection.getDependencies()).toEqual([observable1, observable2])
})
expect(evaluationCount).toEqual(1) // single evaluation
expect(computedInstance.getDependenciesCount()).toEqual(2) // matches value from context
expect(computedInstance.getDependencies()).toEqual([observable1, observable2])
observable1(2)
expect(evaluationCount).toEqual(2) // second evaluation
expect(computedInstance.getDependenciesCount()).toEqual(2) // matches value from context
expect(computedInstance.getDependencies()).toEqual([observable1, observable2])
// value outside of computed is undefined
expect(dependencyDetection.getDependenciesCount()).toBeUndefined()
expect(dependencyDetection.getDependencies()).toBeUndefined()
})
})
describe('observableArray properties', function () {
it('Should be able to call standard mutators without creating a subscription', function () {
var timesEvaluated = 0,
newArray = observableArray(['Alpha', 'Beta', 'Gamma'])
computed(function () {
// Make a few standard mutations
newArray.push('Delta')
newArray.remove('Beta')
newArray.splice(2, 1)
// Peek to ensure we really had the intended effect
expect(newArray.peek()).toEqual(['Alpha', 'Gamma'])
// Also make use of the KO delete/destroy functions to check they don't cause subscriptions
newArray([{ someProp: 123 }])
newArray.destroyAll()
expect(newArray.peek()[0]._destroy).toEqual(true)
newArray.removeAll()
expect(newArray.peek()).toEqual([])
timesEvaluated++
})
// Verify that we haven't caused a subscription
expect(timesEvaluated).toEqual(1)
expect(newArray.getSubscriptionsCount()).toEqual(0)
// Don't just trust getSubscriptionsCount - directly verify that mutating newArray doesn't cause a re-eval
newArray.push('Another')
expect(timesEvaluated).toEqual(1)
})
})
}) | the_stack |
import { expect } from "chai";
import * as React from "react";
import * as sinon from "sinon";
import * as moq from "typemoq";
import { fireEvent, render } from "@testing-library/react";
import { IModelApp, MockRender, QuantityType, QuantityTypeKey } from "@itwin/core-frontend";
import TestUtils, { getButtonWithText, handleError, selectChangeValueByText, stubScrollIntoView } from "../TestUtils";
import { Presentation, PresentationManager } from "@itwin/presentation-frontend";
import { mockPresentationManager } from "@itwin/presentation-components/lib/cjs/test";
import { getQuantityFormatsSettingsManagerEntry } from "../../appui-react/settings/quantityformatting/QuantityFormat";
import { ModalDialogRenderer } from "../../appui-react/dialog/ModalDialogManager";
import { FormatProps, UnitSystemKey } from "@itwin/core-quantity";
import { UiFramework } from "../../appui-react/UiFramework";
describe("QuantityFormatSettingsPage", () => {
let presentationManagerMock: moq.IMock<PresentationManager>;
const sandbox = sinon.createSandbox();
before(async () => {
await TestUtils.initializeUiFramework();
await MockRender.App.startup();
});
after(async () => {
TestUtils.terminateUiFramework();
await MockRender.App.shutdown();
Presentation.terminate();
});
beforeEach(async () => {
await IModelApp.quantityFormatter.reinitializeFormatAndParsingsMaps(new Map<UnitSystemKey, Map<QuantityTypeKey, FormatProps>>(), "imperial");
presentationManagerMock = mockPresentationManager().presentationManager;
presentationManagerMock.setup((x) => x.activeUnitSystem).returns(() => "imperial");
Presentation.setPresentationManager(presentationManagerMock.object);
});
afterEach(() => {
sandbox.restore();
});
stubScrollIntoView();
it("will handle internal unit system change", async () => {
const settingsEntry = getQuantityFormatsSettingsManagerEntry(10);
expect(settingsEntry.itemPriority).to.eql(10);
const unitSystemSpy = sandbox.spy();
// setup fake setter in the mocked object
sandbox.stub(Presentation.presentation, "activeUnitSystem").set(unitSystemSpy);
const wrapper = render(settingsEntry.page);
const selectButton = wrapper.getByTestId("unitSystemSelector");
// initial unit system value should be imperial so no change expected for initial change.
// fireEvent.change(selectButton, { target: { value: "imperial" } });
selectChangeValueByText(selectButton, "presentationUnitSystem.BritishImperial", handleError);
expect(unitSystemSpy.calledOnce).to.be.false;
// fireEvent.change(selectButton, { target: { value: "metric" } });
selectChangeValueByText(selectButton, "presentationUnitSystem.Metric", handleError);
expect(unitSystemSpy.calledOnce).to.be.true;
unitSystemSpy.resetHistory();
await TestUtils.flushAsyncOperations();
// fireEvent.change(selectButton, { target: { value: "usCustomary" } });
selectChangeValueByText(selectButton, "presentationUnitSystem.USCustomary", handleError);
expect(unitSystemSpy.calledOnce).to.be.true;
unitSystemSpy.resetHistory();
await TestUtils.flushAsyncOperations();
// fireEvent.change(selectButton, { target: { value: "usSurvey" } });
selectChangeValueByText(selectButton, "presentationUnitSystem.USSurvey", handleError);
expect(unitSystemSpy.calledOnce).to.be.true;
unitSystemSpy.resetHistory();
await TestUtils.flushAsyncOperations();
// fireEvent.change(selectButton, { target: { value: "imperial" } });
selectChangeValueByText(selectButton, "presentationUnitSystem.BritishImperial", handleError);
expect(unitSystemSpy.calledOnce).to.be.true;
await TestUtils.flushAsyncOperations();
wrapper.unmount();
});
it("will listen for external unit system changes", async () => {
const settingsEntry = getQuantityFormatsSettingsManagerEntry(10, { initialQuantityType: QuantityType.Length });
expect(settingsEntry.itemPriority).to.eql(10);
const unitSystemSpy = sandbox.spy();
// setup fake setter in the mocked object
sandbox.stub(Presentation.presentation, "activeUnitSystem").set(unitSystemSpy);
const wrapper = render(settingsEntry.page);
await IModelApp.quantityFormatter.setActiveUnitSystem("metric", false);
await TestUtils.flushAsyncOperations();
const exampleFormat = wrapper.getByTestId("format-sample-formatted");
expect(exampleFormat.textContent).to.eql("1234.56 m");
wrapper.unmount();
});
it("will render 3 units and process quantity type selection in list", async () => {
await IModelApp.quantityFormatter.setActiveUnitSystem("imperial", false);
const availableUnitSystems = new Set<UnitSystemKey>(["metric", "imperial", "usSurvey"]);
const settingsEntry = getQuantityFormatsSettingsManagerEntry(10, { initialQuantityType: QuantityType.LengthEngineering, availableUnitSystems });
expect(settingsEntry.itemPriority).to.eql(10);
const wrapper = render(settingsEntry.page);
await TestUtils.flushAsyncOperations();
const listSelector = `ul.uifw-quantity-types`;
const categoryList = wrapper.container.querySelector(listSelector);
expect(categoryList!.getAttribute("data-value")).to.eql("QuantityTypeEnumValue-9");
const dataValueSelector = `li[data-value='QuantityTypeEnumValue-7']`;
const categoryEntry = wrapper.container.querySelector(dataValueSelector);
expect(categoryEntry).not.to.be.null;
fireEvent.click(categoryEntry!);
await TestUtils.flushAsyncOperations();
expect(categoryList!.getAttribute("data-value")).to.eql("QuantityTypeEnumValue-7");
wrapper.unmount();
});
it("save prop changes", async () => {
const availableUnitSystems = new Set<UnitSystemKey>(["metric", "imperial", "usSurvey"]);
const settingsEntry = getQuantityFormatsSettingsManagerEntry(10, { initialQuantityType: QuantityType.LengthEngineering, availableUnitSystems });
expect(settingsEntry.itemPriority).to.eql(10);
const wrapper = render(<div>
<ModalDialogRenderer />
{settingsEntry.page}
</div>);
const setButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.setButtonLabel", handleError);
expect(setButton!.hasAttribute("disabled")).to.be.true;
const clearButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.clearButtonLabel", handleError);
expect(clearButton!.hasAttribute("disabled")).to.be.true;
const checkbox = wrapper.getByTestId("show-unit-label-checkbox");
fireEvent.click(checkbox);
await TestUtils.flushAsyncOperations();
expect(setButton!.hasAttribute("disabled")).to.be.false;
fireEvent.click(setButton!);
await TestUtils.flushAsyncOperations();
expect(setButton!.hasAttribute("disabled")).to.be.true;
expect(clearButton!.hasAttribute("disabled")).to.be.false;
fireEvent.click(clearButton!);
await TestUtils.flushAsyncOperations();
expect(clearButton!.hasAttribute("disabled")).to.be.true;
wrapper.unmount();
});
it("will trigger modal and save prop changes", async () => {
const availableUnitSystems = new Set<UnitSystemKey>(["metric", "imperial", "usSurvey"]);
const settingsEntry = getQuantityFormatsSettingsManagerEntry(10, { initialQuantityType: QuantityType.LengthEngineering, availableUnitSystems });
expect(settingsEntry.itemPriority).to.eql(10);
const wrapper = render(<div>
<ModalDialogRenderer />
{settingsEntry.page}
</div>);
const setButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.setButtonLabel", handleError);
expect(setButton!.hasAttribute("disabled")).to.be.true;
const clearButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.clearButtonLabel", handleError);
expect(clearButton!.hasAttribute("disabled")).to.be.true;
const checkbox = wrapper.getByTestId("show-unit-label-checkbox");
fireEvent.click(checkbox);
await TestUtils.flushAsyncOperations();
expect(setButton!.hasAttribute("disabled")).to.be.false;
const dataValueSelector = `li[data-value='QuantityTypeEnumValue-7']`;
const categoryEntry = wrapper.container.querySelector(dataValueSelector);
expect(categoryEntry).not.to.be.null;
fireEvent.click(categoryEntry!);
await TestUtils.flushAsyncOperations();
const yesButton = wrapper.container.querySelector("button.dialog-button-yes");
fireEvent.click(yesButton!);
await TestUtils.flushAsyncOperations();
wrapper.unmount();
});
it("will trigger modal and don't save prop changes", async () => {
const availableUnitSystems = new Set<UnitSystemKey>(["metric", "imperial", "usSurvey"]);
const settingsEntry = getQuantityFormatsSettingsManagerEntry(10, { initialQuantityType: QuantityType.LengthEngineering, availableUnitSystems });
expect(settingsEntry.itemPriority).to.eql(10);
const wrapper = render(<div>
<ModalDialogRenderer />
{settingsEntry.page}
</div>);
const setButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.setButtonLabel", handleError);
expect(setButton!.hasAttribute("disabled")).to.be.true;
const clearButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.clearButtonLabel", handleError);
expect(clearButton!.hasAttribute("disabled")).to.be.true;
await TestUtils.flushAsyncOperations();
const checkbox = wrapper.getByTestId("show-unit-label-checkbox");
fireEvent.click(checkbox);
await TestUtils.flushAsyncOperations();
expect(setButton!.hasAttribute("disabled")).to.be.false;
const dataValueSelector = `li[data-value='QuantityTypeEnumValue-7']`;
const categoryEntry = wrapper.container.querySelector(dataValueSelector);
expect(categoryEntry).not.to.be.null;
fireEvent.click(categoryEntry!);
await TestUtils.flushAsyncOperations();
const noButton = wrapper.container.querySelector("button.dialog-button-no");
fireEvent.click(noButton!);
await TestUtils.flushAsyncOperations();
wrapper.unmount();
});
it("will trigger modal by event from settings manager and don't save prop changes", async () => {
const availableUnitSystems = new Set<UnitSystemKey>(["metric", "imperial", "usSurvey"]);
const settingsEntry = getQuantityFormatsSettingsManagerEntry(10, { initialQuantityType: QuantityType.LengthEngineering, availableUnitSystems });
expect(settingsEntry.itemPriority).to.eql(10);
const wrapper = render(<div>
<ModalDialogRenderer />
{settingsEntry.page}
</div>);
const setButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.setButtonLabel", handleError);
expect(setButton!.hasAttribute("disabled")).to.be.true;
const clearButton = getButtonWithText(wrapper.container, "settings.quantity-formatting.clearButtonLabel", handleError);
expect(clearButton!.hasAttribute("disabled")).to.be.true;
await TestUtils.flushAsyncOperations();
const checkbox = wrapper.getByTestId("show-unit-label-checkbox");
fireEvent.click(checkbox);
await TestUtils.flushAsyncOperations();
expect(setButton!.hasAttribute("disabled")).to.be.false;
UiFramework.settingsManager.onProcessSettingsTabActivation.emit({ requestedSettingsTabId: "unknown", tabSelectionFunc: () => { } });
await TestUtils.flushAsyncOperations();
const noButton = wrapper.container.querySelector("button.dialog-button-no");
fireEvent.click(noButton!);
await TestUtils.flushAsyncOperations();
wrapper.unmount();
});
}); | the_stack |
import RamlWrapper = require('../artifacts/raml10parserapi')
import RamlWrapperImpl = require('../artifacts/raml10parser')
import factory = require('../artifacts/raml10factory')
import core=require("./parserCore");
import ramlPathMatch = require("../../util/raml-path-match")
import hl = require('../highLevelAST');
import hlimpl = require('../highLevelImpl');
import linter = require('../ast.core/linter');
import stubs = require('../stubs');
import defs = require('raml-definition-system');
import tsInterfaces = defs.tsInterfaces
import universeDef = require("../tools/universe");
import universes=require("../tools/universe")
import Opt = require('../../Opt')
import util = require('../../util/index');
import expanderLL=require("../ast.core/expanderLL")
import proxy = require("../ast.core/LowLevelASTProxy")
import referencePatcher = require("../ast.core/referencePatcherLL")
import search=require("../../search/search-interface")
import ll=require("../lowLevelAST");
import llImpl=require("../jsyaml/jsyaml2lowLevel");
import json=require("../jsyaml/json2lowLevel");
import path=require("path");
import ramlservices=defs
import universeHelpers = require("../tools/universeHelpers");
import universeProvider = defs
import rTypes = defs.rt;
import builder = require("../ast.core/builder");
import helpersLL = require("./helpersLL");
let messageRegistry = require("../../../resources/errorMessages");
export function resolveType(p:RamlWrapper.TypeDeclaration):hl.ITypeDefinition{
return p.highLevel().localType();
}
//__$helperMethod__ Runtime representation of type represented by this AST node
export function runtimeType(p:RamlWrapper.TypeDeclaration):hl.ITypeDefinition{
return p.highLevel().localType();
}
export function load(pth: string):core.BasicNode{
var m=new llImpl.Project(path.dirname(pth));
var unit=m.unit(path.basename(pth));
if (unit){
if (unit.isRAMLUnit()){
return (<hlimpl.ASTNodeImpl>hlimpl.fromUnit(unit)).wrapperNode();
}
}
return null;
}
//__$helperMethod__ Path relative to API root
export function completeRelativeUri(res:RamlWrapper.Resource):string{
var uri = '';
var parent:any = res;
do{
res = <RamlWrapper.Resource>parent;//(parent instanceof RamlWrapper.ResourceImpl) ? <RamlWrapper.Resource>parent : null;
uri = res.relativeUri().value() + uri;
parent = res.parent();
}
while (parent.definition().key().name==universes.Universe10.Resource.name);
return uri;
}
/**
* __$helperMethod__
* Equivalent Library which contains all its dependencies
* __$meta__={"name":"expand"}
*/
export function expandLibrarySpec(lib:RamlWrapper.Library):RamlWrapper.Library{
return expanderLL.expandLibrary(lib);
}
/**
* __$helperMethod__
* Equivalent API with traits and resource types expanded
* @expLib whether to apply library expansion or not
* __$meta__={"name":"expand"}
*/
export function expandSpec(api:RamlWrapper.Api,expLib:boolean=false):RamlWrapper.Api{
if(expLib){
return expandLibraries(api);
}
else{
return expandTraitsAndResourceTypes(api);
}
}
/**
* Equivalent API with traits and resource types expanded
*/
export function expandTraitsAndResourceTypes(api:RamlWrapper.Api):RamlWrapper.Api{
var lowLevelNode = api.highLevel().lowLevel();
if(proxy.LowLevelProxyNode.isInstance(lowLevelNode)){
return api;
}
return expanderLL.expandTraitsAndResourceTypes(api);
}
/**
* Expand traits, resource types and libraries for the API
* __$meta__={"name":"expandLibraries"}
*/
export function expandLibraries(api:RamlWrapper.Api):RamlWrapper.Api{
return expanderLL.expandLibraries(api);
}
//__$helperMethod__ baseUri of owning Api concatenated with completeRelativeUri
export function absoluteUri(res:RamlWrapper.Resource):string{
var uri = '';
var parent:any = res;
do{
res = <RamlWrapper.Resource>parent;//(parent instanceof RamlWrapper.ResourceImpl) ? <RamlWrapper.Resource>parent : null;
uri = res.relativeUri().value() + uri;
parent = res.parent();
}
while (parent.definition().key().name==universes.Universe10.Resource.name);
parent = getParent(res);
var buri=(<RamlWrapper.Api>parent).baseUri();
var base =buri?buri.value():"";
base = base ? base : '';
if(res){
base = base.replace(/\/+$/,"");
}
uri = base + uri;
return uri;
}
//__$helperMethod__ validate an instance against type
export function validateInstance(res:RamlWrapper.TypeDeclaration, value: any):string[]{
return res.runtimeType().validate(value).map(x=>x.getMessage());
//throw new Error("Fix me");
}
//__$helperMethod__ validate an instance against type
export function validateInstanceWithDetailedStatuses(res:RamlWrapper.TypeDeclaration, value: any): any{
return res.runtimeType().validate(value);
}
/**
* __$helperMethod__
* Retrieve all traits including those defined in libraries
* __$meta__{"name":"traits","override":true}
*/
export function traitsPrimary(a:RamlWrapper.LibraryBase):RamlWrapper.Trait[]{
return allTraits(a);
}
/**
* __$helperMethod__ Retrieve all traits including those defined in libraries
* __$meta__{"deprecated":true}
*/
export function allTraits(a:RamlWrapper.LibraryBase):RamlWrapper.Trait[]{
if(a.highLevel().lowLevel().actual().libExpanded){
return (<RamlWrapperImpl.LibraryBaseImpl>a).traits_original();
}
return helpersLL.allTraits(a.highLevel(),true).map(x=><RamlWrapper.Trait>x.wrapperNode());
}
/**
* __$helperMethod__
* Retrieve all resource types including those defined in libraries
* __$meta__{"name":"resourceTypes","override":true}
*/
export function resourceTypesPrimary(a:RamlWrapper.LibraryBase):RamlWrapper.ResourceType[]{
return allResourceTypes(a);
}
/**
* __$helperMethod__ Retrieve all resource types including those defined in libraries
* __$meta__{"deprecated":true}
*/
export function allResourceTypes(a:RamlWrapper.LibraryBase):RamlWrapper.ResourceType[]{
if(a.highLevel().lowLevel().actual().libExpanded){
return (<RamlWrapperImpl.LibraryBaseImpl>a).resourceTypes_original();
}
return helpersLL.allResourceTypes(a.highLevel(),true).map(x=><RamlWrapper.ResourceType>x.wrapperNode());
}
export function relativeUriSegments(res:RamlWrapper.Resource):string[]{
var result:string[] = [];
var parent:any = res;
do{
res = <RamlWrapper.Resource>parent;//(parent instanceof RamlWrapper.ResourceImpl) ? <RamlWrapper.Resource>parent : null;
result.push(res.relativeUri().value());
parent = res.parent();
}
while (parent.definition().key().name==universes.Universe10.Resource.name);
return result.reverse();
}
//__$helperMethod__ For methods of Resources returns parent resource. For methods of ResourceTypes returns null.
export function parentResource(method:RamlWrapper.Method):RamlWrapper.Resource{
if(RamlWrapperImpl.ResourceImpl.isInstance(method.parent())) {
return <RamlWrapper.Resource><any>method.parent();
}
return null;
}
/**
* __$helperMethod__
* Parent resource for non top level resources
* __$meta__={"name":"parentResource"}
*/
export function parent(resource:RamlWrapper.Resource):RamlWrapper.Resource{
var parent = resource.parent();
if(parent.definition().key().name==universes.Universe10.Resource.name){
return <RamlWrapper.Resource>parent
}
return null;
}
//__$helperMethod__ Get child resource by its relative path
export function childResource(container:RamlWrapper.Resource|RamlWrapper.Api, relPath:string):RamlWrapper.Resource{
if(container==null){
return null;
}
var resources:RamlWrapper.Resource[] = container.resources();
if(!resources){
return null;
}
resources = resources.filter(x=>x.relativeUri().value()==relPath);
if(resources.length==0){
return null;
}
return resources[0];
}
export function getResource(container:RamlWrapper.Api|RamlWrapper.Resource, path:string[]):RamlWrapper.Resource{
if(!container){
return null;
}
var res:RamlWrapper.Resource = null;
for (var i = 0; i < path.length; i++) {
res = childResource(container, path[i]);
if(!res){
return null;
}
container = res;
}
return res;
}
//__$helperMethod__ Get child method by its name
export function childMethod(resource:RamlWrapper.Resource, method:string):RamlWrapper.Method[]{
if(!resource){
return null;
}
return resource.methods().filter(x=>x.method()==method);
}
export function getMethod(container:RamlWrapper.Resource|RamlWrapper.Api, path:string[],method:string):RamlWrapper.Method[]{
var resource = getResource(container,path);
if(!resource){
return null;
}
return childMethod(resource,method);
}
function isApi(obj:core.BasicNode) {
return universeHelpers.isApiSibling(obj.definition());
};
//__$helperMethod__ Api owning the resource as a sibling
export function ownerApi(method:RamlWrapper.Method|RamlWrapper.Resource):RamlWrapper.Api{
var obj:core.BasicNode = method;
while(!isApi(obj)){
obj = obj.parent();
}
return <RamlWrapper.Api>obj;
}
/**
* __$helperMethod__
* For methods of Resources: `{parent Resource relative path} {methodName}`.
* For methods of ResourceTypes: `{parent ResourceType name} {methodName}`.
* For other methods throws Exception.
*/
export function methodId(method:RamlWrapper.Method):string{
var parent = method.parent();
if(RamlWrapperImpl.ResourceImpl.isInstance(parent)){
return completeRelativeUri(<RamlWrapper.Resource>parent) + ' ' + method.method().toLowerCase();
}
else if(RamlWrapperImpl.ResourceTypeImpl.isInstance(parent)){
return (<RamlWrapper.ResourceType>parent).name() + ' ' + method.method().toLowerCase();
}
throw new Error(linter.applyTemplate(messageRegistry.METHOD_OWNED_BY, {owner:method.definition().key().name}));
}
//__$helperMethod__ true for codes < 400 and false otherwise
export function isOkRange(response:RamlWrapper.Response):boolean{
var str:string = response.code().value();
var err = linter.validateResponseString(str);
if(err!=null){
return false;
}
try{
if(parseInt(str.charAt(0)) < 4){
return true;
}
}
catch(e){}
return false;
}
//__$helperMethod__ Retrieve all resources of the Api
export function allResources(api:RamlWrapper.Api):RamlWrapper.Resource[]{
var resources:RamlWrapper.Resource[] = []
var visitor = (res:RamlWrapper.Resource) => {
resources.push(res);
res.resources().forEach(x=>visitor(x));
}
api.resources().forEach(x=>visitor(x));
return resources;
}
export function matchUri(apiRootRelativeUri:string, resource:RamlWrapper.Resource):Opt<ParamValue[]>{
var allParameters:Raml08Parser.NamedParameterMap = {}
while(resource != null){
uriParameters(resource).forEach(x=>allParameters[x.name()]=new ParamWrapper(x));
resource = parent(resource);
}
var result = ramlPathMatch.ramlPathMatch(completeRelativeUri(resource), allParameters, {})(apiRootRelativeUri);
if (result) {
return new Opt<ParamValue[]>(Object.keys((<any>result).params)
.map(x=>new ParamValue(x, result['params'][x])));
}
return Opt.empty<ParamValue[]>();
}
var schemaContentChars:string[] = [ '{', '<' ];
// export function schema(body:RamlWrapper.TypeDeclaration, api:RamlWrapper.Api):Opt<SchemaDef>{
//
// var schemaNode = body.schema();
// if(!schemaNode){
// return Opt.empty<SchemaDef>();
// }
// var schemaString = schemaNode;
// var isContent:boolean = false;
// schemaContentChars.forEach(x=>{try{ isContent = isContent||schemaString.indexOf(x)>=0}catch(e){}});
// var schDef:SchemaDef;
// if(isContent) {
// schDef = new SchemaDef(schemaString);
// }
// else{
// var globalSchemes = api.schemas().filter(x=>x.name()==schemaString);
// if(globalSchemes.length>0){
// schDef = new SchemaDef(globalSchemes[0].type(),globalSchemes[0].name());
// }
// else{
// return Opt.empty<SchemaDef>();
// }
// }
// return new Opt<SchemaDef>(schDef);
// }
/**
* __$helperMethod__
* Retrieve an ordered list of all uri parameters including those which are not described in the `uriParameters` node.
* Consider a fragment of RAML specification:
* ```yaml
* /resource/{objectId}/{propertyId}:
* uriParameters:
* objectId:
* ```
* Here `propertyId` uri parameter is not described in the `uriParameters` node,
* but it is among Resource.uriParameters().
* __$meta__={"name":"uriParameters","override": true}
*/
export function uriParametersPrimary(resource:RamlWrapper.ResourceBase):RamlWrapper.TypeDeclaration[]{
return uriParameters(resource);
}
/**
* __$helperMethod__
* Retrieve an ordered list of all uri parameters including those which are not described in the `uriParameters` node.
* Consider a fragment of RAML specification:
* ```yaml
* /resource/{objectId}/{propertyId}:
* uriParameters:
* objectId:
* ```
* Here `propertyId` uri parameter is not described in the `uriParameters` node,
* but it is among Resource.allUriParameters().
* __$meta__={"name":"allUriParameters","deprecated":true}
*/
export function uriParameters(resource:RamlWrapper.ResourceBase):RamlWrapper.TypeDeclaration[]{
var params = (<RamlWrapperImpl.ResourceBaseImpl>resource).uriParameters_original();
if(!(RamlWrapperImpl.ResourceImpl.isInstance(resource))){
return params;
}
var uri = (<RamlWrapper.Resource>resource).relativeUri().value();
var propName = universes.Universe10.ResourceBase.properties.uriParameters.name;
return extractParams(params, uri, resource, propName);
}
/**
* __$helperMethod__
* Retrieve an ordered list of all base uri parameters regardless of whether they are described in `baseUriParameters` or not
* Consider a fragment of RAML specification:
* ```yaml
* version: v1
* baseUri: https://{organization}.example.com/{version}/{service}
* baseUriParameters:
* service:
* ```
* Here `version` and `organization` are base uri parameters which are not described in the `baseUriParameters` node,
* but they are among `Api.baseUriParameters()`.
* __$meta__={"name":"baseUriParameters","override":true}
*/
export function baseUriParametersPrimary(api:RamlWrapper.Api):RamlWrapper.TypeDeclaration[]{
return baseUriParameters(api);
}
/**
* __$helperMethod__
* Retrieve an ordered list of all base uri parameters regardless of whether they are described in `baseUriParameters` or not
* Consider a fragment of RAML specification:
* ```yaml
* version: v1
* baseUri: https://{organization}.example.com/{version}/{service}
* baseUriParameters:
* service:
* ```
* Here `version` and `organization` are base uri parameters which are not described in the `baseUriParameters` node,
* but they are among `Api.allBaseUriParameters()`.
* __$meta__={"name":"allBaseUriParameters","deprecated":true}
*/
export function baseUriParameters(api:RamlWrapper.Api):RamlWrapper.TypeDeclaration[]{
var uri = api.baseUri() ? api.baseUri().value() : '';
var params = (<RamlWrapperImpl.ApiImpl>api).baseUriParameters_original();
var propName = universes.Universe10.Api.properties.baseUriParameters.name;
return extractParams(params, uri, api, propName);
}
/**
* __$helperMethod__
* Retrieve an ordered list of all absolute uri parameters. Returns a union of `Api.baseUriParameters()`
* for `Api` owning the `Resource` and `Resource.uriParameters()`.
*/
export function absoluteUriParameters(res:RamlWrapper.Resource):RamlWrapper.TypeDeclaration[]{
var params:RamlWrapper.TypeDeclaration[] = [];
var parent:any = res;
do{
res = <RamlWrapper.Resource>parent;
params = uriParameters(res).concat(params);
parent = getParent(res);
}
while (parent.definition().key().name==universes.Universe10.Resource.name);
var api = <RamlWrapper.Api>parent;
var baseUriParams = api.baseUriParameters();
params = baseUriParameters(api).concat(params);
return params;
}
function getParent(wNode:core.BasicNode){
let parent = wNode.parent();
if(!parent){
return null;
}
let slaveHL = parent.highLevel().getSlaveCounterPart();
if(slaveHL){
parent = slaveHL.wrapperNode();
}
return parent;
}
/**
* _//_$helperMethod__
* Protocols used by the API. Returns the `protocols` property value if it is specified.
* Otherwise, returns protocol, specified in the base URI.
* __$meta__={"name":"protocols","override":true}
*/
export function protocolsPrimary(api:RamlWrapper.Api):string[]{
return allProtocols(api);
}
/**
* __$helperMethod__
* Protocols used by the API. Returns the `protocols` property value if it is specified.
* Otherwise, returns protocol, specified in the base URI.
* __$meta__{"deprecated":true}
*/
export function allProtocols(api:RamlWrapper.Api):string[]{
return api.protocols().map(x=>x.toUpperCase());
//var attributeDefaults = (<RamlWrapper.ApiImpl>api).attributeDefaults();
//var result = (<RamlWrapper.ApiImpl>api).protocols_original();
//if(result.length!=0||!attributeDefaults){
// return result;
//}
//var baseUriAttr = api.baseUri();
//if(baseUriAttr) {
// var baseUri = baseUriAttr.value();
// if (baseUri) {
// var ind = baseUri.indexOf('://');
// if (ind >= 0) {
// result = [baseUri.substring(0, ind)];
// }
// if(result.length==0){
// result = [ 'HTTP' ];
// }
// }
//}
//return result;
}
/**
* _//_$helperMethod__
* Returns security schemes, resource or method is secured with. If no security schemes are set at resource or method level,
* returns schemes defined with `securedBy` at API level.
* __$meta__={"name":"securedBy","override":true}
*/
export function securedByPrimary(resourceOrMethod : RamlWrapper.ResourceBase | RamlWrapper.Method):RamlWrapper.SecuritySchemeRef[] {
return allSecuredBy(resourceOrMethod);
}
/**
* __$helperMethod__
* Returns security schemes, resource or method is secured with. If no security schemes are set at resource or method level,
* returns schemes defined with `securedBy` at API level.
* __$meta__{"deprecated":true}
*/
export function allSecuredBy(resourceOrMethod : RamlWrapper.ResourceBase | RamlWrapper.Method):RamlWrapper.SecuritySchemeRef[] {
//var currentSecuredBy = (<RamlWrapper.ResourceBaseImpl|RamlWrapper.MethodImpl>resourceOrMethod).securedBy_original();
//if (currentSecuredBy && currentSecuredBy.length > 0) {
// return currentSecuredBy;
//}
//
////instanceof, but have to avoid direct usage of instanceof in JS.
//var key = resourceOrMethod.highLevel().definition().key();
//if (key == universes.Universe10.Method) {
// var method = (<RamlWrapper.Method>resourceOrMethod);
// var resource = <RamlWrapper.ResourceImpl>method.parentResource();
// if (resource && resource.securedBy_original() && resource.securedBy_original().length > 0) {
// return resource.securedBy_original();
// }
// return method.ownerApi().securedBy();
//}
//if (key == universes.Universe10.Resource) {
// return (<RamlWrapper.Resource>resourceOrMethod).ownerApi().securedBy();
//}
return resourceOrMethod.securedBy();//return currentSecuredBy;
}
/**
* __$helperMethod__
* __$meta__={"primary":true}
*/
export function securitySchemeName(schemeReference : RamlWrapper.SecuritySchemeRef) : string {
var highLevel = schemeReference.highLevel();
if (!highLevel) return "";
var attributeValue = highLevel.value();
if (!attributeValue) return "";
return attributeValue.toString();
}
/**
* __$helperMethod__
* __$meta__={"primary":true}
*/
export function securityScheme(schemeReference : RamlWrapper.SecuritySchemeRef) : RamlWrapper.AbstractSecurityScheme {
var highLevel = schemeReference.highLevel();
if (!highLevel) return null;
var declaration = search.findDeclarationByNode(highLevel, search.LocationKind.VALUE_COMPLETION);
if (!declaration) return null;
if (!(<any>declaration).getKind || (<any>declaration).getKind() != hl.NodeKind.NODE) {
return null;
}
var result = (<hl.IHighLevelNode> declaration).wrapperNode();
if (!(RamlWrapperImpl.AbstractSecuritySchemeImpl.isInstance(result))) {
//I do not see how to avoid instanceof here
return null;
}
return <RamlWrapper.AbstractSecurityScheme> result;
}
/**
* __$helperMethod__
* __$meta__={"primary":true}
*/
export function RAMLVersion(api:RamlWrapper.Api):string{
return api.highLevel().definition().universe().version();
}
/**
* __$helperMethod__
* __$meta__={"primary":true}
*/
export function structuredValue(reference:RamlWrapper.Reference):RamlWrapper.TypeInstance{
var llNode = reference.value().lowLevel();
var type:rTypes.IParsedType = null;
var hlNode = llNode.highLevelParseResult();
if(hlNode) {
var types:rTypes.IParsedTypeCollection = null;
var isAnnotations = false;
if(hlNode.isAttr()){
isAnnotations = universeHelpers.isAnnotationsProperty(hlNode.property());
types = hlNode.parent().types();
}
else if(hlNode.isElement()){
types = hlNode.asElement().types();
}
if(types){
var refName = reference.name();
var fromLib = refName.indexOf(".")>=0;
if(fromLib){
var reg = isAnnotations ? types.getAnnotationTypeRegistry() : types.getTypeRegistry();
type = reg.get(refName);
}
else{
type = isAnnotations ? types.getAnnotationType(refName) : types.getType(refName);
}
}
}
return <RamlWrapper.TypeInstance><any>new core.TypeInstanceImpl(llNode,type);
}
/**
* __$helperMethod__
* __$meta__={"name":"name","primary":true}
*/
export function referenceName(reference:RamlWrapper.Reference):string{
var val = reference.highLevel().value();
if(typeof val == 'string' || val==null){
return val;
}
else if(hlimpl.StructuredValue.isInstance(val)){
return val.valueName();
}
return null;
}
/**
* __$helperMethod__
* __$meta__={"name":"trait","primary":true}
*/
export function referencedTrait(ref:RamlWrapper.TraitRef):RamlWrapper.Trait{
return <RamlWrapper.Trait>referencedObject(ref);
}
/**
* __$helperMethod__
* __$meta__={"name":"annotation","primary":true}
*/
export function referencedAnnotation(ref:RamlWrapper.AnnotationRef):RamlWrapper.TypeDeclaration{
return <RamlWrapper.TypeDeclaration>referencedObject(ref);
}
/**
* __$helperMethod__
* __$meta__={"name":"resourceType","primary":true}
*/
export function referencedResourceType(ref:RamlWrapper.ResourceTypeRef):RamlWrapper.ResourceType{
return <RamlWrapper.ResourceType>referencedObject(ref);
}
function referencedObject(ref:RamlWrapper.Reference):core.BasicNode{
var attr = ref.highLevel();
var parent = attr.parent();
var vn = ref.name();
var cands = search.referenceTargets(attr.property(),parent).filter(x=>hlimpl.qName(x,parent)==vn);
if(cands.length==0){
return null;
}
return cands[0].wrapperNode();
}
var toAnnotationWrappers = function (
annotations:any,
jsonNode:json.AstNode,
hlNode:hl.IHighLevelNode,
unit:ll.ICompilationUnit) {
var wrapperAnnotations:RamlWrapperImpl.AnnotationRefImpl[] = [];
if (annotations) {
var universe = defs.getUniverse("RAML10");
var aProp = universe.type("Annotable").property("annotations");
for (var aName of Object.keys(annotations)) {
var a = annotations[aName];
var aJson = new json.AstNode(unit, a.value(), jsonNode, null, "(" + aName + ")");
var aHlNode = new hlimpl.ASTPropImpl(aJson, hlNode, aProp.range(), aProp)
var wAnnotation = new RamlWrapperImpl.AnnotationRefImpl(aHlNode);
wrapperAnnotations.push(wAnnotation);
}
}
return wrapperAnnotations;
};
export function examplesFromNominal(
runtimeDefinition:hl.ITypeDefinition,
hlParent:hl.IHighLevelNode,
isSingle:boolean,
patchHL:boolean = true) {
var llParent = hlParent.lowLevel();
var property = hlParent.definition().property(isSingle ? "example" : "examples");
var universe = defs.getUniverse("RAML10");
var definition = universe.type(universeDef.Universe10.ExampleSpec.name);
var expandables = runtimeDefinition.examples().filter(x=>x!=null && !x.isEmpty() && x.isSingle() == isSingle);
return expandables.map(x=> {
var obj = x.asJSON();
var key = x.isSingle() ? "example" : null;
var unit = llParent.unit();
var jsonNode = new json.AstNode(unit, obj, llParent, null, key);
var hlNode = patchHL ? new hlimpl.ASTNodeImpl(jsonNode, hlParent, definition, property) : hlParent;
var annotations = x.annotations();
var wrapperAnnotations = toAnnotationWrappers(annotations, jsonNode, hlNode, unit);
var sa = x.scalarsAnnotations();
var sa1:{[key:string]:RamlWrapperImpl.AnnotationRefImpl[]} = {};
Object.keys(sa).forEach(x=>sa1[x]=toAnnotationWrappers(sa[x],jsonNode,hlNode,unit));
var result = new ExampleSpecImpl(hlNode, x, wrapperAnnotations, {
description: ()=>sa1["description"]||[],
displayName: ()=>sa1["displayName"]||[],
strict: ()=>sa1["strict"]||[]
});
return result;
});
};
function getExpandableExamples(node:core.BasicNode,isSingle:boolean=false):ExampleSpecImpl[] {
var runtimeDefinition = node.runtimeDefinition();
if(!runtimeDefinition){
return [];
}
var isTopLevel = runtimeDefinition.getExtra(tsInterfaces.TOP_LEVEL_EXTRA)
var nodeProperty = node.highLevel().property()
var isInTypes = nodeProperty && (universeHelpers.isTypesProperty(nodeProperty)
||universeHelpers.isSchemasProperty(nodeProperty))
if(isInTypes || !isTopLevel) {
var hlParent = node.highLevel();
return examplesFromNominal(runtimeDefinition, hlParent, isSingle);
}
else {
return []
}
};
/**
* __$helperMethod__
* __$meta__={"name":"example","primary":true}
*/
export function getTypeExample(td:RamlWrapper.TypeDeclaration):RamlWrapper.ExampleSpec{
var examples = getExpandableExamples(td,true);
if(examples.length>0){
return <RamlWrapper.ExampleSpec>examples[0];
}
return null;
}
/**
* __$helperMethod__
* __$meta__={"name":"examples","primary":true}
*/
export function getTypeExamples(td:RamlWrapper.TypeDeclaration):RamlWrapper.ExampleSpec[]{
return <RamlWrapper.ExampleSpec[]>getExpandableExamples(td);
}
/**
* __$helperMethod__
* __$meta__={"name":"fixedFacets","primary":true}
*/
export function typeFixedFacets(td:RamlWrapper.TypeDeclaration):RamlWrapper.TypeInstance{
var rDef = td.runtimeDefinition();
var obj = rDef.fixedFacets();
if(td.kind()==universeDef.Universe10.UnionTypeDeclaration.name) {
var builtInFacets = rDef.allFixedBuiltInFacets();
for (var key of Object.keys(builtInFacets)) {
obj[key] = builtInFacets[key];
}
}
else {
var keys = Object.keys(obj);
for (var key of keys) {
if (rDef.facet(key) == null) {
delete obj[key];
}
}
}
if(Object.keys(obj).length==0){
return null;
}
var node = new json.AstNode(null,obj);
return <RamlWrapper.TypeInstance><any>new core.TypeInstanceImpl(node);
}
/**
* __$helperMethod__ A base type which the current type extends, or more generally a type expression.
* __$meta__={"name":"type","override":true}
*/
export function typeValue(typeDeclaration:RamlWrapper.TypeDeclaration):string[]{
return (<RamlWrapperImpl.TypeDeclarationImpl>typeDeclaration).type_original();
// var attrs
// =typeDeclaration.highLevel().attributes(defs.universesInfo.Universe10.TypeDeclaration.properties.type.name);
//
// var structuredAttrs = attrs.filter(x=>hlimpl.StructuredValue.isInstance(x.value()));
// if(structuredAttrs.length==0){
// return (<RamlWrapperImpl.TypeDeclarationImpl>typeDeclaration).type_original().map(x=>{
// if(x===null||x==="NULL"||x==="Null"){
// return "string";
// }
// return x;
// });
// }
// var nullify=false;
// var values:string[] = attrs.map(x=>{
// var val = x.value();
// if(val==null){
// return null;
// }
// if(typeof(val)=="string"){
// return val;
// }
// else if(hlimpl.StructuredValue.isInstance(val)){
// nullify=true;
// }
// return val.toString();
// });
// if (nullify){
// return null;
// }
// return values;
}
/**
* __$helperMethod__ A base type which the current type extends, or more generally a type expression.
* __$meta__={"name":"schema","override":true}
*/
export function schemaValue(typeDeclaration:RamlWrapper.TypeDeclaration):string[]{
return (<RamlWrapperImpl.TypeDeclarationImpl>typeDeclaration).schema_original()
// var nullify=false;
// var attrs
// =typeDeclaration.highLevel().attributes(defs.universesInfo.Universe10.TypeDeclaration.properties.schema.name);
// if (nullify){
// return null;
// }
// var structuredAttrs = attrs.filter(x=>hlimpl.StructuredValue.isInstance(x.value()));
// if(structuredAttrs.length==0){
// return (<RamlWrapperImpl.TypeDeclarationImpl>typeDeclaration).schema_original();
// }
// var values:string[] = attrs.map(x=>{
// var val = x.value();
// if(typeof(val)=="string"){
// return val;
// }
// else if(hlimpl.StructuredValue.isInstance(val)){
// nullify=true;
// }
// return val.toString();
// });
// if (nullify){
// return null;
// }
// return values;
}
/**
* __$helperMethod__ Inlined supertype definition.
* __$meta__={"name":"structuredType","primary":true}
*/
export function typeStructuredValue(typeDeclaration:RamlWrapper.TypeDeclaration):RamlWrapper.TypeInstance{
var attrs
=typeDeclaration.highLevel().attributes(defs.universesInfo.Universe10.TypeDeclaration.properties.type.name);
attrs=attrs.concat(typeDeclaration.highLevel().attributes(defs.universesInfo.Universe10.TypeDeclaration.properties.schema.name))
var values = attrs.map(x=>x.value());
for(var val of values){
if(hlimpl.StructuredValue.isInstance(val)){
var typeInstance = new core.TypeInstanceImpl((<hlimpl.StructuredValue><any>val).lowLevel());
return typeInstance;
}
}
return null;
}
/**
* __$helperMethod__ Inlined component type definition.
* __$meta__={"name":"structuredItems","primary":true}
*/
export function itemsStructuredValue(typeDeclaration:RamlWrapper.ArrayTypeDeclaration):RamlWrapper.TypeInstance{
var attrs
=typeDeclaration.highLevel().attributes(defs.universesInfo.Universe10.ArrayTypeDeclaration.properties.items.name);
var values = attrs.map(x=>x.value());
for(var val of values){
if(hlimpl.StructuredValue.isInstance(val)){
var typeInstance = new core.TypeInstanceImpl((<hlimpl.StructuredValue><any>val).lowLevel());
return typeInstance;
}
}
return null;
}
/**
* __$helperMethod__
* Returns the root node of the AST, uses statement refers.
* __$meta__={"name":"ast"}
*/
export function referencedNode (usesDecl:RamlWrapper.UsesDeclaration):RamlWrapper.Library {
var ref = usesDecl.value();
var unit = usesDecl.highLevel().lowLevel().unit().resolve(ref);
var hlNode = unit.highLevel();
var hlElement = hlNode.asElement();
if(hlElement){
//we know, only libraries can be referenced from uses
var wrapperNode = hlElement.wrapperNode();
if (RamlWrapper.isLibrary(wrapperNode)) {
(<any>wrapperNode).setAttributeDefaults((<any>usesDecl).attributeDefaults())
return wrapperNode;
} else {
return null;
}
}
return null;
}
/**
* __$helperMethod__
* Anonymous type declaration defined by "items" keyword.
* If no "items" is defined explicitly, this one is null.
* __$meta__={"name":"items"}
*/
export function getItems(typeDeclaration:RamlWrapper.ArrayTypeDeclaration):string[] {
var attrs = typeDeclaration.highLevel().attributes(
defs.universesInfo.Universe10.ArrayTypeDeclaration.properties.items.name);
var structuredAttrs = attrs.filter(x=>hlimpl.StructuredValue.isInstance(x.value()));
if (structuredAttrs.length == 0) {
return (<RamlWrapperImpl.ArrayTypeDeclarationImpl>typeDeclaration).items_original().map(x=> {
if (x === null || x === "NULL" || x === "Null") {
return "string";
}
return x;
});
}
var nullify = false;
var values:string[] = attrs.map(x=> {
var val = x.value();
if (val == null) {
return null;
}
if (typeof(val) == "string") {
return val;
}
else if (hlimpl.StructuredValue.isInstance(val)) {
nullify = true;
}
return val.toString();
});
if (nullify) {
return null;
}
return values;
}
function findComponentTypeDeclBySearch(
arrayTypeDecl: RamlWrapper.ArrayTypeDeclaration) : RamlWrapper.TypeDeclaration {
var typeHighLevel = arrayTypeDecl.highLevel();
if (!typeHighLevel) return null;
var attrType = typeHighLevel.attr(universes.Universe10.TypeDeclaration.properties.type.name);
if (attrType == null) return null;
var attrTypeLowLevel = attrType.lowLevel();
if (attrTypeLowLevel == null) return null;
var attrTypeValue = attrType.value();
if (!attrTypeValue || typeof(attrTypeValue) != "string") return null;
var offset = attrTypeLowLevel.end() - attrTypeValue.length+1;
var unit = attrType.lowLevel().unit();
if (!unit) return null;
var declaration = search.findDeclaration(
unit, offset);
if (!declaration) return null;
if (!(<any>declaration).getKind || (<any>declaration).getKind() != hl.NodeKind.NODE) {
return null;
}
if(!universeHelpers.isTypeDeclarationSibling(
(<hl.IHighLevelNode> declaration).definition())) return null;
return <RamlWrapper.TypeDeclaration>(<hl.IHighLevelNode> declaration).wrapperNode();
}
function findComponentTypeDeclByRuntimeType(
arrayTypeDecl: RamlWrapper.ArrayTypeDeclaration) : RamlWrapper.TypeDeclaration {
var runtimeType = arrayTypeDecl.runtimeType();
if (!runtimeType) return null;
if(!runtimeType.isArray() || !(<any>runtimeType).componentType) return null;
var runtimeArrayType = <hl.IArrayType> runtimeType;
var componentType : hl.ITypeDefinition = runtimeArrayType.componentType();
if (!componentType) return null;
var componentTypeHLSourceProvider = search.getNominalTypeSource(componentType);
if (!componentTypeHLSourceProvider) return null;
var componentTypeSource = componentTypeHLSourceProvider.getSource();
if (!componentTypeSource) return null;
if (!componentTypeSource.isElement()) return null;
if(!universeHelpers.isTypeDeclarationSibling(
(<hl.IHighLevelNode> componentTypeSource).definition())) return null;
var basicNodeSource = (<hl.IHighLevelNode>componentTypeSource).wrapperNode();
return <RamlWrapper.TypeDeclaration> basicNodeSource;
}
/**
* __$helperMethod__
* Returns anonymous type defined by "items" keyword, or a component type if declaration can be found.
* Does not resolve type expressions. Only returns component type declaration if it is actually defined
* somewhere in AST.
*/
export function findComponentTypeDeclaration(arrayTypeDecl: RamlWrapper.ArrayTypeDeclaration) : RamlWrapper.TypeDeclaration {
var original = (<RamlWrapperImpl.ArrayTypeDeclarationImpl>arrayTypeDecl).items_original();
if (original && typeof(original)!="string" && (!Array.isArray(original)||original.length!=0)){
var highLevelNode = arrayTypeDecl.highLevel();
var itemsPropName = universeDef.Universe10.ArrayTypeDeclaration.properties.items.name;
var attr = highLevelNode.attr(itemsPropName);
var td = highLevelNode.definition().universe().type(universeDef.Universe10.TypeDeclaration.name);
var hasType = highLevelNode.definition().universe().type(universeDef.Universe10.ArrayTypeDeclaration.name);
var tNode = new hlimpl.ASTNodeImpl(attr.lowLevel(), highLevelNode, td, hasType.property(itemsPropName));
tNode.patchType(builder.doDescrimination(tNode));
}
var foundByRuntimeType = findComponentTypeDeclByRuntimeType(arrayTypeDecl);
if (foundByRuntimeType) return foundByRuntimeType;
return findComponentTypeDeclBySearch(arrayTypeDecl);
}
function extractParams(
params:RamlWrapper.TypeDeclaration[],
uri:string,
owner:core.BasicNode,
propName:string):RamlWrapper.TypeDeclaration[] {
if(typeof(uri)!='string'){
uri = "";
}
let ownerHl = owner.highLevel();
let definition = ownerHl.definition();
let prop = definition.property(propName);
let describedParams = {};
params.forEach(x=>{
let arr = describedParams[x.name()];
if(!arr){
arr = [];
describedParams[x.name()] = arr;
}
arr.push(x);
});
let allParams:RamlWrapper.TypeDeclaration[] = [];
let prev = 0;
let mentionedParams = {};
for (let i = uri.indexOf('{'); i >= 0; i = uri.indexOf('{', prev)) {
prev = uri.indexOf('}', ++i);
if(prev<0){
break;
}
let paramName = uri.substring(i, prev);
mentionedParams[paramName] = true;
if (describedParams[paramName]) {
describedParams[paramName].forEach(x=>allParams.push(x));
}
else {
let universe = definition.universe();
let nc=<defs.NodeClass>universe.type(universeDef.Universe10.StringTypeDeclaration.name);
let node=stubs.createStubNode(nc,null,paramName,ownerHl.lowLevel().unit());
let uriParameter = factory.buildWrapperNode(node);
let hlNode = uriParameter.highLevel();
hlNode.setParent(ownerHl);
(<core.NodeMetadataImpl>uriParameter.meta()).setCalculated();
(<RamlWrapperImpl.TypeDeclarationImpl>uriParameter).setName(paramName);
(<hlimpl.ASTNodeImpl>hlNode).patchProp(prop);
allParams.push(<RamlWrapper.TypeDeclaration>uriParameter);
}
}
Object.keys(describedParams).filter(x=>!mentionedParams[x])
.forEach(x=>describedParams[x].forEach(y=>allParams.push(y)));
return allParams;
}
/**
* __$helperMethod__
* __$meta__={"name":"parametrizedProperties","primary":true}
*/
export function getTemplateParametrizedProperties(
node:RamlWrapper.Trait|RamlWrapper.ResourceType|RamlWrapper.Method|RamlWrapper.Response|RamlWrapper.TypeDeclaration):RamlWrapper.TypeInstance{
if(node.kind()==universeDef.Universe10.Method.name||universeHelpers.isTypeDeclarationSibling(node.definition())){
var isInsideTemplate = false;
var parent = node.highLevel().parent();
while(parent!=null){
var pDef = parent.definition();
if(universeHelpers.isResourceTypeType(pDef)||universeHelpers.isTraitType(pDef)){
isInsideTemplate = true;
break;
}
parent = parent.parent();
}
if(!isInsideTemplate){
return null;
}
}
var highLevelNode = node.highLevel();
if(highLevelNode==null){
return null;
}
var lowLevelNode = highLevelNode.lowLevel();
if(lowLevelNode==null){
return null;
}
var children = lowLevelNode.children().filter(x=>{
var key = x.key();
if(!key){
return false;
}
if(key.charAt(0)=="("&&key.charAt(key.length-1)==")"){
return false;
}
return key.indexOf("<<")>=0
});
if(children.length==0){
return null;
}
var result = new core.TypeInstanceImpl(children);
return result;
}
export class SchemaDef{
constructor(private _content:string, private _name?:string){}
name():string{return this._name}
content(): string{return this._content}
}
export class ParamValue{
key:string
value:any
constructor(key:string, value:any) {
this.key = key;
this.value = value;
}
}
class ParamWrapper implements Raml08Parser.BasicNamedParameter{
constructor(private _param:RamlWrapper.TypeDeclaration){
this.description = _param.description() ? _param.description().value() : this.description;
this.displayName = _param.displayName();
// this.enum = _param.enum();
this.type = _param.type().length > 0 ? _param.type()[0] : "string";
this.example = _param.example();
this.required = _param.required();
this.default = _param.default();
}
description: Raml08Parser.MarkdownString
displayName: string
'enum': any[]
type: string
example: any
repeat: boolean
required: boolean
'default': any
}
export class ExampleSpecImpl extends core.BasicNodeImpl{
constructor(
hlNode:hl.IHighLevelNode,
protected expandable,
protected _annotations:core.AttributeNodeImpl[],
protected _scalarAnnotations:RamlWrapper.ExampleSpecScalarsAnnotations){
super(hlNode);
}
value():any{
return this.expandable.asString();
}
structuredValue():core.TypeInstanceImpl{
var obj;
if(this.expandable.isJSONString()||this.expandable.isYAML()) {
obj = this.expandable.asJSON();
}
else {
obj = this.expandable.original();
}
var llParent = this._node.lowLevel();
var key = this.expandable.isSingle() ? "example" : null;
var jsonNode = new json.AstNode(llParent.unit(),obj,llParent,null,key);
return new core.TypeInstanceImpl(jsonNode);
}
strict():boolean{
return this.expandable.strict();
}
description():RamlWrapper.MarkdownString{
var descriptionValue = this.expandable.description();
if(descriptionValue==null&&descriptionValue!==null){
return null;
}
var attr = stubs.createAttr(
this._node.definition().property(universeDef.Universe10.ExampleSpec.properties.description.name),
descriptionValue);
(<llImpl.ASTNode>attr.lowLevel()).setUnit(this._node.lowLevel().unit());
var result = new RamlWrapperImpl.MarkdownStringImpl(attr);
return result;
}
name():string{
return this.expandable.name();
}
displayName():string{
return this.expandable.displayName();
}
annotations():any[]{
return this._annotations;
}
scalarsAnnotations():RamlWrapper.ExampleSpecScalarsAnnotations{
return this._scalarAnnotations;
}
uses():RamlWrapper.UsesDeclaration[]{
return <RamlWrapper.UsesDeclaration[]>super.elements('uses');
}
} | the_stack |
import { TFile, Notice, LinkCache, getLinkpath } from "obsidian";
import ThePlugin from '../main';
import { FileCacheAnalyzer, CacheDetails } from '../utils/FileCacheAnalyzer';
import { SuggesterItem } from "../ui/GenericFuzzySuggester";
import { displayFileLineSuggester, openFileInObsidian, parseBookmarkForItsElements, getUniqueLinkPath } from "../utils/fileNavigatior";
import { generateBlockId } from "../utils/blockId";
import { getActiveView } from "../utils/views";
export function cleanupHeaderNameForBlockReference(header: string): string {
return header.replace(/\[|\]|#|\|/g, '').replace(/:/g, ' ');
}
// loops through current selected text and adds block refs to each paragraph
// returns all block refs found in selection
// optionally copies them to clipboard
export async function addBlockRefsToSelection(plugin: ThePlugin, copyToClipbard: boolean, copyAsAlias = false, aliasText = "*"): Promise<Array<string>> {
const activeView = getActiveView(plugin);
const activeEditor = activeView.editor;
const f = new FileCacheAnalyzer(plugin, activeView.file.path);
const curSels = activeEditor.listSelections();
const blockRefs = [];
for (const sel of curSels) {
const startLine = sel.anchor.line > sel.head.line ? sel.head.line : sel.anchor.line;
const endLine = sel.anchor.line > sel.head.line ? sel.anchor.line : sel.head.line;
for (let selectedLineInEditor = startLine; selectedLineInEditor <= endLine; selectedLineInEditor++) {
for (let sectionCounter = 0; sectionCounter < f.details.length; sectionCounter++) {
const section = f.details[sectionCounter];
if (selectedLineInEditor >= section.position.start.line && selectedLineInEditor <= section.position.end.line) {
if ((section.type === "paragraph" || section.type === "list" || section.type === "blockquote" ) && !section.blockId) {
const newId = generateBlockId();
activeEditor.replaceRange(` ^${newId}`, { line: Number(section.position.end.line), ch: section.position.end.col }, { line: Number(section.position.end.line), ch: section.position.end.col });
blockRefs.push("#^" + newId);
selectedLineInEditor = section.position.end.line;
break;
} else if (section.type === "paragraph" || section.type === "list" || section.type === "blockquote") {
blockRefs.push("#^" + section.blockId);
selectedLineInEditor = section.position.end.line;
break;
} else if (section.type === "heading") {
blockRefs.push("#" + cleanupHeaderNameForBlockReference(section.headingText));
selectedLineInEditor = section.position.end.line;
break;
}
}
}
} //selectedLineInEditor
} //curSels
if (copyToClipbard && blockRefs.length > 0) {
let block = "";
const blockPrefix = copyAsAlias === false ? "!" : ""; //if alias, don't do embed preview
aliasText = copyAsAlias === true ? "|" + aliasText : "";
const uniqueLinkPath = getUniqueLinkPath(activeView.file.path);
blockRefs.forEach(b => block += `${blockPrefix}[[${uniqueLinkPath}${b}${aliasText}]]\n`);
navigator.clipboard.writeText(block).then(text => text);
}
return blockRefs;
}
export async function copyOrPushLineOrSelectionToNewLocation(plugin: ThePlugin, copySelection: boolean, newText: string, targetFileName:string, targetFileLineNumber:number, targetFileContentsArray: Array<SuggesterItem>): Promise<void> {
if (targetFileLineNumber === -1) { //go to top of file, but test for YAML
const f = new FileCacheAnalyzer(plugin, targetFileName);
if (f.details.length > 0 && f.details[0].type === "yaml")
targetFileLineNumber = f.details[0].lineEnd;
}
targetFileContentsArray.splice(Number(targetFileLineNumber) + 1, 0, { display: newText, info: "" });
let newContents = "";
for (const line of targetFileContentsArray)
newContents += line.display + "\n";
newContents = newContents.substring(0, newContents.length - 1);
await plugin.app.vault.adapter.write(targetFileName, newContents);
if (copySelection === false) {//this is a move, so delete the selection
const activeEditor = getActiveView(plugin).editor;
const currentLine = activeEditor.getCursor().line;
const textSelection = activeEditor.getSelection();
if (textSelection === "" || activeEditor.getLine(currentLine).length === textSelection.length)
activeEditor.replaceRange("", { line: currentLine, ch: 0 }, { line: currentLine + 1, ch: 0 })
else
activeEditor.replaceSelection(""); //replace whatever is the selection
}
}
// Copies or pushes (transfers) the current line or selection to another file
// copySelection = true for copy, false for move
// defaultSelectionText (use this function to push text, without changes to local editor)
export async function copyOrPushLineOrSelectionToNewLocationWithFileLineSuggester(plugin: ThePlugin, copySelection: boolean, defaultSelectionText = ""): Promise<void> {
const activeEditor = defaultSelectionText === "" ? getActiveView(plugin).editor : null;
let selectedText = defaultSelectionText === "" ? activeEditor.getSelection() : defaultSelectionText;
if (selectedText === "") selectedText = activeEditor.getLine(activeEditor.getCursor().line); //get text from current line
await displayFileLineSuggester(plugin, false, true, false, async (targetFileName, fileContentsArray, lineNumber, endLineNumber, evtFileSelected, evtFirstLine) => {
await copyOrPushLineOrSelectionToNewLocation(plugin, copySelection, selectedText, targetFileName, lineNumber, fileContentsArray);
if ((evtFileSelected && (evtFileSelected.ctrlKey || evtFileSelected.metaKey)) || (evtFirstLine && (evtFirstLine.ctrlKey || evtFirstLine.metaKey))) {
const linesSelected = selectedText.split("\n").length;
const lineCount = linesSelected > 1 ? linesSelected - 1 : 0;
openFileInObsidian(plugin, targetFileName, lineNumber + 1, lineCount)
}
});
}
// this is primarily used by the context menu for doing copy/push actions
export async function copyOrPushLineOrSelectionToNewLocationUsingCurrentCursorLocationAndBoomark(plugin: ThePlugin, copySelection: boolean, bookmarkText: string, evt?: MouseEvent | KeyboardEvent): Promise<void> {
const bookmarkInfo = await parseBookmarkForItsElements(plugin, bookmarkText, false);
if(bookmarkInfo.errorNumber===1)
new Notice("Location in the bookmark does not exist.");
else if(bookmarkInfo.errorNumber===2)
new Notice("File as defined in the bookmark does not exist.");
else {
const activeEditor = getActiveView(plugin).editor;
const currentLine = activeEditor.getCursor().line;
let textSelection = activeEditor.getSelection();
if (textSelection === "") textSelection = activeEditor.getLine(currentLine); //get text from current line
copyOrPushLineOrSelectionToNewLocation(plugin, copySelection, textSelection, bookmarkInfo.fileName,bookmarkInfo.fileLineNumber,bookmarkInfo.fileBookmarkContentsArray);
if (evt && (evt.ctrlKey || evt.metaKey)) {
const linesSelected = textSelection.split("\n").length;
const lineCount = linesSelected > 1 ? linesSelected - 1 : 0;
openFileInObsidian(plugin, bookmarkInfo.fileName, bookmarkInfo.fileLineNumber + 1, lineCount)
}
}
}
//Copies current file to clipbaord as a link or sends it to another file
export async function copyCurrentFileNameAsLinkToNewLocation(plugin: ThePlugin, copyToCliboard: boolean): Promise<void> {
const fileLink= "[[" + getUniqueLinkPath( getActiveView(plugin).file.path ) + "]]"
if(copyToCliboard) {
navigator.clipboard.writeText(fileLink).then(text => text);
new Notice(`${fileLink}\n\n Copied to the clipboard.`)
} else
copyOrPushLineOrSelectionToNewLocationWithFileLineSuggester(plugin, true, fileLink);
}
//copy a block reference of the current line to another file
export async function pushBlockReferenceToAnotherFile(plugin: ThePlugin): Promise<void> {
await displayFileLineSuggester(plugin, false, true, false, async (targetFileName, fileContentsArray, startLine, endLineNumber, evtFileSelected, evtFirstLine) => {
if (startLine === -1) { //go to top of file, but test for YAML
const f = new FileCacheAnalyzer(plugin, targetFileName);
if (f.details.length > 0 && f.details[0].type === "yaml")
startLine = f.details[0].lineEnd;
}
const results = await addBlockRefsToSelection(plugin, false);
let blockRefs = "";
const fileName = getActiveView(plugin).file.path;
if (results.length > 0) {
for (const ref of results)
blockRefs += `![[${fileName}${ref}]]\n`;
blockRefs = blockRefs.substring(0, blockRefs.length - 1);
fileContentsArray.splice(Number(startLine) + 1, 0, { display: blockRefs, info: "" });
let newContents = "";
for (const line of fileContentsArray)
newContents += line.display + "\n";
newContents = newContents.substring(0, newContents.length - 1);
plugin.app.vault.adapter.write(targetFileName, newContents);
if ((evtFileSelected && (evtFileSelected.ctrlKey || evtFileSelected.metaKey)) || (evtFirstLine && (evtFirstLine.ctrlKey || evtFirstLine.metaKey))) {
openFileInObsidian(plugin, targetFileName, startLine + 1)
}
}
});
}
// Pull (move) a line or lines from another file
export async function copyOrPulLineOrSelectionFromAnotherLocation(plugin: ThePlugin, copySelection: boolean): Promise<void> {
await displayFileLineSuggester(plugin, true, false, true, async (targetFileName, fileContentsArray, startLine, endLine, evtFileSelected, evtFirstLine, evetLastLine) => {
const ctrlKey = (evtFileSelected && evtFileSelected.ctrlKey) || (evtFirstLine && evtFirstLine.ctrlKey) || (evetLastLine && evetLastLine.ctrlKey);
startLine = startLine === -1 ? startLine = 0 : startLine;
endLine = endLine === -1 ? endLine = 0 : endLine;
let stringToInsertIntoSelection = "";
for (const element of fileContentsArray.slice(startLine, endLine + 1))
stringToInsertIntoSelection += element.display + "\n";
stringToInsertIntoSelection = stringToInsertIntoSelection.substring(0, stringToInsertIntoSelection.length - 1);
getActiveView(plugin).editor.replaceSelection(stringToInsertIntoSelection);
if (copySelection === false) {
//pull selection, which means deleting what was just copied from original file
fileContentsArray.splice(startLine, (endLine + 1) - startLine);
let newContents = "";
for (const line of fileContentsArray)
newContents += line.display + "\n";
newContents = newContents.substring(0, newContents.length - 1);
await plugin.app.vault.adapter.write(targetFileName, newContents);
if (ctrlKey) await openFileInObsidian(plugin, targetFileName, startLine);
} else
if (ctrlKey) await openFileInObsidian(plugin, targetFileName, startLine, endLine - startLine);
});
}
// pull a block reference from another file and insert into the current location
export async function pullBlockReferenceFromAnotherFile(plugin: ThePlugin): Promise<void> {
await displayFileLineSuggester(plugin, true, false, true, async (targetFileName, fileContentsArray, startLine, endLine, evtFileSelected, evtFirstLine, evetLastLine) => {
startLine = startLine === -1 ? startLine = 0 : startLine;
endLine = endLine === -1 ? endLine = 0 : endLine;
const f = new FileCacheAnalyzer(plugin, targetFileName);
const fileContents = (await plugin.app.vault.adapter.read(targetFileName)).split("\n");
let fileChanged = false;
const blockRefs = [];
for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
for (let sectionCounter = 0; sectionCounter < f.details.length; sectionCounter++) {
const section = f.details[sectionCounter];
if (lineNumber >= section.position.start.line && lineNumber <= section.position.end.line) {
if ((section.type === "paragraph" || section.type === "list") && !section.blockId) {
const newId = generateBlockId();
fileContents.splice(section.position.end.line, 1, fileContents[section.position.end.line] + " ^" + newId);
blockRefs.push("#^" + newId);
fileChanged = true;
lineNumber = section.position.end.line;
break;
} else if (section.type === "paragraph" || section.type === "list") {
blockRefs.push("#^" + section.blockId);
lineNumber = section.position.end.line;
break;
} else if (section.type === "heading") {
const heading = cleanupHeaderNameForBlockReference(section.headingText);
blockRefs.push("#" + heading);
lineNumber = section.position.end.line;
break;
}
}
} //sectionCounter
} //lineNumber
// Save new block refs to target file
if (fileChanged === true) {
let newContents = "";
for (const line of fileContents)
newContents += line + "\n";
newContents = newContents.substring(0, newContents.length - 1);
await plugin.app.vault.adapter.write(targetFileName, newContents);
}
// insert the block refs in current cursor location
if (blockRefs.length > 0) {
let blockRefTextToInsert = "";
for (const ref of blockRefs)
blockRefTextToInsert += `![[${targetFileName}${ref}]]\n`;
blockRefTextToInsert = blockRefTextToInsert.substring(0, blockRefTextToInsert.length - 1);
getActiveView(plugin).editor.replaceSelection(blockRefTextToInsert);
}
if (evtFileSelected.ctrlKey || evtFirstLine.ctrlKey || evetLastLine.ctrlKey) {
openFileInObsidian(plugin, targetFileName, startLine, endLine - startLine);
}
});
}
export function testIfCursorIsOnALink(plugin: ThePlugin): LinkCache {
const activeView = getActiveView(plugin);
const activeEditor = activeView.editor;
const currentLine = activeEditor.getCursor().line;
const cache = this.app.metadataCache.getFileCache(activeView.file);
if (cache.links || cache.embeds || cache.headings) {
const ch = activeEditor.getCursor().ch;
let linkInfo: LinkCache = null;
if (cache.links)
linkInfo = cache.links.find((l: LinkCache) => l.position.start.line === currentLine && (ch >= l.position.start.col && ch <= l.position.end.col));
if (!linkInfo && cache.embeds)
linkInfo = cache.embeds.find((l: LinkCache) => l.position.start.line === currentLine && (ch >= l.position.start.col && ch <= l.position.end.col));
return linkInfo ? linkInfo : null;
} else
return null;
}
export async function copyBlockReferenceToCurrentCusorLocation(plugin: ThePlugin, linkInfo: LinkCache, leaveAliasToFile: boolean): Promise<void> {
const file: TFile = plugin.app.metadataCache.getFirstLinkpathDest(getLinkpath(linkInfo.link), "/");
let fileContents = await plugin.app.vault.read(file);
const cache = new FileCacheAnalyzer(plugin, file.path);
if (cache.details && linkInfo.link.includes("^")) { //blockref
const blockRefId = linkInfo.link.substr(linkInfo.link.indexOf("^") + 1);
const pos = cache.details.find((b: CacheDetails) => b.blockId === blockRefId).position;
fileContents = fileContents.split("\n").slice(pos.start.line, pos.end.line + 1).join("\n");
fileContents = fileContents.replace("^" + blockRefId, "");
} else if (cache.details && linkInfo.link.contains("#")) {//header link
const headerId = linkInfo.link.substr(linkInfo.link.indexOf("#") + 1);
const pos = cache.getPositionOfHeaderAndItsChildren(headerId);
fileContents = fileContents.split("\n").slice(pos.start.line, pos.end.line + 1).join("\n");
}
if (leaveAliasToFile) fileContents += " [[" + linkInfo.link + "|*]]";
getActiveView(plugin).editor.replaceRange(fileContents, { line: linkInfo.position.start.line, ch: linkInfo.position.start.col }, { line: linkInfo.position.end.line, ch: linkInfo.position.end.col });
} | the_stack |
import {assert} from '../../../platform/assert-web.js';
import {HandleConnectionSpec} from '../../arcs-types/particle-spec.js';
import {connectionMatchesHandleDirection} from '../../arcs-types/direction-util.js';
import {HandleConnection} from './handle-connection.js';
import {Direction} from '../../arcs-types/enums.js';
import {Handle} from './handle.js';
import {Particle} from './particle.js';
import {RecipeComponent, Recipe as PublicRecipe} from './recipe-interface.js';
import {Recipe} from './recipe.js';
import {Dictionary} from '../../../utils/lib-utils.js';
class Shape {
recipe: Recipe;
particles: Dictionary<Particle>;
handles: Map<string, Handle>;
reverse: Map<RecipeComponent, string>;
constructor(recipe: Recipe, particles: Dictionary<Particle>, handles: Map<string, Handle>, hcs: Dictionary<HandleConnection>) {
this.recipe = recipe;
this.particles = particles;
this.handles = handles;
this.reverse = new Map();
for (const p of Object.keys(particles)) {
this.reverse.set(particles[p], p);
}
for (const h of handles.keys()) {
this.reverse.set(handles.get(h), h);
}
for (const hc of Object.keys(hcs)) {
this.reverse.set(hcs[hc], hc);
}
}
}
export type HandleRepr = {localName?: string, handle: string, tags?: string[], direction?: Direction};
type RecipeUtilComponent = RecipeComponent | HandleConnectionSpec;
type Match = {forward: Map<RecipeComponent, RecipeUtilComponent>, reverse: Map<RecipeUtilComponent, RecipeComponent>, score: number};
export function makeShape(particles: string[], handles: string[], map: Dictionary<Dictionary<HandleRepr>>, recipe?: Recipe): Shape {
recipe = recipe as Recipe || new Recipe();
const pMap: Dictionary<Particle> = {};
const hMap: Map<string, Handle> = new Map();
const hcMap: Dictionary<HandleConnection> = {};
particles.forEach(particle => pMap[particle] = recipe.newParticle(particle));
handles.forEach(handle => hMap.set(handle, recipe.newHandle()));
Object.keys(map).forEach(key => {
Object.keys(map[key]).forEach(name => {
const handle: HandleRepr = map[key][name];
const tags: string[] = handle.tags || [];
if (handle.localName) {
hMap.get(handle.handle).localName = handle.localName;
}
const connection = pMap[key].addConnectionName(name);
// NOTE: for now, 'any' on the connection and shape means 'accept anything'.
connection.direction = handle.direction || 'any';
hMap.get(handle.handle).tags = tags;
connection.connectToHandle(hMap.get(handle.handle));
hcMap[key + ':' + name] = pMap[key].connections[name];
});
});
return new Shape(recipe, pMap, hMap, hcMap);
}
function recipeToShape(recipe: Recipe) {
const particles = {};
let id = 0;
recipe.particles.forEach(particle => particles[particle.name] = particle);
const handles = new Map<string, Handle>();
recipe.handles.forEach(handle => handles.set('h' + id++, handle));
const hcs = {};
recipe.handleConnections.forEach(hc => hcs[hc.particle.name + ':' + hc.name] = hc);
return new Shape(recipe, particles, handles, hcs);
}
function _buildNewHCMatches(recipe: Recipe, shapeHC: HandleConnection, match: Match, outputList: Match[]) {
const {forward, reverse, score} = match;
let matchFound = false;
for (const recipeParticle of recipe.particles) {
if (!recipeParticle.spec) {
continue;
}
for (const recipeConnSpec of recipeParticle.spec.handleConnections) {
// TODO are there situations where multiple handleConnections should
// be allowed to point to the same one in the recipe?
if (reverse.has(recipeConnSpec)) {
continue;
}
// TODO support unnamed shape particles.
if (recipeParticle.name !== shapeHC.particle.name) {
continue;
}
if (shapeHC.name && shapeHC.name !== recipeConnSpec.name) {
continue;
}
if (!connectionMatchesHandleDirection(shapeHC.direction, recipeConnSpec.direction)) {
continue;
}
const recipeHC = recipeParticle.connections[recipeConnSpec.name];
if (shapeHC.handle && recipeHC && recipeHC.handle && shapeHC.handle.localName &&
shapeHC.handle.localName !== recipeHC.handle.localName) {
continue;
}
// recipeHC is a candidate for shapeHC. shapeHC references a
// particle, so recipeHC must reference the matching particle,
// or a particle that isn't yet mapped from shape.
if (reverse.has(recipeParticle)) {
if (reverse.get(recipeParticle) !== shapeHC.particle) {
continue;
}
} else if (forward.has(shapeHC.particle)) {
// we've already mapped the particle referenced by shapeHC
// and it doesn't match recipeHC's particle as recipeHC's
// particle isn't mapped
continue;
}
// shapeHC doesn't necessarily reference a handle, but if it does
// then recipeHC needs to reference the matching handle, or one
// that isn't yet mapped, or no handle yet.
if (shapeHC.handle && recipeHC && recipeHC.handle) {
if (reverse.has(recipeHC.handle)) {
if (reverse.get(recipeHC.handle) !== shapeHC.handle) {
continue;
}
} else if (forward.has(shapeHC.handle) && forward.get(shapeHC.handle) !== null) {
continue;
}
// Check whether shapeHC and recipeHC reference the same handle.
if (shapeHC.handle.fate !== 'create' || (recipeHC.handle.fate !== 'create' && recipeHC.handle.originalFate !== 'create')) {
if (Boolean(shapeHC.handle.immediateValue) !== Boolean(recipeHC.handle.immediateValue)) {
continue; // One is an immediate value handle and the other is not.
}
if (recipeHC.handle.immediateValue) {
if (!recipeHC.handle.immediateValue.equals(shapeHC.handle.immediateValue)) {
continue; // Immediate values are different.
}
} else {
// Note: the id of a handle with 'copy' fate changes during recipe instantiation, hence comparing to original id too.
// Skip the check if handles have 'create' fate (their ids are arbitrary).
if (shapeHC.handle.id !== recipeHC.handle.id && shapeHC.handle.id !== recipeHC.handle.originalId) {
continue; // This is a different handle.
}
}
}
}
// clone forward and reverse mappings and establish new components.
const newMatch = {forward: new Map(forward), reverse: new Map(reverse), score};
assert(!newMatch.reverse.has(recipeParticle) || newMatch.reverse.get(recipeParticle) === shapeHC.particle);
assert(!newMatch.forward.has(shapeHC.particle) || newMatch.forward.get(shapeHC.particle) === recipeParticle);
newMatch.forward.set(shapeHC.particle, recipeParticle);
newMatch.reverse.set(recipeParticle, shapeHC.particle);
if (shapeHC.handle) {
if (!recipeHC || !recipeHC.handle) {
if (!newMatch.forward.has(shapeHC.handle)) {
newMatch.forward.set(shapeHC.handle, null);
newMatch.score -= 2;
}
} else {
newMatch.forward.set(shapeHC.handle, recipeHC.handle);
newMatch.reverse.set(recipeHC.handle, shapeHC.handle);
}
}
newMatch.forward.set(shapeHC, recipeConnSpec);
newMatch.reverse.set(recipeConnSpec, shapeHC);
outputList.push(newMatch);
matchFound = true;
}
}
if (matchFound === false) {
// Non-null particle in the `forward` map means that some of the particle
// handle connections were successful matches, but some couldn't be matched.
// It means that this match in invalid.
if (match.forward.get(shapeHC.particle)) {
return;
}
// The current handle connection from the shape doesn't match anything
// in the recipe. Find (or create) a particle for it.
const newMatches: Match[] = [];
_buildNewParticleMatches(recipe, shapeHC.particle, match, newMatches);
newMatches.forEach(newMatch => {
// the shape references a handle, might also need to create a recipe
// handle for it (if there isn't already one from a previous match).
if (shapeHC.handle && !newMatch.forward.has(shapeHC.handle)) {
newMatch.forward.set(shapeHC.handle, null);
newMatch.score -= 2;
}
newMatch.forward.set(shapeHC, null);
newMatch.score -= 1;
outputList.push(newMatch);
});
}
}
function _buildNewParticleMatches(recipe: Recipe, shapeParticle: Particle, match: Match, newMatches: Match[]) {
const {forward, reverse, score} = match;
let matchFound = false;
for (const recipeParticle of recipe.particles) {
if (reverse.has(recipeParticle)) {
continue;
}
if (recipeParticle.name !== shapeParticle.name) {
continue;
}
let handleNamesMatch = true;
for (const connectionName of Object.keys(recipeParticle.connections)) {
const recipeConnection = recipeParticle.connections[connectionName];
if (!recipeConnection.handle) {
continue;
}
const shapeConnection = shapeParticle.connections[connectionName];
if (shapeConnection && shapeConnection.handle && shapeConnection.handle.localName && shapeConnection.handle.localName !== recipeConnection.handle.localName) {
handleNamesMatch = false;
break;
}
}
if (!handleNamesMatch) {
continue;
}
const newMatch = {forward: new Map(forward), reverse: new Map(reverse), score};
assert(!newMatch.forward.has(shapeParticle) || newMatch.forward.get(shapeParticle) === recipeParticle);
assert(!newMatch.reverse.has(recipeParticle) || newMatch.reverse.get(recipeParticle) === shapeParticle);
newMatch.forward.set(shapeParticle, recipeParticle);
newMatch.reverse.set(recipeParticle, shapeParticle);
newMatches.push(newMatch);
matchFound = true;
}
if (matchFound === false) {
const newMatch: Match = {forward: new Map(), reverse: new Map(), score: 0};
forward.forEach((value, key) => {
assert(!newMatch.forward.has(key) || newMatch.forward.get(key) === value);
newMatch.forward.set(key, value);
});
reverse.forEach((value, key) => {
assert(!newMatch.reverse.has(key) || newMatch.reverse.get(key) === value);
newMatch.reverse.set(key, value);
});
if (!newMatch.forward.has(shapeParticle)) {
newMatch.forward.set(shapeParticle, null);
newMatch.score = match.score - 1;
}
newMatches.push(newMatch);
}
}
function _assignHandlesToEmptyPosition(shape: Shape, match: Match, emptyHandles: Handle[], nullHandles: Handle[]) {
if (emptyHandles.length === 1) {
const matches: Match[] = [];
const {forward, reverse, score} = match;
for (const nullHandle of nullHandles) {
let tagsMatch = true;
for (const tag of nullHandle.tags) {
if (!emptyHandles[0].tags.includes(tag)) {
tagsMatch = false;
break;
}
}
if (!tagsMatch) {
continue;
}
const newMatch = {forward: new Map(forward), reverse: new Map(reverse), score: score + 1};
newMatch.forward.set(nullHandle, emptyHandles[0]);
newMatch.reverse.set(emptyHandles[0], nullHandle);
matches.push(newMatch);
}
return matches;
}
const thisHandle = emptyHandles.pop();
const matches: Match[] = _assignHandlesToEmptyPosition(shape, match, emptyHandles, nullHandles);
let newMatches: Match[] = [];
for (const match of matches) {
const nullHandles = [...shape.handles.values()].filter(handle => match.forward.get(handle) === null);
if (nullHandles.length > 0) {
newMatches = newMatches.concat(
_assignHandlesToEmptyPosition(shape, match, [thisHandle], nullHandles));
} else {
newMatches = newMatches.concat(match);
}
}
return newMatches;
}
export function find(recipe: PublicRecipe, shape: Shape): {match: Dictionary<RecipeUtilComponent>, score: number}[] {
// Particles and Handles are initially stored by a forward map from
// shape component to recipe component.
// Handle connections, particles and handles are also stored by a reverse map
// from recipe component to shape component.
const _recipe = recipe as Recipe;
// Start with a single, empty match
let matches: Match[] = [{forward: new Map(), reverse: new Map(), score: 0}];
for (const shapeHC of shape.recipe.handleConnections) {
const newMatches: Match[] = [];
for (const match of matches) {
// collect matching handle connections into a new matches list
_buildNewHCMatches(_recipe, shapeHC, match, newMatches);
}
matches = newMatches;
}
for (const shapeParticle of shape.recipe.particles) {
if (Object.keys(shapeParticle.connections).length > 0) {
continue;
}
if (shapeParticle.unnamedConnections.length > 0) {
continue;
}
const newMatches: Match[] = [];
for (const match of matches) {
_buildNewParticleMatches(_recipe, shapeParticle, match, newMatches);
}
matches = newMatches;
}
const emptyHandles = _recipe.handles.filter(handle => handle.connections.length === 0);
if (emptyHandles.length > 0) {
let newMatches: Match[] = [];
for (const match of matches) {
const nullHandles = [...shape.handles.values()].filter(handle => match.forward.get(handle) === null);
if (nullHandles.length > 0) {
newMatches = newMatches.concat(
_assignHandlesToEmptyPosition(shape, match, emptyHandles, nullHandles));
} else {
newMatches = newMatches.concat(match);
}
}
matches = newMatches;
}
return matches.map((match: {forward: Map<RecipeComponent, RecipeUtilComponent>, score: number}) => {
const result: Dictionary<RecipeUtilComponent> = {};
match.forward.forEach((value: RecipeUtilComponent, key: RecipeComponent) => result[shape.reverse.get(key)] = value);
return {match: result, score: match.score};
});
}
// Returns true if `otherRecipe` matches the shape of recipe.
export function matchesRecipe(recipe: PublicRecipe, otherRecipe: PublicRecipe): boolean {
const shape = recipeToShape(otherRecipe as Recipe);
const result = find(recipe as Recipe, shape);
return result.some(r => r.score === 0);
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Provides an AppConfig Configuration Profile resource.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.appconfig.ConfigurationProfile("example", {
* applicationId: aws_appconfig_application.example.id,
* description: "Example Configuration Profile",
* locationUri: "hosted",
* validators: [{
* content: aws_lambda_function.example.arn,
* type: "LAMBDA",
* }],
* tags: {
* Type: "AppConfig Configuration Profile",
* },
* });
* ```
*
* ## Import
*
* AppConfig Configuration Profiles can be imported by using the configuration profile ID and application ID separated by a colon (`:`), e.g.
*
* ```sh
* $ pulumi import aws:appconfig/configurationProfile:ConfigurationProfile example 71abcde:11xxxxx
* ```
*/
export class ConfigurationProfile extends pulumi.CustomResource {
/**
* Get an existing ConfigurationProfile resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ConfigurationProfileState, opts?: pulumi.CustomResourceOptions): ConfigurationProfile {
return new ConfigurationProfile(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:appconfig/configurationProfile:ConfigurationProfile';
/**
* Returns true if the given object is an instance of ConfigurationProfile. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is ConfigurationProfile {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === ConfigurationProfile.__pulumiType;
}
/**
* The application ID. Must be between 4 and 7 characters in length.
*/
public readonly applicationId!: pulumi.Output<string>;
/**
* The Amazon Resource Name (ARN) of the AppConfig Configuration Profile.
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* The configuration profile ID.
*/
public /*out*/ readonly configurationProfileId!: pulumi.Output<string>;
/**
* The description of the configuration profile. Can be at most 1024 characters.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* A URI to locate the configuration. You can specify the AWS AppConfig hosted configuration store, Systems Manager (SSM) document, an SSM Parameter Store parameter, or an Amazon S3 object. For the hosted configuration store, specify `hosted`. For an SSM document, specify either the document name in the format `ssm-document://<Document_name>` or the Amazon Resource Name (ARN). For a parameter, specify either the parameter name in the format `ssm-parameter://<Parameter_name>` or the ARN. For an Amazon S3 object, specify the URI in the following format: `s3://<bucket>/<objectKey>`.
*/
public readonly locationUri!: pulumi.Output<string>;
/**
* The name for the configuration profile. Must be between 1 and 64 characters in length.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ARN of an IAM role with permission to access the configuration at the specified `locationUri`. A retrieval role ARN is not required for configurations stored in the AWS AppConfig `hosted` configuration store. It is required for all other sources that store your configuration.
*/
public readonly retrievalRoleArn!: pulumi.Output<string | undefined>;
/**
* A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block).
*/
public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* A set of methods for validating the configuration. Maximum of 2. See Validator below for more details.
*/
public readonly validators!: pulumi.Output<outputs.appconfig.ConfigurationProfileValidator[] | undefined>;
/**
* Create a ConfigurationProfile resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: ConfigurationProfileArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ConfigurationProfileArgs | ConfigurationProfileState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ConfigurationProfileState | undefined;
inputs["applicationId"] = state ? state.applicationId : undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["configurationProfileId"] = state ? state.configurationProfileId : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["locationUri"] = state ? state.locationUri : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["retrievalRoleArn"] = state ? state.retrievalRoleArn : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["validators"] = state ? state.validators : undefined;
} else {
const args = argsOrState as ConfigurationProfileArgs | undefined;
if ((!args || args.applicationId === undefined) && !opts.urn) {
throw new Error("Missing required property 'applicationId'");
}
if ((!args || args.locationUri === undefined) && !opts.urn) {
throw new Error("Missing required property 'locationUri'");
}
inputs["applicationId"] = args ? args.applicationId : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["locationUri"] = args ? args.locationUri : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["retrievalRoleArn"] = args ? args.retrievalRoleArn : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["validators"] = args ? args.validators : undefined;
inputs["arn"] = undefined /*out*/;
inputs["configurationProfileId"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(ConfigurationProfile.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering ConfigurationProfile resources.
*/
export interface ConfigurationProfileState {
/**
* The application ID. Must be between 4 and 7 characters in length.
*/
applicationId?: pulumi.Input<string>;
/**
* The Amazon Resource Name (ARN) of the AppConfig Configuration Profile.
*/
arn?: pulumi.Input<string>;
/**
* The configuration profile ID.
*/
configurationProfileId?: pulumi.Input<string>;
/**
* The description of the configuration profile. Can be at most 1024 characters.
*/
description?: pulumi.Input<string>;
/**
* A URI to locate the configuration. You can specify the AWS AppConfig hosted configuration store, Systems Manager (SSM) document, an SSM Parameter Store parameter, or an Amazon S3 object. For the hosted configuration store, specify `hosted`. For an SSM document, specify either the document name in the format `ssm-document://<Document_name>` or the Amazon Resource Name (ARN). For a parameter, specify either the parameter name in the format `ssm-parameter://<Parameter_name>` or the ARN. For an Amazon S3 object, specify the URI in the following format: `s3://<bucket>/<objectKey>`.
*/
locationUri?: pulumi.Input<string>;
/**
* The name for the configuration profile. Must be between 1 and 64 characters in length.
*/
name?: pulumi.Input<string>;
/**
* The ARN of an IAM role with permission to access the configuration at the specified `locationUri`. A retrieval role ARN is not required for configurations stored in the AWS AppConfig `hosted` configuration store. It is required for all other sources that store your configuration.
*/
retrievalRoleArn?: pulumi.Input<string>;
/**
* A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block).
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A set of methods for validating the configuration. Maximum of 2. See Validator below for more details.
*/
validators?: pulumi.Input<pulumi.Input<inputs.appconfig.ConfigurationProfileValidator>[]>;
}
/**
* The set of arguments for constructing a ConfigurationProfile resource.
*/
export interface ConfigurationProfileArgs {
/**
* The application ID. Must be between 4 and 7 characters in length.
*/
applicationId: pulumi.Input<string>;
/**
* The description of the configuration profile. Can be at most 1024 characters.
*/
description?: pulumi.Input<string>;
/**
* A URI to locate the configuration. You can specify the AWS AppConfig hosted configuration store, Systems Manager (SSM) document, an SSM Parameter Store parameter, or an Amazon S3 object. For the hosted configuration store, specify `hosted`. For an SSM document, specify either the document name in the format `ssm-document://<Document_name>` or the Amazon Resource Name (ARN). For a parameter, specify either the parameter name in the format `ssm-parameter://<Parameter_name>` or the ARN. For an Amazon S3 object, specify the URI in the following format: `s3://<bucket>/<objectKey>`.
*/
locationUri: pulumi.Input<string>;
/**
* The name for the configuration profile. Must be between 1 and 64 characters in length.
*/
name?: pulumi.Input<string>;
/**
* The ARN of an IAM role with permission to access the configuration at the specified `locationUri`. A retrieval role ARN is not required for configurations stored in the AWS AppConfig `hosted` configuration store. It is required for all other sources that store your configuration.
*/
retrievalRoleArn?: pulumi.Input<string>;
/**
* A map of tags to assign to the resource. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A set of methods for validating the configuration. Maximum of 2. See Validator below for more details.
*/
validators?: pulumi.Input<pulumi.Input<inputs.appconfig.ConfigurationProfileValidator>[]>;
} | the_stack |
import { BigNumber, BigNumberish, Contract, ContractTransaction, ethers } from 'ethers';
import { ErrorCode } from '@ethersproject/logger';
import { EthMessageSigner } from './eth-message-signer';
import { SyncProvider } from './provider-interface';
import { Create2WalletSigner, Signer, unableToSign } from './signer';
import { BatchBuilder } from './batch-builder';
import {
AccountState,
Address,
ChangePubKey,
ChangePubKeyCREATE2,
ChangePubKeyECDSA,
ChangePubKeyOnchain,
ChangePubkeyTypes,
Create2Data,
EthSignerType,
ForcedExit,
MintNFT,
NFT,
Nonce,
Order,
PriorityOperationReceipt,
PubKeyHash,
Ratio,
SignedTransaction,
Swap,
TokenLike,
TransactionReceipt,
Transfer,
TxEthSignature,
Withdraw,
WithdrawNFT,
TokenRatio,
WeiRatio,
Toggle2FARequest
} from './types';
import {
ERC20_APPROVE_TRESHOLD,
ERC20_DEPOSIT_GAS_LIMIT,
ERC20_RECOMMENDED_DEPOSIT_GAS_LIMIT,
ETH_RECOMMENDED_DEPOSIT_GAS_LIMIT,
getChangePubkeyLegacyMessage,
getChangePubkeyMessage,
getEthereumBalance,
getSignedBytesFromMessage,
IERC20_INTERFACE,
isTokenETH,
MAX_ERC20_APPROVE_AMOUNT,
MAX_TIMESTAMP,
signMessagePersonalAPI,
isNFT,
SYNC_MAIN_CONTRACT_INTERFACE,
getToggle2FAMessage
} from './utils';
const EthersErrorCode = ErrorCode;
export class ZKSyncTxError extends Error {
constructor(message: string, public value: PriorityOperationReceipt | TransactionReceipt) {
super(message);
}
}
export class Wallet {
public provider: SyncProvider;
private constructor(
public ethSigner: ethers.Signer,
public ethMessageSigner: EthMessageSigner,
public cachedAddress: Address,
public signer?: Signer,
public accountId?: number,
public ethSignerType?: EthSignerType
) {}
connect(provider: SyncProvider) {
this.provider = provider;
return this;
}
static async fromEthSigner(
ethWallet: ethers.Signer,
provider: SyncProvider,
signer?: Signer,
accountId?: number,
ethSignerType?: EthSignerType
): Promise<Wallet> {
if (signer == null) {
const signerResult = await Signer.fromETHSignature(ethWallet);
signer = signerResult.signer;
ethSignerType = ethSignerType || signerResult.ethSignatureType;
} else if (ethSignerType == null) {
throw new Error('If you passed signer, you must also pass ethSignerType.');
}
const ethMessageSigner = new EthMessageSigner(ethWallet, ethSignerType);
const wallet = new Wallet(
ethWallet,
ethMessageSigner,
await ethWallet.getAddress(),
signer,
accountId,
ethSignerType
);
wallet.connect(provider);
return wallet;
}
static async fromCreate2Data(
syncSigner: Signer,
provider: SyncProvider,
create2Data: Create2Data,
accountId?: number
): Promise<Wallet> {
const create2Signer = new Create2WalletSigner(await syncSigner.pubKeyHash(), create2Data);
return await Wallet.fromEthSigner(create2Signer, provider, syncSigner, accountId, {
verificationMethod: 'ERC-1271',
isSignedMsgPrefixed: true
});
}
static async fromEthSignerNoKeys(
ethWallet: ethers.Signer,
provider: SyncProvider,
accountId?: number,
ethSignerType?: EthSignerType
): Promise<Wallet> {
const ethMessageSigner = new EthMessageSigner(ethWallet, ethSignerType);
const wallet = new Wallet(
ethWallet,
ethMessageSigner,
await ethWallet.getAddress(),
undefined,
accountId,
ethSignerType
);
wallet.connect(provider);
return wallet;
}
static async fromSyncSigner(
ethWallet: ethers.Signer,
syncSigner: Signer,
provider: SyncProvider,
accountId?: number
) {
return await Wallet.fromEthSigner(ethWallet, provider, syncSigner, accountId, {
verificationMethod: 'ERC-1271',
isSignedMsgPrefixed: true
});
}
async getEthMessageSignature(message: ethers.utils.BytesLike): Promise<TxEthSignature> {
if (this.ethSignerType == null) {
throw new Error('ethSignerType is unknown');
}
const signedBytes = getSignedBytesFromMessage(message, !this.ethSignerType.isSignedMsgPrefixed);
const signature = await signMessagePersonalAPI(this.ethSigner, signedBytes);
return {
type: this.ethSignerType.verificationMethod === 'ECDSA' ? 'EthereumSignature' : 'EIP1271Signature',
signature
};
}
batchBuilder(nonce?: Nonce): BatchBuilder {
return BatchBuilder.fromWallet(this, nonce);
}
async getTransfer(transfer: {
to: Address;
token: TokenLike;
amount: BigNumberish;
fee: BigNumberish;
nonce: number;
validFrom: number;
validUntil: number;
}): Promise<Transfer> {
if (!this.signer) {
throw new Error('ZKSync signer is required for sending zksync transactions.');
}
await this.setRequiredAccountIdFromServer('Transfer funds');
const tokenId = this.provider.tokenSet.resolveTokenId(transfer.token);
const transactionData = {
accountId: this.accountId,
from: this.address(),
to: transfer.to,
tokenId,
amount: transfer.amount,
fee: transfer.fee,
nonce: transfer.nonce,
validFrom: transfer.validFrom,
validUntil: transfer.validUntil
};
return this.signer.signSyncTransfer(transactionData);
}
async signSyncTransfer(transfer: {
to: Address;
token: TokenLike;
amount: BigNumberish;
fee: BigNumberish;
nonce: number;
validFrom?: number;
validUntil?: number;
}): Promise<SignedTransaction> {
transfer.validFrom = transfer.validFrom || 0;
transfer.validUntil = transfer.validUntil || MAX_TIMESTAMP;
const signedTransferTransaction = await this.getTransfer(transfer as any);
const stringAmount = BigNumber.from(transfer.amount).isZero()
? null
: this.provider.tokenSet.formatToken(transfer.token, transfer.amount);
const stringFee = BigNumber.from(transfer.fee).isZero()
? null
: this.provider.tokenSet.formatToken(transfer.token, transfer.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(transfer.token);
const ethereumSignature = unableToSign(this.ethSigner)
? null
: await this.ethMessageSigner.ethSignTransfer({
stringAmount,
stringFee,
stringToken,
to: transfer.to,
nonce: transfer.nonce,
accountId: this.accountId
});
return {
tx: signedTransferTransaction,
ethereumSignature
};
}
async signRegisterFactory(factoryAddress: Address): Promise<{
signature: TxEthSignature;
accountId: number;
accountAddress: Address;
}> {
await this.setRequiredAccountIdFromServer('Sign register factory');
const signature = await this.ethMessageSigner.ethSignRegisterFactoryMessage(
factoryAddress,
this.accountId,
this.address()
);
return {
signature,
accountId: this.accountId,
accountAddress: this.address()
};
}
async getForcedExit(forcedExit: {
target: Address;
token: TokenLike;
fee: BigNumberish;
nonce: number;
validFrom?: number;
validUntil?: number;
}): Promise<ForcedExit> {
if (!this.signer) {
throw new Error('ZKSync signer is required for sending zksync transactions.');
}
await this.setRequiredAccountIdFromServer('perform a Forced Exit');
const tokenId = this.provider.tokenSet.resolveTokenId(forcedExit.token);
const transactionData = {
initiatorAccountId: this.accountId,
target: forcedExit.target,
tokenId,
fee: forcedExit.fee,
nonce: forcedExit.nonce,
validFrom: forcedExit.validFrom || 0,
validUntil: forcedExit.validUntil || MAX_TIMESTAMP
};
return await this.signer.signSyncForcedExit(transactionData);
}
async signSyncForcedExit(forcedExit: {
target: Address;
token: TokenLike;
fee: BigNumberish;
nonce: number;
validFrom?: number;
validUntil?: number;
}): Promise<SignedTransaction> {
const signedForcedExitTransaction = await this.getForcedExit(forcedExit);
const stringFee = BigNumber.from(forcedExit.fee).isZero()
? null
: this.provider.tokenSet.formatToken(forcedExit.token, forcedExit.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(forcedExit.token);
const ethereumSignature = unableToSign(this.ethSigner)
? null
: await this.ethMessageSigner.ethSignForcedExit({
stringToken,
stringFee,
target: forcedExit.target,
nonce: forcedExit.nonce
});
return {
tx: signedForcedExitTransaction,
ethereumSignature
};
}
async syncForcedExit(forcedExit: {
target: Address;
token: TokenLike;
fee?: BigNumberish;
nonce?: Nonce;
validFrom?: number;
validUntil?: number;
}): Promise<Transaction> {
forcedExit.nonce = forcedExit.nonce != null ? await this.getNonce(forcedExit.nonce) : await this.getNonce();
if (forcedExit.fee == null) {
const fullFee = await this.provider.getTransactionFee('ForcedExit', forcedExit.target, forcedExit.token);
forcedExit.fee = fullFee.totalFee;
}
const signedForcedExitTransaction = await this.signSyncForcedExit(forcedExit as any);
return submitSignedTransaction(signedForcedExitTransaction, this.provider);
}
// Note that in syncMultiTransfer, unlike in syncTransfer,
// users need to specify the fee for each transaction.
// The main reason is that multitransfer enables paying fees
// in multiple tokens, (as long as the total sum
// of fees is enough to cover up the fees for all of the transactions).
// That might bring an inattentive user in a trouble like the following:
//
// A user wants to submit transactions in multiple tokens and
// wants to pay the fees with only some of them. If the user forgets
// to set the fees' value to 0 for transactions with tokens
// he won't pay the fee with, then this user will overpay a lot.
//
// That's why we want the users to be explicit about fees in multitransfers.
async syncMultiTransfer(
transfers: {
to: Address;
token: TokenLike;
amount: BigNumberish;
fee: BigNumberish;
nonce?: Nonce;
validFrom?: number;
validUntil?: number;
}[]
): Promise<Transaction[]> {
if (!this.signer) {
throw new Error('ZKSync signer is required for sending zksync transactions.');
}
if (transfers.length == 0) return [];
await this.setRequiredAccountIdFromServer('Transfer funds');
let batch = [];
let messages: string[] = [];
let nextNonce = transfers[0].nonce != null ? await this.getNonce(transfers[0].nonce) : await this.getNonce();
const batchNonce = nextNonce;
for (let i = 0; i < transfers.length; i++) {
const transfer = transfers[i];
const nonce = nextNonce;
nextNonce += 1;
const tx: Transfer = await this.getTransfer({
to: transfer.to,
token: transfer.token,
amount: transfer.amount,
fee: transfer.fee,
nonce,
validFrom: transfer.validFrom || 0,
validUntil: transfer.validUntil || MAX_TIMESTAMP
});
const message = await this.getTransferEthMessagePart(transfer);
messages.push(message);
batch.push({ tx, signature: null });
}
messages.push(`Nonce: ${batchNonce}`);
const message = messages.filter((part) => part.length != 0).join('\n');
const ethSignatures = unableToSign(this.ethSigner)
? []
: [await this.ethMessageSigner.getEthMessageSignature(message)];
const transactionHashes = await this.provider.submitTxsBatch(batch, ethSignatures);
return transactionHashes.map((txHash, idx) => new Transaction(batch[idx], txHash, this.provider));
}
async syncTransferNFT(transfer: {
to: Address;
token: NFT;
feeToken: TokenLike;
fee?: BigNumberish;
nonce?: Nonce;
validFrom?: number;
validUntil?: number;
}): Promise<Transaction[]> {
transfer.nonce = transfer.nonce != null ? await this.getNonce(transfer.nonce) : await this.getNonce();
let fee: BigNumberish;
if (transfer.fee == null) {
fee = await this.provider.getTransactionsBatchFee(
['Transfer', 'Transfer'],
[transfer.to, this.address()],
transfer.feeToken
);
} else {
fee = transfer.fee;
}
const txNFT = {
to: transfer.to,
token: transfer.token.id,
amount: 1,
fee: 0
};
const txFee = {
to: this.address(),
token: transfer.feeToken,
amount: 0,
fee
};
return await this.syncMultiTransfer([txNFT, txFee]);
}
async getLimitOrder(order: {
tokenSell: TokenLike;
tokenBuy: TokenLike;
ratio: TokenRatio | WeiRatio;
recipient?: Address;
nonce?: Nonce;
validFrom?: number;
validUntil?: number;
}): Promise<Order> {
return this.getOrder({
...order,
amount: 0
});
}
async getOrder(order: {
tokenSell: TokenLike;
tokenBuy: TokenLike;
ratio: TokenRatio | WeiRatio;
amount: BigNumberish;
recipient?: Address;
nonce?: Nonce;
validFrom?: number;
validUntil?: number;
}): Promise<Order> {
if (!this.signer) {
throw new Error('zkSync signer is required for signing an order');
}
await this.setRequiredAccountIdFromServer('Swap order');
const nonce = order.nonce != null ? await this.getNonce(order.nonce) : await this.getNonce();
const recipient = order.recipient || this.address();
let ratio: Ratio;
const sell = order.tokenSell;
const buy = order.tokenBuy;
if (!order.ratio[sell] || !order.ratio[buy]) {
throw new Error(`Wrong tokens in the ratio object: should be ${sell} and ${buy}`);
}
if (order.ratio.type == 'Wei') {
ratio = [order.ratio[sell], order.ratio[buy]];
} else if (order.ratio.type == 'Token') {
ratio = [
this.provider.tokenSet.parseToken(sell, order.ratio[sell].toString()),
this.provider.tokenSet.parseToken(buy, order.ratio[buy].toString())
];
}
const signedOrder = await this.signer.signSyncOrder({
accountId: this.accountId,
recipient,
nonce,
amount: order.amount || BigNumber.from(0),
tokenSell: this.provider.tokenSet.resolveTokenId(order.tokenSell),
tokenBuy: this.provider.tokenSet.resolveTokenId(order.tokenBuy),
validFrom: order.validFrom || 0,
validUntil: order.validUntil || MAX_TIMESTAMP,
ratio
});
return this.signOrder(signedOrder);
}
async signOrder(order: Order): Promise<Order> {
const stringAmount = BigNumber.from(order.amount).isZero()
? null
: this.provider.tokenSet.formatToken(order.tokenSell, order.amount);
const stringTokenSell = await this.provider.getTokenSymbol(order.tokenSell);
const stringTokenBuy = await this.provider.getTokenSymbol(order.tokenBuy);
const ethereumSignature = unableToSign(this.ethSigner)
? null
: await this.ethMessageSigner.ethSignOrder({
amount: stringAmount,
tokenSell: stringTokenSell,
tokenBuy: stringTokenBuy,
nonce: order.nonce,
recipient: order.recipient,
ratio: order.ratio
});
order.ethSignature = ethereumSignature;
return order;
}
async getSwap(swap: {
orders: [Order, Order];
feeToken: number;
amounts: [BigNumberish, BigNumberish];
nonce: number;
fee: BigNumberish;
}): Promise<Swap> {
if (!this.signer) {
throw new Error('zkSync signer is required for swapping funds');
}
await this.setRequiredAccountIdFromServer('Swap submission');
const feeToken = this.provider.tokenSet.resolveTokenId(swap.feeToken);
return this.signer.signSyncSwap({
...swap,
submitterId: await this.getAccountId(),
submitterAddress: this.address(),
feeToken
});
}
async signSyncSwap(swap: {
orders: [Order, Order];
feeToken: number;
amounts: [BigNumberish, BigNumberish];
nonce: number;
fee: BigNumberish;
}): Promise<SignedTransaction> {
const signedSwapTransaction = await this.getSwap(swap);
const stringFee = BigNumber.from(swap.fee).isZero()
? null
: this.provider.tokenSet.formatToken(swap.feeToken, swap.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(swap.feeToken);
const ethereumSignature = unableToSign(this.ethSigner)
? null
: await this.ethMessageSigner.ethSignSwap({
fee: stringFee,
feeToken: stringToken,
nonce: swap.nonce
});
return {
tx: signedSwapTransaction,
ethereumSignature: [
ethereumSignature,
swap.orders[0].ethSignature || null,
swap.orders[1].ethSignature || null
]
};
}
async syncSwap(swap: {
orders: [Order, Order];
feeToken: TokenLike;
amounts?: [BigNumberish, BigNumberish];
nonce?: number;
fee?: BigNumberish;
}): Promise<Transaction> {
swap.nonce = swap.nonce != null ? await this.getNonce(swap.nonce) : await this.getNonce();
if (swap.fee == null) {
const fullFee = await this.provider.getTransactionFee('Swap', this.address(), swap.feeToken);
swap.fee = fullFee.totalFee;
}
if (swap.amounts == null) {
let amount0 = BigNumber.from(swap.orders[0].amount);
let amount1 = BigNumber.from(swap.orders[1].amount);
if (!amount0.eq(0) && !amount1.eq(0)) {
swap.amounts = [amount0, amount1];
} else {
throw new Error('If amounts in orders are implicit, you must specify them during submission');
}
}
const signedSwapTransaction = await this.signSyncSwap(swap as any);
return submitSignedTransaction(signedSwapTransaction, this.provider);
}
async syncTransfer(transfer: {
to: Address;
token: TokenLike;
amount: BigNumberish;
fee?: BigNumberish;
nonce?: Nonce;
validFrom?: number;
validUntil?: number;
}): Promise<Transaction> {
transfer.nonce = transfer.nonce != null ? await this.getNonce(transfer.nonce) : await this.getNonce();
if (transfer.fee == null) {
const fullFee = await this.provider.getTransactionFee('Transfer', transfer.to, transfer.token);
transfer.fee = fullFee.totalFee;
}
const signedTransferTransaction = await this.signSyncTransfer(transfer as any);
return submitSignedTransaction(signedTransferTransaction, this.provider);
}
async getMintNFT(mintNFT: {
recipient: string;
contentHash: string;
feeToken: TokenLike;
fee: BigNumberish;
nonce: number;
}): Promise<MintNFT> {
if (!this.signer) {
throw new Error('ZKSync signer is required for sending zksync transactions.');
}
await this.setRequiredAccountIdFromServer('MintNFT');
const feeTokenId = this.provider.tokenSet.resolveTokenId(mintNFT.feeToken);
const transactionData = {
creatorId: this.accountId,
creatorAddress: this.address(),
recipient: mintNFT.recipient,
contentHash: mintNFT.contentHash,
feeTokenId,
fee: mintNFT.fee,
nonce: mintNFT.nonce
};
return await this.signer.signMintNFT(transactionData);
}
async getWithdrawNFT(withdrawNFT: {
to: string;
token: TokenLike;
feeToken: TokenLike;
fee: BigNumberish;
nonce: number;
validFrom: number;
validUntil: number;
}): Promise<WithdrawNFT> {
if (!this.signer) {
throw new Error('ZKSync signer is required for sending zksync transactions.');
}
await this.setRequiredAccountIdFromServer('WithdrawNFT');
const tokenId = this.provider.tokenSet.resolveTokenId(withdrawNFT.token);
const feeTokenId = this.provider.tokenSet.resolveTokenId(withdrawNFT.feeToken);
const transactionData = {
accountId: this.accountId,
from: this.address(),
to: withdrawNFT.to,
tokenId,
feeTokenId,
fee: withdrawNFT.fee,
nonce: withdrawNFT.nonce,
validFrom: withdrawNFT.validFrom,
validUntil: withdrawNFT.validUntil
};
return await this.signer.signWithdrawNFT(transactionData);
}
async getWithdrawFromSyncToEthereum(withdraw: {
ethAddress: string;
token: TokenLike;
amount: BigNumberish;
fee: BigNumberish;
nonce: number;
validFrom: number;
validUntil: number;
}): Promise<Withdraw> {
if (!this.signer) {
throw new Error('ZKSync signer is required for sending zksync transactions.');
}
await this.setRequiredAccountIdFromServer('Withdraw funds');
const tokenId = this.provider.tokenSet.resolveTokenId(withdraw.token);
const transactionData = {
accountId: this.accountId,
from: this.address(),
ethAddress: withdraw.ethAddress,
tokenId,
amount: withdraw.amount,
fee: withdraw.fee,
nonce: withdraw.nonce,
validFrom: withdraw.validFrom,
validUntil: withdraw.validUntil
};
return await this.signer.signSyncWithdraw(transactionData);
}
async signMintNFT(mintNFT: {
recipient: string;
contentHash: string;
feeToken: TokenLike;
fee: BigNumberish;
nonce: number;
}): Promise<SignedTransaction> {
const signedMintNFTTransaction = await this.getMintNFT(mintNFT as any);
const stringFee = BigNumber.from(mintNFT.fee).isZero()
? null
: this.provider.tokenSet.formatToken(mintNFT.feeToken, mintNFT.fee);
const stringFeeToken = this.provider.tokenSet.resolveTokenSymbol(mintNFT.feeToken);
const ethereumSignature = unableToSign(this.ethSigner)
? null
: await this.ethMessageSigner.ethSignMintNFT({
stringFeeToken,
stringFee,
recipient: mintNFT.recipient,
contentHash: mintNFT.contentHash,
nonce: mintNFT.nonce
});
return {
tx: signedMintNFTTransaction,
ethereumSignature
};
}
async signWithdrawNFT(withdrawNFT: {
to: string;
token: number;
feeToken: TokenLike;
fee: BigNumberish;
nonce: number;
validFrom?: number;
validUntil?: number;
}): Promise<SignedTransaction> {
withdrawNFT.validFrom = withdrawNFT.validFrom || 0;
withdrawNFT.validUntil = withdrawNFT.validUntil || MAX_TIMESTAMP;
const signedWithdrawNFTTransaction = await this.getWithdrawNFT(withdrawNFT as any);
const stringFee = BigNumber.from(withdrawNFT.fee).isZero()
? null
: this.provider.tokenSet.formatToken(withdrawNFT.feeToken, withdrawNFT.fee);
const stringFeeToken = this.provider.tokenSet.resolveTokenSymbol(withdrawNFT.feeToken);
const ethereumSignature = unableToSign(this.ethSigner)
? null
: await this.ethMessageSigner.ethSignWithdrawNFT({
token: withdrawNFT.token,
to: withdrawNFT.to,
stringFee,
stringFeeToken,
nonce: withdrawNFT.nonce
});
return {
tx: signedWithdrawNFTTransaction,
ethereumSignature
};
}
async signWithdrawFromSyncToEthereum(withdraw: {
ethAddress: string;
token: TokenLike;
amount: BigNumberish;
fee: BigNumberish;
nonce: number;
validFrom?: number;
validUntil?: number;
}): Promise<SignedTransaction> {
withdraw.validFrom = withdraw.validFrom || 0;
withdraw.validUntil = withdraw.validUntil || MAX_TIMESTAMP;
const signedWithdrawTransaction = await this.getWithdrawFromSyncToEthereum(withdraw as any);
const stringAmount = BigNumber.from(withdraw.amount).isZero()
? null
: this.provider.tokenSet.formatToken(withdraw.token, withdraw.amount);
const stringFee = BigNumber.from(withdraw.fee).isZero()
? null
: this.provider.tokenSet.formatToken(withdraw.token, withdraw.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(withdraw.token);
const ethereumSignature = unableToSign(this.ethSigner)
? null
: await this.ethMessageSigner.ethSignWithdraw({
stringAmount,
stringFee,
stringToken,
ethAddress: withdraw.ethAddress,
nonce: withdraw.nonce,
accountId: this.accountId
});
return {
tx: signedWithdrawTransaction,
ethereumSignature
};
}
async mintNFT(mintNFT: {
recipient: Address;
contentHash: ethers.BytesLike;
feeToken: TokenLike;
fee?: BigNumberish;
nonce?: Nonce;
}): Promise<Transaction> {
mintNFT.nonce = mintNFT.nonce != null ? await this.getNonce(mintNFT.nonce) : await this.getNonce();
mintNFT.contentHash = ethers.utils.hexlify(mintNFT.contentHash);
if (mintNFT.fee == null) {
const fullFee = await this.provider.getTransactionFee('MintNFT', mintNFT.recipient, mintNFT.feeToken);
mintNFT.fee = fullFee.totalFee;
}
const signedMintNFTTransaction = await this.signMintNFT(mintNFT as any);
return submitSignedTransaction(signedMintNFTTransaction, this.provider, false);
}
async withdrawNFT(withdrawNFT: {
to: string;
token: number;
feeToken: TokenLike;
fee?: BigNumberish;
nonce?: Nonce;
fastProcessing?: boolean;
validFrom?: number;
validUntil?: number;
}): Promise<Transaction> {
withdrawNFT.nonce = withdrawNFT.nonce != null ? await this.getNonce(withdrawNFT.nonce) : await this.getNonce();
if (!isNFT(withdrawNFT.token)) {
throw new Error('This token ID does not correspond to an NFT');
}
if (withdrawNFT.fee == null) {
const feeType = withdrawNFT.fastProcessing === true ? 'FastWithdrawNFT' : 'WithdrawNFT';
const fullFee = await this.provider.getTransactionFee(feeType, withdrawNFT.to, withdrawNFT.feeToken);
withdrawNFT.fee = fullFee.totalFee;
}
const signedWithdrawNFTTransaction = await this.signWithdrawNFT(withdrawNFT as any);
return submitSignedTransaction(signedWithdrawNFTTransaction, this.provider, withdrawNFT.fastProcessing);
}
async withdrawFromSyncToEthereum(withdraw: {
ethAddress: string;
token: TokenLike;
amount: BigNumberish;
fee?: BigNumberish;
nonce?: Nonce;
fastProcessing?: boolean;
validFrom?: number;
validUntil?: number;
}): Promise<Transaction> {
withdraw.nonce = withdraw.nonce != null ? await this.getNonce(withdraw.nonce) : await this.getNonce();
if (withdraw.fee == null) {
const feeType = withdraw.fastProcessing === true ? 'FastWithdraw' : 'Withdraw';
const fullFee = await this.provider.getTransactionFee(feeType, withdraw.ethAddress, withdraw.token);
withdraw.fee = fullFee.totalFee;
}
const signedWithdrawTransaction = await this.signWithdrawFromSyncToEthereum(withdraw as any);
return submitSignedTransaction(signedWithdrawTransaction, this.provider, withdraw.fastProcessing);
}
async isSigningKeySet(): Promise<boolean> {
if (!this.signer) {
throw new Error('ZKSync signer is required for current pubkey calculation.');
}
const currentPubKeyHash = await this.getCurrentPubKeyHash();
const signerPubKeyHash = await this.signer.pubKeyHash();
return currentPubKeyHash === signerPubKeyHash;
}
async getChangePubKey(changePubKey: {
feeToken: TokenLike;
fee: BigNumberish;
nonce: number;
ethAuthData?: ChangePubKeyOnchain | ChangePubKeyECDSA | ChangePubKeyCREATE2;
ethSignature?: string;
validFrom: number;
validUntil: number;
}): Promise<ChangePubKey> {
if (!this.signer) {
throw new Error('ZKSync signer is required for current pubkey calculation.');
}
const feeTokenId = this.provider.tokenSet.resolveTokenId(changePubKey.feeToken);
const newPkHash = await this.signer.pubKeyHash();
await this.setRequiredAccountIdFromServer('Set Signing Key');
const changePubKeyTx: ChangePubKey = await this.signer.signSyncChangePubKey({
accountId: this.accountId,
account: this.address(),
newPkHash,
nonce: changePubKey.nonce,
feeTokenId,
fee: BigNumber.from(changePubKey.fee).toString(),
ethAuthData: changePubKey.ethAuthData,
ethSignature: changePubKey.ethSignature,
validFrom: changePubKey.validFrom,
validUntil: changePubKey.validUntil
});
return changePubKeyTx;
}
async getToggle2FA(enable: boolean): Promise<Toggle2FARequest> {
const accountId = await this.getAccountId();
const timestamp = new Date().getTime();
const signature = await this.getEthMessageSignature(getToggle2FAMessage(enable, timestamp));
return {
accountId,
signature,
timestamp,
enable
};
}
async toggle2FA(enable: boolean): Promise<boolean> {
await this.setRequiredAccountIdFromServer('Toggle 2FA');
return await this.provider.toggle2FA(await this.getToggle2FA(enable));
}
async signSetSigningKey(changePubKey: {
feeToken: TokenLike;
fee: BigNumberish;
nonce: number;
ethAuthType: ChangePubkeyTypes;
batchHash?: string;
validFrom?: number;
validUntil?: number;
}): Promise<SignedTransaction> {
const newPubKeyHash = await this.signer.pubKeyHash();
let ethAuthData;
let ethSignature;
if (changePubKey.ethAuthType === 'Onchain') {
ethAuthData = {
type: 'Onchain'
};
} else if (changePubKey.ethAuthType === 'ECDSA') {
await this.setRequiredAccountIdFromServer('ChangePubKey authorized by ECDSA.');
const changePubKeyMessage = getChangePubkeyMessage(
newPubKeyHash,
changePubKey.nonce,
this.accountId,
changePubKey.batchHash
);
const ethSignature = (await this.getEthMessageSignature(changePubKeyMessage)).signature;
ethAuthData = {
type: 'ECDSA',
ethSignature,
batchHash: changePubKey.batchHash
};
} else if (changePubKey.ethAuthType === 'CREATE2') {
if (this.ethSigner instanceof Create2WalletSigner) {
const create2data = this.ethSigner.create2WalletData;
ethAuthData = {
type: 'CREATE2',
creatorAddress: create2data.creatorAddress,
saltArg: create2data.saltArg,
codeHash: create2data.codeHash
};
} else {
throw new Error('CREATE2 wallet authentication is only available for CREATE2 wallets');
}
} else if (changePubKey.ethAuthType === 'ECDSALegacyMessage') {
await this.setRequiredAccountIdFromServer('ChangePubKey authorized by ECDSALegacyMessage.');
const changePubKeyMessage = getChangePubkeyLegacyMessage(newPubKeyHash, changePubKey.nonce, this.accountId);
ethSignature = (await this.getEthMessageSignature(changePubKeyMessage)).signature;
} else {
throw new Error('Unsupported SetSigningKey type');
}
const changePubkeyTxUnsigned = Object.assign(changePubKey, { ethAuthData, ethSignature });
changePubkeyTxUnsigned.validFrom = changePubKey.validFrom || 0;
changePubkeyTxUnsigned.validUntil = changePubKey.validUntil || MAX_TIMESTAMP;
const changePubKeyTx = await this.getChangePubKey(changePubkeyTxUnsigned as any);
return {
tx: changePubKeyTx
};
}
async setSigningKey(changePubKey: {
feeToken: TokenLike;
ethAuthType: ChangePubkeyTypes;
fee?: BigNumberish;
nonce?: Nonce;
validFrom?: number;
validUntil?: number;
}): Promise<Transaction> {
changePubKey.nonce =
changePubKey.nonce != null ? await this.getNonce(changePubKey.nonce) : await this.getNonce();
if (changePubKey.fee == null) {
changePubKey.fee = 0;
if (changePubKey.ethAuthType === 'ECDSALegacyMessage') {
const feeType = {
ChangePubKey: {
onchainPubkeyAuth: false
}
};
const fullFee = await this.provider.getTransactionFee(feeType, this.address(), changePubKey.feeToken);
changePubKey.fee = fullFee.totalFee;
} else {
const feeType = {
ChangePubKey: changePubKey.ethAuthType
};
const fullFee = await this.provider.getTransactionFee(feeType, this.address(), changePubKey.feeToken);
changePubKey.fee = fullFee.totalFee;
}
}
const txData = await this.signSetSigningKey(changePubKey as any);
const currentPubKeyHash = await this.getCurrentPubKeyHash();
if (currentPubKeyHash === (txData.tx as ChangePubKey).newPkHash) {
throw new Error('Current signing key is already set');
}
return submitSignedTransaction(txData, this.provider);
}
getWithdrawNFTEthMessagePart(withdrawNFT: {
to: string;
token: number;
feeToken: TokenLike;
fee: BigNumberish;
}): string {
const stringFee = BigNumber.from(withdrawNFT.fee).isZero()
? null
: this.provider.tokenSet.formatToken(withdrawNFT.feeToken, withdrawNFT.fee);
const stringFeeToken = this.provider.tokenSet.resolveTokenSymbol(withdrawNFT.feeToken);
return this.ethMessageSigner.getWithdrawNFTEthMessagePart({
token: withdrawNFT.token,
to: withdrawNFT.to,
stringFee,
stringFeeToken
});
}
// The following methods are needed in case user decided to build
// a message for the batch himself (e.g. in case of multi-authors batch).
// It might seem that these belong to ethMessageSigner, however, we have
// to resolve the token and format amount/fee before constructing the
// transaction.
async getTransferEthMessagePart(transfer: {
to: Address;
token: TokenLike;
amount: BigNumberish;
fee: BigNumberish;
}): Promise<string> {
const stringAmount = BigNumber.from(transfer.amount).isZero()
? null
: this.provider.tokenSet.formatToken(transfer.token, transfer.amount);
const stringFee = BigNumber.from(transfer.fee).isZero()
? null
: this.provider.tokenSet.formatToken(transfer.token, transfer.fee);
const stringToken = await this.provider.getTokenSymbol(transfer.token);
return this.ethMessageSigner.getTransferEthMessagePart({
stringAmount,
stringFee,
stringToken,
to: transfer.to
});
}
getWithdrawEthMessagePart(withdraw: {
ethAddress: string;
token: TokenLike;
amount: BigNumberish;
fee: BigNumberish;
}): string {
const stringAmount = BigNumber.from(withdraw.amount).isZero()
? null
: this.provider.tokenSet.formatToken(withdraw.token, withdraw.amount);
const stringFee = BigNumber.from(withdraw.fee).isZero()
? null
: this.provider.tokenSet.formatToken(withdraw.token, withdraw.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(withdraw.token);
return this.ethMessageSigner.getWithdrawEthMessagePart({
stringAmount,
stringFee,
stringToken,
ethAddress: withdraw.ethAddress
});
}
getChangePubKeyEthMessagePart(changePubKey: {
pubKeyHash: string;
feeToken: TokenLike;
fee: BigNumberish;
}): string {
const stringFee = BigNumber.from(changePubKey.fee).isZero()
? null
: this.provider.tokenSet.formatToken(changePubKey.feeToken, changePubKey.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(changePubKey.feeToken);
return this.ethMessageSigner.getChangePubKeyEthMessagePart({
pubKeyHash: changePubKey.pubKeyHash,
stringToken,
stringFee
});
}
getMintNFTEthMessagePart(mintNFT: {
recipient: string;
contentHash: string;
feeToken: TokenLike;
fee: BigNumberish;
}): string {
const stringFee = BigNumber.from(mintNFT.fee).isZero()
? null
: this.provider.tokenSet.formatToken(mintNFT.feeToken, mintNFT.fee);
const stringFeeToken = this.provider.tokenSet.resolveTokenSymbol(mintNFT.feeToken);
return this.ethMessageSigner.getMintNFTEthMessagePart({
stringFeeToken,
stringFee,
recipient: mintNFT.recipient,
contentHash: mintNFT.contentHash
});
}
getSwapEthSignMessagePart(swap: { fee: BigNumberish; feeToken: TokenLike }): string {
const stringFee = BigNumber.from(swap.fee).isZero()
? null
: this.provider.tokenSet.formatToken(swap.feeToken, swap.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(swap.feeToken);
return this.ethMessageSigner.getSwapEthSignMessagePart({
fee: stringFee,
feeToken: stringToken
});
}
getForcedExitEthMessagePart(forcedExit: { target: Address; token: TokenLike; fee: BigNumberish }): string {
const stringFee = BigNumber.from(forcedExit.fee).isZero()
? null
: this.provider.tokenSet.formatToken(forcedExit.token, forcedExit.fee);
const stringToken = this.provider.tokenSet.resolveTokenSymbol(forcedExit.token);
return this.ethMessageSigner.getForcedExitEthMessagePart({
stringToken,
stringFee,
target: forcedExit.target
});
}
async isOnchainAuthSigningKeySet(nonce: Nonce = 'committed'): Promise<boolean> {
const mainZkSyncContract = this.getZkSyncMainContract();
const numNonce = await this.getNonce(nonce);
try {
const onchainAuthFact = await mainZkSyncContract.authFacts(this.address(), numNonce);
return onchainAuthFact !== '0x0000000000000000000000000000000000000000000000000000000000000000';
} catch (e) {
this.modifyEthersError(e);
}
}
async onchainAuthSigningKey(
nonce: Nonce = 'committed',
ethTxOptions?: ethers.providers.TransactionRequest
): Promise<ContractTransaction> {
if (!this.signer) {
throw new Error('ZKSync signer is required for current pubkey calculation.');
}
const currentPubKeyHash = await this.getCurrentPubKeyHash();
const newPubKeyHash = await this.signer.pubKeyHash();
if (currentPubKeyHash === newPubKeyHash) {
throw new Error('Current PubKeyHash is the same as new');
}
const numNonce = await this.getNonce(nonce);
const mainZkSyncContract = this.getZkSyncMainContract();
try {
return mainZkSyncContract.setAuthPubkeyHash(newPubKeyHash.replace('sync:', '0x'), numNonce, {
gasLimit: BigNumber.from('200000'),
...ethTxOptions
});
} catch (e) {
this.modifyEthersError(e);
}
}
async getCurrentPubKeyHash(): Promise<PubKeyHash> {
return (await this.provider.getState(this.address())).committed.pubKeyHash;
}
async getNonce(nonce: Nonce = 'committed'): Promise<number> {
if (nonce === 'committed') {
return (await this.provider.getState(this.address())).committed.nonce;
} else if (typeof nonce === 'number') {
return nonce;
}
}
async getAccountId(): Promise<number | undefined> {
return (await this.provider.getState(this.address())).id;
}
address(): Address {
return this.cachedAddress;
}
async getAccountState(): Promise<AccountState> {
return this.provider.getState(this.address());
}
async getNFT(tokenId: number, type: 'committed' | 'verified' = 'committed'): Promise<NFT> {
const accountState = await this.getAccountState();
let token: NFT;
if (type === 'committed') {
token = accountState.committed.nfts[tokenId];
} else {
token = accountState.verified.nfts[tokenId];
}
return token;
}
async getBalance(token: TokenLike, type: 'committed' | 'verified' = 'committed'): Promise<BigNumber> {
const accountState = await this.getAccountState();
const tokenSymbol = this.provider.tokenSet.resolveTokenSymbol(token);
let balance: BigNumberish;
if (type === 'committed') {
balance = accountState.committed.balances[tokenSymbol] || '0';
} else {
balance = accountState.verified.balances[tokenSymbol] || '0';
}
return BigNumber.from(balance);
}
async getEthereumBalance(token: TokenLike): Promise<BigNumber> {
try {
return getEthereumBalance(this.ethSigner.provider, this.provider, this.cachedAddress, token);
} catch (e) {
this.modifyEthersError(e);
}
}
async isERC20DepositsApproved(
token: TokenLike,
erc20ApproveThreshold: BigNumber = ERC20_APPROVE_TRESHOLD
): Promise<boolean> {
if (isTokenETH(token)) {
throw Error('ETH token does not need approval.');
}
const tokenAddress = this.provider.tokenSet.resolveTokenAddress(token);
const erc20contract = new Contract(tokenAddress, IERC20_INTERFACE, this.ethSigner);
try {
const currentAllowance = await erc20contract.allowance(
this.address(),
this.provider.contractAddress.mainContract
);
return BigNumber.from(currentAllowance).gte(erc20ApproveThreshold);
} catch (e) {
this.modifyEthersError(e);
}
}
async approveERC20TokenDeposits(
token: TokenLike,
max_erc20_approve_amount: BigNumber = MAX_ERC20_APPROVE_AMOUNT
): Promise<ContractTransaction> {
if (isTokenETH(token)) {
throw Error('ETH token does not need approval.');
}
const tokenAddress = this.provider.tokenSet.resolveTokenAddress(token);
const erc20contract = new Contract(tokenAddress, IERC20_INTERFACE, this.ethSigner);
try {
return erc20contract.approve(this.provider.contractAddress.mainContract, max_erc20_approve_amount);
} catch (e) {
this.modifyEthersError(e);
}
}
async depositToSyncFromEthereum(deposit: {
depositTo: Address;
token: TokenLike;
amount: BigNumberish;
ethTxOptions?: ethers.providers.TransactionRequest;
approveDepositAmountForERC20?: boolean;
}): Promise<ETHOperation> {
const gasPrice = await this.ethSigner.provider.getGasPrice();
const mainZkSyncContract = this.getZkSyncMainContract();
let ethTransaction;
if (isTokenETH(deposit.token)) {
try {
ethTransaction = await mainZkSyncContract.depositETH(deposit.depositTo, {
value: BigNumber.from(deposit.amount),
gasLimit: BigNumber.from(ETH_RECOMMENDED_DEPOSIT_GAS_LIMIT),
gasPrice,
...deposit.ethTxOptions
});
} catch (e) {
this.modifyEthersError(e);
}
} else {
const tokenAddress = this.provider.tokenSet.resolveTokenAddress(deposit.token);
// ERC20 token deposit
const erc20contract = new Contract(tokenAddress, IERC20_INTERFACE, this.ethSigner);
let nonce: number;
if (deposit.approveDepositAmountForERC20) {
try {
const approveTx = await erc20contract.approve(
this.provider.contractAddress.mainContract,
deposit.amount
);
nonce = approveTx.nonce + 1;
} catch (e) {
this.modifyEthersError(e);
}
}
const args = [
tokenAddress,
deposit.amount,
deposit.depositTo,
{
nonce,
gasPrice,
...deposit.ethTxOptions
} as ethers.providers.TransactionRequest
];
// We set gas limit only if user does not set it using ethTxOptions.
const txRequest = args[args.length - 1] as ethers.providers.TransactionRequest;
if (txRequest.gasLimit == null) {
try {
const gasEstimate = await mainZkSyncContract.estimateGas.depositERC20(...args).then(
(estimate) => estimate,
() => BigNumber.from('0')
);
const isMainnet = (await this.ethSigner.getChainId()) == 1;
let recommendedGasLimit =
isMainnet && ERC20_DEPOSIT_GAS_LIMIT[tokenAddress]
? BigNumber.from(ERC20_DEPOSIT_GAS_LIMIT[tokenAddress])
: ERC20_RECOMMENDED_DEPOSIT_GAS_LIMIT;
txRequest.gasLimit = gasEstimate.gte(recommendedGasLimit) ? gasEstimate : recommendedGasLimit;
args[args.length - 1] = txRequest;
} catch (e) {
this.modifyEthersError(e);
}
}
try {
ethTransaction = await mainZkSyncContract.depositERC20(...args);
} catch (e) {
this.modifyEthersError(e);
}
}
return new ETHOperation(ethTransaction, this.provider);
}
async resolveAccountId(): Promise<number> {
if (this.accountId !== undefined) {
return this.accountId;
} else {
const accountState = await this.getAccountState();
if (!accountState.id) {
throw new Error("Can't resolve account id from the zkSync node");
}
return accountState.id;
}
}
async emergencyWithdraw(withdraw: {
token: TokenLike;
accountId?: number;
ethTxOptions?: ethers.providers.TransactionRequest;
}): Promise<ETHOperation> {
const gasPrice = await this.ethSigner.provider.getGasPrice();
let accountId: number = withdraw.accountId != null ? withdraw.accountId : await this.resolveAccountId();
const mainZkSyncContract = this.getZkSyncMainContract();
const tokenAddress = this.provider.tokenSet.resolveTokenAddress(withdraw.token);
try {
const ethTransaction = await mainZkSyncContract.requestFullExit(accountId, tokenAddress, {
gasLimit: BigNumber.from('500000'),
gasPrice,
...withdraw.ethTxOptions
});
return new ETHOperation(ethTransaction, this.provider);
} catch (e) {
this.modifyEthersError(e);
}
}
async emergencyWithdrawNFT(withdrawNFT: {
tokenId: number;
accountId?: number;
ethTxOptions?: ethers.providers.TransactionRequest;
}): Promise<ETHOperation> {
const gasPrice = await this.ethSigner.provider.getGasPrice();
let accountId: number = withdrawNFT.accountId != null ? withdrawNFT.accountId : await this.resolveAccountId();
const mainZkSyncContract = this.getZkSyncMainContract();
try {
const ethTransaction = await mainZkSyncContract.requestFullExitNFT(accountId, withdrawNFT.tokenId, {
gasLimit: BigNumber.from('500000'),
gasPrice,
...withdrawNFT.ethTxOptions
});
return new ETHOperation(ethTransaction, this.provider);
} catch (e) {
this.modifyEthersError(e);
}
}
getZkSyncMainContract() {
return new ethers.Contract(
this.provider.contractAddress.mainContract,
SYNC_MAIN_CONTRACT_INTERFACE,
this.ethSigner
);
}
private modifyEthersError(error: any): never {
if (this.ethSigner instanceof ethers.providers.JsonRpcSigner) {
// List of errors that can be caused by user's actions, which have to be forwarded as-is.
const correct_errors = [
EthersErrorCode.NONCE_EXPIRED,
EthersErrorCode.INSUFFICIENT_FUNDS,
EthersErrorCode.REPLACEMENT_UNDERPRICED,
EthersErrorCode.UNPREDICTABLE_GAS_LIMIT
];
if (!correct_errors.includes(error.code)) {
// This is an error which we don't expect
error.message = `Ethereum smart wallet JSON RPC server returned the following error while executing an operation: "${error.message}". Please contact your smart wallet support for help.`;
}
}
throw error;
}
private async setRequiredAccountIdFromServer(actionName: string) {
if (this.accountId === undefined) {
const accountIdFromServer = await this.getAccountId();
if (accountIdFromServer == null) {
throw new Error(`Failed to ${actionName}: Account does not exist in the zkSync network`);
} else {
this.accountId = accountIdFromServer;
}
}
}
}
export class ETHOperation {
state: 'Sent' | 'Mined' | 'Committed' | 'Verified' | 'Failed';
error?: ZKSyncTxError;
priorityOpId?: BigNumber;
constructor(public ethTx: ContractTransaction, public zkSyncProvider: SyncProvider) {
this.state = 'Sent';
}
async awaitEthereumTxCommit() {
if (this.state !== 'Sent') return;
const txReceipt = await this.ethTx.wait();
for (const log of txReceipt.logs) {
try {
const priorityQueueLog = SYNC_MAIN_CONTRACT_INTERFACE.parseLog(log);
if (priorityQueueLog && priorityQueueLog.args.serialId != null) {
this.priorityOpId = priorityQueueLog.args.serialId;
}
} catch {}
}
if (!this.priorityOpId) {
throw new Error('Failed to parse tx logs');
}
this.state = 'Mined';
return txReceipt;
}
async awaitReceipt(): Promise<PriorityOperationReceipt> {
this.throwErrorIfFailedState();
await this.awaitEthereumTxCommit();
if (this.state !== 'Mined') return;
let query: number | string;
if (this.zkSyncProvider.providerType === 'RPC') {
query = this.priorityOpId.toNumber();
} else {
query = this.ethTx.hash;
}
const receipt = await this.zkSyncProvider.notifyPriorityOp(query, 'COMMIT');
if (!receipt.executed) {
this.setErrorState(new ZKSyncTxError('Priority operation failed', receipt));
this.throwErrorIfFailedState();
}
this.state = 'Committed';
return receipt;
}
async awaitVerifyReceipt(): Promise<PriorityOperationReceipt> {
await this.awaitReceipt();
if (this.state !== 'Committed') return;
let query: number | string;
if (this.zkSyncProvider.providerType === 'RPC') {
query = this.priorityOpId.toNumber();
} else {
query = this.ethTx.hash;
}
const receipt = await this.zkSyncProvider.notifyPriorityOp(query, 'VERIFY');
this.state = 'Verified';
return receipt;
}
private setErrorState(error: ZKSyncTxError) {
this.state = 'Failed';
this.error = error;
}
private throwErrorIfFailedState() {
if (this.state === 'Failed') throw this.error;
}
}
export class Transaction {
state: 'Sent' | 'Committed' | 'Verified' | 'Failed';
error?: ZKSyncTxError;
constructor(public txData, public txHash: string, public sidechainProvider: SyncProvider) {
this.state = 'Sent';
}
async awaitReceipt(): Promise<TransactionReceipt> {
this.throwErrorIfFailedState();
if (this.state !== 'Sent') return;
const receipt = await this.sidechainProvider.notifyTransaction(this.txHash, 'COMMIT');
if (!receipt.success) {
this.setErrorState(new ZKSyncTxError(`zkSync transaction failed: ${receipt.failReason}`, receipt));
this.throwErrorIfFailedState();
}
this.state = 'Committed';
return receipt;
}
async awaitVerifyReceipt(): Promise<TransactionReceipt> {
await this.awaitReceipt();
const receipt = await this.sidechainProvider.notifyTransaction(this.txHash, 'VERIFY');
this.state = 'Verified';
return receipt;
}
private setErrorState(error: ZKSyncTxError) {
this.state = 'Failed';
this.error = error;
}
private throwErrorIfFailedState() {
if (this.state === 'Failed') throw this.error;
}
}
export async function submitSignedTransaction(
signedTx: SignedTransaction,
provider: SyncProvider,
fastProcessing?: boolean
): Promise<Transaction> {
const transactionHash = await provider.submitTx(signedTx.tx, signedTx.ethereumSignature, fastProcessing);
return new Transaction(signedTx, transactionHash, provider);
}
export async function submitSignedTransactionsBatch(
provider: SyncProvider,
signedTxs: SignedTransaction[],
ethSignatures?: TxEthSignature[]
): Promise<Transaction[]> {
const transactionHashes = await provider.submitTxsBatch(
signedTxs.map((tx) => {
return { tx: tx.tx, signature: tx.ethereumSignature };
}),
ethSignatures
);
return transactionHashes.map((txHash, idx) => new Transaction(signedTxs[idx], txHash, provider));
} | the_stack |
import fs from 'fs';
import path from 'path';
import nock from 'nock';
import validateGeneratedFile from '../validateGeneratedFile';
const {
HOST,
RAW_DEFAULT_SOURCE_MAP,
RAW_INLINE_SOURCE_MAP,
ONE_JS,
TWO_JS
} = require('./fixtures/examples');
const appPath = '/static/app.js';
const url = `${HOST}${appPath}`;
it('should download the target minified file, source maps, and external source files', (done) => {
const scope = nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map')
.get('/static/app.js.map')
.reply(200, RAW_DEFAULT_SOURCE_MAP)
.get('/static/one.js')
.reply(200, ONE_JS)
.get('/static/two.js')
.reply(200, TWO_JS);
validateGeneratedFile(url, (report) => {
// verify all mocked requests satisfied
scope.done();
expect(report.errors).toHaveLength(0);
expect(report.sources).toEqual([
`${HOST}/static/one.js`, // note: source-map resolves these
`${HOST}/static/two.js`
]);
done();
});
});
describe('source map location', () => {
it('should resolve absolute sourceMappingURLs', (done) => {
nock(HOST)
.get(appPath)
.reply(
200,
'//#sourceMappingURL=https://127.0.0.1:8000/static/app.js.map'
);
nock('https://127.0.0.1:8000')
.get('/static/app.js.map')
.reply(200, RAW_INLINE_SOURCE_MAP);
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(0);
done();
});
});
it('should resolve sourceMappingURLs that contain data-uri source map data', (done) => {
const minFilePath = path.join(
__dirname,
'fixtures',
'build',
'add.dataUri.js'
);
nock(HOST)
.get(appPath)
.reply(200, fs.readFileSync(minFilePath, 'utf-8'));
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(0);
done();
});
});
it("should locate sourceMappingURLs that aren't on the last line", (done) => {
nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map\n\n');
nock(HOST)
.get('/static/app.js.map')
.reply(200, RAW_INLINE_SOURCE_MAP);
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(0);
done();
});
});
it('should resolve SourceMap headers', (done) => {
nock(HOST)
.get(appPath)
.reply(200, 'function(){}();', {
SourceMap: 'app.js.map'
});
nock(HOST)
.get('/static/app.js.map')
.reply(200, RAW_INLINE_SOURCE_MAP);
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(0);
done();
});
});
it('should resolve X-SourceMap headers', (done) => {
nock(HOST)
.get(appPath)
.reply(200, 'function(){}();', {
'X-SourceMap': 'app.js.map'
});
nock(HOST)
.get('/static/app.js.map')
.reply(200, RAW_INLINE_SOURCE_MAP);
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(0);
done();
});
});
it('should report missing sourceMappingURL', (done) => {
nock(HOST)
.get(appPath)
.reply(200, 'function(){}();');
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('SourceMapNotFoundError');
done();
});
});
}); // source map location
describe('http failures', () => {
it('should report a target file that times out', (done) => {
nock(HOST)
.get(appPath)
.socketDelay(5001)
.reply(200, '<html></html>');
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('ResourceTimeoutError');
expect(report.errors[0]).toHaveProperty(
'message',
'Resource timed out (exceeded 5000ms): https://example.org/static/app.js'
);
done();
});
});
it('should report a source map that times out', (done) => {
nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map');
nock(HOST)
.get('/static/app.js.map')
.socketDelay(5001)
.reply(200, RAW_DEFAULT_SOURCE_MAP);
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('ResourceTimeoutError');
expect(report.errors[0]).toHaveProperty(
'message',
'Resource timed out (exceeded 5000ms): https://example.org/static/app.js.map'
);
done();
});
});
it('should report a target file does not return 200', (done) => {
nock(HOST)
.get(appPath)
.reply(401, 'Not Authenticated');
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('UnableToFetchMinifiedError');
done();
});
});
it('should report a target file does not return a connection', (done) => {
nock(HOST)
.get(appPath)
.replyWithError({
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 1337
});
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('ConnectionRefusedError');
done();
});
});
it('should report a source map file does not return 200', (done) => {
nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map');
nock(HOST)
.get('/static/app.js.map')
.reply(401, 'Not Authenticated');
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('UnableToFetchSourceMapError');
done();
});
});
it('should report a source file that does not return 200', (done) => {
const scope = nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map')
.get('/static/app.js.map')
.reply(200, RAW_DEFAULT_SOURCE_MAP)
.get('/static/one.js')
.reply(200, ONE_JS)
.get('/static/two.js')
.reply(401, 'Not authenticated');
validateGeneratedFile(url, (report) => {
// verify all mocked requests satisfied
scope.done();
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('UnableToFetchSourceError');
done();
});
});
}); // http failures
describe('parsing failures', () => {
it('should report a source map file that is no valid JSON', (done) => {
nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map');
nock(HOST)
.get('/static/app.js.map')
.reply(200, '!@#(!*@#(*&@');
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('InvalidJSONError');
expect(report.errors[0]).toHaveProperty(
'message',
'Does not parse as JSON: Unexpected token ! in JSON at position 0'
);
done();
});
});
it('should report a source map file that does not parse as a Source Map', (done) => {
nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map');
nock(HOST)
.get('/static/app.js.map')
.reply(200, '{"version":"3"}');
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('InvalidSourceMapFormatError');
expect(report.errors[0]).toHaveProperty(
'message',
'Invalid SourceMap format: "sources" is a required argument.'
);
done();
});
});
}); // parsing failures
describe('content failures', () => {
it('should report source files that are not JavaScript', (done) => {
const scope = nock(HOST)
.get(appPath)
.reply(200, '//#sourceMappingURL=app.js.map')
.get('/static/app.js.map')
.reply(200, RAW_DEFAULT_SOURCE_MAP)
.get('/static/one.js')
.reply(200, ONE_JS)
.get('/static/two.js')
.reply(200, ' \n\n\n<!DOCTYPE html><html>lol</html>');
validateGeneratedFile(url, (report) => {
scope.done();
expect(report.errors).toHaveLength(1);
expect(report.errors[0].name).toBe('BadContentError');
expect(report.errors[0]).toHaveProperty(
'message',
'File is not JavaScript: https://example.org/static/two.js'
);
done();
});
});
});
describe('mappings', () => {
describe('inline sources', () => {
it('should parse and validate every mapping', (done) => {
const minFilePath = path.join(
__dirname,
'fixtures',
'build',
'add.inlineSources.js'
);
const mapFilePath = `${minFilePath}.map`;
nock(HOST)
.get(appPath)
.reply(200, fs.readFileSync(minFilePath, 'utf-8'));
nock(HOST)
.get('/static/add.inlineSources.js.map')
.reply(200, fs.readFileSync(mapFilePath, 'utf-8'));
validateGeneratedFile(url, (report) => {
expect(report.errors).toHaveLength(0);
done();
});
});
it("should detect invalid mappings where tokens aren't located on same line", (done) => {
const minFilePath = path.join(
__dirname,
'fixtures',
'build',
'add.fuzzLines.js'
);
const mapFilePath = `${minFilePath}.map`;
nock(HOST)
.get(appPath)
.reply(200, fs.readFileSync(minFilePath, 'utf-8'));
nock(HOST)
.get('/static/add.fuzzLines.js.map')
.reply(200, fs.readFileSync(mapFilePath, 'utf-8'));
validateGeneratedFile(url, (report) => {
expect(report.errors).not.toHaveLength(0);
expect(report.errors[0].name).toBe('BadTokenError');
expect(report.errors[0]).toHaveProperty(
'message',
'Expected token not in correct location'
);
done();
});
});
it('should detect invalid mappings where tokens are on wrong column', (done) => {
const minFilePath = path.join(
__dirname,
'fixtures',
'build',
'add.fuzzColumns.js'
);
const mapFilePath = `${minFilePath}.map`;
nock(HOST)
.get(appPath)
.reply(200, fs.readFileSync(minFilePath, 'utf-8'));
nock(HOST)
.get('/static/add.fuzzColumns.js.map')
.reply(200, fs.readFileSync(mapFilePath, 'utf-8'));
validateGeneratedFile(url, (report) => {
expect(report.warnings).not.toHaveLength(0);
expect(report.warnings[0].name).toBe('BadColumnError');
expect(report.warnings[0]).toHaveProperty(
'message',
'Expected token not in correct location'
);
done();
});
});
});
}); | the_stack |
// eslint-disable-next-line
export type ValueType = number | boolean | string | Date | Object;
export interface Context {
getVariable(name: string): ValueType;
}
export class ShadowContext implements Context {
constructor(
public upstream: Context = null,
public shadows: { [name: string]: ValueType } = {}
) {}
public getVariable(name: string): ValueType {
// eslint-disable-next-line
if (this.shadows.hasOwnProperty(name)) {
return this.shadows[name];
}
return this.upstream.getVariable(name);
}
}
export class SimpleContext implements Context {
public variables: { [name: string]: ValueType } = {};
public getVariable(name: string): ValueType {
return this.variables[name];
}
}
import { constants, functions, operators, precedences } from "./intrinsics";
import { parse } from "./parser";
import {
DataflowTable,
DataflowTableGroupedContext,
} from "../prototypes/dataflow";
import { getFormat, Specification } from "..";
export type PatternReplacer = (expr: Expression) => Expression | void;
export function variableReplacer(map: { [name: string]: string }) {
return (expr: Expression) => {
if (expr instanceof Variable) {
// eslint-disable-next-line
if (map.hasOwnProperty(expr.name)) {
return new Variable(map[expr.name]);
}
}
};
}
export abstract class Expression {
public abstract getValue(context: Context): ValueType;
public abstract toString(): string;
protected abstract getPrecedence(): number;
protected abstract replaceChildren(r: PatternReplacer): Expression;
public toStringPrecedence(parent: number) {
if (this.getPrecedence() < parent) {
return `(${this.toString()})`;
} else {
return this.toString();
}
}
public getNumberValue(c: Context) {
const v = this.getValue(c);
return <number>v;
}
public getStringValue(c: Context) {
const v = this.getValue(c);
return v !== null && v !== undefined ? v.toString() : "null";
}
public static Parse(expr: string): Expression {
return <Expression>parse(expr);
}
public replace(replacer: PatternReplacer): Expression {
const r = replacer(this);
if (r) {
// If the expression matches the pattern, replace itself
return r;
} else {
// Otherwise, replace any pattern found inside
return this.replaceChildren(replacer);
}
}
}
export interface TextExpressionPart {
string?: string;
expression?: Expression;
format?: string;
}
/** Text expression is a special class, it cannot be used inside other expression */
export class TextExpression {
public parts: TextExpressionPart[];
constructor(parts: TextExpressionPart[] = []) {
this.parts = parts;
}
public getValue(context: Context): string {
return this.parts
.map((part) => {
if (part.string) {
return part.string;
} else if (part.expression) {
const val = part.expression.getValue(context);
if (part.format) {
try {
return getFormat()(part.format)(+val);
} catch (ex) {
// try to handle specific format
if (part.format.match(/^%raw$/).length > 0) {
return getFormattedValue(context, val, part.expression);
} else {
throw ex;
}
}
} else {
return val;
}
}
})
.join("");
}
public isTrivialString() {
return this.parts.every((x) => x.string != null);
}
public toString(): string {
return this.parts
.map((part) => {
if (part.string) {
return part.string.replace(/([$\\])/g, "\\$1");
} else if (part.expression) {
const str = part.expression.toString();
if (part.format) {
return "${" + str + "}{" + part.format + "}";
} else {
return "${" + str + "}";
}
}
})
.join("");
}
public static Parse(expr: string): TextExpression {
return <TextExpression>parse(expr, { startRule: "start_text" });
}
public replace(r: PatternReplacer): TextExpression {
return new TextExpression(
this.parts.map((part) => {
if (part.string) {
return { string: part.string };
} else if (part.expression) {
if (part.format) {
return {
expression: part.expression.replace(r),
format: part.format,
};
} else {
return { expression: part.expression.replace(r) };
}
}
})
);
}
}
export class Value<T> extends Expression {
constructor(public value: T) {
super();
}
public getValue() {
return this.value;
}
public toString() {
return JSON.stringify(this.value);
}
protected getPrecedence(): number {
return precedences.VALUE;
}
// eslint-disable-next-line
protected replaceChildren(r: PatternReplacer): Expression {
return new Value<T>(this.value);
}
}
export class StringValue extends Value<string> {}
export class NumberValue extends Value<number> {}
export class BooleanValue extends Value<boolean> {}
export class DateValue extends Value<Date> {}
export class FieldAccess extends Expression {
constructor(public expr: Expression, public fields: string[]) {
super();
}
public getValue(c: Context) {
let v = <any>this.expr.getValue(c);
for (const f of this.fields) {
v = v[f];
}
return v;
}
public toString() {
return `${this.expr.toStringPrecedence(
precedences.FIELD_ACCESS
)}.${this.fields.map(Variable.VariableNameToString).join(".")}`;
}
protected getPrecedence(): number {
return precedences.FIELD_ACCESS;
}
protected replaceChildren(r: PatternReplacer): Expression {
return new FieldAccess(this.expr.replace(r), this.fields);
}
}
export class FunctionCall extends Expression {
public name: string;
// eslint-disable-next-line
public function: Function;
public args: Expression[];
constructor(parts: string[], args: Expression[]) {
super();
this.name = parts.join(".");
this.args = args;
let v = <any>functions;
for (const part of parts) {
// eslint-disable-next-line
if (v.hasOwnProperty(part)) {
v = v[part];
} else {
v = undefined;
}
}
if (v == undefined) {
throw new SyntaxError(`undefiend function ${this.name}`);
} else {
this.function = v;
}
}
public getValue(c: Context) {
return this.function(...this.args.map((arg) => arg.getValue(c)));
}
public toString() {
return `${this.name}(${this.args
.map((arg) => arg.toStringPrecedence(precedences.FUNCTION_ARGUMENT))
.join(", ")})`;
}
protected getPrecedence(): number {
return precedences.FUNCTION_CALL;
}
protected replaceChildren(r: PatternReplacer): Expression {
return new FunctionCall(
this.name.split("."),
this.args.map((x) => x.replace(r))
);
}
}
export class Operator extends Expression {
// eslint-disable-next-line
private op: Function;
constructor(
public name: string,
public lhs: Expression,
public rhs?: Expression
) {
super();
if (rhs != undefined) {
this.op = operators[name];
} else {
this.op = operators["unary:" + name];
}
}
public getValue(c: Context) {
const lhs = this.lhs.getValue(c);
if (this.rhs != undefined) {
const rhs = this.rhs.getValue(c);
return this.op(lhs, rhs);
} else {
return this.op(lhs);
}
}
public toString() {
const p = this.getMyPrecedence();
if (this.rhs != undefined) {
return `${this.lhs.toStringPrecedence(p[1])} ${
this.name
} ${this.rhs.toStringPrecedence(p[2])}`;
} else {
return `${this.name} ${this.lhs.toStringPrecedence(p[1])}`;
}
}
protected getMyPrecedence(): number[] {
if (this.rhs != undefined) {
return precedences.OPERATORS[this.name];
} else {
return precedences.OPERATORS["unary:" + this.name];
}
}
protected getPrecedence(): number {
return this.getMyPrecedence()[0];
}
protected replaceChildren(r: PatternReplacer): Expression {
return new Operator(
this.name,
this.lhs.replace(r),
this.rhs ? this.rhs.replace(r) : null
);
}
}
export class LambdaFunction extends Expression {
public readonly expr: Expression;
public readonly argNames: string[];
public constructor(expr: Expression, argNames: string[]) {
super();
this.expr = expr;
this.argNames = argNames;
}
public getValue(c: Context) {
return (...args: ValueType[]) => {
const lambdaContext = new ShadowContext(c);
for (let i = 0; i < this.argNames.length; i++) {
lambdaContext.shadows[this.argNames[i]] = args[i];
}
return this.expr.getValue(lambdaContext);
};
}
public toString() {
return `(${this.argNames.join(", ")}) => ${this.expr.toStringPrecedence(
precedences.LAMBDA_EXPRESSION
)}`;
}
protected getPrecedence(): number {
return precedences.LAMBDA_FUNCTION;
}
protected replaceChildren(r: PatternReplacer): Expression {
// Mask the argument variables in the lambda function
const rMasked = (expr: Expression) => {
if (expr instanceof Variable && this.argNames.indexOf(expr.name) >= 0) {
return undefined;
} else {
return r(expr);
}
};
return new LambdaFunction(this.expr.replace(rMasked), this.argNames);
}
}
export class Variable extends Expression {
constructor(public readonly name: string) {
super();
}
public getValue(c: Context) {
const v = c.getVariable(this.name);
if (v === undefined) {
return constants[this.name];
} else {
return v;
}
}
public toString() {
return Variable.VariableNameToString(this.name);
}
protected getPrecedence(): number {
return precedences.VARIABLE;
}
public static VariableNameToString(name: string) {
if (name.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
return name;
} else {
return JSON.stringify(name).replace(/^"|"$/g, "`");
}
}
// eslint-disable-next-line
protected replaceChildren(r: PatternReplacer): Expression {
return new Variable(this.name);
}
}
function getFormattedValue(context: Context, val: any, expression: Expression) {
if (val === undefined || val === null) {
return val;
}
if (context instanceof ShadowContext) {
if (
expression instanceof FunctionCall &&
expression.args[0] instanceof Variable
) {
const columnName = (<Variable>expression.args[0]).name;
const column = (<DataflowTable>(
(<ShadowContext>context).upstream
)).columns.find((col) => col.name == columnName);
if (
column.metadata.rawColumnName &&
(column.metadata.kind === Specification.DataKind.Temporal ||
column.type === Specification.DataType.Boolean)
) {
return (<ShadowContext>context).getVariable(
column.metadata.rawColumnName
);
}
}
}
if (context instanceof DataflowTableGroupedContext) {
if (
expression instanceof FunctionCall &&
expression.args[0] instanceof Variable
) {
const columnName = (<Variable>expression.args[0]).name;
const rawColumnName = (<DataflowTableGroupedContext>context)
.getTable()
.columns.find((col) => col.name == columnName).metadata.rawColumnName;
if (rawColumnName) {
return (<DataflowTableGroupedContext>context).getVariable(
rawColumnName
);
}
}
}
return val;
} | the_stack |
module Spriter {
export class Loader {
private _spriter: Spriter;
private _fileType: eFileType;
// -------------------------------------------------------------------------
public load(file: SpriterFile): Spriter {
this._spriter = new Spriter();
this._fileType = file.getType();
// folders and files
var folders = file.getNodes("folder");
this.loadFolders(this._spriter, folders);
folders.processed();
// tags
var tags = file.getNodes("tag_list");
this.loadTags(this._spriter, tags);
tags.processed();
// entity
var entities = file.getNodes("entity");
this.loadEntities(this._spriter, entities);
entities.processed();
return this._spriter;
}
// -------------------------------------------------------------------------
private loadFolders(spriter: Spriter, folders: ISpriterNodeList): void {
// through all folders
for (var i = 0; i < folders.length(); i++) {
var folder = folders.getFolder(i);
// images in folder - ignore sounds
var files = folders.getChildNodes(i, "file");
this.loadFiles(folder, files);
files.processed();
// add folder to spriter object
spriter.addFolder(folder);
}
}
// -------------------------------------------------------------------------
private loadFiles(folder: Folder, files: ISpriterNodeList): void {
for (var f = 0; f < files.length(); f++) {
var file = files.getFile(f);
// null is returned if file is not image but sound
if (file !== null) {
folder.addFile(file);
}
}
}
// -------------------------------------------------------------------------
private loadTags(spriter: Spriter, tags: ISpriterNodeList): void {
// no tags
if (tags.length() === 0) {
return;
}
// different structure for json than for xml
var tagDefs: ISpriterNodeList;
if (this._fileType !== eFileType.JSON) {
tagDefs = tags.getChildNodes(0, "i");
} else {
tagDefs = tags;
}
for (var i = 0; i < tagDefs.length(); i++) {
var tag = tagDefs.getTag(i);
spriter.addTag(tag);
}
// different structure for json than for xml
if (this._fileType !== eFileType.JSON) {
tagDefs.processed();
}
}
// -------------------------------------------------------------------------
private loadEntities(spriter: Spriter, entities: ISpriterNodeList): void {
for (var i = 0; i < entities.length(); i++) {
var entity = entities.getEntity(i);
// bones, boxes, ...
var objInfos = entities.getChildNodes(i, "obj_info");
this.loadObjInfo(entity, objInfos);
objInfos.processed();
// character maps
var charMaps = entities.getChildNodes(i, "character_map");
this.loadCharMaps(entity, charMaps);
charMaps.processed();
// variable definitions
var variables = entities.getChildNodes(i, "var_defs");
this.loadVariables(entity, variables);
variables.processed();
// animations
var animations = entities.getChildNodes(i, "animation");
this.loadAnimations(entity, animations);
animations.processed();
spriter.addEntity(entity);
}
}
// -------------------------------------------------------------------------
private loadObjInfo(entity: Entity, objInfos: ISpriterNodeList): void {
for (var i = 0; i < objInfos.length(); i++) {
var objInfo = objInfos.getObjectInfo(i);
entity.addObjectInfo(objInfo);
}
}
// -------------------------------------------------------------------------
private loadCharMaps(entity: Entity, charMaps: ISpriterNodeList): void {
for (var i = 0; i < charMaps.length(); i++) {
var charMap = charMaps.getCharMap(i);
var charMapEntries = charMaps.getChildNodes(i, "map");
this.loadCharMapEntries(charMap, charMapEntries);
charMapEntries.processed();
entity.addCharMap(charMap);
}
}
// -------------------------------------------------------------------------
private loadCharMapEntries(charMap: CharMap, charMapEntries: ISpriterNodeList): void {
for (var i = 0; i < charMapEntries.length(); i++) {
charMapEntries.getCharMapEntry(i, charMap, this._spriter);
}
}
// -------------------------------------------------------------------------
private loadVariables(entity: Entity, variables: ISpriterNodeList): void {
// no variables
if (variables.length() === 0) {
return;
}
// different structure for json than for xml
var varDefs: ISpriterNodeList;
if (this._fileType !== eFileType.JSON) {
varDefs = variables.getChildNodes(0, "i");
} else {
varDefs = variables;
}
for (var i = 0; i < varDefs.length(); i++) {
var varDef = varDefs.getVariable(i);
entity.addVariable(varDef);
}
// different structure for json than for xml
if (this._fileType !== eFileType.JSON) {
varDefs.processed();
}
}
// -------------------------------------------------------------------------
private loadAnimations(entity: Entity, animations: ISpriterNodeList): void {
for (var i = 0; i < animations.length(); i++) {
var animation = animations.getAnimation(i);
// main line keys
var mainlines = animations.getChildNodes(i, "mainline");
this.loadMainline(animation, mainlines);
mainlines.processed();
// timelines
var timelines = animations.getChildNodes(i, "timeline");
this.loadTimelines(animation, timelines);
timelines.processed();
// sound lines
var soundlines = animations.getChildNodes(i, "soundline");
this.loadSoundlines(animation, soundlines);
soundlines.processed();
// event lines
var eventlines = animations.getChildNodes(i, "eventline");
this.loadEventlines(animation, eventlines);
eventlines.processed();
// get meta tag
var meta = animations.getChildNodes(i, "meta");
if (meta.length() > 0) {
// var lines
// OMG - typo in attribute name in JSOUN export... what the hell! TODO - remove when corrected
var varlines = meta.getChildNodes(0, (this._fileType !== eFileType.JSON) ? "varline" : "valline");
this.loadVarlines(entity, animation, varlines);
varlines.processed();
// tag lines
var taglines = meta.getChildNodes(0, "tagline");
this.loadTaglines(animation, taglines);
taglines.processed();
}
meta.processed();
// add completely built animation to entity
entity.addAnimation(animation);
}
}
// -------------------------------------------------------------------------
private loadMainline(animation: Animation, mainlines: ISpriterNodeList): void {
var mainline = mainlines.getMainline(0);
mainline.type = eTimelineType.MAIN_LINE;
var mainlineKeys = mainlines.getChildNodes(0, "key");
this.loadMainlineKeys(mainline, mainlineKeys);
mainlineKeys.processed();
animation.mainline = mainline;
}
// -------------------------------------------------------------------------
private loadMainlineKeys(mainline: Baseline, mainlineKeys: ISpriterNodeList): void {
for (var i = 0; i < mainlineKeys.length(); i++) {
var mainLineKey = mainlineKeys.getMainlineKey(i);
// load bone refs
var boneRefs = mainlineKeys.getChildNodes(i, "bone_ref");
for (var b = 0; b < boneRefs.length(); b++) {
mainLineKey.addBoneRef(boneRefs.getRef(b));
}
boneRefs.processed();
// load sprite refs (object refs)
var spriteRefs = mainlineKeys.getChildNodes(i, "object_ref");
for (var s = 0; s < spriteRefs.length(); s++) {
mainLineKey.addObjectRef(spriteRefs.getRef(s));
}
spriteRefs.processed();
mainline.add(mainLineKey);
}
}
// -------------------------------------------------------------------------
private loadTimelines(animation: Animation, aTimelines: ISpriterNodeList): void {
for (var i = 0; i < aTimelines.length(); i++) {
var timeline = aTimelines.getTimeline(i);
var keys = aTimelines.getChildNodes(i, "key");
this.loadTimelineKeys(timeline, keys);
keys.processed();
animation.addTimeline(timeline);
}
}
// -------------------------------------------------------------------------
private loadTimelineKeys(aTimeline: Timeline, aKeys: ISpriterNodeList): void {
for (var i = 0; i < aKeys.length(); i++) {
var key = aKeys.getTimelineKey(i, this._spriter);
aTimeline.add(key);
}
}
// -------------------------------------------------------------------------
private loadSoundlines(animation: Animation, soundlines: ISpriterNodeList): void {
for (var i = 0; i < soundlines.length(); i++) {
var soundline = soundlines.getSoundline(i);
soundline.type = eTimelineType.SOUND_LINE;
var keys = soundlines.getChildNodes(i, "key");
this.loadKeys(soundline, keys);
keys.processed();
animation.addLine(soundline);
}
}
// -------------------------------------------------------------------------
private loadKeys(timeline: Baseline, keys: ISpriterNodeList): void {
for (var i = 0; i < keys.length(); i++) {
var key = keys.getKey(i);
timeline.add(key);
}
}
// -------------------------------------------------------------------------
private loadEventlines(animation: Animation, eventlines: ISpriterNodeList): void {
for (var i = 0; i < eventlines.length(); i++) {
var eventline = eventlines.getEventline(i);
eventline.type = eTimelineType.EVENT_LINE;
var keys = eventlines.getChildNodes(i, "key");
this.loadKeys(eventline, keys);
keys.processed();
animation.addLine(eventline);
}
}
// -------------------------------------------------------------------------
private loadTaglines(animation: Animation, taglines: ISpriterNodeList): void {
for (var i = 0; i < taglines.length(); i++) {
var tagline = taglines.getTagline(i);
tagline.type = eTimelineType.TAG_LINE;
var keys = taglines.getChildNodes(i, "key");
this.loadTagKeys(tagline, keys);
keys.processed();
animation.addLine(tagline);
}
}
// -------------------------------------------------------------------------
private loadTagKeys(tagline: Baseline, keys: ISpriterNodeList): void {
for (var i = 0; i < keys.length(); i++) {
var key = keys.getTagKey(i);
var tagChangeElements = keys.getChildNodes(i, "tag");
var tagChanges = tagChangeElements.getTagChanges(this._spriter);
tagChangeElements.processed();
key.tagsOn = tagChanges;
tagline.add(key);
}
}
// -------------------------------------------------------------------------
private loadVarlines(entity: Entity, animation: Animation, varlines: ISpriterNodeList): void {
for (var i = 0; i < varlines.length(); i++) {
var varline = varlines.getVarline(i);
var type = entity.getVariableById(varline.varDefId).type;
var keys = varlines.getChildNodes(i, "key");
this.loadVariableKeys(varline, keys, type);
keys.processed();
animation.addLine(varline);
}
}
// -------------------------------------------------------------------------
private loadVariableKeys(varline: Varline, keys: ISpriterNodeList, type: eVariableType): void {
for (var i = 0; i < keys.length(); i++) {
var key = keys.getVariableKey(i, type);
varline.add(key);
}
}
}
} | the_stack |
import * as React from 'react';
import * as _ from 'lodash';
import Toolbar from 'react-md/lib/Toolbars';
import Button from 'react-md/lib/Buttons';
import Dialog from 'react-md/lib/Dialogs';
import { Spinner } from '../Spinner';
import { AutoRefreshSelector } from '../AutoRefreshSelector';
import * as ReactGridLayout from 'react-grid-layout';
var ResponsiveReactGridLayout = ReactGridLayout.Responsive;
var WidthProvider = ReactGridLayout.WidthProvider;
ResponsiveReactGridLayout = WidthProvider(ResponsiveReactGridLayout);
import ElementConnector from '../ElementConnector';
import { loadDialogsFromDashboard } from '../generic/Dialogs';
import { downloadBlob } from './DownloadFile';
import { SettingsButton } from '../Settings';
import ConfigurationsActions from '../../actions/ConfigurationsActions';
import ConfigurationsStore from '../../stores/ConfigurationsStore';
import VisibilityStore from '../../stores/VisibilityStore';
import { Editor, EditorActions } from './Editor';
import { Settings } from '../Card/Settings';
const renderHTML = require('react-render-html');
import List from 'react-md/lib/Lists/List';
import ListItem from 'react-md/lib/Lists/ListItem';
import FontIcon from 'react-md/lib/FontIcons';
import Avatar from 'react-md/lib/Avatars';
import Subheader from 'react-md/lib/Subheaders';
import Divider from 'react-md/lib/Dividers';
import TextField from 'react-md/lib/TextFields';
import MenuButton from 'react-md/lib/Menus/MenuButton';
interface IDashboardProps {
dashboard?: IDashboardConfig;
}
interface IDashboardState {
editMode?: boolean;
askDelete?: boolean;
askSaveAsTemplate?: boolean;
mounted?: boolean;
currentBreakpoint?: string;
layouts?: ILayouts;
grid?: any;
askConfig?: boolean;
visibilityFlags?: IDict<boolean>;
infoVisible?: boolean;
infoHtml?: string;
newTemplateName?: string;
newTemplateDescription?: string;
}
export default class Dashboard extends React.Component<IDashboardProps, IDashboardState> {
layouts = {};
state = {
editMode: false,
askDelete: false,
askSaveAsTemplate: false,
currentBreakpoint: 'lg',
mounted: false,
layouts: {},
grid: null,
askConfig: false,
visibilityFlags: {},
infoVisible: false,
infoHtml: '',
newTemplateName: '',
newTemplateDescription: '',
};
constructor(props: IDashboardProps) {
super(props);
this.onBreakpointChange = this.onBreakpointChange.bind(this);
this.onLayoutChangeActive = this.onLayoutChangeActive.bind(this);
this.onLayoutChangeInactive = this.onLayoutChangeInactive.bind(this);
this.onConfigDashboard = this.onConfigDashboard.bind(this);
this.toggleEditMode = this.toggleEditMode.bind(this);
this.onDeleteDashboard = this.onDeleteDashboard.bind(this);
this.onDeleteDashboardApprove = this.onDeleteDashboardApprove.bind(this);
this.onDeleteDashboardCancel = this.onDeleteDashboardCancel.bind(this);
this.onUpdateLayout = this.onUpdateLayout.bind(this);
this.onOpenInfo = this.onOpenInfo.bind(this);
this.onCloseInfo = this.onCloseInfo.bind(this);
this.onDownloadDashboard = this.onDownloadDashboard.bind(this);
this.onSaveAsTemplate = this.onSaveAsTemplate.bind(this);
this.newTemplateNameChange = this.newTemplateNameChange.bind(this);
this.onSaveAsTemplateApprove = this.onSaveAsTemplateApprove.bind(this);
this.onSaveAsTemplateCancel = this.onSaveAsTemplateCancel.bind(this);
this.newTemplateDescriptionChange = this.newTemplateDescriptionChange.bind(this);
this.onVisibilityStoreChange = this.onVisibilityStoreChange.bind(this);
VisibilityStore.listen(this.onVisibilityStoreChange);
this.state.newTemplateName = this.props.dashboard.name;
this.state.newTemplateDescription = this.props.dashboard.description;
}
componentDidMount() {
let { dashboard } = this.props;
let { mounted } = this.state;
this.onLayoutChange = this.onLayoutChangeActive;
if (dashboard && !mounted) {
const layout = dashboard.config.layout;
// For each column, create a layout according to number of columns
let layouts = ElementConnector.loadLayoutFromDashboard(dashboard, dashboard);
layouts = _.extend(layouts, dashboard.layouts || {});
this.layouts = layouts;
this.setState({
mounted: true,
layouts: { lg: layouts['lg'] },
grid: {
className: 'layout',
rowHeight: layout.rowHeight || 30,
cols: layout.cols,
breakpoints: layout.breakpoints,
verticalCompact: false
}
});
}
}
componentDidUpdate() {
this.componentDidMount();
}
componentWillUnmount() {
this.onLayoutChange = this.onLayoutChangeInactive;
VisibilityStore.unlisten(this.onVisibilityStoreChange);
}
onVisibilityStoreChange(state: any) {
this.setState({ visibilityFlags: state.flags });
}
onBreakpointChange(breakpoint: any) {
var layouts = this.state.layouts;
layouts[breakpoint] = layouts[breakpoint] || this.layouts[breakpoint];
this.setState({
currentBreakpoint: breakpoint,
layouts: layouts
});
}
onLayoutChange(layout: any, layouts: any) { }
onLayoutChangeActive(layout: any, layouts: any) {
// Waiting for breakpoint to change
let breakpoint = this.state.currentBreakpoint;
let newLayouts = this.state.layouts;
newLayouts[breakpoint] = layout;
this.setState({
layouts: newLayouts
});
// Saving layout to API
let { dashboard } = this.props;
dashboard.layouts = dashboard.layouts || {};
dashboard.layouts[breakpoint] = layout;
if (this.state.editMode) {
ConfigurationsActions.saveConfiguration(dashboard);
}
}
onLayoutChangeInactive(layout: any, layouts: any) {
}
onConfigDashboard() {
this.setState({ askConfig: true });
}
toggleEditMode() {
this.setState({ editMode: !this.state.editMode });
}
onDeleteDashboard() {
this.setState({ askDelete: true });
}
onSaveAsTemplate() {
this.setState({ askSaveAsTemplate: true });
}
onSaveAsTemplateApprove() {
let { dashboard } = this.props;
var template = _.cloneDeep(dashboard);
template.name = this.state.newTemplateName;
template.description = this.state.newTemplateDescription;
template.category = 'Custom Templates';
template.id = template.url = dashboard.id + (Math.floor(Math.random() * 1000) + 1); // generate random id
// Removing connections so private info will not be included
template.config.connections = {};
ConfigurationsActions.saveAsTemplate(template);
window.location.href = '/';
this.setState({ askSaveAsTemplate: false });
}
onSaveAsTemplateCancel() {
this.setState({ askSaveAsTemplate: false });
}
newTemplateNameChange(value: string, e: any) {
this.setState({ newTemplateName: value });
}
newTemplateDescriptionChange(value: string, e: any) {
this.setState({ newTemplateDescription: value });
}
onDeleteDashboardApprove() {
let { dashboard } = this.props;
if (!dashboard) {
console.warn('Dashboard not found. Aborting delete.');
}
ConfigurationsActions.deleteDashboard(dashboard.id);
window.location.href = '/';
this.setState({ askDelete: false });
}
onDeleteDashboardCancel() {
this.setState({ askDelete: false });
}
onConfigDashboardCancel() {
this.setState({ askConfig: false });
}
onUpdateLayout() {
this.setState({ editMode: !this.state.editMode });
this.setState({ editMode: !this.state.editMode });
}
onOpenInfo(html: string) {
this.setState({ infoVisible: true, infoHtml: html });
}
onCloseInfo() {
this.setState({ infoVisible: false });
}
onDownloadDashboard() {
let { dashboard } = this.props;
dashboard.layouts = dashboard.layouts || {};
let stringDashboard = ConfigurationsActions.convertDashboardToString(dashboard);
var dashboardName = dashboard.id.replace(/ +/g, ' ');
dashboardName = dashboard.id.replace(/ +/g, '_');
downloadBlob('return ' + stringDashboard, 'application/json', dashboardName + '.private.js');
}
render() {
const { dashboard } = this.props;
const {
currentBreakpoint,
grid,
editMode,
askDelete,
askConfig ,
askSaveAsTemplate,
newTemplateName,
newTemplateDescription
} = this.state;
const { infoVisible, infoHtml } = this.state;
const layout = this.state.layouts[currentBreakpoint];
if (!grid) {
return null;
}
// Creating visual elements
var elements = ElementConnector.loadElementsFromDashboard(dashboard, layout);
// Creating filter elements
var { filters, /*additionalFilters*/ } = ElementConnector.loadFiltersFromDashboard(dashboard);
// Loading dialogs
var dialogs = loadDialogsFromDashboard(dashboard);
// Actions to perform on an active dashboard
let toolbarActions = [];
// Edit toggle button
const editLabel = editMode ? 'Save layout' : 'Edit layout' ;
toolbarActions.push(
(
<span>
<AutoRefreshSelector/>
</span>
),
(
<span>
<Button key="edit-grid" icon primary={editMode} tooltipLabel={editLabel} onClick={this.toggleEditMode}>
edit
</Button>
</span>
),
(
<SettingsButton onUpdateLayout={this.onUpdateLayout} />
),
(
<span>
<MenuButton
id="vert-menu"
icon
buttonChildren="more_vert"
tooltipLabel="More">
<ListItem
key="info"
primaryText="Info"
leftIcon={<FontIcon key="info">info</FontIcon>}
onClick={this.onOpenInfo.bind(this, dashboard.html)}
/>
<Divider />
<ListItem
key="edit"
primaryText="Edit code"
leftIcon={<FontIcon key="code">code</FontIcon>}
onClick={() => EditorActions.loadDashboard(dashboard.id)}
/>
<ListItem
key="down"
primaryText="Download dashboard"
leftIcon={<FontIcon key="file_download">file_download</FontIcon>}
onClick={this.onDownloadDashboard}
/>
<ListItem
key="temp"
primaryText="Save as template"
leftIcon={<FontIcon key="cloud_download">cloud_download</FontIcon>}
onClick={this.onSaveAsTemplate}
/>
<Divider />
<ListItem
key="del"
primaryText="Delete dashboard"
leftIcon={<FontIcon key="delete">delete</FontIcon>}
onClick={this.onDeleteDashboard}
/>
</MenuButton>
</span>
)
);
return (
<div style={{width: '100%'}}>
<Toolbar width={100} actions={toolbarActions}>
{filters}
<Spinner />
</Toolbar>
<ResponsiveReactGridLayout
{...grid}
isDraggable={editMode}
isResizable={editMode}
layouts={this.state.layouts}
onBreakpointChange={this.onBreakpointChange}
onLayoutChange={this.onLayoutChange}
// WidthProvider option
measureBeforeMount={false}
// I like to have it animate on mount. If you don't, delete `useCSSTransforms` (it's default `true`)
// and set `measureBeforeMount={true}`.
useCSSTransforms={this.state.mounted}
>
{elements}
</ResponsiveReactGridLayout>
{dialogs}
<Dialog
id="infoDialog"
visible={infoVisible}
onHide={this.onCloseInfo}
dialogStyle={{ width: '80%' }}
contentStyle={{ padding: '0', maxHeight: 'calc(100vh - 148px)' }}
aria-label="Info"
focusOnMount={false}
>
<div className="md-grid">
{renderHTML(infoHtml)}
</div>
</Dialog>
<Editor dashboard={dashboard} />
<Settings dashboard={dashboard} />
<Dialog
id="deleteDashboard"
visible={askDelete}
title="Are you sure?"
aria-labelledby="deleteDashboardDescription"
modal
actions={[
{ onClick: this.onDeleteDashboardApprove, primary: false, label: 'Permanently Delete', },
{ onClick: this.onDeleteDashboardCancel, primary: true, label: 'Cancel' }
]}
>
<p id="deleteDashboardDescription" className="md-color--secondary-text">
Deleting this dashboard will remove all Connections/Customization you have made to it.
Are you sure you want to permanently delete this dashboard?
</p>
</Dialog>
<Dialog
dialogStyle={{ width: '50%' }}
id="saveAsTemplateDialog"
visible={askSaveAsTemplate}
title="Save this dashoard as a custom template"
modal
actions={[
{ onClick: this.onSaveAsTemplateApprove, primary: false, label: 'Save as custom template', },
{ onClick: this.onSaveAsTemplateCancel, primary: true, label: 'Cancel' }
]}
>
<p>You can save this dashboard as a custom template for a future reuse</p>
<TextField
id="templateName"
label="New Template Name"
placeholder="Template Name"
className="md-cell md-cell--bottom"
value={newTemplateName}
onChange={this.newTemplateNameChange}
required
/>
<TextField
id="templateDescription"
label="New Template Description"
placeholder="Template Description"
className="md-cell md-cell--bottom"
value={newTemplateDescription}
onChange={this.newTemplateDescriptionChange}
required
/>
</Dialog>
</div>
);
}
} | the_stack |
import Adapt, {
AnyProps,
BuildData,
BuiltinProps,
gql,
Handle,
isHandle,
isMountedElement,
ObserveForStatus,
SFCBuildProps,
SFCDeclProps,
useBuildHelpers,
useDeployedWhen,
useImperativeMethods,
useState,
waiting,
Waiting
} from "@adpt/core";
import { Omit, removeUndef } from "@adpt/utils";
import { isObject } from "lodash";
import {
NetworkScope,
NetworkServiceInstance,
NetworkServiceProps,
NetworkServiceScope,
targetPort
} from "../NetworkService";
import {
ClusterInfo,
computeNamespaceFromMetadata,
isLabelSelector,
LabelSelector,
Metadata,
ResourceBase,
ResourceProps,
ResourcePropsWithConfig,
ResourceService
} from "./common";
import { K8sObserver } from "./k8s_observer";
import { labelKey, registerResourceKind, resourceElementToName, resourceIdToName } from "./manifest_support";
import { Resource } from "./Resource";
/** @public */
export interface ServiceProps extends ServiceSpec {
/** Legal configuration loaded from kubeconfig */
config: ClusterInfo;
metadata?: Metadata;
selector?: Handle | EndpointSelector;
}
/** @public */
export interface ServiceSpec {
/**
* Cluster IP for a {@link k8s.Service}
*
* @remarks
* `clusterIP` is the IP address of the service and is usually assigned
* randomly by the master. If an address is specified manually and is not
* in use by others, it will be allocated to the service; otherwise,
* creation of the service will fail. This field can not be changed through
* updates. Valid values are "None", empty string (""), or a valid IP
* address. "None" can be specified for headless services when proxying is
* not required. Only applies to types ClusterIP, NodePort, and
* LoadBalancer. Ignored if type is ExternalName.
*
* For more information, see the
* {@link https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies |
* Kubernetes documentation}.
*/
clusterIP?: string;
/**
* A list of IP addresses for which nodes in the cluster
* will also accept traffic for this service.
*
* @remarks
* These IPs are not managed by
* Kubernetes. The user is responsible for ensuring that traffic arrives at
* a node with this IP. A common example is external load balancers that are
* not part of the Kubernetes system.
*/
externalIPs?: string[];
/**
* The external reference that kubedns or equivalent
* will return as a CNAME record for this service.
*
* @remarks
* No proxying will be involved. Must be a
* {@link https://tools.ietf.org/html/rfc1123 | valid RFC-1123 hostname}
* and requires Type to be ExternalName.
*/
externalName?: string;
/**
* Denotes if this Service desires to route
* external traffic to node-local or cluster-wide endpoints.
*
* @remarks
* "Local" preserves the client source IP and avoids a second hop for
* LoadBalancer and Nodeport type services, but risks potentially
* imbalanced traffic spreading. "Cluster" obscures the client source IP
* and may cause a second hop to another node, but should have good overall
* load-spreading.
*/
externalTrafficPolicy?: string;
/**
* Specifies the healthcheck nodePort for the service.
*
* @remarks
* If not specified, HealthCheckNodePort is created by the service
* api backend with the allocated nodePort. Will use user-specified nodePort
* value if specified by the client. Only affects when Type is set to
* LoadBalancer and ExternalTrafficPolicy is set to Local.
*/
healthCheckNodePort?: number;
/**
* Only applies to Service Type: LoadBalancer. LoadBalancer will
* get created with the IP specified in this field.
*
* @remarks
* This feature depends on
* whether the underlying cloud provider supports specifying the loadBalancerIP
* when a load balancer is created. This field will be ignored if the
* cloud provider does not support the feature.
*/
loadBalancerIP?: string;
/**
* If specified and supported by the platform, this will
* restrict traffic through the cloud provider load balancer
* to the specified client IPs.
*
* @remarks
* This field will be ignored if the cloud provider
* does not support the feature.
*
* For more information, see the
* {@link https://v1-17.docs.kubernetes.io/docs/tasks/access-application-cluster/configure-cloud-provider-firewall/ |
* Kubernetes documentation}.
*/
loadBalancerSourceRanges?: string[];
/**
* The list of ports that are exposed by this service.
*
* @remarks
* For more information, see the
* {@link https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies |
* Kubernetes documentation}.
*/
ports?: ServicePort[];
/**
* When set to true, indicates that
* DNS implementations must publish the notReadyAddresses of subsets for the
* Endpoints associated with the Service.
*
* @remarks
* The default value is false. The
* primary use case for setting this field is to use a StatefulSet's Headless
* Service to propagate SRV records for its Pods without respect to their
* readiness for purpose of peer discovery.
*/
publishNotReadyAddresses?: boolean;
/**
* Route service traffic to pods with label keys and values
* matching this selector.
*
* @remarks
* If empty or not present, the service is assumed to
* have an external process managing its endpoints, which Kubernetes will not
* modify. Only applies to types ClusterIP, NodePort, and LoadBalancer.
* Ignored if type is ExternalName.
*
* For more information, see the
* {@link https://kubernetes.io/docs/concepts/services-networking/service/ |
* Kubernetes documentation}.
*/
selector?: EndpointSelector | object; //FIXME(manishv) object allows ServiceProps to expand type, need a better fix
/**
* Used to maintain session affinity.
*
* @remarks
* Possible values are:
*
* - `"ClientIP"`: Enables client IP based session affinity.
*
* - `"None"`: Disables session affinity.
*
* For more information, see the
* {@link https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies |
* Kubernetes documentation}.
* @defaultValue `"None"`
*/
sessionAffinity?: string;
// sessionAffinityConfig contains the configurations of session affinity.
//sessionAffinityConfig?: SessionAffinityConfig;
/**
* Determines how the Service is exposed.
*
* @remarks
* Valid options are:
*
* - `"ExternalName"`: maps to the specified externalName.
*
* - `"ClusterIP"`: allocates a cluster-internal IP address for load
* balancing to endpoints. Endpoints are determined by the selector or if
* that is not specified, by manual construction of an Endpoints object. If
* clusterIP is "None", no virtual IP is allocated and the endpoints are
* published as a set of endpoints rather than a stable IP.
*
* - `"NodePort"`: Builds on ClusterIP and allocates a port on every node
* which routes to the clusterIP.
*
* - `"LoadBalancer"`: Builds on NodePort and creates an external load
* balancer (if supported in the current cloud) which routes to the
* clusterIP.
*
* For more information, see the
* {@link https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types |
* Kubernetes documentation}.
* @defaultValue `"ClusterIP"`
*/
type?: string;
}
/** @public */
export interface ServicePort {
/**
* The name of this port within the service.
*
* @remarks
* This must be a DNS_LABEL.
* All ports within a ServiceSpec must have unique names.This maps to the
* Name' field in EndpointPort objects. Optional if only one ServicePort is
* defined on this service.
*/
name?: string;
/**
* The port on each node on which this service is exposed when
* type=NodePort or LoadBalancer.
*
* @remarks
* Usually assigned by the system. If
* specified, it will be allocated to the service if unused or else creation
* of the service will fail.
*
* For more information, see the
* {@link https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport |
* Kubernetes documentation}.
* @defaultValue Automatically allocates a port if the ServiceType of this
* Service requires one.
*/
nodePort?: number;
/** The port that will be exposed by this service. */
port?: number;
/** The IP protocol for this port.Supports "TCP" and "UDP".Default is TCP. */
protocol?: string;
/**
* Number or name of the port to access on the pods targeted by the
* service.
*
* @remarks
* Number must be in the range 1 to 65535. Name must be an
* IANA_SVC_NAME. If this is a string, it will be looked up as a named port
* in the target Pod's container ports. If this is not specified, the value
* of the 'port' field is used (an identity map). This field is ignored for
* services with clusterIP = None, and should be omitted or set equal to the
* 'port' field.
*
* For more information, see the
* {@link https://kubernetes.io/docs/concepts/services-networking/service/#defining-a-service |
* Kubernetes documentation}.
*/
targetPort?: number | string;
}
function toServiceType(scope: NetworkServiceScope | undefined) {
switch (scope) {
case "cluster-internal":
case undefined:
return "ClusterIP";
case "cluster-public":
return "NodePort";
case "external":
return "LoadBalancer";
default:
throw new Error(`Service: NetworkService scope '${scope}' not mapped to a Kubernetes service type`);
}
}
/**
* Convert {@link NetworkService} props to {@link k8s.Service} props
* @param abstractProps - props to convert
* @returns Kubernetes spec corresponding to `abstractProps`
*
* @internal
*/
export function k8sServiceProps(abstractProps: NetworkServiceProps & BuiltinProps): Omit<ServiceProps, keyof ResourceBase> {
if (typeof abstractProps.port !== "number") throw new Error(`Service: Port string not yet implemented`);
if (abstractProps.ip != null) throw new Error(`Service: IP not yet implemented`);
if (abstractProps.name != null) throw new Error(`Service: name not yet implemented`);
const port: ServicePort = {
port: abstractProps.port,
targetPort: targetPort(abstractProps),
};
if (abstractProps.protocol != null) port.protocol = abstractProps.protocol;
const ret: Omit<ServiceProps, keyof ResourceBase> & Partial<BuiltinProps> = {
key: abstractProps.key,
ports: [port],
selector: abstractProps.endpoint,
type: toServiceType(abstractProps.scope),
};
return ret;
}
interface EndpointSelector {
[key: string]: string;
}
const defaultProps = {
metadata: {},
sessionAffinity: "None",
type: "ClusterIP",
};
function findInArray<T extends { [key: string]: any }>(arr: T[] | undefined | null, keyProp: string, key: any) {
if (!arr) return undefined;
for (const item of arr) {
if (item[keyProp] === key) return item;
}
return undefined;
}
interface NoExternalName {
noName: true;
}
const noExternalName: NoExternalName = { noName: true };
function isNoExternalName(x: any): x is NoExternalName {
return x === noExternalName;
}
async function getExternalName(props: SFCBuildProps<ServiceProps, typeof defaultProps>):
Promise<string | NoExternalName | Waiting> {
const log = console; //FIXME(manishv) Use proper logger here
const resourceHand = props.handle;
const resourceElem = resourceHand.target;
if (!resourceElem) return noExternalName; //This should not be able to happen
if (!isMountedElement(resourceElem)) return noExternalName; //Should not be possible
//Don't fetch status if we don't need it
if (!(props.type === "LoadBalancer" || props.type === "ExternalName")) return noExternalName;
let statusTop: any;
try {
statusTop = await resourceElem.status<any>();
} catch (e) {
//Status not available yet
if (e.message.startsWith("Resource not found")) return waiting("Waiting for resource to be created");
throw e;
}
if (!statusTop) return waiting("Waiting for status from k8s");
const spec = statusTop.spec;
const status = statusTop.status;
if (!status) return waiting("Waiting for status from k8s");
if (spec.type === "LoadBalancer") {
if (status.loadBalancer === undefined) return waiting("Waiting for loadBlancer status from k8s");
const ingresses: string | string[] | undefined | null | unknown = status.loadBalancer.ingress;
if (ingresses == null) return waiting("Waiting for Ingress IP");
if (typeof ingresses === "string") return ingresses;
if (Array.isArray(ingresses)) {
if (ingresses.length === 0) return noExternalName;
if (ingresses.length !== 1) log.warn(`Multiple k8s LoadBalancer ingresses returned, using only one: ${ingresses}`);
for (const ingress of ingresses as { hostname: string | null; ip: string | null }[]) {
if (ingress.hostname) return ingress.hostname;
if (ingress.ip) return ingress.ip;
}
}
return noExternalName;
}
if (spec.type === "ExternalName" && spec.externalName) return spec.externalName as string;
return noExternalName;
}
/**
* Native Kubernetes Service resource
*
* @remarks
*
* Implements the {@link NetworkServiceInstance} interface.
*
* @public
*/
export function Service(propsIn: SFCDeclProps<ServiceProps, typeof defaultProps>) {
const props = propsIn as SFCBuildProps<ServiceProps, typeof defaultProps>;
const helpers = useBuildHelpers();
const deployID = helpers.deployID;
if (props.ports && (props.ports.length > 1)) {
for (const port of props.ports) {
if (port.name === undefined) throw new Error("Service with multiple ports but no name on port");
}
}
const [externalName, setExternalName] = useState<string | NoExternalName | undefined>(undefined);
const [epSelector, updateSelector] = useState<EndpointSelector | undefined>(undefined);
const manifest = makeSvcManifest(props, { endpointSelector: epSelector });
useImperativeMethods<NetworkServiceInstance>(() => ({
hostname: (scope?: NetworkScope) => {
const resourceHand = props.handle;
const resourceElem = resourceHand.target;
if (!resourceElem) return undefined;
if (scope && scope === NetworkScope.external) {
if (isNoExternalName(externalName)) throw new Error("External name request for element, but no external name available");
if (typeof externalName === "string") return externalName;
return undefined;
} else {
const resourceName = resourceElementToName(resourceElem, deployID);
const namespace = computeNamespaceFromMetadata(manifest.metadata);
return `${resourceName}.${namespace}.svc.cluster.local.`;
}
},
port: (name?: string) => {
if (name) {
const item = findInArray(props.ports, "name", name);
if (!item) return undefined;
return item.port;
} else if (props.ports) {
//Should it be an error to ask for ports without a name when there is more than one?
return props.ports[0].port;
} else {
return undefined;
}
}
}));
useDeployedWhen(async () => {
const statusName = await getExternalName(props);
if ((typeof statusName === "string") || isNoExternalName(statusName)) {
setExternalName(statusName);
return true;
}
return statusName;
});
updateSelector(async () => {
const { selector: ep } = props;
if (!isHandle(ep)) return removeUndef(ep || {});
if (!ep.target) return {};
if (!isMountedElement(ep.target)) return {};
if (ep.target.componentType !== Resource) {
throw new Error(`Cannot handle k8s.Service endpoint of type ${ep.target.componentType.name}`);
}
const epProps: ResourceProps = ep.target.props as AnyProps as ResourceProps;
if (epProps.kind === "Pod") {
return removeUndef({
[labelKey("name")]: resourceElementToName(ep.target, deployID)
});
}
if (hasSelector(epProps)) {
const sel = epProps.spec.selector;
if (isLabelSelector(sel)) {
if (sel.matchExpressions !== undefined) {
throw new Error(`Cannot have k8s.Service endpoint of kind ${epProps.kind} with a matchExpressions selector`);
}
return sel.matchLabels;
} else {
return sel;
}
}
throw new Error(`Cannot have k8s.Service endpoint of kind ${epProps.kind}, is not Pod and does not have a selector prop.`);
});
return (
<Resource
key={props.key}
config={props.config}
kind={manifest.kind}
metadata={manifest.metadata}
spec={manifest.spec}
/>);
}
// TODO: The "as any" is a workaround for an api-extractor bug. See issue #185.
(Service as any).defaultProps = defaultProps;
(Service as any).status = async (_props: ServiceProps & BuiltinProps,
_observe: ObserveForStatus,
buildData: BuildData) => {
const succ = buildData.successor;
if (!succ) return undefined;
return succ.status();
};
function hasSelector(props: ResourceProps): props is ResourceProps & { spec: { selector: LabelSelector | EndpointSelector }} {
return (props as any).spec.selector != undefined;
}
interface MakeManifestOptions {
endpointSelector?: EndpointSelector;
}
function makeSvcManifest(props: ServiceProps & Partial<BuiltinProps>, options: MakeManifestOptions): ResourceService {
const { config, key, handle, metadata, ...spec } = props;
// Explicit default for ports.protocol
if (spec.ports) {
for (const p of spec.ports) {
if (p.protocol === undefined) p.protocol = "TCP";
}
}
if (spec.type === "LoadBalancer") {
if (spec.sessionAffinity === undefined) spec.sessionAffinity = "None";
if (spec.externalTrafficPolicy === undefined) spec.externalTrafficPolicy = "Cluster";
}
return {
kind: "Service",
metadata: metadata ?? {},
spec: { ...spec, selector: isHandle(spec.selector) ? options.endpointSelector : spec.selector },
config,
};
}
function deployedWhen(statusObj: unknown) {
const status: any = statusObj;
// There doesn't appear to be much actual status for a
// service like there is for a Pod.
if (status == null || !isObject(status.status)) {
return waiting(`Kubernetes cluster returned invalid status for Service`);
}
return true;
}
/** @internal */
export const serviceResourceInfo = {
kind: "Service",
deployedWhen,
statusQuery: async (props: ResourcePropsWithConfig, observe: ObserveForStatus, buildData: BuildData) => {
const obs: any = await observe(K8sObserver, gql`
query ($name: String!, $kubeconfig: JSON!, $namespace: String!) {
withKubeconfig(kubeconfig: $kubeconfig) {
readCoreV1NamespacedService(name: $name, namespace: $namespace) @all(depth: 100)
}
}`,
{
name: resourceIdToName(props.key, buildData.id, buildData.deployID),
kubeconfig: props.config.kubeconfig,
namespace: computeNamespaceFromMetadata(props.metadata)
}
);
return obs.withKubeconfig.readCoreV1NamespacedService;
},
};
registerResourceKind(serviceResourceInfo); | the_stack |
import _ from 'lodash';
import Vuex from 'vuex';
import { createLocalVue } from '@vue/test-utils';
import { FeedResponse } from '~/server/routers/api/feed';
import { parseWikiRevId } from '~/shared/utility-shared';
import { InteractionProps } from '~/shared/models/interaction-item.model';
import { MwActionApiClient2 } from '~/shared/mwapi2';
describe('store/feed2', () => {
const localVue = createLocalVue();
localVue.use(Vuex);
let NuxtStore;
let store;
let mock;
beforeAll(async () => {
// note the store will mutate across tests
const storePath = `${process.env.buildDir}/store.js`;
NuxtStore = await import(storePath);
});
beforeEach(async () => {
store = await NuxtStore.createStore();
const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');
mock = new MockAdapter(axios);
store.$axios = axios;
// axios.interceptors.request.use(request => {
// console.log('Starting Request', JSON.stringify(request, null, 2));
// return request;
// });
store.$mock = mock;
});
function mockFeed(feed, wikiRevIds) {
const mockedRes = {
useMixer: false,
feed,
wikiRevIds,
} as FeedResponse;
store.$mock
.onGet('/api/feed/lastbad', {
params: {
wiki: 'enwiki',
limit: 10,
},
})
.reply(function(_) {
return [200, mockedRes];
});
}
function mockRevision(wikiRevId, { title, pageId, comment, user, timestampStr }) {
const [wiki, revid] = parseWikiRevId(wikiRevId);
const mockedRes = {
wiki,
revid,
title,
pageId,
comment,
user,
timestamp:timestampStr
};
store.$mock
.onGet(`/api/revision/${wikiRevId}`)
.reply(function(_) {
return [200, mockedRes];
});
}
function mockInteractions(wikiRevId, items:InteractionProps[]) {
const mockedRes = items;
store.$mock
.onGet(`/api/interaction/beta/${wikiRevId}`)
.reply(function(_) {
return [200, mockedRes];
});
}
function mockFetchDiff(wikiRevId, diffHtml) {
const mockedRes = { compare: { '*' : diffHtml } };
const [wiki, revId] = parseWikiRevId(wikiRevId);
store.$mock
.onGet(MwActionApiClient2.endPoint(wiki), {
params: {
'action': 'compare',
'format': 'json',
'origin': '*',
'fromrev': revId,
'torelative': 'prev'
} })
.reply(function (_) {
// const c = new MwActionApiClient2();
// const ret = await c.fetchDiff(wiki, revId);
return [200, mockedRes];
});
}
describe('after setup', () => {
test('has current default value.', () => {
const feed = store.state.feed2.feed;
expect(feed).toEqual('lastbad');
const reviewQueue = store.state.feed2.reviewQueue;
expect(_.isArray(reviewQueue)).toBe(true);
expect((reviewQueue as []).length).toBe(0);
});
test('can setFeed', () => {
expect(store.state.feed2.feed).toEqual('lastbad');
store.commit('feed2/setFeed', 'recent');
expect(store.state.feed2.feed).toEqual('recent');
});
});
describe('reviewQueue', () => {
test('can add and clear reviewQueue', () => {
expect(store.state.feed2.reviewQueue.length).toBe(0);
store.commit('feed2/addToReviewQueue', [
'enwiki:9990001',
'enwiki:9990002',
'enwiki:9990003'
]);
expect(store.getters['feed2/getHeadItem']()).toBe(undefined);
expect(store.state.feed2.reviewQueue.length).toBe(3);
store.commit('feed2/clearReviewQueue');
expect(store.state.feed2.reviewQueue.length).toBe(0);
});
test('should skip revisions that is already in the queue.', () => {
// The test beging with an empty queue.
expect(store.state.feed2.reviewQueue.length).toBe(0);
store.commit('feed2/addToReviewQueue', [
'enwiki:9990001',
'enwiki:9990002',
'enwiki:9990003'
]);
// After adding 3 revisions, the reviewQueue becomes an array of 3.
expect(store.state.feed2.reviewQueue.length).toBe(3);
expect(store.state.feed2.reviewQueue).toEqual([
'enwiki:9990001',
'enwiki:9990002',
'enwiki:9990003'
]);
store.commit('feed2/addToReviewQueue', [
'enwiki:9990002',
]);
// The review queue maintains the same length after adding a repeated revision
expect(store.state.feed2.reviewQueue.length).toBe(3);
expect(store.state.feed2.reviewQueue).toEqual([
'enwiki:9990001',
'enwiki:9990002',
'enwiki:9990003'
]);
store.commit('feed2/addToReviewQueue', [
'enwiki:9990004',
]);
expect(store.state.feed2.reviewQueue.length).toBe(4);
expect(store.state.feed2.reviewQueue).toEqual([
'enwiki:9990001',
'enwiki:9990002',
'enwiki:9990003',
'enwiki:9990004',
]);
});
test('should handle enqueue and dequeue', async () => {
store.commit('feed2/addToReviewQueue', ['enwiki:9990001']);
store.commit('feed2/addToReviewQueue', ['enwiki:9990002']);
const wikiRevId1 = await store.dispatch('feed2/deReviewQueue');
expect(wikiRevId1).toBe('enwiki:9990001');
const wikiRevId2 = await store.dispatch('feed2/deReviewQueue');
expect(wikiRevId2).toBe('enwiki:9990002');
});
});
describe('MOCK loadMoreWikiRevIds', () => {
test('MOCK can load more wikiRevIds', async () => {
mockFeed('lastbad', [
'enwiki:9990001',
'enwiki:9990002',
'enwiki:9990003',
'enwiki:9990004',
'enwiki:9990005',
'enwiki:9990006',
'enwiki:9990007',
'enwiki:9990008',
'enwiki:9990009',
'enwiki:9990010',
]);
mockRevision('enwiki:9990001', {
title: 'John Smith',
pageId: 10001,
comment: 'Some good edits',
user: 'GoodGuy',
timestampStr: '2020-11-10T00:18:07'
});
expect(store.state.feed2.reviewQueue.length).toBe(0);
await new Promise((resolve, reject) => {
const mutations = [];
const unsubscribe = store.subscribe((mutation, state) => {
unsubscribe();
resolve(mutations);
});
store.dispatch('feed2/loadMoreWikiRevIds');
});
expect(store.state.feed2.reviewQueue.length).toBe(10);
expect(store.state.feed2.reviewQueue[0]).toBe('enwiki:9990001');
expect(store.state.feed2.reviewQueue[9]).toBe('enwiki:9990010');
});
test('MOCK should kickoff prefetching for reviewQueueHead', async (done) => {
mockFeed('lastbad', [
'enwiki:9990001',
'enwiki:9990002',
]);
mockRevision('enwiki:9990001', {
title: 'John Smith',
pageId: 10001,
comment: 'Some good edits',
user: 'GoodGuy',
timestampStr: '2020-11-10T00:18:07'
});
mockRevision('enwiki:9990002', {
title: 'Second John Smith',
pageId: 10002,
comment: 'Second Some good edits',
user: 'GoodGuy 2',
timestampStr: '2020-11-20T00:18:07'
});
const commits = [];
store.subscribe((mutation, state) => {
commits.push(mutation);
});
expect(store.state.feed2.reviewQueue.length).toBe(0);
await store.dispatch('feed2/loadMoreWikiRevIds');
expect(store.state.feed2.reviewQueue.length).toBe(2);
expect(store.state.feed2.reviewQueue).toStrictEqual([
'enwiki:9990001',
'enwiki:9990002'
]);
setTimeout(function() {
expect(commits.length).toBe(3);
expect(commits[0].type).toBe('feed2/addToReviewQueue');
expect(commits[0].payload).toStrictEqual([ 'enwiki:9990001', 'enwiki:9990002' ]);
expect(commits[1].type).toBe('feed2/addToCache');
expect(commits[1].payload).toStrictEqual({
key: 'enwiki:9990001',
value:{
title: 'John Smith',
wiki: 'enwiki',
revId: 9990001,
summary: 'Some good edits',
author: 'GoodGuy',
timestamp: NaN
}});
done();
}, 1000);
});
it('MOCK should handle failed loadMoreWikiRevIds', async () => {
store.$mock
.onAny()
.reply(function(_) {
return [404];
});
expect(store.state.feed2.reviewQueue.length).toBe(0);
await store.dispatch('feed2/loadMoreWikiRevIds');
expect(store.state.feed2.reviewQueue.length).toBe(0);
});
it('MOCK should handle loadMoreWikiRevIds when there is empty revIds', async () => {
mockFeed('lastbad', []);
expect(store.state.feed2.reviewQueue.length).toBe(0);
await store.dispatch('feed2/loadMoreWikiRevIds');
expect(store.state.feed2.reviewQueue.length).toBe(0);
});
});
describe('cache', () => {
test('should handle caching', async (done) => {
const item = {
wiki: 'enwiki',
revId: 9990001,
title: 'John Smith',
pageId: 10001,
summary: 'Some good edits',
author: 'GoodGuy',
timestamp: new Date('2020-11-10T00:18:07').getTime() / 1000
};
// Verify add to cache
const [mutation, state] = await new Promise((resolve, reject) => {
const unsubscribe = store.subscribe((mutation, state) => {
unsubscribe();
resolve([mutation, state]);
});
store.commit('feed2/addToCache', { key: 'enwiki:9990001', value: item });
});
expect(mutation.type).toBe('feed2/addToCache');
expect(mutation.payload.key).toBe('enwiki:9990001');
expect(mutation.payload.value).toStrictEqual(item);
expect(state.feed2.cache['enwiki:9990001']).toStrictEqual(item);
// Verify cached content
const wikiRevId = 'enwiki:9990001';
const cachedItem = store.getters['feed2/getFromCache'](wikiRevId);
expect(wikiRevId).toBe('enwiki:9990001');
expect(cachedItem.pageId).toBe(10001);
expect(cachedItem.summary).toBe('Some good edits');
expect(state.feed2.cache['enwiki:9990001']).toEqual(cachedItem);
store.commit('feed2/removeFromCache', wikiRevId);
expect(state.feed2.cache['enwiki:9990001']).toStrictEqual(undefined);
expect(state.feed2.cache).toStrictEqual({});
// re-add to Cache
store.commit('feed2/addToCache', { key: 'enwiki:9990001', value: item });
// Verify clearCache
const [mutation2, state2] = await new Promise((resolve, reject) => {
const unsubscribe = store.subscribe((mutation, state) => {
unsubscribe();
resolve([mutation, state]);
});
store.commit('feed2/clearCache');
});
expect(mutation2.type).toBe('feed2/clearCache');
expect(mutation2.payload).toBe(undefined);
expect(state2.feed2.cache).toStrictEqual({});
const nullItem = store.getters['feed2/getFromCache'](wikiRevId);
expect(nullItem).toBe(undefined);
done();
});
});
describe('Upon fetch revision action', () => {
test('should dispatch action to fetching diff and interaction and commit them.', done => {
const wikiRevId = 'enwiki:9990001';
const actions = [];
const mutations = [];
store.subscribeAction((action, state) => actions.push(action));
store.subscribe((mutation, state) => mutations.push(mutation));
mockRevision('enwiki:9990001', {
title: 'John Smith',
pageId: 10001,
comment: 'Some good edits',
user: 'GoodGuy',
timestampStr: '2020-11-10T00:18:07'
});
mockInteractions(wikiRevId, [{
feed: 'lastbad',
wikiRevId,
judgement: 'ShouldRevert',
} as InteractionProps]);
mockFetchDiff(wikiRevId, '<tr></tr>');
store.dispatch('feed2/fetchRevision', wikiRevId);
setTimeout(() => {
expect(mutations.length).toBe(2);
expect(mutations[0].type).toBe('feed2/cacheInteractions');
expect(mutations[1].type).toBe('feed2/cacheDiffHtml');
expect(actions.length).toBe(3);
expect(actions[0].type).toBe('feed2/fetchRevision');
expect(actions[1].type).toBe('feed2/fetchDiff');
expect(actions[2].type).toBe('feed2/fetchInteractions');
done();
}, 500);
});
test('should handle failure of fetchDiff.', (done) => {
const wikiRevId = 'enwiki:9990001';
const actions = [];
const mutations = [];
store.subscribeAction((action, state) => actions.push(action));
store.subscribe((mutation, state) => mutations.push(mutation));
store.dispatch('feed2/fetchRevision', wikiRevId);
mockRevision('enwiki:9990001', {
title: 'John Smith',
pageId: 10001,
comment: 'Some good edits',
user: 'GoodGuy',
timestampStr: '2020-11-10T00:18:07'
});
mockInteractions(wikiRevId, [{
feed: 'lastbad',
wikiRevId,
judgement: 'ShouldRevert',
} as InteractionProps]);
// mockFetchDiff(wikiRevId, '<tr></tr>'); // we are obmitting the mockFetchDiff so it generate a 404
setTimeout(() => {
expect(mutations.length).toBe(1);
expect(mutations[0].type).toBe('feed2/cacheInteractions');
expect(actions.length).toBe(3);
expect(actions[0].type).toBe('feed2/fetchRevision');
expect(actions[1].type).toBe('feed2/fetchDiff');
expect(actions[2].type).toBe('feed2/fetchInteractions');
done();
}, 1000);
});
it('should handle failure of fetchInteraction', (done) => {
const wikiRevId = 'enwiki:9990001';
const actions = [];
const mutations = [];
store.subscribeAction((action, state) => actions.push(action));
store.subscribe((mutation, state) => mutations.push(mutation));
store.dispatch('feed2/fetchRevision', wikiRevId);
mockRevision('enwiki:9990001', {
title: 'John Smith',
pageId: 10001,
comment: 'Some good edits',
user: 'GoodGuy',
timestampStr: '2020-11-10T00:18:07'
});
// We comment out the following
// to EXPLICITLY obmit the mockFetchInteraction
// so it generate a 404
// mockInteractions(wikiRevId, [{
// feed: 'lastbad',
// wikiRevId,
// judgement: 'ShouldRevert',
// } as InteractionProps]);
mockFetchDiff(wikiRevId, '<tr></tr>');
setTimeout(() => {
expect(mutations.length).toBe(1);
expect(mutations[0].type).toBe('feed2/cacheDiffHtml');
expect(actions.length).toBe(3);
expect(actions[0].type).toBe('feed2/fetchRevision');
expect(actions[1].type).toBe('feed2/fetchDiff');
expect(actions[2].type).toBe('feed2/fetchInteractions');
done();
}, 1000);
});
});
describe('skipMap', () => {
it('should handle add, remove and clear skipMap', () => {
const wikiRevId1 = 'enwiki:9901';
const wikiRevId2 = 'enwiki:9902';
const wikiRevId3 = 'enwiki:9903';
expect(store.state.feed2.skipMap).toStrictEqual({});
store.commit('feed2/addToSkipMap', wikiRevId1);
store.commit('feed2/addToSkipMap', wikiRevId2);
store.commit('feed2/addToSkipMap', wikiRevId3);
expect(store.state.feed2.skipMap[wikiRevId1]).toEqual(true);
expect(store.state.feed2.skipMap[wikiRevId2]).toEqual(true);
expect(store.state.feed2.skipMap[wikiRevId3]).toEqual(true);
store.commit('feed2/removeFromSkipMap', wikiRevId1);
expect(store.state.feed2.skipMap[wikiRevId1]).toEqual(undefined);
expect(store.state.feed2.skipMap[wikiRevId2]).toEqual(true);
expect(store.state.feed2.skipMap[wikiRevId3]).toEqual(true);
store.commit('feed2/clearSkipMap');
expect(store.state.feed2.skipMap[wikiRevId1]).toEqual(undefined);
expect(store.state.feed2.skipMap[wikiRevId2]).toEqual(undefined);
expect(store.state.feed2.skipMap[wikiRevId3]).toEqual(undefined);
});
});
}); | the_stack |
import {EventEmitter} from 'events';
import {URL} from 'url';
import {AddressInfo} from 'net';
import * as http from 'http';
import * as path from 'path';
import {Readable} from 'stream';
import {request, GaxiosResponse} from 'gaxios';
import {Queue} from './queue';
import {getLinks} from './links';
import {startWebServer} from './server';
import {CheckOptions, InternalCheckOptions, processOptions} from './options';
export {CheckOptions};
export enum LinkState {
OK = 'OK',
BROKEN = 'BROKEN',
SKIPPED = 'SKIPPED',
}
export interface RetryInfo {
url: string;
secondsUntilRetry: number;
status: number;
}
export interface LinkResult {
url: string;
status?: number;
state: LinkState;
parent?: string;
failureDetails?: {}[];
}
export interface CrawlResult {
passed: boolean;
links: LinkResult[];
}
interface CrawlOptions {
url: URL;
parent?: string;
crawl: boolean;
results: LinkResult[];
cache: Set<string>;
delayCache: Map<string, number>;
checkOptions: CheckOptions;
queue: Queue;
rootPath: string;
retry: boolean;
}
// Spoof a normal looking User-Agent to keep the servers happy
export const headers = {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
};
export declare interface LinkChecker {
on(event: 'link', listener: (result: LinkResult) => void): this;
on(event: 'pagestart', listener: (link: string) => void): this;
on(event: 'retry', listener: (details: RetryInfo) => void): this;
}
/**
* Instance class used to perform a crawl job.
*/
export class LinkChecker extends EventEmitter {
/**
* Crawl a given url or path, and return a list of visited links along with
* status codes.
* @param options Options to use while checking for 404s
*/
async check(opts: CheckOptions) {
const options = await processOptions(opts);
if (!Array.isArray(options.path)) {
options.path = [options.path];
}
options.linksToSkip = options.linksToSkip || [];
let server: http.Server | undefined;
const hasHttpPaths = options.path.find(x => x.startsWith('http'));
if (!hasHttpPaths) {
let port = options.port;
server = await startWebServer({
root: options.serverRoot!,
port,
markdown: options.markdown,
directoryListing: options.directoryListing,
});
if (port === undefined) {
const addr = server.address() as AddressInfo;
port = addr.port;
}
for (let i = 0; i < options.path.length; i++) {
if (options.path[i].startsWith('/')) {
options.path[i] = options.path[i].slice(1);
}
options.path[i] = `http://localhost:${port}/${options.path[i]}`;
}
options.staticHttpServerHost = `http://localhost:${port}/`;
}
if (process.env.LINKINATOR_DEBUG) {
console.log(options);
}
const queue = new Queue({
concurrency: options.concurrency || 100,
});
const results = new Array<LinkResult>();
const initCache: Set<string> = new Set();
const delayCache: Map<string, number> = new Map();
for (const path of options.path) {
const url = new URL(path);
initCache.add(url.href);
queue.add(async () => {
await this.crawl({
url,
crawl: true,
checkOptions: options,
results,
cache: initCache,
delayCache,
queue,
rootPath: path,
retry: !!opts.retry,
});
});
}
await queue.onIdle();
const result = {
links: results,
passed: results.filter(x => x.state === LinkState.BROKEN).length === 0,
};
if (server) {
server.destroy();
}
return result;
}
/**
* Crawl a given url with the provided options.
* @pram opts List of options used to do the crawl
* @private
* @returns A list of crawl results consisting of urls and status codes
*/
async crawl(opts: CrawlOptions): Promise<void> {
// apply any regex url replacements
if (opts.checkOptions.urlRewriteExpressions) {
for (const exp of opts.checkOptions.urlRewriteExpressions) {
const newUrl = opts.url.href.replace(exp.pattern, exp.replacement);
if (opts.url.href !== newUrl) {
opts.url.href = newUrl;
}
}
}
// explicitly skip non-http[s] links before making the request
const proto = opts.url.protocol;
if (proto !== 'http:' && proto !== 'https:') {
const r: LinkResult = {
url: mapUrl(opts.url.href, opts.checkOptions),
status: 0,
state: LinkState.SKIPPED,
parent: mapUrl(opts.parent, opts.checkOptions),
};
opts.results.push(r);
this.emit('link', r);
return;
}
// Check for a user-configured function to filter out links
if (
typeof opts.checkOptions.linksToSkip === 'function' &&
(await opts.checkOptions.linksToSkip(opts.url.href))
) {
const result: LinkResult = {
url: mapUrl(opts.url.href, opts.checkOptions),
state: LinkState.SKIPPED,
parent: opts.parent,
};
opts.results.push(result);
this.emit('link', result);
return;
}
// Check for a user-configured array of link regular expressions that should be skipped
if (Array.isArray(opts.checkOptions.linksToSkip)) {
const skips = opts.checkOptions.linksToSkip
.map(linkToSkip => {
return new RegExp(linkToSkip).test(opts.url.href);
})
.filter(match => !!match);
if (skips.length > 0) {
const result: LinkResult = {
url: mapUrl(opts.url.href, opts.checkOptions),
state: LinkState.SKIPPED,
parent: mapUrl(opts.parent, opts.checkOptions),
};
opts.results.push(result);
this.emit('link', result);
return;
}
}
// Check if this host has been marked for delay due to 429
if (opts.delayCache.has(opts.url.host)) {
const timeout = opts.delayCache.get(opts.url.host)!;
if (timeout > Date.now()) {
opts.queue.add(
async () => {
await this.crawl(opts);
},
{
delay: timeout - Date.now(),
}
);
return;
}
}
// Perform a HEAD or GET request based on the need to crawl
let status = 0;
let state = LinkState.BROKEN;
let shouldRecurse = false;
let res: GaxiosResponse<Readable> | undefined = undefined;
const failures: {}[] = [];
try {
res = await request<Readable>({
method: opts.crawl ? 'GET' : 'HEAD',
url: opts.url.href,
headers,
responseType: 'stream',
validateStatus: () => true,
timeout: opts.checkOptions.timeout,
});
if (this.shouldRetryAfter(res, opts)) {
return;
}
// If we got an HTTP 405, the server may not like HEAD. GET instead!
if (res.status === 405) {
res = await request<Readable>({
method: 'GET',
url: opts.url.href,
headers,
responseType: 'stream',
validateStatus: () => true,
timeout: opts.checkOptions.timeout,
});
if (this.shouldRetryAfter(res, opts)) {
return;
}
}
} catch (err) {
// request failure: invalid domain name, etc.
// this also occasionally catches too many redirects, but is still valid (e.g. https://www.ebay.com)
// for this reason, we also try doing a GET below to see if the link is valid
failures.push(err as Error);
}
try {
//some sites don't respond to a stream response type correctly, especially with a HEAD. Try a GET with a text response type
if (
(res === undefined || res.status < 200 || res.status >= 300) &&
!opts.crawl
) {
res = await request<Readable>({
method: 'GET',
url: opts.url.href,
responseType: 'stream',
validateStatus: () => true,
headers,
timeout: opts.checkOptions.timeout,
});
if (this.shouldRetryAfter(res, opts)) {
return;
}
}
} catch (ex) {
failures.push(ex as Error);
// catch the next failure
}
if (res !== undefined) {
status = res.status;
shouldRecurse = isHtml(res);
}
// Assume any 2xx status is 👌
if (status >= 200 && status < 300) {
state = LinkState.OK;
} else {
failures.push(res!);
}
const result: LinkResult = {
url: mapUrl(opts.url.href, opts.checkOptions),
status,
state,
parent: mapUrl(opts.parent, opts.checkOptions),
failureDetails: failures,
};
opts.results.push(result);
this.emit('link', result);
// If we need to go deeper, scan the next level of depth for links and crawl
if (opts.crawl && shouldRecurse) {
this.emit('pagestart', opts.url);
const urlResults = res?.data
? await getLinks(res.data, opts.url.href)
: [];
for (const result of urlResults) {
// if there was some sort of problem parsing the link while
// creating a new URL obj, treat it as a broken link.
if (!result.url) {
const r = {
url: mapUrl(result.link, opts.checkOptions),
status: 0,
state: LinkState.BROKEN,
parent: mapUrl(opts.url.href, opts.checkOptions),
};
opts.results.push(r);
this.emit('link', r);
continue;
}
let crawl = (opts.checkOptions.recurse! &&
result.url?.href.startsWith(opts.rootPath)) as boolean;
// only crawl links that start with the same host
if (crawl) {
try {
const pathUrl = new URL(opts.rootPath);
crawl = result.url!.host === pathUrl.host;
} catch {
// ignore errors
}
}
// Ensure the url hasn't already been touched, largely to avoid a
// very large queue length and runaway memory consumption
if (!opts.cache.has(result.url.href)) {
opts.cache.add(result.url.href);
opts.queue.add(async () => {
await this.crawl({
url: result.url!,
crawl,
cache: opts.cache,
delayCache: opts.delayCache,
results: opts.results,
checkOptions: opts.checkOptions,
queue: opts.queue,
parent: opts.url.href,
rootPath: opts.rootPath,
retry: opts.retry,
});
});
}
}
}
}
/**
* Check the incoming response for a `retry-after` header. If present,
* and if the status was an HTTP 429, calculate the date at which this
* request should be retried. Ensure the delayCache knows that we're
* going to wait on requests for this entire host.
* @param res GaxiosResponse returned from the request
* @param opts CrawlOptions used during this request
*/
shouldRetryAfter(res: GaxiosResponse, opts: CrawlOptions): boolean {
if (!opts.retry) {
return false;
}
const retryAfterRaw = res.headers['retry-after'];
if (res.status !== 429 || !retryAfterRaw) {
return false;
}
// The `retry-after` header can come in either <seconds> or
// A specific date to go check.
let retryAfter = Number(retryAfterRaw) * 1000 + Date.now();
if (isNaN(retryAfter)) {
retryAfter = Date.parse(retryAfterRaw);
if (isNaN(retryAfter)) {
return false;
}
}
// check to see if there is already a request to wait for this host
if (opts.delayCache.has(opts.url.host)) {
// use whichever time is higher in the cache
const currentTimeout = opts.delayCache.get(opts.url.host)!;
if (retryAfter > currentTimeout) {
opts.delayCache.set(opts.url.host, retryAfter);
}
} else {
opts.delayCache.set(opts.url.host, retryAfter);
}
opts.queue.add(
async () => {
await this.crawl(opts);
},
{
delay: retryAfter - Date.now(),
}
);
const retryDetails: RetryInfo = {
url: opts.url.href,
status: res.status,
secondsUntilRetry: Math.round((retryAfter - Date.now()) / 1000),
};
this.emit('retry', retryDetails);
return true;
}
}
/**
* Convenience method to perform a scan.
* @param options CheckOptions to be passed on
*/
export async function check(options: CheckOptions) {
const checker = new LinkChecker();
const results = await checker.check(options);
return results;
}
/**
* Checks to see if a given source is HTML.
* @param {object} response Page response.
* @returns {boolean}
*/
function isHtml(response: GaxiosResponse): boolean {
const contentType = response.headers['content-type'] || '';
return (
!!contentType.match(/text\/html/g) ||
!!contentType.match(/application\/xhtml\+xml/g)
);
}
/**
* When running a local static web server for the user, translate paths from
* the Url generated back to something closer to a local filesystem path.
* @example
* http://localhost:0000/test/route/README.md => test/route/README.md
* @param url The url that was checked
* @param options Original CheckOptions passed into the client
*/
function mapUrl(url?: string, options?: InternalCheckOptions): string {
if (!url) {
return url!;
}
let newUrl = url;
// trim the starting http://localhost:0000 if we stood up a local static server
if (
options?.staticHttpServerHost?.length &&
url?.startsWith(options.staticHttpServerHost)
) {
newUrl = url.slice(options.staticHttpServerHost.length);
// add the full filesystem path back if we trimmed it
if (options?.syntheticServerRoot?.length) {
newUrl = path.join(options.syntheticServerRoot, newUrl);
}
if (newUrl === '') {
newUrl = `.${path.sep}`;
}
}
return newUrl!;
} | the_stack |
"use strict";
import $ = require('jquery');
import utils = require('base/js/utils');
import dialog = require('base/js/dialog');
import gapiutils = require('./gapiutils');
import driveutils = require('./driveutils');
import notebook_model = require('./notebook_model');
import iface = require('content-interface');
import Notebook = notebook_model.Notebook;
import Path = iface.Path
import IContents = iface.IContents
import CheckpointId = iface.CheckpointId
declare var gapi;
/**
* Takes a contents model and converts it into metadata and bytes for
* Google Drive upload.
*/
var contents_model_to_metadata_and_bytes = function(model):[any, string] {
var content = model.content;
var mimetype = model.mimetype;
var format = model.format;
if (model['type'] === 'notebook') {
// This seem to be wrong content is Notebook here. string below
content = notebook_model.notebook_json_contents_from_notebook(content);
format = 'json';
mimetype = driveutils.NOTEBOOK_MIMETYPE;
} else if (model['type'] === 'file') {
format = format || 'text/plain';
} else if (model['type'] === 'directory') {
format = 'json'
mimetype = driveutils.FOLDER_MIME_TYPE;
} else {
throw ("Unrecognized type " + model['type']);
}
// Set mime type according to format if it's not set
if (format == 'json') {
// This seem to have been wrong content, as type was String Here,
// instead of a Notebook Json model. This lead to double serialisation.
// as typescript does not seem to catch that, let's be safe.
if(typeof(content) === 'string'){
console.warn(new Error('(\\)(°,,°)(\\) blblblblbl you are stringifying a string, bailing out'))
} else {
content = JSON.stringify(content);
}
mimetype = mimetype || 'application/json';
} else if (format == 'base64') {
mimetype = mimetype || 'application/octet-stream';
} else if (format == 'text') {
mimetype = mimetype || 'text/plain';
} else {
throw ("Unrecognized format " + format)
}
var metadata = {
'title' : model['name'],
'mimeType' : mimetype
};
return [metadata, content];
}
/**
* Converts a Google Drive files resource, (see https://developers.google.com/drive/v2/reference/files)
* to an IPEP 27 contents model (see https://github.com/ipython/ipython/wiki/IPEP-27:-Contents-Service)
*
* Note that files resources can represent files or directories.
*
* TODO: check that date formats are the same, and either
* convert to the IPython format, or document the difference.
*
* @param {string} path Path of resoure (including file name)
* @param {Object} resource Google Drive files resource
* @return {Object} IPEP 27 compliant contents model
*/
// TODO remove contents ?
var files_resource_to_contents_model = function(path:Path, resource, content?) {
var title = resource['title'];
var mimetype = resource['mimeType'];
// Determine resource type.
var nbextension = '.ipynb';
var type = 'file';
var model_content;
if (mimetype === driveutils.FOLDER_MIME_TYPE) {
type = 'directory';
} else if (mimetype === driveutils.NOTEBOOK_MIMETYPE ||
title.indexOf(nbextension, title.length - nbextension.length) !== -1) {
type = 'notebook';
if( typeof content !== 'undefined'){
model_content = notebook_model.notebook_from_file_contents(content);
}
} else {
if( typeof content !== 'undefined'){
model_content = content;
}
}
return {
type: type,
name: title,
path: path,
created: resource['createdDate'],
last_modified: resource['modifiedDate'],
content : model_content,
writable : resource['editable']
};
};
/**
*
* Implement a contents manager that talks to Google Drive. Expose itself also
* as `Contents` to be able to by transparently dynamically loaded and replace
* any other contents manager that expose the `IContents` interface.
*
* For a higher level description on how to use these interfaces, see the
* `IContents` interface docs
*
**/
export class GoogleDriveContents implements IContents {
private _base_url:string;
private _config:any;
private _last_observed_revision:any;
/**
*
* A contentmanager handles passing file operations
* to the back-end. This includes checkpointing
* with the normal file operations.
*
* Parameters:
* options: dictionary
* Dictionary of keyword arguments.
* base_url: string
**/
constructor(options) {
this._base_url = options.base_url;
this._config = options.common_config;
/**
* Stores the revision id from the last save or load. This is used
* when checking if a file has been modified by another user.
*/
this._last_observed_revision = {};
var that = this;
this._config.loaded.then((data) => {
gapiutils.config(this._config);
gapiutils.gapi_ready.then(driveutils.set_user_info);
})
}
/**
* Utility functions
*/
/**
* This function should be called when a file is modified or opened. It
* caches the revisionId of the head revision of that file. This
* information is used for two purposes. First, it is used to determine
* if another user has changed a file, in order to warn a user that they
* may be overwriting another user's work. Second, it is used to
* checkpoint after saving.
*
* @param {resource} resource_prm a Google Drive file resource.
*/
private _observe_file_resource(resource) {
this._last_observed_revision[resource['id']] = resource['headRevisionId'];
}
/**
* Saves a version of an existing file on drive
* @param {Object} resource The Drive resource representing the file
* @param {Object} model The IPython model object to be saved
* @return {Promise} A promise fullfilled with the resource of the saved file.
*/
private _save_existing(resource, model) {
var that = this;
if(typeof(model) == 'string'){
var e = new Error("[drive-contents.ts] `_save_existing`'s model is a string");
console.error(e);
throw e
}
var converted = contents_model_to_metadata_and_bytes(model);
var contents = converted[1];
var save = function() {
return driveutils.upload_to_drive(contents, undefined, resource['id']);
};
if (resource['headRevisionId'] !=
that._last_observed_revision[resource['id']]) {
// The revision id of the files resource does not match the
// cached revision id for this file. This implies that the
// file has been modified by another user/tab during this
// session. Before saving, the user must be warned that they
// may be overwriting the work of another user.
return new Promise(function(resolve, reject) {
var options = {
title: 'File modified by other user',
body: ('Another user has modified this file. Click'
+ ' ok to overwrite this file with your'
+ ' content.'),
buttons: {
'ok': { click : function() { resolve(save()); },
},
'cancel': { click : function() { reject(new Error('save cancelled')); } }
}
};
dialog.modal(options);
});
}
return save();
}
/**
* Uploads a model to drive
* @param {string} folder_id The id of the folder to create the file in
* @param {Object} model The IPython model object to be saved
* @return {Promise} A promise fullfilled with the resource of the saved file.
*/
private _upload_new(folder_id, model) {
var that = this;
if(typeof(model) == 'string'){
var e = new Error("[drive-contents.ts] `_save_existing`'s model is a string");
console.error(e);
throw e
}
var converted = contents_model_to_metadata_and_bytes(model);
var metadata = converted[0];
var contents = converted[1];
metadata['parents'] = [{'id' : folder_id}];
if (model['type'] === 'directory') {
return gapiutils.execute(gapi.client.drive.files.insert({'resource': metadata}));
} else {
return driveutils.upload_to_drive(contents, metadata);
}
}
/**
* Notebook Functions
*/
get(path:Path, options:any) {
var that = this;
var metadata_prm = gapiutils.gapi_ready.then(
$.proxy(driveutils.get_resource_for_path, this, path, driveutils.FileType.FILE));
var contents_prm = metadata_prm.then(function(resource) {
that._observe_file_resource(resource);
return driveutils.get_contents(resource, false);
});
return Promise.all([metadata_prm, contents_prm]).then(function(values) {
var metadata = values[0];
var contents = values[1];
var model = files_resource_to_contents_model(path, metadata, contents);
return model;
});
}
/**
* Creates a new untitled file or directory in the specified directory path.
*
* @param {String} path: the directory in which to create the new file/directory
* @param {Object} options:
* ext: file extension to use
* type: model type to create ('notebook', 'file', or 'directory')
*/
new_untitled(path:Path, options) {
// Construct all data needed to upload file
var default_ext = '';
var base_name = '';
var model = null;
if (options['type'] === 'notebook') {
default_ext = '.ipynb';
base_name = 'Untitled'
model = {
'type': 'notebook',
'content': notebook_model.new_notebook(),
'mimetype': driveutils.NOTEBOOK_MIMETYPE,
'format': 'json'
};
} else if (options['type'] === 'file') {
default_ext = '.txt';
base_name = 'Untitled';
model = {
'type': 'file',
'content': '',
'mimetype': 'text/plain',
'format': 'text'
};
} else if (options['type'] === 'directory') {
base_name = 'Untitled_Folder';
model = {
'type': 'directory',
'content': {},
'format' : 'json'
}
} else {
return Promise.reject(new Error("Unrecognized type " + options['type']));
}
var folder_id_prm = gapiutils.gapi_ready
.then($.proxy(driveutils.get_id_for_path, this, path, driveutils.FileType.FOLDER))
var filename_prm = folder_id_prm.then(function(resource){
return driveutils.get_new_filename(resource, options['ext'] || default_ext, base_name);
});
return Promise.all([folder_id_prm, filename_prm]).then((values) => {
var folder_id = values[0];
var filename = values[1];
model['name'] = filename;
return this._upload_new(folder_id, model);
})
.then(function(resource) {
var fullpath = <Path>utils.url_path_join(<string>path, <string>resource['title']);
return files_resource_to_contents_model(fullpath, resource);
});
}
delete(path:Path) {
return gapiutils.gapi_ready
.then(function() {
return driveutils.get_id_for_path(path, driveutils.FileType.FILE);
})
.then(function(file_id){
return gapiutils.execute(gapi.client.drive.files.delete({'fileId': file_id}));
});
}
rename(path:Path, new_path:Path) {
var that = this;
// Rename is only possible when path and new_path differ except in
// their last component, so check this first.
var path_components = driveutils.split_path(path);
var new_path_components = driveutils.split_path(new_path);
var base_path = [];
var name:Path;
var new_name:Path;
if (path_components.length != new_path_components.length) {
return Promise.reject(new Error('Rename cannot change path'));
}
for (var i = 0; i < path_components.length; ++i) {
var component = path_components[i];
var new_component = new_path_components[i];
if (i == path_components.length - 1) {
name = component;
new_name = new_component;
} else {
if (component != new_component) {
return Promise.reject(new Error('Rename cannot change path'));
}
base_path.push(component);
}
}
return gapiutils.gapi_ready
.then(function() {
return driveutils.get_id_for_path(path)
})
.then(function(file_id) {
var body = {'title': new_name};
var request = gapi.client.drive.files.patch({
'fileId': file_id,
'resource': body
});
return gapiutils.execute(request);
})
.then(function(resource) {
that._observe_file_resource(resource);
return files_resource_to_contents_model(new_path, resource);
});
}
/**
* Given a path and a model, save the document.
* If the resource has been modifeied on Drive in the
* meantime, prompt user for overwrite.
**/
save(path:Path, model, options?:any) {
var that = this;
var path_and_filename = <Path[]>utils.url_path_split(<string>path);
var path = path_and_filename[0];
var filename = path_and_filename[1];
return driveutils.get_resource_for_path(<string>path, driveutils.FileType.FOLDER)
.then(function(folder_resource) {
return driveutils.get_resource_for_relative_path(filename, driveutils.FileType.FILE, false, folder_resource['id'])
.then(function(file_resource) {
return that._save_existing(file_resource, model)
}, function(error) {
// If the file does not exist (but the directory does) then a
// new file must be uploaded.
if (error.name !== 'NotFoundError') {
return Promise.reject(error);
}
model['name'] = filename;
return that._upload_new(folder_resource['id'], model)
});
})
.then(function(file_resource) {
that._observe_file_resource(file_resource);
return files_resource_to_contents_model(path, file_resource);
});
}
copy(path:Path, model) {
return Promise.reject(new Error('Copy not implemented yet.'));
}
/**
* Checkpointing Functions
*/
// NOTE: it would be better modify the API to combine create_checkpoint with
// save
create_checkpoint(path:Path, options:any) {
var that = this;
return gapiutils.gapi_ready
.then($.proxy(driveutils.get_id_for_path, this, path, driveutils.FileType.FILE))
.then(function(file_id) {
var revision_id = that._last_observed_revision[file_id];
if (!revision_id) {
return Promise.reject(new Error('File must be saved before checkpointing'));
}
var body = {'pinned': true};
var request = gapi.client.drive.revisions.patch({
'fileId': file_id,
'revisionId': revision_id,
'resource': body
});
return gapiutils.execute(request);
})
.then(function(item) {
return {
last_modified: item['modifiedDate'],
id: item['id'],
drive_resource: item
};
});
}
restore_checkpoint(path:Path, checkpoint_id:CheckpointId, options) {
var file_id_prm = gapiutils.gapi_ready
.then($.proxy(driveutils.get_id_for_path, this, path, driveutils.FileType.FILE))
var contents_prm = file_id_prm.then(function(file_id) {
var request = gapi.client.drive.revisions.get({
'fileId': file_id,
'revisionId': checkpoint_id
});
return gapiutils.execute(request);
})
.then(function(response) {
return gapiutils.download(response['downloadUrl']);
})
return Promise.all([file_id_prm, contents_prm])
.then(function(values) {
var file_id = values[0];
var contents = values[1];
return driveutils.upload_to_drive(contents, undefined, file_id);
});
}
list_checkpoints(path:Path, options:any) {
return gapiutils.gapi_ready
.then($.proxy(driveutils.get_id_for_path, this, path, driveutils.FileType.FILE))
.then(function(file_id) {
var request = gapi.client.drive.revisions.list({'fileId': file_id });
return gapiutils.execute(request);
})
.then(function(response) {
return response['items']
.filter(function(item) { return item['pinned']; })
.map(function(item) {
return {
last_modified: item['modifiedDate'],
id: item['id'],
drive_resource: item
};
});
});
}
/**
* File management functions
*/
/**
* List notebooks and directories at a given path
*
* On success, load_callback is called with an array of dictionaries
* representing individual files or directories. Each dictionary has
* the keys:
* type: "notebook" or "directory"
* name: the name of the file or directory
* created: created date
* last_modified: last modified dat
* path: the path
* @method list_notebooks
* @param {String} path The path to list notebooks in
* @param {Object} options Object with the following keys
* success: success callback
* error: error callback
*/
list_contents(path:Path, options):Promise<any>{
var that = this;
return gapiutils.gapi_ready
.then($.proxy(driveutils.get_id_for_path, this, path, driveutils.FileType.FOLDER))
.then(function(folder_id) {
// Gets contents of the folder 1000 items at a time. Google Drive
// returns at most 1000 items in each call to drive.files.list.
// Therefore we need to make multiple calls, using the following
// recursive method.
// Returns all items starting from the specified page token
// (or from the start if no page token is specified), and
// combines these with the items given.
var get_items = function(items, page_token?) {
var query = ('\'' + folder_id + '\' in parents'
+ ' and trashed = false');
var params = {
'maxResults' : 1000,
'q' : query
};
if (page_token) {
params['pageToken'] = page_token;
};
var request = gapi.client.drive.files.list(params)
return gapiutils.execute(request)
.then(function(response) {
var combined_items = items.concat(response['items']);
var next_page_token = response['nextPageToken'];
if (next_page_token) {
return get_items(combined_items, next_page_token);
}
return combined_items;
});
};
return get_items([]);
})
.then(function(items) {
var list = $.map(items, function(resource) {
var fullpath = <Path>utils.url_path_join(<string>path, resource['title']);
return files_resource_to_contents_model(fullpath, resource)
});
return {content: list};
});
}
}
export var Contents = GoogleDriveContents | the_stack |
import * as sinon from 'sinon';
import {GVL, TCString, TCModel} from '../src';
import {XMLHttpTestTools, makeRandomInt, GVLFactory} from '@iabtcf/testing';
import {expect} from 'chai';
import {PurposeRestriction} from '../src/model/PurposeRestriction';
import {RestrictionType} from '../src/model/RestrictionType';
describe('Issues Reported', (): void => {
it('112 Vendor ranges incorrectly decoded from publisher restrictions', async (): Promise<void> => {
const CMPID = makeRandomInt(2, 100);
const CMPVERSION = makeRandomInt(1, 63);
const CONSENTSCREEN = makeRandomInt(1, 63);
const purposeRestriction = new PurposeRestriction(2, RestrictionType.NOT_ALLOWED);
const tcModel = new TCModel(GVLFactory.getVersion(23) as unknown as GVL);
const vendorID1 = 8;
const vendorID2 = vendorID1 + 1;
tcModel.cmpId = CMPID;
tcModel.cmpVersion = CMPVERSION;
tcModel.consentScreen = CONSENTSCREEN;
tcModel.publisherRestrictions.add(vendorID1, purposeRestriction);
tcModel.publisherRestrictions.add(vendorID2, purposeRestriction);
await tcModel.gvl.readyPromise;
const encodedTCString = TCString.encode(tcModel);
const newTCModel = TCString.decode(encodedTCString);
const vendors = newTCModel.publisherRestrictions.getVendors(purposeRestriction);
for (let i = 1; i < 17; i++) {
if (i === vendorID1 || i === vendorID2) {
expect(vendors.includes(i), `vendor id ${i}`).to.be.true;
} else {
expect(vendors.includes(i), `vendor id ${i}`).to.be.false;
}
}
});
it('91 TCString.encode use 0 as vendorListVersion instead of gvl', async (): Promise<void> => {
const CMPID = makeRandomInt(2, 100);
const CMPVERSION = makeRandomInt(1, 63);
const CONSENTSCREEN = makeRandomInt(1, 63);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const vendorlist = require('@iabtcf/testing/lib/vendorlist/vendor-list.json');
GVL.baseUrl = 'http://mydomain.com/cmp/vendorlist';
const gvl = new GVL('LATEST');
const req: sinon.SinonFakeXMLHttpRequest = XMLHttpTestTools.requests[0];
req.respond(200, XMLHttpTestTools.JSON_HEADER, JSON.stringify(vendorlist));
await gvl.readyPromise;
const tcModel = new TCModel(gvl);
tcModel.cmpId = CMPID;
tcModel.cmpVersion = CMPVERSION;
tcModel.consentScreen = CONSENTSCREEN;
const encodedTCString = TCString.encode(tcModel);
const decodeFunc = (): void => {
TCString.decode(encodedTCString);// Throw error
};
expect(decodeFunc, 'decodeFunc').not.to.throw();
});
it('77 should not delete tcfPolicyVersion and gvlSpecificationVersion after a language is changed', (done: () => void): void => {
GVL.baseUrl = 'http://sweetcmp.com';
const language = 'fr';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const translationJson = require('@iabtcf/testing/lib/vendorlist/purposes-fr.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const gvl = new GVL(require('@iabtcf/testing/lib/vendorlist/vendor-list.json'));
const {tcfPolicyVersion, gvlSpecificationVersion} = gvl;
expect(tcfPolicyVersion, 'tcfPolicyVersion').to.equal(2);
expect(gvlSpecificationVersion, 'gvlSpecificationVersion').to.equal(2);
gvl.changeLanguage(language).then((): void => {
expect(gvl.tcfPolicyVersion, 'gvl.tcfPolicyVersion').to.equal(tcfPolicyVersion);
expect(gvl.gvlSpecificationVersion, 'gvl.gvlSpecificationVersion').to.equal(gvlSpecificationVersion);
done();
});
const req: sinon.SinonFakeXMLHttpRequest = XMLHttpTestTools.requests[0];
req.respond(200, XMLHttpTestTools.JSON_HEADER, JSON.stringify(translationJson));
});
it('122 consentLanguage should not be ignored', (): void => {
const FRENCH = 'FR';
const ENGLISH = 'EN';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const gvl = new GVL(require('@iabtcf/testing/lib/vendorlist/vendor-list.json'));
const tcModel = new TCModel(gvl);
expect(tcModel.consentLanguage, 'consentLanguage').to.equal(ENGLISH);
tcModel.consentLanguage = FRENCH;
expect(tcModel.consentLanguage, 'consentLanguage').to.equal(FRENCH);
});
it('117 TCString.encode writes all vendors as disclosed even after GVL.narrowVendorsTo([...])', async (): Promise<void> => {
const tcModel = new TCModel(new GVL());
tcModel.cmpId = makeRandomInt(2, 100);
tcModel.cmpVersion = makeRandomInt(1, 100);
const req: sinon.SinonFakeXMLHttpRequest = XMLHttpTestTools.requests[0];
// eslint-disable-next-line @typescript-eslint/no-var-requires
const vendorlist = require('@iabtcf/testing/lib/vendorlist/vendor-list.json');
req.respond(200, XMLHttpTestTools.JSON_HEADER, JSON.stringify(vendorlist));
await tcModel.gvl.readyPromise;
const vendors = [12, 100];
tcModel.gvl.narrowVendorsTo(vendors);
tcModel.vendorsDisclosed.empty();
tcModel.setAllVendorsDisclosed();
expect(tcModel.vendorsDisclosed.size, 'tcModel.vendorsDisclosed.size').to.equal(vendors.length);
const decoded = TCString.decode(TCString.encode(tcModel));
expect(decoded.vendorsDisclosed.size, 'decoded.vendorsDisclosed.size').to.equal(vendors.length);
});
it('142 it should throw an error if the bitfield length does not match the maxId', (): void => {
const str = 'CLSYjTaOngnCIAOABBENAXCMAGOAABBAAA7IA5n-m7fP6_3fbqVv6E__PoA5Aqff3aJx8tv_1967rfnQEQoAIAAQCrwkAEABAcACABIMACAAuApEVABABUSABgBCAVSAtIoACACIArYQAHACgAFgAVwBJgDcAI7AWgMAAgBiKgAgBMgFfKQAQBRkQAQA4AFiBAAoA-AEVAJlAVgAtYcACAJcAr4eABAK8OgBgFzAOmAqwgABAWyA.IFukWSQh';
expect((): void => {
TCString.decode(str);
}).to.throw();
});
it('156 it should auto detect 1 version', (): void => {
const str = 'BOhwdphOxFC7tAHABBFRC--AAAAuhr_7__7-_9_-_f__9uj3Or_v_f__32ccL59v_h_7v-_7fi_20nV4u_1vft9yfk1-5ctDztp507iakivXmqdeb9v_nz3_5pxP78k89r7337Ew_v8_v-b7BCON_YxEiA';
const decoded = TCString.decode(str);
expect(decoded.version, 'decoded.version').to.equal(1);
});
it('162 Legal basis purpose restriction is reflected on vendors without flexible purposes too', async (): Promise<void> => {
const gvl = GVLFactory.getVersion(36) as unknown as GVL;
await gvl.readyPromise;
// Vendor 4 does not have any flexible purpose at GVL version 36
const vendorId = 4;
// Vendor 4 specifies purpose 2 as consent purpose
const purposeId = 2;
const tcModel = new TCModel(gvl);
const purposeRestriction = new PurposeRestriction(purposeId, RestrictionType.REQUIRE_LI);
tcModel.cmpId = makeRandomInt(2, 100);
tcModel.isServiceSpecific = true;
tcModel.publisherRestrictions.add(vendorId, purposeRestriction);
const decodedTCModel = TCString.decode(TCString.encode(tcModel));
expect(decodedTCModel.publisherRestrictions.getVendors(purposeRestriction)).be.an('array')
.that.is.empty;
});
it('204 Not possible to set vendorConsent for vendor which declared felxiblePurposes but no purposes', async (): Promise<void> => {
const gvl = GVLFactory.getVersion(51) as unknown as GVL;
await gvl.readyPromise;
const vendorIds = [688, 751, 684, 729, 730];
const tcModel = new TCModel(gvl);
tcModel.cmpId = makeRandomInt(2, 100);
tcModel.isServiceSpecific = true;
vendorIds.forEach((vendorId: number): void => {
const vendor = gvl.vendors[vendorId];
// check the vendor first – if the GVL changes then this may not be the same
expect(vendor.flexiblePurposes, 'flexiblePurposes for ' + vendor.id).to.be.an('array').that.is.not.empty;
const purposeId = vendor.flexiblePurposes[0];
let purposeRestriction: PurposeRestriction;
if (vendor.purposes.length) {
purposeRestriction = new PurposeRestriction(purposeId, RestrictionType.REQUIRE_CONSENT);
tcModel.vendorConsents.set(vendorId);
} else if (vendor.legIntPurposes.length) {
purposeRestriction = new PurposeRestriction(purposeId, RestrictionType.REQUIRE_LI);
tcModel.vendorLegitimateInterests.set(vendorId);
}
tcModel.publisherRestrictions.add(vendorId, purposeRestriction);
});
const decodedTCModel = TCString.decode(TCString.encode(tcModel));
vendorIds.forEach((vendorId: number): void => {
const vendor = gvl.vendors[vendorId];
if (vendor.purposes.length) {
expect(decodedTCModel.vendorConsents.has(vendorId), `decoded tcModel.vendorConsents.has(${vendorId})`).to.be.true;
} else if (vendor.legIntPurposes.length) {
expect(decodedTCModel.vendorLegitimateInterests.has(vendorId), `decoded tcModel.vendorLegitimateInterests.has(${vendorId})`).to.be.true;
}
});
});
it('191 vendorConsents empty when decoding TCF 1.1 consentString that uses vendorRangeList', async (): Promise<void> => {
const tcModel = TCString.decode('BO2e4qiO2e4qiB9ABADEDS-AAAAxKABgACBiQA');
expect(tcModel.vendorConsents.size, `vendorConsents size`).not.to.equal(0);
});
it('201 unable to decode valid TCF2 String', (): void => {
let tcModel: TCModel;
/**
* This TC String has a purpose restriction encoded for a vendor multiple
* times
*/
expect((): void => {
tcModel = TCString.decode('CO4VGswO4VGswAfZCBDEAzCsAP_AAH_AAAigGUNf_X9fb2vj-_599_t0eY1f9_63t-wzjheMs-8NyZ-X_J4Wv2MyvB34JqQKGRgkunLBAQdtHGncTQgBwIlViTLMY02MjzNKJrJEilsbe2dYGH9vn8XT_ZKZ70-_v__7v3___33_5Ayhr_6_r7e18f3_Pvv9ujzGr_v_W9v2GccLxln3huTPy_5PC1-xmV4O_BNSBQyMEl05YICDto407iaEAOBEqsSZZjGmxkeZpRNZIkUtjb2zrAw_t8_i6f7JTPen39___d-___--__ICgKAOAAcAA4AFAAjgB6AEYALcGACAW0AtoJAHAAOAAcACgARwA9ACMAFuFABALaAW0GgDgAHAAOABQAI4AegBGAC3DgAgFtALaEQBwADgAHAAoAEcAPQAjABbiQAQC2gFtCoA4ABwADgAUACOAHoARgAtxYAIBbQC2hkAcAA4ABwAKABHAD0AIwAW40AEAtoBbQ6AOAAcAA4AFAAjgB6AEYALceACAW0AtohAHAAOAAcACgARwA9ACMAFuRABALaAW0SgDgAHAAOABQAI4AegBGAC3JgAgFtALaKQBwADgAHAAoAEcAPQAjABblQAQC2gFtA');
}).not.to.throw();
expect(tcModel.version, `tcModel.version`).to.equal(2);
expect(tcModel.publisherRestrictions.getVendors(new PurposeRestriction(1, 1)), `tcModel.publisherRestrictions vendor array`).to.deep.equal([7, 20, 71, 122, 140, 183]);
});
}); | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { ShapeStyleModel } from '../../../src/diagram/core/appearance-model';
import { PathElement } from '../../../src/diagram/core/elements/path-element';
import { ShadowModel, RadialGradientModel, StopModel, LinearGradientModel, GradientModel } from '../../../src/diagram/core/appearance-model';
import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec';
describe('Diagram Control', () => {
describe('render path element with size', () => {
let diagram: Diagram;
let ele: HTMLElement;
let element1: PathElement;
let element2: PathElement;
let element3: PathElement;
let element4: PathElement;
let element5: PathElement;
let element6: PathElement;
let element7: PathElement;
let element8: PathElement;
let element9: PathElement;
let element10: PathElement;
let element11: PathElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram33' });
document.body.appendChild(ele);
let nodes: PathElement[];
element1 = new PathElement();
let shapestyle: ShapeStyleModel = {};
element1.width = 50;
element1.height = 50;
element1.offsetX = 300;
element1.offsetY = 100;
element1.style.strokeWidth = 1;
element1.data = 'm10 80 q 52.5 10, 95 80 t 180 80 ';
element2 = new PathElement();
element2.width = 100;
element2.height = 100;
element2.offsetX = 700;
element2.style.strokeWidth = 1;
element2.offsetY = 100;
element2.data = 'M300,200 h-150 a150,150 0 1,0 150,-150 z';
element2.style.fill = 'red';
element3 = new PathElement();
element3.width = 100;
element3.height = 100;
element3.offsetX = 500;
element3.offsetY = 100;
element3.style.strokeWidth = 1;
element3.data = 'M35.2441,25 L22.7161,49.9937 L22.7161,0.00657536 L35.2441,25 z M22.7167,25 L-0.00131226,25 M35.2441,49.6337 L35.2441,0.368951 M35.2441,25 L49.9981,25';
element3.style.fill = 'blue';
element4 = new PathElement();
element4.width = 100;
element4.height = 100;
element4.offsetX = 350;
element4.style.strokeWidth = 1;
element4.offsetY = 300;
element4.data = 'M100,200 C100,100 250,100 250,200 S400,300 400,200';
element5 = new PathElement();
element5.width = 100;
element5.height = 100;
element5.offsetX = 500;
element5.offsetY = 300;
element5.style.strokeWidth = 1;
element5.data = 'M433.4624,503.8848C429.4244,493.2388,419.1354,485.6678,407.0734,485.6678C391.4884,485.6678,378.8544,498.3018,378.8544,513.8868L384.4984,513.8868C384.4984,501.4178,394.6054,491.3108,407.0734,491.3108C415.9494,491.3108,423.6264,496.4338,427.3144,503.8848L422.9114,503.8848L426.8974,508.8848L430.8824,513.8868L434.8684,508.8848L438.8544,503.8848L433.4624,503.8848z';
element6 = new PathElement();
element6.width = 50;
element6.height = 50;
element6.offsetX = 50;
element6.offsetY = 50;
element6.style.strokeWidth = 1;
element6.data = 'M10 80 T 180 80 ';
element8 = new PathElement();
element8.width = 50;
element8.height = 50;
element8.offsetX = 150;
element8.style.strokeWidth = 1;
element8.offsetY = 150;
element8.data = 'M300,200 h-150 a150,150 0 0,1 150,-150 z';
element8.style.fill = 'red';
element9 = new PathElement();
element9.width = 50;
element9.height = 50;
element9.offsetX = 200;
element9.style.strokeWidth = 1;
element9.offsetY = 200;
element9.data = 'M300,200 h-150 a150,150 0 0,0 150,-150 z';
element9.style.fill = 'red';
element10 = new PathElement();
element10.width = 50;
element10.height = 50;
element10.offsetX = 150;
element10.style.strokeWidth = 1;
element10.offsetY = 300;
element10.data = 'M300,200 h-150 a150,150 0 1,1 150,-150 z';
element10.style.fill = 'red';
element11 = new PathElement();
element11.width = 50;
element11.height = 50;
element11.offsetX = 370;
element11.offsetY = 130;
element11.style.strokeWidth = 1;
element11.style.strokeDashArray = '';
element11.style.fill = '';
element11.data = 'M10 80 Q 52.5 10, 95 80 T 180 80 ';
diagram = new Diagram({
mode: 'Canvas',
width: 1000, height: 1000,
basicElements: [element1, element2, element3, element4, element5, element6, element8, element9,
element10, element11],
});
diagram.appendTo('#diagram33');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking stack panel without children in SVG rendering Mode', (done: Function) => {
expect(element1.absolutePath === "M 0 0 Q 9.55 3.13 17.27 25 T 50 50" &&
(element2.absolutePath === 'M 50 50 H 0 A 50 49.999994913737495 0 1 0 50 0 Z' || element2.absolutePath ==="M 50 50 H 0 A 50 50 0 1 0 50 0 Z") &&
element3.absolutePath === "M 70.49 50 L 45.44 100 L 45.44 0 L 70.49 50 Z M 45.44 50 L 0 50 M 70.49 99.28 L 70.49 0.72 M 70.49 50 L 100 50" &&
element4.absolutePath === "M 0 50 C 0 -16.67 50 -16.67 50 50 S 100 116.67 100 50" &&
element5.absolutePath === "M 91.01 64.56 C 84.28 26.83 67.13 0 47.03 0 C 21.06 0 0 44.77 0 100 L 9.41 100 C 9.41 55.81 26.25 20 47.03 20 C 61.82 20 74.62 38.15 80.77 64.56 L 73.43 64.56 L 80.07 82.27 L 86.71 100 L 93.36 82.27 L 100 64.56 L 91.01 64.56 Z" &&
element6.absolutePath === "M 0 0 T 50 0" &&
element8.absolutePath === "M 50 50 H 0 A 50 50 0 0 1 50 0 Z" &&
element9.absolutePath === "M 50 50 H 0 A 50 50 0 0 0 50 0 Z" &&
element10.absolutePath === "M 50 50 H 25 A 25 25 0 1 1 50 25 Z" &&
element11.absolutePath === "M 0 25 Q 12.5 -25 25 25 T 50 25"
).toBe(true);
done();
});
});
describe('render path element without size', () => {
let diagram: Diagram;
let ele: HTMLElement;
let element1: PathElement;
let element2: PathElement;
let element3: PathElement;
let element4: PathElement;
let element5: PathElement;
let element6: PathElement;
let element7: PathElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram34' });
document.body.appendChild(ele);
let nodes: PathElement[];
element1 = new PathElement();
element1.offsetX = 300;
element1.offsetY = 100;
element1.style.strokeWidth = 1;
element1.data = 'M 0,0 L 100,0 M100,0 L100,100 M100,100 L0,100 M0,100 L0,0 Z ';
element1.style.fill = 'red';
element2 = new PathElement();
element2.offsetX = 700;
element2.offsetY = 100;
element2.data = 'M300,200 h-150 a150,150 0 1,0 150,-150 z';
element2.style.fill = 'red';
element2.style.strokeWidth = 1;
element3 = new PathElement();
element3.offsetX = 500;
element3.offsetY = 100;
element3.data = 'M35.2441,25 L22.7161,49.9937 L22.7161,0.00657536 L35.2441,25 z M22.7167,25 L-0.00131226,25 M35.2441,49.6337 L35.2441,0.368951 M35.2441,25 L49.9981,25';
element3.style.fill = 'blue';
element3.style.strokeWidth = 1;
element4 = new PathElement();
element4.offsetX = 350;
element4.offsetY = 300;
element4.data = 'M100,200 C100,100 250,100 250,200 S400,300 400,200';
element4.style.strokeWidth = 1;
element5 = new PathElement();
element5.offsetX = 100;
element5.offsetY = 100;
element5.style.strokeWidth = 1;
element5.data = 'M433.4624,503.8848C429.4244,493.2388,419.1354,485.6678,407.0734,485.6678C391.4884,485.6678,378.8544,498.3018,378.8544,513.8868L384.4984,513.8868C384.4984,501.4178,394.6054,491.3108,407.0734,491.3108C415.9494,491.3108,423.6264,496.4338,427.3144,503.8848L422.9114,503.8848L426.8974,508.8848L430.8824,513.8868L434.8684,508.8848L438.8544,503.8848L433.4624,503.8848z';
element6 = new PathElement();
element6.offsetX = 50;
element6.offsetY = 50;
element6.width = 50;
element6.height = 50;
element6.data = 'M100,200 S400,300 400,200';
element6.style.strokeWidth = 1;
element7 = new PathElement();
element7.width = 75;
element7.height = 75;
element7.offsetX = 75;
element7.offsetY = 75;
element7.style.strokeWidth = 1;
element7.data = '';//S400,300 400,200 ';
diagram = new Diagram({
mode: 'Canvas',
width: 1000, height: 1000, basicElements: [element1, element2, element3, element4, element5, element6, element7]
,
});
diagram.appendTo('#diagram34');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking stack panel without children in SVG rendering Mode', (done: Function) => {
expect(element1.absolutePath === "M 0 0 L 100 0 M 100 0 L 100 100 M 100 100 L 0 100 M 0 100 L 0 0 Z" &&
element2.absolutePath === "M 150 150 H 0 A 150 150 0 1 0 150 0 Z" &&
element3.absolutePath === "M 35.25 24.99 L 22.72 49.99 L 22.72 0 L 35.25 24.99 Z M 22.72 24.99 L 0 24.99 M 35.25 49.63 L 35.25 0.36 M 35.25 24.99 L 50 24.99" &&
element4.absolutePath === "M 0 75 C 0 -25 150 -25 150 75 S 300 175 300 75" &&
element5.absolutePath === "M 54.61 18.22 C 50.57 7.57 40.28 0 28.22 0 C 12.63 0 0 12.63 0 28.22 L 5.64 28.22 C 5.64 15.75 15.75 5.64 28.22 5.64 C 37.09 5.64 44.77 10.77 48.46 18.22 L 44.06 18.22 L 48.04 23.22 L 52.03 28.22 L 56.01 23.22 L 60 18.22 L 54.61 18.22 Z" &&
element6.absolutePath === "M 0 0 S 50 112.5 50 0" &&
element7.absolutePath === "").toBe(true);
done();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
}); | the_stack |
interface MustacheStatic {
/**
* The name of the module.
*/
readonly name: string;
/**
* The version of the module.
*/
readonly version: string;
/**
* The default opening and closing tags used while parsing the templates.
*
* Different default tags can be overridden by setting this field. They will have effect on all subsequent
* calls to `.render()` or `.parse()`, unless custom tags are given as arguments to those functions.
*
* Default value is `[ "{{", "}}" ]`.
*/
tags: OpeningAndClosingTags;
/**
* A simple string scanner that is used by the template parser to find tokens in template strings.
*/
Scanner: typeof MustacheScanner;
/**
* Represents a rendering context by wrapping a view object and maintaining a reference to the parent context.
*/
Context: typeof MustacheContext;
/**
* A Writer knows how to take a stream of tokens and render them to a `string`, given a context.
*
* It also maintains a cache of templates to avoid the need to parse the same template twice.
*/
Writer: typeof MustacheWriter;
/**
* Escapes HTML-characters.
*
* @param value
* The string to escape.
*/
escape: (value: string) => string;
/**
* Clears all cached templates in this writer.
*/
clearCache(): void;
/**
* Customise the template caching behaviour by either:
*
* disable it completely by setting it to `undefined`
*
* -- or --
*
* provide a custom cache strategy that satisfies the `TemplateCache` interface
*/
templateCache: TemplateCache | undefined;
/**
* Parses and caches the given template in the default writer and returns the array of tokens it contains.
*
* Doing this ahead of time avoids the need to parse templates on the fly as they are rendered.
*
* @param template
* The template to parse.
*
* @param tags
* The tags to use.
*/
parse(template: string, tags?: OpeningAndClosingTags): TemplateSpans;
/**
* Renders the `template` with the given `view` and `partials` using the default writer.
*
* @param template
* The template to render.
*
* @param view
* The view to render the template with.
*
* @param partials
* Either an object that contains the names and templates of partials that are used in a template
*
* -- or --
*
* A function that is used to load partial template on the fly that takes a single argument: the name of the partial.
*
* @param tags
* The tags to use.
*/
render(template: string, view: any | MustacheContext, partials?: PartialsOrLookupFn, tags?: OpeningAndClosingTags): string;
}
/**
* A simple string scanner that is used by the template parser to find tokens in template strings.
*/
declare class MustacheScanner {
string: string;
tail: string;
pos: number;
/**
* Initializes a new instance of the `MustacheScanner` class.
*/
constructor(string: string);
/**
* Returns `true` if the tail is empty (end of string).
*/
eos(): boolean;
/**
* Tries to match the given regular expression at the current position.
*
* @param re
* The regex-pattern to match.
*
* @returns
* The matched text if it can match, the empty string otherwise.
*/
scan(re: RegExp): string;
/**
* Skips all text until the given regular expression can be matched.
*
* @param re
* The regex-pattern to match.
*
* @returns
* Returns the skipped string, which is the entire tail if no match can be made.
*/
scanUntil(re: RegExp): string;
}
/**
* Represents a rendering context by wrapping a view object and maintaining a reference to the parent context.
*/
declare class MustacheContext {
view: any;
parentContext: MustacheContext | undefined;
/**
* Initializes a new instance of the `MustacheContext` class.
*/
constructor(view: any, parentContext?: MustacheContext);
/**
* Creates a new context using the given view with this context as the parent.
*
* @param view
* The view to create the new context with.
*/
push(view: any): MustacheContext;
/**
* Returns the value of the given name in this context, traversing up the context hierarchy if the value is absent in this context's view.
*
* @param name
* The name to look up.
*/
lookup(name: string): any;
}
/**
* A Writer knows how to take a stream of tokens and render them to a `string`, given a context.
*
* It also maintains a cache of templates to avoid the need to parse the same template twice.
*/
declare class MustacheWriter {
/**
* Initializes a new instance of the `MustacheWriter` class.
*/
constructor();
/**
* Clears all cached templates in this writer.
*/
clearCache(): void;
/**
* Parses and caches the given `template` and returns the array of tokens that is generated from the parse.
*
* @param template
* The template to parse.
*
* @param tags
* The tags to use.
*/
parse(template: string, tags?: OpeningAndClosingTags): any;
/**
* High-level method that is used to render the given `template` with the given `view`.
*
* @param template
* The template to render.
*
* @param view
* The view to render the template with.
*
* @param partials
* Either an object that contains the names and templates of partials that are used in a template
*
* -- or --
*
* A function that is used to load partial template on the fly that takes a single argument: the name of the partial.
*
* @param tags
* The tags to use.
*/
render(template: string, view: any | MustacheContext, partials?: PartialsOrLookupFn, tags?: OpeningAndClosingTags): string;
/**
* Low-level method that renders the given array of `tokens` using the given `context` and `partials`.
*
* @param tokens
* The tokens to render.
*
* @param context
* The context to use for rendering the tokens.
*
* @param partials
* The partials to use for rendering the tokens.
*
* @param originalTemplate
* An object used to extract the portion of the original template that was contained in a higher-order section.
*
* If the template doesn't use higher-order sections, this argument may be omitted.
*/
renderTokens(tokens: string[][], context: MustacheContext, partials?: PartialsOrLookupFn, originalTemplate?: string): string;
/**
* Renders a section block.
*
* @param token
* The token to render.
*
* @param context
* The context to use for rendering the token.
*
* @param partials
* The partials to use for rendering the token.
*
* @param originalTemplate
* An object used to extract the portion of the original template that was contained in a higher-order section.
*/
renderSection(token: string[], context: MustacheContext, partials?: PartialsOrLookupFn, originalTemplate?: string): string;
/**
* Renders an inverted section block.
*
* @param token
* The token to render.
*
* @param context
* The context to use for rendering the token.
*
* @param partials
* The partials to use for rendering the token.
*
* @param originalTemplate
* An object used to extract the portion of the original template that was contained in a higher-order section.
*/
renderInverted(token: string[], context: MustacheContext, partials?: PartialsOrLookupFn, originalTemplate?: string): string;
/**
* Adds indentation to each line of the given partial.
*
* @param partial
* The partial to indent.
*
* @param indentation
* String containing a combination of spaces and tabs to use as indentation.
*
* @param lineHasNonSpace
* Whether to indent lines that are empty.
*/
indentPartial(partial: string, indentation: string, lineHasNonSpace: boolean): string;
/**
* Renders a partial.
*
* @param token
* The token to render.
*
* @param context
* The context to use for rendering the token.
*
* @param partials
* The partials to use for rendering the token.
*
* @param tags
* The tags to use.
*/
renderPartial(token: string[], context: MustacheContext, partials?: PartialsOrLookupFn, tags?: OpeningAndClosingTags): string;
/**
* Renders an unescaped value.
*
* @param token
* The token to render.
*
* @param context
* The context to use for rendering the token.
*/
unescapedValue(token: string[], context: MustacheContext): string;
/**
* Renders an escaped value.
*
* @param token
* The token to render.
*
* @param context
* The context to use for rendering the token.
*/
escapedValue(token: string[], context: MustacheContext): string;
/**
* Renders a raw token.
*
* @param token
* The token to render.
*/
rawValue(token: string[]): string;
}
type RAW_VALUE = "text";
type ESCAPED_VALUE = "name";
type UNESCAPED_VALUE = "&";
type SECTION = "#";
type INVERTED = "^";
type COMMENT = "!";
type PARTIAL = ">";
type EQUAL = "=";
type TemplateSpanType =
| RAW_VALUE
| ESCAPED_VALUE
| SECTION
| UNESCAPED_VALUE
| INVERTED
| COMMENT
| PARTIAL
| EQUAL;
type TemplateSpans = Array<
| [TemplateSpanType, string, number, number]
| [TemplateSpanType, string, number, number, TemplateSpans, number]
| [TemplateSpanType, string, number, number, string, number, boolean]
>;
/**
* An array of two strings, representing the opening and closing tags respectively, to be used in the templates being rendered.
*/
type OpeningAndClosingTags = [string, string];
/**
* Whenever partials are provided, it can either be an object that contains the names and templates of partials that are used in tempaltes
*
* -- or --
*
* A function that is used to load partial template on the fly that takes a single argument: the name of the partial.
*/
type PartialsOrLookupFn = Record<string, string> | PartialLookupFn
type PartialLookupFn = (partialName: string) => string | undefined
interface TemplateCache {
set(cacheKey: string, value: string): void
get(cacheKey: string): string | undefined
clear(): void
}
/**
* Provides the functionality to render templates with `{{mustaches}}`.
*/
declare var Mustache: MustacheStatic;
export = Mustache;
export as namespace Mustache; | the_stack |
export namespace ExpectedPackage {
export type Any = ExpectedPackageMediaFile | ExpectedPackageQuantelClip
export enum PackageType {
MEDIA_FILE = 'media_file',
QUANTEL_CLIP = 'quantel_clip',
// TALLY_LABEL = 'tally_label'
// VIZ_GFX = 'viz_gfx'
}
/** Generic (used in extends) */
export interface Base {
/** Unique id of the expectedPackage */
_id: string
/** Reference to which timeline-layer(s) the Package is going to be used in.
* (Used to route the package to the right playout-device (targets))
*/
layers: string[]
/** What type of package it is */
type: PackageType
/** Definition of the content of the Package.
* With "content", we mean what's the basic definition of a package. For a media file, think "filename".
*/
content: unknown
/** Definition of the version of the Package
* A "version" is used to differ between different "modifications" for the same content. For a media file, think "modified date".
*/
version: unknown
/** Hash that changes whenever the content or version changes. */
contentVersionHash: string
/** Definition of the source-PackageContainers of the Package
* The source is used by the package manager to be able to be able to do an action on the Package. For a media file about to be copied, think "source file path".
* Multiple sources can be defined, in order of preference(?)
*/
sources: {
/** Reference to a PackageContainer */
containerId: string
/** Locally defined Accessors, these are combined (deep extended) with the PackageContainer (if it is found) Accessors */
accessors?: { [accessorId: string]: AccessorOnPackage.Any }
}[]
/** The sideEffect is used by the Package Manager to generate extra artifacts, such as thumbnails & previews */
sideEffect: {
/** Which container previews are to be put into */
previewContainerId?: string
previewPackageSettings?: SideEffectPreviewSettings
/** Which container thumbnails are to be put into */
thumbnailContainerId?: string
thumbnailPackageSettings?: SideEffectThumbnailSettings
}
}
export interface SideEffectPreviewSettings {
/** What the preview package filePath is going to be */
path: string
}
export interface SideEffectThumbnailSettings {
/** What the thumbnails package filePath is going to be */
path: string
/** What time to pick the thumbnail from [ms] */
seekTime?: number
}
export interface ExpectedPackageMediaFile extends Base {
type: PackageType.MEDIA_FILE
content: {
/** Local file path on the playout device */
filePath: string
}
version: {
fileSize?: number // in bytes
modifiedDate?: number // timestamp (ms)
checksum?: string
checkSumType?: 'sha' | 'md5' | 'whatever'
}
sources: {
containerId: string
accessors: {
[accessorId: string]:
| AccessorOnPackage.LocalFolder
| AccessorOnPackage.FileShare
| AccessorOnPackage.HTTP
}
}[]
}
export interface ExpectedPackageQuantelClip extends Base {
type: PackageType.QUANTEL_CLIP
content:
| {
guid: string
title?: string
}
| {
guid?: string
title: string
}
version: {
/** The time the clips was created */
created?: string
/** Quantel cloneId defines a clip across multiple servers */
cloneId?: number
}
sources: {
containerId: string
accessors: { [accessorId: string]: AccessorOnPackage.Quantel }
}[]
}
}
/** A PackageContainer defines a place that contains Packages, that can be read or written to.
* For example:
* A PackageContainer could be a folder on a computer that contains media files.
* That folder could be accessed locally (Accessor.LocalFolder)
* and if the folder is shared, by a Accessor.FileShare over the network
*/
export interface PackageContainer {
/** Short name, for displaying to user */
label: string
/** A list of ways to access the PackageContainer. Note: The accessors are different ways to access THE SAME PackageContainer. */
accessors: { [accessorId: string]: Accessor.Any }
}
/** Defines different ways of accessing a PackageContainer.
* For example, a local folder on a computer might be accessed through a LocalFolder and a FileShare
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace Accessor {
export type Any = LocalFolder | FileShare | HTTP | Quantel | CorePackageCollection
export enum AccessType {
LOCAL_FOLDER = 'local_folder',
FILE_SHARE = 'file_share',
HTTP = 'http',
QUANTEL = 'quantel',
CORE_PACKAGE_INFO = 'core_package_info',
}
/** Generic (used in extends) */
export interface Base {
type: AccessType
label: string
allowRead: boolean
allowWrite: boolean
}
/** Defines access to a local folder */
export interface LocalFolder extends Base {
type: AccessType.LOCAL_FOLDER
/** Name/id of the resource, this could for example be the computer name. */
resourceId?: string // todo: rename?
/** Path to the folder
* @example 'C:\media\'
*/
folderPath: string
}
export interface FileShare extends Base {
type: AccessType.FILE_SHARE
/** Name/Id of the network the share exists on. Used to differ between different local networks. */
networkId?: string
/** Path to a folder on a network-share
* @example '\\192.168.0.1\shared\'
*/
folderPath: string
userName?: string
password?: string
}
export interface HTTP extends Base {
type: AccessType.HTTP
/** Base url (url to the host), for example http://myhost.com/fileShare/ */
baseUrl: string
/** Any headers to send along with the request */
// headers?: { [name: string]: any } // Not implemented (yet)
/** Name/Id of the network the share exists on. Used to differ between different local networks. Leave empty if globally accessible. */
networkId?: string
}
export interface Quantel extends Base {
type: AccessType.QUANTEL
/** URL to a Quantel-gateway (https://github.com/nrkno/tv-automation-quantel-gateway) */
quantelGatewayUrl: string
/** Locations of the Quantel ISA:s (in order of importance) */
ISAUrls: string[]
/** Zone id, defaults to 'default' */
zoneId?: string
/** Server id. Can be omitted for sources, as clip-searches are zone-wide */
serverId?: number
/** Name/Id of the network the share exists on. Used to differ between different networks. Leave empty if globally accessible. */
networkId?: string
/** URL to a HTTP-transformer. Used for thumbnails, previews etc.. (http://hostname:port) */
transformerURL?: string
}
/** Virtual PackageContainer used for piping data into core */
export interface CorePackageCollection extends Base {
type: Accessor.AccessType.CORE_PACKAGE_INFO
// empty
}
}
/**
* AccessorOnPackage contains interfaces for Accessor definitions that are put ON the Package.
* The info is then (optionally) combined with the Accessor data
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace AccessorOnPackage {
export type Any = LocalFolder | FileShare | HTTP | Quantel | CorePackageCollection
export interface LocalFolder extends Partial<Accessor.LocalFolder> {
/** Path to the file (starting from .folderPath). If not set, the filePath of the ExpectedPackage will be used */
filePath?: string
}
export interface FileShare extends Partial<Accessor.FileShare> {
/** Path to the file (starting from .folderPath). If not set, the filePath of the ExpectedPackage will be used */
filePath?: string
}
export interface HTTP extends Partial<Accessor.HTTP> {
/** URL path to resource (combined with .baseUrl gives the full URL), for example: /folder/myFile */
url?: string
}
export interface Quantel extends Partial<Accessor.Quantel> {
guid?: string
title?: string
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CorePackageCollection extends Partial<Accessor.CorePackageCollection> {
// empty
}
}
export interface PackageContainerOnPackage extends Omit<PackageContainer, 'accessors'> {
containerId: string
/** Short name, for displaying to user */
label: string
accessors: { [accessorId: string]: AccessorOnPackage.Any }
}
// todo: should this be moved into core-integration?
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace ExpectedPackageStatusAPI {
/** Information about the status of some work being performed with regards to an Expected Package */
export interface WorkStatus extends WorkBaseInfo, WorkStatusInfo {}
export interface WorkBaseInfo {
/** Which packages the WorkStatus belongs to */
fromPackages: WorkBaseInfoFromPackage[]
/** Short Display label */
label: string
/** Longer expanation on what the Expectation does */
description: string
/** Used in status GUI to order the Expecations within the same packageId. */
displayRank?: number
/** If the expectation is required to be fullfilled for playout */
requiredForPlayout?: boolean
}
export interface WorkBaseInfoFromPackage {
/** Reference to the id of the Package */
id: string
/** Reference to the contentVersionHash of the ExpectedPackage, used to reference the expected content+version of the Package */
expectedContentVersionHash: string
/** Referring to the actual contentVersionHash of the Package, used to reference the exact content+version of the Package */
actualContentVersionHash: string
}
/** The stat */
export interface WorkStatusInfo {
/** Short description on what the current status is. Example "working", "fulfilled" */
status: string
/** Longer reason as to why the status is what it is */
statusReason: string
/** Progress, 0-1 */
progress?: number
/** Calculated time left of this step */
expectedLeft?: number
}
/** Describes the status of a Package in a PackageContainer */
export interface PackageContainerPackageStatus extends Omit<WorkStatusInfo, 'status'> {
status: PackageContainerPackageStatusStatus
/** Indicates that the Package is a Placeholder / Is NOT ready to be played out */
isPlaceholder: boolean
contentVersionHash: string
/* Progress (0-1), used when status = TRANSFERRING_* */
progress: number
/** Calculated time left, used when status = TRANSFERRING_* */
expectedLeft?: number
/** Longer reason as to why the status is what it is */
statusReason: string
}
export enum PackageContainerPackageStatusStatus {
/** The Package source isn't found at all */
NOT_FOUND = 'not_found',
/** The Package source is found, but not able to be transferred */
NOT_READY = 'not_ready',
/** The Package is currently transferring, but can be played out */
TRANSFERRING_READY = 'transferring_ready',
/** The Package is currently transferring, and is not ready to be played out */
TRANSFERRING_NOT_READY = 'transferring_not_ready',
/** All good, the package is in place and ready to play*/
READY = 'ready',
}
}
export interface ListenToPackageUpdate {
/** Same type of _id as in expectedPackages */
packageId: string
} | the_stack |
import { Placement } from "../../src";
import {
render,
cleanup,
PLACEMENTS_NO_CENTER,
ExpectBoundsProps,
fixViewport
} from "./util";
before(fixViewport);
describe("e2e/overflow-container", () => {
afterEach(cleanup);
it("tracks the triggers position while overflowing the container", async () => {
const tools = render();
// open the layer
tools.clickTrigger();
/**
* ----------------------
* | |
* | layer |
* | |
* ----------------------
*
* -----------
* | trigger |
* -----------
*/
await tools.expectBounds({
layerSide: "top",
layer: {
top: 173,
left: 580,
bottom: 413,
right: 820,
width: 240,
height: 240
},
arrow: {
top: 413,
left: 692,
bottom: 429,
right: 708,
width: 16,
height: 16
}
});
// scroll 100px to bottom
tools.scrollContainer(800, 700);
/**
* ----------------------
* | |
* | layer |
* | |
* ----------------------
*
* -----------
* | trigger |
* -----------
*/
await tools.expectBounds({
layerSide: "top",
layer: {
top: 73,
left: 580,
bottom: 313,
right: 820,
width: 240,
height: 240
},
arrow: {
top: 313,
left: 692,
bottom: 329,
right: 708,
width: 16,
height: 16
}
});
});
it("tracks the triggers position while overflowing the container and adjusts automatically", async () => {
const tools = render({ auto: true });
// open the layer
tools.clickTrigger();
// scroll to bottom so that "top" fits exacly within window
tools.scrollContainer(857, 700);
/**
* ----------------------
* | |
* | layer |
* | |
* ----------------------
*
* -----------
* | trigger |
* -----------
*/
await tools.expectBounds({
layerSide: "top",
layer: {
top: 16,
left: 580,
bottom: 256,
right: 820,
width: 240,
height: 240
},
arrow: {
top: 256,
left: 692,
bottom: 272,
right: 708,
width: 16,
height: 16
}
});
// scroll a little bit futher so that layer jumps to another placement
tools.scrollContainer(858, 700);
/**
*
*
*
*
* ----------------------
* | |
* ----------- | layer |
* | trigger | | |
* ----------- ----------------------
*/
await tools.expectBounds({
layerSide: "right",
layer: {
top: 77,
left: 762,
bottom: 317,
right: 1002,
width: 240,
height: 240
},
arrow: {
top: 284,
left: 746,
bottom: 300,
right: 762,
width: 16,
height: 16
}
});
});
it("positions the right placements", async () => {
const tools = render({ placement: "bottom-center" });
tools.clickTrigger();
const expectedBounds: Record<
Exclude<Placement, "center">,
ExpectBoundsProps
> = {
"top-start": {
layerSide: "top",
layer: {
top: 173,
left: 650,
bottom: 413,
right: 890,
width: 240,
height: 240
},
arrow: {
top: 413,
left: 692,
bottom: 429,
right: 708,
width: 16,
height: 16
}
},
"top-center": {
layerSide: "top",
layer: {
top: 173,
left: 580,
bottom: 413,
right: 820,
width: 240,
height: 240
},
arrow: {
top: 413,
left: 692,
bottom: 429,
right: 708,
width: 16,
height: 16
}
},
"top-end": {
layerSide: "top",
layer: {
top: 173,
left: 510,
bottom: 413,
right: 750,
width: 240,
height: 240
},
arrow: {
top: 413,
left: 692,
bottom: 429,
right: 708,
width: 16,
height: 16
}
},
"left-start": {
layerSide: "left",
layer: {
top: 425,
left: 398,
bottom: 665,
right: 638,
width: 240,
height: 240
},
arrow: {
top: 442,
left: 638,
bottom: 458,
right: 654,
width: 16,
height: 16
}
},
"left-center": {
layerSide: "left",
layer: {
top: 330,
left: 398,
bottom: 570,
right: 638,
width: 240,
height: 240
},
arrow: {
top: 442,
left: 638,
bottom: 458,
right: 654,
width: 16,
height: 16
}
},
"left-end": {
layerSide: "left",
layer: {
top: 235,
left: 398,
bottom: 475,
right: 638,
width: 240,
height: 240
},
arrow: {
top: 442,
left: 638,
bottom: 458,
right: 654,
width: 16,
height: 16
}
},
"right-start": {
layerSide: "right",
layer: {
top: 425,
left: 762,
bottom: 665,
right: 1002,
width: 240,
height: 240
},
arrow: {
top: 442,
left: 746,
bottom: 458,
right: 762,
width: 16,
height: 16
}
},
"right-center": {
layerSide: "right",
layer: {
top: 330,
left: 762,
bottom: 570,
right: 1002,
width: 240,
height: 240
},
arrow: {
top: 442,
left: 746,
bottom: 458,
right: 762,
width: 16,
height: 16
}
},
"right-end": {
layerSide: "right",
layer: {
top: 235,
left: 762,
bottom: 475,
right: 1002,
width: 240,
height: 240
},
arrow: {
top: 442,
left: 746,
bottom: 458,
right: 762,
width: 16,
height: 16
}
},
"bottom-start": {
layerSide: "bottom",
layer: {
top: 487,
left: 650,
bottom: 727,
right: 890,
width: 240,
height: 240
},
arrow: {
top: 471,
left: 692,
bottom: 487,
right: 708,
width: 16,
height: 16
}
},
"bottom-center": {
layerSide: "bottom",
layer: {
top: 487,
left: 580,
bottom: 727,
right: 820,
width: 240,
height: 240
},
arrow: {
top: 471,
left: 692,
bottom: 487,
right: 708,
width: 16,
height: 16
}
},
"bottom-end": {
layerSide: "bottom",
layer: {
top: 487,
left: 510,
bottom: 727,
right: 750,
width: 240,
height: 240
},
arrow: {
top: 471,
left: 692,
bottom: 487,
right: 708,
width: 16,
height: 16
}
}
};
for (const placement of PLACEMENTS_NO_CENTER) {
tools.reRender({ placement });
await tools.expectBounds(expectedBounds[placement]);
}
});
it("positions the right placements when trigger is bigger", async () => {
const tools = render({ placement: "bottom-center", triggerIsBigger: true });
tools.clickTrigger();
const expectedBounds: Record<
Exclude<Placement, "center">,
ExpectBoundsProps
> = {
"top-start": {
layerSide: "top",
layer: {
top: 268,
left: 580,
bottom: 318,
right: 680,
width: 100,
height: 50
},
arrow: {
top: 318,
left: 622,
bottom: 334,
right: 638,
width: 16,
height: 16
}
},
"top-center": {
layerSide: "top",
layer: {
top: 268,
left: 650,
bottom: 318,
right: 750,
width: 100,
height: 50
},
arrow: {
top: 318,
left: 692,
bottom: 334,
right: 708,
width: 16,
height: 16
}
},
"top-end": {
layerSide: "top",
layer: {
top: 268,
left: 720,
bottom: 318,
right: 820,
width: 100,
height: 50
},
arrow: {
top: 318,
left: 762,
bottom: 334,
right: 778,
width: 16,
height: 16
}
},
"left-start": {
layerSide: "left",
layer: {
top: 330,
left: 468,
bottom: 380,
right: 568,
width: 100,
height: 50
},
arrow: {
top: 347,
left: 568,
bottom: 363,
right: 584,
width: 16,
height: 16
}
},
"left-center": {
layerSide: "left",
layer: {
top: 425,
left: 468,
bottom: 475,
right: 568,
width: 100,
height: 50
},
arrow: {
top: 442,
left: 568,
bottom: 458,
right: 584,
width: 16,
height: 16
}
},
"left-end": {
layerSide: "left",
layer: {
top: 520,
left: 468,
bottom: 570,
right: 568,
width: 100,
height: 50
},
arrow: {
top: 537,
left: 568,
bottom: 553,
right: 584,
width: 16,
height: 16
}
},
"right-start": {
layerSide: "right",
layer: {
top: 330,
left: 832,
bottom: 380,
right: 932,
width: 100,
height: 50
},
arrow: {
top: 347,
left: 816,
bottom: 363,
right: 832,
width: 16,
height: 16
}
},
"right-center": {
layerSide: "right",
layer: {
top: 425,
left: 832,
bottom: 475,
right: 932,
width: 100,
height: 50
},
arrow: {
top: 442,
left: 816,
bottom: 458,
right: 832,
width: 16,
height: 16
}
},
"right-end": {
layerSide: "right",
layer: {
top: 520,
left: 832,
bottom: 570,
right: 932,
width: 100,
height: 50
},
arrow: {
top: 537,
left: 816,
bottom: 553,
right: 832,
width: 16,
height: 16
}
},
"bottom-start": {
layerSide: "bottom",
layer: {
top: 582,
left: 580,
bottom: 632,
right: 680,
width: 100,
height: 50
},
arrow: {
top: 566,
left: 622,
bottom: 582,
right: 638,
width: 16,
height: 16
}
},
"bottom-center": {
layerSide: "bottom",
layer: {
top: 582,
left: 650,
bottom: 632,
right: 750,
width: 100,
height: 50
},
arrow: {
top: 566,
left: 692,
bottom: 582,
right: 708,
width: 16,
height: 16
}
},
"bottom-end": {
layerSide: "bottom",
layer: {
top: 582,
left: 720,
bottom: 632,
right: 820,
width: 100,
height: 50
},
arrow: {
top: 566,
left: 762,
bottom: 582,
right: 778,
width: 16,
height: 16
}
}
};
for (const placement of PLACEMENTS_NO_CENTER) {
tools.reRender({ placement, triggerIsBigger: true });
await tools.expectBounds(expectedBounds[placement]);
}
});
});
// const expectedBounds: Record<
// Exclude<Placement, "center">,
// ExpectBoundsProps
// > = {
// "top-start": ,
// "top-center": ,
// "top-end": ,
// "left-start": ,
// "left-center": ,
// "left-end": ,
// "right-start": ,
// "right-center": ,
// "right-end": ,
// "bottom-start": ,
// "bottom-center": ,
// "bottom-end":
// }; | the_stack |
import arrify = require('arrify');
import {Key} from 'readline';
import {Datastore} from '.';
import {Entity} from './entity';
import {Transaction} from './transaction';
import {CallOptions} from 'google-gax';
import {RunQueryStreamOptions} from '../src/request';
export type Operator = '=' | '<' | '>' | '<=' | '>=' | 'HAS_ANCESTOR';
export interface OrderOptions {
descending?: boolean;
}
export interface Order {
name: string;
sign: '-' | '+';
}
export interface Filter {
name: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
val: any;
op: Operator;
}
/**
* Build a Query object.
*
* **Queries are built with {module:datastore#createQuery} and
* {@link Transaction#createQuery}.**
*
* @see {@link http://goo.gl/Cag0r6| Datastore Queries}
*
* @class
* @param {Datastore|Transaction} scope The parent scope the query was created
* from.
* @param {string} [namespace] Namespace to query entities from.
* @param {string[]} kinds Kind to query.
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const query = datastore.createQuery('AnimalNamespace', 'Lion');
*/
class Query {
scope?: Datastore | Transaction;
namespace?: string | null;
kinds: string[];
filters: Filter[];
orders: Order[];
groupByVal: Array<{}>;
selectVal: Array<{}>;
startVal: string | Buffer | null;
endVal: string | Buffer | null;
limitVal: number;
offsetVal: number;
constructor(scope?: Datastore | Transaction, kinds?: string[] | null);
constructor(
scope?: Datastore | Transaction,
namespace?: string | null,
kinds?: string[]
);
constructor(
scope?: Datastore | Transaction,
namespaceOrKinds?: string | string[] | null,
kinds?: string[]
) {
let namespace = namespaceOrKinds as string | null;
if (!kinds) {
kinds = namespaceOrKinds as string[];
namespace = null;
}
/**
* @name Query#scope
* @type {Datastore|Transaction}
*/
this.scope = scope;
/**
* @name Query#namespace
* @type {?string}
*/
this.namespace = namespace || null;
/**
* @name Query#kinds
* @type {string}
*/
this.kinds = kinds;
/**
* @name Query#filters
* @type {array}
*/
this.filters = [];
/**
* @name Query#orders
* @type {array}
*/
this.orders = [];
/**
* @name Query#groupByVal
* @type {array}
*/
this.groupByVal = [];
/**
* @name Query#selectVal
* @type {array}
*/
this.selectVal = [];
// pagination
/**
* @name Query#startVal
* @type {?number}
*/
this.startVal = null;
/**
* @name Query#endVal
* @type {?number}
*/
this.endVal = null;
/**
* @name Query#limitVal
* @type {number}
*/
this.limitVal = -1;
/**
* @name Query#offsetVal
* @type {number}
*/
this.offsetVal = -1;
}
filter(property: string, value: {}): Query;
filter(property: string, operator: Operator, value: {}): Query;
/**
* Datastore allows querying on properties. Supported comparison operators
* are `=`, `<`, `>`, `<=`, and `>=`. "Not equal" and `IN` operators are
* currently not supported.
*
* *To filter by ancestors, see {module:datastore/query#hasAncestor}.*
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-property-filter-nodejs| Datastore Filters}
*
* @param {string} property The field name.
* @param {string} [operator="="] Operator (=, <, >, <=, >=).
* @param {*} value Value to compare property to.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const query = datastore.createQuery('Company');
*
* //-
* // List all companies that are located in California.
* //-
* const caliQuery = query.filter('state', 'CA');
*
* //-
* // List all companies named Google that have less than 400 employees.
* //-
* const companyQuery = query
* .filter('name', 'Google')
* .filter('size', '<', 400);
*
* //-
* // To filter by key, use `__key__` for the property name. Filter on keys
* // stored as properties is not currently supported.
* //-
* const key = datastore.key(['Company', 'Google']);
* const keyQuery = query.filter('__key__', key);
*/
filter(property: string, operatorOrValue: Operator, value?: {}): Query {
let operator = operatorOrValue as Operator;
if (arguments.length === 2) {
value = operatorOrValue as {};
operator = '=';
}
this.filters.push({
name: property.trim(),
op: operator.trim() as Operator,
val: value,
});
return this;
}
/**
* Filter a query by ancestors.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-ancestor-query-nodejs| Datastore Ancestor Filters}
*
* @param {Key} key Key object to filter by.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const query = datastore.createQuery('MyKind');
* const ancestoryQuery = query.hasAncestor(datastore.key(['Parent', 123]));
*/
hasAncestor(key: Key) {
this.filters.push({name: '__key__', op: 'HAS_ANCESTOR', val: key});
return this;
}
/**
* Sort the results by a property name in ascending or descending order. By
* default, an ascending sort order will be used.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-ascending-sort-nodejs| Datastore Sort Orders}
*
* @param {string} property The property to order by.
* @param {object} [options] Options object.
* @param {boolean} [options.descending=false] Sort the results by a property
* name in descending order.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const companyQuery = datastore.createQuery('Company');
*
* // Sort by size ascendingly.
* const companiesAscending = companyQuery.order('size');
*
* // Sort by size descendingly.
* const companiesDescending = companyQuery.order('size', {
* descending: true
* });
*/
order(property: string, options?: OrderOptions) {
const sign = options && options.descending ? '-' : '+';
this.orders.push({name: property, sign});
return this;
}
/**
* Group query results by a list of properties.
*
* @param {array} properties Properties to group by.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const companyQuery = datastore.createQuery('Company');
* const groupedQuery = companyQuery.groupBy(['name', 'size']);
*/
groupBy(fieldNames: string | string[]) {
this.groupByVal = arrify(fieldNames);
return this;
}
/**
* Retrieve only select properties from the matched entities.
*
* Queries that select a subset of properties are called Projection Queries.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/projectionqueries| Projection Queries}
*
* @param {string|string[]} fieldNames Properties to return from the matched
* entities.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const companyQuery = datastore.createQuery('Company');
*
* // Only retrieve the name property.
* const selectQuery = companyQuery.select('name');
*
* // Only retrieve the name and size properties.
* const selectQuery = companyQuery.select(['name', 'size']);
*/
select(fieldNames: string | string[]) {
this.selectVal = arrify(fieldNames);
return this;
}
/**
* Set a starting cursor to a query.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#cursors_limits_and_offsets| Query Cursors}
*
* @param {string} cursorToken The starting cursor token.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const companyQuery = datastore.createQuery('Company');
*
* const cursorToken = 'X';
*
* // Retrieve results starting from cursorToken.
* const startQuery = companyQuery.start(cursorToken);
*/
start(start: string | Buffer) {
this.startVal = start;
return this;
}
/**
* Set an ending cursor to a query.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#Datastore_Query_cursors| Query Cursors}
*
* @param {string} cursorToken The ending cursor token.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const companyQuery = datastore.createQuery('Company');
*
* const cursorToken = 'X';
*
* // Retrieve results limited to the extent of cursorToken.
* const endQuery = companyQuery.end(cursorToken);
*/
end(end: string | Buffer) {
this.endVal = end;
return this;
}
/**
* Set a limit on a query.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-limit-nodejs| Query Limits}
*
* @param {number} n The number of results to limit the query to.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const companyQuery = datastore.createQuery('Company');
*
* // Limit the results to 10 entities.
* const limitQuery = companyQuery.limit(10);
*/
limit(n: number) {
this.limitVal = n;
return this;
}
/**
* Set an offset on a query.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-limit-nodejs| Query Offsets}
*
* @param {number} n The offset to start from after the start cursor.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const companyQuery = datastore.createQuery('Company');
*
* // Start from the 101st result.
* const offsetQuery = companyQuery.offset(100);
*/
offset(n: number) {
this.offsetVal = n;
return this;
}
run(options?: RunQueryOptions): Promise<RunQueryResponse>;
run(options: RunQueryOptions, callback: RunQueryCallback): void;
run(callback: RunQueryCallback): void;
/**
* Run the query.
*
* @param {object} [options] Optional configuration.
* @param {string} [options.consistency] Specify either `strong` or `eventual`.
* If not specified, default values are chosen by Datastore for the
* operation. Learn more about strong and eventual consistency
* [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).
* @param {object} [options.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {boolean | IntegerTypeCastOptions} [options.wrapNumbers=false]
* Wrap values of integerValue type in {@link Datastore#Int} objects.
* If a `boolean`, this will wrap values in {@link Datastore#Int} objects.
* If an `object`, this will return a value returned by
* `wrapNumbers.integerTypeCastFunction`.
* Please see {@link IntegerTypeCastOptions} for options descriptions.
* @param {function} [callback] The callback function. If omitted, a readable
* stream instance is returned.
* @param {?error} callback.err An error returned while making this request
* @param {object[]} callback.entities A list of entities.
* @param {object} callback.info An object useful for pagination.
* @param {?string} callback.info.endCursor Use this in a follow-up query to
* begin from where these results ended.
* @param {string} callback.info.moreResults Datastore responds with one of:
*
* - {@link Datastore#MORE_RESULTS_AFTER_LIMIT}: There *may* be more
* results after the specified limit.
* - {@link Datastore#MORE_RESULTS_AFTER_CURSOR}: There *may* be more
* results after the specified end cursor.
* - {@link Datastore#NO_MORE_RESULTS}: There are no more results.
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const query = datastore.createQuery('Company');
*
* query.run((err, entities, info) => {
* // entities = An array of records.
*
* // Access the Key object for an entity.
* const firstEntityKey = entities[0][datastore.KEY];
* });
*
* //-
* // A keys-only query returns just the keys of the result entities instead
* of
* // the entities themselves, at lower latency and cost.
* //-
* query.select('__key__');
*
* query.run((err, entities) => {
* const keys = entities.map((entity) => {
* return entity[datastore.KEY];
* });
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* query.run().then((data) => {
* const entities = data[0];
* });
*/
run(
optionsOrCallback?: RunQueryOptions | RunQueryCallback,
cb?: RunQueryCallback
): void | Promise<RunQueryResponse> {
const options =
typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
const callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!;
const runQuery = this.scope!.runQuery.bind(this.scope);
return runQuery(this, options, callback);
}
/**
* Run the query as a readable object stream.
*
* @method Query#runStream
* @param {object} [options] Optional configuration. See
* {@link Query#run} for a complete list of options.
* @returns {stream}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const query = datastore.createQuery('Company');
*
* query.runStream()
* .on('error', console.error)
* .on('data', function (entity) {
* // Access the Key object for this entity.
* const key = entity[datastore.KEY];
* })
* .on('info', (info) => {})
* .on('end', () => {
* // All entities retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* query.runStream()
* .on('data', function (entity) {
* this.end();
* });
*/
runStream(options?: RunQueryStreamOptions) {
return this.scope!.runQueryStream(this, options);
}
}
export interface QueryProto {
startCursor?: string | Buffer;
distinctOn: {};
kind: {};
order: {};
projection: {};
endCursor?: string | Buffer;
limit?: {};
offset?: number;
filter?: {};
}
/**
* Reference to the {@link Query} class.
* @name module:@google-cloud/datastore.Query
* @see Query
*/
export {Query};
export interface IntegerTypeCastOptions {
integerTypeCastFunction: Function;
properties?: string | string[];
}
export interface RunQueryOptions {
consistency?: 'strong' | 'eventual';
gaxOptions?: CallOptions;
wrapNumbers?: boolean | IntegerTypeCastOptions;
}
export interface RunQueryCallback {
(err: Error | null, entities?: Entity[], info?: RunQueryInfo): void;
}
export type RunQueryResponse = [Entity[], RunQueryInfo];
export interface RunQueryInfo {
endCursor?: string;
moreResults?:
| 'MORE_RESULTS_TYPE_UNSPECIFIED'
| 'NOT_FINISHED'
| 'MORE_RESULTS_AFTER_LIMIT'
| 'MORE_RESULTS_AFTER_CURSOR'
| 'NO_MORE_RESULTS';
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.