text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { createElement, L10n } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { BackgroundModel } from '../../../src/diagram/diagram/page-settings-model'; import { DiagramModel, ConnectorModel, NodeModel } from '../../../src/diagram/index'; import { MouseEvents } from '../interaction/mouseevents.spec'; import { MenuItemModel, MenuEventArgs } from '@syncfusion/ej2-navigations'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; ; /** * Page Background  */ describe('Diagram Control', () => { describe('Background', () => { let diagram: Diagram; let ele: HTMLElement; 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: 'diagrama' }); document.body.appendChild(ele); diagram = new Diagram({ width: '1000px', height: '600px', } as DiagramModel); diagram.appendTo('#diagrama'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram without background', (done: Function) => { diagram.getPersistData(); done(); }); }); describe('Background', () => { let diagram: Diagram; let ele: HTMLElement; 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: 'diagramb' }); document.body.appendChild(ele); let background: BackgroundModel = { source: 'base/spec/images/bike.jpg' }; diagram = new Diagram({ width: '1000px', height: '600px', pageSettings: { background: background } } as DiagramModel); diagram.appendTo('#diagramb'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking with background image', (done: Function) => { done(); }); }); describe('Text element white space and break word property', () => { let diagram: Diagram; let ele: HTMLElement; 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: 'diagramc' }); document.body.appendChild(ele); let background: BackgroundModel = { color: 'red' }; diagram = new Diagram({ width: '1000px', height: '600px', pageSettings: { background: background } } as DiagramModel); diagram.appendTo('#diagramc'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking wiht background color', (done: Function) => { done(); }); }); describe('Diagram checking localization', () => { let node1: NodeModel = { id: 'NewIdea', width: 100, height: 100, offsetX: 300, offsetY: 60, shape: { type: 'Flow', shape: 'Terminator' }, annotations: [{ id: 'label1', content: 'New idea identified', offset: { x: 0.5, y: 0.5 } }] }; let node2: NodeModel = { id: 'Meeting', width: 150, height: 60, offsetX: 300, offsetY: 155, shape: { type: 'Flow', shape: 'Process' }, annotations: [{ id: 'label2', content: 'Meeting with board', offset: { x: 0.5, y: 0.5 } }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Straight', sourceID: 'NewIdea', targetID: 'Meeting' }; L10n.load({ 'de-DE': { 'diagram': { Cut: 'Corte', Copy: 'Copia', Paste: 'Pasta', Undo: 'Deshacer', Redo: 'Rehacer', SelectAll: 'Seleccionar todo', Grouping: 'Agrupación', Group: 'Grupo', Ungroup: 'Desagrupar', Order: 'Fin', BringToFront: 'Traer a delante', MoveForward: 'Movimiento adelante', SendToBack: 'Enviar a espalda', SendBackward: 'Enviar hacia atrás' }, } }); let diagram: Diagram; let ele: HTMLElement; let mouseEvents: MouseEvents = new MouseEvents(); 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: 'diagramdraw' }); document.body.appendChild(ele); diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node1, node2], connectors: [connector1], locale: 'de-DE', contextMenuSettings: { show: true }, }); diagram.appendTo('#diagramdraw'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('check Context Menu - localization', (done: Function) => { let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.clickEvent(diagramCanvas, 350, 110); (diagram.contextMenuModule as any).eventArgs = { target: document.getElementById('diagramdraw_diagramAdorner_svg') }; let e = { event: (diagram.contextMenuModule as any).eventArgs, items: diagram.contextMenuModule.contextMenu.items as MenuItemModel[], }; expect((diagram.contextMenuModule as any).element).not.toBe(null); expect((diagram.contextMenuModule as any).element.id).toBe(diagram.element.id + '_contextMenu'); expect(diagram.contextMenuModule.contextMenu.locale).toBe(diagram.locale); expect(diagram.contextMenuModule.contextMenu.items[0].text).toBe('Copia'); (diagram.contextMenuModule as any).contextMenuOpen(); (diagram.contextMenuModule as any).contextMenuOnClose(e); diagram.clearSelection(); done(); }); }); describe('Diagram checking Context menu template ', () => { let node1: NodeModel = { id: 'NewIdea', width: 100, height: 100, offsetX: 300, offsetY: 60, shape: { type: 'Flow', shape: 'Terminator' }, annotations: [{ id: 'label1', content: 'New idea identified', offset: { x: 0.5, y: 0.5 } }] }; let node2: NodeModel = { id: 'Meeting', width: 150, height: 60, offsetX: 300, offsetY: 155, shape: { type: 'Flow', shape: 'Process' }, annotations: [{ id: 'label2', content: 'Meeting with board', offset: { x: 0.5, y: 0.5 } }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Straight', sourceID: 'NewIdea', targetID: 'Meeting' }; let diagram: Diagram; let ele: HTMLElement; let mouseEvents: MouseEvents = new MouseEvents(); 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: 'diagramdraw' }); document.body.appendChild(ele); diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node1, node2], connectors: [connector1], contextMenuSettings: { show: true, items: [{ text: 'Cut', id: 'Cut', target: '.e-diagramcontent', iconCss: 'e-Cut' }, { text: 'Copy', id: 'Copy', target: '.e-diagramcontent', iconCss: 'e-Copy' }], showCustomMenuOnly: true, }, contextMenuBeforeItemRender: (args: MenuEventArgs) => { // To render template in li. let shortCutSpan: HTMLElement = createElement('span'); let text: string = args.item.text; let shortCutText: string = text === 'Cut' ? 'Ctrl + S' : (text === 'Copy' ? 'Ctrl + U' : 'Ctrl + Shift + I'); shortCutSpan.textContent = shortCutText; args.element.appendChild(shortCutSpan); shortCutSpan.setAttribute('class', 'shortcut'); } }); diagram.appendTo('#diagramdraw'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); 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
import renderer from 'react-test-renderer'; import React from 'react'; import { createElement } from 'react'; import '../utils/react-env-init'; import { leafWrapper } from '../../src/hoc/leaf'; import components from '../utils/components'; import Node from '../utils/node'; let rerenderCount = 0; const nodeMap = new Map(); const makeSnapshot = (component) => { let tree = component.toJSON(); expect(tree).toMatchSnapshot(); } const baseRenderer: any = { __debug () {}, __getComponentProps (schema: any) { return schema.props; }, __getSchemaChildrenVirtualDom (schema: any) { return schema.children; }, context: { engine: { createElement, } }, props: { __host: {}, getNode: (id) => nodeMap.get(id), __container: { rerender: () => { rerenderCount = 1 + rerenderCount; } }, documentId: '01' } } let Div, DivNode, Text, TextNode, component, textSchema, divSchema; let id = 0; beforeEach(() => { textSchema = { id: 'text' + id, props: { content: 'content' }, }; divSchema = { id: 'div' + id, }; id++; Div = leafWrapper(components.Div as any, { schema: divSchema, baseRenderer, componentInfo: {}, scope: {}, }); DivNode = new Node(divSchema); TextNode = new Node(textSchema); nodeMap.set(divSchema.id, DivNode); nodeMap.set(textSchema.id, TextNode); Text = leafWrapper(components.Text as any, { schema: textSchema, baseRenderer, componentInfo: {}, scope: {}, }); component = renderer.create( // @ts-ignore <Div _leaf={DivNode}> <Text _leaf={TextNode} content="content"></Text> </Div> ); }); afterEach(() => { component.unmount(component); }); describe('onPropChange', () => { it('change textNode [key:content] props', () => { TextNode.emitPropChange({ key: 'content', newValue: 'new content', } as any); const root = component.root; expect(root.findByType(components.Text).props.content).toEqual('new content') }); it('change textNode [key:___condition___] props, hide textNode component', () => { // mock leaf?.export result TextNode.schema.condition = false; TextNode.emitPropChange({ key: '___condition___', newValue: false, } as any); makeSnapshot(component); }); it('change textNode [key:___condition___] props, but not hidden component', () => { TextNode.schema.condition = true; TextNode.emitPropChange({ key: '___condition___', newValue: false, } as any); makeSnapshot(component); }); it('change textNode [key:content], content in this.props but not in leaf.export result', () => { makeSnapshot(component); delete TextNode.schema.props.content; TextNode.emitPropChange({ key: 'content', newValue: null, } as any, true); makeSnapshot(component); const root = component.root; const TextInst = root.findByType(components.Text); expect(TextInst.props.content).toBeNull(); }); it('change textNode [key:___loop___], make rerender', () => { expect(leafWrapper(components.Text as any, { schema: textSchema, baseRenderer, componentInfo: {}, scope: {}, })).toEqual(Text); const nextRerenderCount = rerenderCount + 1; TextNode.emitPropChange({ key: '___loop___', newValue: 'new content', } as any); expect(rerenderCount).toBe(nextRerenderCount); expect(leafWrapper(components.Text as any, { schema: textSchema, baseRenderer, componentInfo: {}, scope: {}, })).not.toEqual(Text); }); }); describe('lifecycle', () => { it('props change and make componentWillReceiveProps', () => { makeSnapshot(component); // 没有 __tag 标识 component.update(( <Div _leaf={DivNode}> <Text _leaf={TextNode} content="content 123"></Text> </Div> )); makeSnapshot(component); // 有 __tag 标识 component.update(( <Div _leaf={DivNode}> <Text _leaf={TextNode} __tag="111" content="content 123"></Text> </Div> )); makeSnapshot(component); }); it('leaf change and make componentWillReceiveProps', () => { const newTextNodeLeaf = new Node(textSchema); component.update(( <Div _leaf={DivNode}> <Text _leaf={newTextNodeLeaf} __tag="222" content="content 123"></Text> </Div> )); newTextNodeLeaf.emitPropChange({ key: 'content', newValue: 'content new leaf', }); makeSnapshot(component); }); }); describe('mini unit render', () => { let miniRenderSchema, MiniRenderDiv, MiniRenderDivNode; beforeEach(() => { miniRenderSchema = { id: 'miniDiv' + id, }; MiniRenderDiv = leafWrapper(components.MiniRenderDiv as any, { schema: miniRenderSchema, baseRenderer, componentInfo: {}, scope: {}, }); MiniRenderDivNode = new Node(miniRenderSchema, { componentMeta: { isMinimalRenderUnit: true, }, }); TextNode = new Node(textSchema, { parent: MiniRenderDivNode, }); component = renderer.create( // @ts-ignore <MiniRenderDiv _leaf={MiniRenderDivNode}> <Text _leaf={TextNode} content="content"></Text> </MiniRenderDiv> ); }) it('make text props change', () => { if (!MiniRenderDivNode.schema.props) { MiniRenderDivNode.schema.props = {}; } MiniRenderDivNode.schema.props['newPropKey'] = 'newPropValue'; makeSnapshot(component); const inst = component.root; const TextInst = inst.findByType(Text).children[0]; TextNode.emitPropChange({ key: 'content', newValue: 'new content', } as any); expect((TextInst as any)?._fiber.stateNode.renderUnitInfo).toEqual({ singleRender: false, minimalUnitId: 'miniDiv' + id, minimalUnitName: undefined, }); makeSnapshot(component); }); it('dont render mini render component', () => { const TextNode = new Node(textSchema, { parent: new Node({ id: 'random', }, { componentMeta: { isMinimalRenderUnit: true, }, }), }); renderer.create( // @ts-ignore <div> <Text _leaf={TextNode} content="content"></Text> </div> ); const nextCount = rerenderCount + 1; TextNode.emitPropChange({ key: 'content', newValue: 'new content', } as any); expect(rerenderCount).toBe(nextCount); }); it('leaf is a mock function', () => { const TextNode = new Node(textSchema, { parent: { isEmpty: () => false, } }); renderer.create( // @ts-ignore <div> <Text _leaf={TextNode} content="content"></Text> </div> ); TextNode.emitPropChange({ key: 'content', newValue: 'new content', } as any); }); it('change component leaf isRoot is true', () => { const TextNode = new Node(textSchema, { isRoot: true, }); const component = renderer.create( <Text _leaf={TextNode} content="content"></Text> ); const inst = component.root; TextNode.emitPropChange({ key: 'content', newValue: 'new content', } as any); expect((inst.children[0] as any)?._fiber.stateNode.renderUnitInfo).toEqual({ singleRender: true, }); }); it('change component leaf parent isRoot is true', () => { const TextNode = new Node(textSchema, { parent: new Node({ id: 'first-parent', }, { componentMeta: { isMinimalRenderUnit: true, }, parent: new Node({ id: 'rootId', }, { isRoot: true, }), }) }); const component = renderer.create( <Text _leaf={TextNode} content="content"></Text> ); const inst = component.root; TextNode.emitPropChange({ key: 'content', newValue: 'new content', } as any); expect((inst.children[0] as any)?._fiber.stateNode.renderUnitInfo).toEqual({ singleRender: false, minimalUnitId: 'first-parent', minimalUnitName: undefined, }); }); it('parent is a mock leaf', () => { const MiniRenderDivNode = {}; const component = renderer.create( // @ts-ignore <MiniRenderDiv _leaf={MiniRenderDivNode}> <Text _leaf={TextNode} content="content"></Text> </MiniRenderDiv> ); TextNode.emitPropChange({ key: 'content', newValue: 'new content to mock', } as any); makeSnapshot(component); }); it('props has new children', () => { MiniRenderDivNode.schema.props.children = [ 'children 01', 'children 02', ]; TextNode.emitPropChange({ key: 'content', newValue: 'props' }); makeSnapshot(component); }); it('leaf has a loop, render from parent', () => { MiniRenderDivNode = new Node(miniRenderSchema, {}); TextNode = new Node(textSchema, { parent: MiniRenderDivNode, hasLoop: true, }); component = renderer.create( // @ts-ignore <MiniRenderDiv _leaf={MiniRenderDivNode}> <Text _leaf={TextNode} content="content"></Text> </MiniRenderDiv> ); MiniRenderDivNode.schema.children = ['this is a new children']; TextNode.emitPropChange({ key: 'content', newValue: '1', }); makeSnapshot(component); }); }); describe('component cache', () => { it('get different component with same is and different doc id', () => { const baseRenderer02 = { ...baseRenderer, props: { ...baseRenderer.props, documentId: '02', } } const Div3 = leafWrapper(components.Div as any, { schema: divSchema, baseRenderer: baseRenderer02, componentInfo: {}, scope: {}, }); expect(Div).not.toEqual(Div3); }); it('get component again and get ths cache component', () => { const Div2 = leafWrapper(components.Div as any, { schema: divSchema, baseRenderer, componentInfo: {}, scope: {}, }); expect(Div).toEqual(Div2); }); }); describe('onVisibleChange', () => { it('visible is false', () => { TextNode.emitVisibleChange(false); makeSnapshot(component); }); it('visible is true', () => { TextNode.emitVisibleChange(true); makeSnapshot(component); }); }); describe('children', () => { it('this.props.children is array', () => { const component = renderer.create( // @ts-ignore <Div _leaf={DivNode}> <Text _leaf={TextNode} content="content"></Text> <Text _leaf={TextNode} content="content"></Text> </Div> ); makeSnapshot(component); }); }); describe('onChildrenChange', () => { it('children is array string', () => { DivNode.schema.children = [ 'onChildrenChange content 01', 'onChildrenChange content 02' ] DivNode.emitChildrenChange(); makeSnapshot(component); }); }); describe('not render leaf', () => { let miniRenderSchema, MiniRenderDiv, MiniRenderDivNode; beforeEach(() => { miniRenderSchema = { id: 'miniDiv' + id, }; MiniRenderDivNode = new Node(miniRenderSchema, { componentMeta: { isMinimalRenderUnit: true, }, }); nodeMap.set(miniRenderSchema.id, MiniRenderDivNode); MiniRenderDiv = leafWrapper(components.MiniRenderDiv as any, { schema: miniRenderSchema, baseRenderer, componentInfo: {}, scope: {}, }); TextNode = new Node(textSchema, { parent: MiniRenderDivNode, }); component = renderer.create( <Text _leaf={TextNode} content="content"></Text> ); }); it('onPropsChange', () => { const nextCount = rerenderCount + 1; MiniRenderDivNode.emitPropChange({ key: 'any', newValue: 'any', }); expect(rerenderCount).toBe(nextCount); }); it('onChildrenChange', () => { const nextCount = rerenderCount + 1; MiniRenderDivNode.emitChildrenChange({ key: 'any', newValue: 'any', }); expect(rerenderCount).toBe(nextCount); }); it('onVisibleChange', () => { const nextCount = rerenderCount + 1; MiniRenderDivNode.emitVisibleChange(true); expect(rerenderCount).toBe(nextCount); }); });
the_stack
import { mochaTmpdir, repoVersions } from "@adpt/testutils"; import { grep, repoDirs } from "@adpt/utils"; import execa from "execa"; import fs from "fs-extra"; import os from "os"; import path from "path"; import { clitest, expect } from "../../common/fancy"; const basicTestChain = clitest .stdout() .stderr() // fancy-test types are incorrect. See https://github.com/oclif/fancy-test/issues/113 .stub(process.stdout, "isTTY", false as any); // Turn off progress, etc const cliVersion = repoVersions.cli; const testStarters = path.join(repoDirs.cli, "test_starters"); function trying(stdout: string) { return grep(stdout, "Trying").map((l) => l.replace(/^.*Trying /, "")); } describe("project:new errors", () => { mochaTmpdir.each("adapt-cli-test-new"); basicTestChain .command(["project:new"]) .catch((err) => { expect(err.message).matches(/Missing 1 required arg:/); expect((err as any).oclif.exit).equals(2); }) .it("Should error if not enough args"); basicTestChain .command(["project:new", "./doesntexist"]) .catch((err) => { expect(err.message).equals( `Unable to use './doesntexist' as a starter: ` + `'${path.resolve("doesntexist")}' not found`); expect((err as any).oclif.exit).equals(2); }) .it("Should error if local spec doesn't exist"); basicTestChain .do(() => fs.writeFile("./empty", "")) .command(["project:new", "./empty"]) .catch((err) => { expect(err.message).equals( `Unable to use './empty' as a starter: ` + `'${path.resolve("empty")}' is not a directory`); expect((err as any).oclif.exit).equals(2); }) .it("Should error if local spec isn't a directory"); basicTestChain .do(() => fs.ensureDir("./empty")) .command(["project:new", "./empty"]) .catch((err) => { expect(err.message).equals( `Unable to use './empty' as a starter: ` + `no adapt_starter.json file found`); expect((err as any).oclif.exit).equals(2); }) .it("Should error adapt_starter.json not found"); basicTestChain .do(async () => { await fs.ensureDir("./invalid"); await fs.writeFile("./invalid/adapt_starter.json", "foo:"); }) .command(["project:new", "./invalid"]) .catch((err) => { expect(err.message).equals( `Unable to use './invalid' as a starter: ` + `unable to parse adapt_starter.json: invalid character 'o' at line 1, column 2:\n` + `foo:\n` + ` ^-- error here`); expect((err as any).oclif.exit).equals(2); }) .it("Should error with invalid adapt_starter.json"); }); interface Files { [ filename: string ]: string; } async function writeFiles(files: Files, dest: string) { for (const rel of Object.keys(files)) { const file = path.resolve(dest, rel); if (rel.includes("/")) await fs.mkdirp(path.dirname(file)); await fs.writeFile(file, files[rel]); } } async function checkFiles(files: Files, dest: string) { for (const rel of Object.keys(files)) { const file = path.resolve(dest, rel); const contents = (await fs.readFile(file)).toString(); expect(contents).equals(files[rel]); } } const files1 = { "test.js": "test.js\n", "deploy/package.json": `{ "name": "package.json" }`, "deploy/README": "README\n", }; const dirOnly = { "deploy/package.json": `{ "name": "package.json" }`, }; describe("project:new files", () => { mochaTmpdir.each("adapt-cli-test-new"); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeJson("./starter/adapt_starter.json", { files: ["test.js", "deploy"] }); await writeFiles(files1, "./starter"); }) .command(["project:new", "./starter", "project"]) .it("Should create new project and copy files", async () => { await checkFiles(files1, "project"); }); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeJson("./starter/adapt_starter.json", { files: ["test.js", "deploy"] }); await writeFiles(files1, "./starter"); }) .command(["new", "./starter", "project"]) .it("Should create new project and copy files using alias", async () => { await checkFiles(files1, "project"); }); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeJson("./starter/adapt_starter.json", { files: ["deploy"] }); await writeFiles(dirOnly, "./starter"); }) .command(["project:new", "./starter", "project"]) .it("Should create new project with a single dir to copy", async () => { await checkFiles(dirOnly, "project"); }); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeJson("./starter/adapt_starter.json", { files: ["test.js", "deploy", "foo"] }); await writeFiles(files1, "./starter"); }) .command(["project:new", "./starter", "project"]) .catch((err) => { const f = path.resolve("starter/foo"); expect(err.message).equals( `Unable to use './starter' as a starter: ` + `Error copying files: '${f}' not found`); expect((err as any).oclif.exit).equals(2); }) .it("Should error if files are not present in starter"); const uvStarter = path.join(testStarters, "update_version"); basicTestChain .command(["new", uvStarter, "project"]) .it("Should create new project and update versions using defaults", async () => { const pj = await fs.readJson("./project/deploy/package.json"); expect(pj.dependencies["@adpt/core"]).equals(cliVersion); expect(pj.dependencies["@adpt/cloud"]).equals(cliVersion); expect(pj.devDependencies["@adpt/utils"]).equals(cliVersion); expect(pj.devDependencies["@adpt/cli"]).equals(cliVersion); }); basicTestChain .command(["new", "--adaptVersion=1.2.3-foo", uvStarter, "project"]) .it("Should create new project and update versions using specific version", async () => { const pj = await fs.readJson("./project/deploy/package.json"); expect(pj.dependencies["@adpt/core"]).equals("1.2.3-foo"); expect(pj.dependencies["@adpt/cloud"]).equals("1.2.3-foo"); expect(pj.devDependencies["@adpt/utils"]).equals("1.2.3-foo"); expect(pj.devDependencies["@adpt/cli"]).equals("1.2.3-foo"); }); }); // Name of a starter repo that exists in the gallery, but specifically set up // for these unit tests. const testStarter = "cli-unit-tests"; // The version of Adapt to use for simple starter tests. The testStarter repo // above should have a tag that corresponds to this version. The tag should // follow the Adapt Version Label format for starters. // Example tag: adapt-v0.0.3 const testAdaptVer = "0.0.3"; const testAdaptVerCli = "--adaptVersion=" + testAdaptVer; const testAdaptVerLabel = "adapt-v" + testAdaptVer; // Name of a starter repo that is private and therefore requires credentials // to access. const testStarterPrivate = "gitlab:adpt/starters/cli-unit-tests-private"; async function checkAdaptVersion(expectedLabel: string) { const verPath = path.resolve(path.join("project", "ADAPT_VERSION")); const actual = (await fs.readFile(verPath)).toString().replace(/\s+/g, ""); expect(actual).equals(expectedLabel, "Downloaded ADAPT_VERSION doesn't match expected"); } async function checkTestStarter(expectedLabel: string) { await checkAdaptVersion(expectedLabel); const pjPath = path.resolve(path.join("project", "package.json")); const pkg = await fs.readJson(pjPath); expect(pkg.name).equals(testStarter); } describe("project:new download", () => { mochaTmpdir.each("adapt-cli-test-new"); basicTestChain .command(["project:new", testAdaptVerCli, `git+https://gitlab.com/adpt/starters/${testStarter}`, "project"]) .it("Should download from git+https URL", async ({ stdout, stderr }) => { expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkTestStarter(testAdaptVerLabel); expect(trying(stdout)).eqls([ `git+https://gitlab.com/adpt/starters/${testStarter}#${testAdaptVerLabel}`, ]); }); basicTestChain .command(["project:new", testAdaptVerCli, `gitlab:adpt/starters/${testStarter}`, "project"]) .it("Should download from gitlab: URL", async ({ stdout, stderr }) => { expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkTestStarter(testAdaptVerLabel); expect(trying(stdout)).eqls([ `gitlab:adpt/starters/${testStarter}#${testAdaptVerLabel}`, ]); }); basicTestChain .command(["project:new", testAdaptVerCli, testStarter, "project"]) .it("Should download from adpt gallery", async ({ stdout, stderr }) => { expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkTestStarter(testAdaptVerLabel); expect(trying(stdout)).eqls([ `git+https://gitlab.com/adpt/starters/${testStarter}#${testAdaptVerLabel}`, ]); }); basicTestChain .command(["project:new", testAdaptVerCli, "is-promise", "project"]) .catch((err) => { expect(err.message).equals( `Unable to use 'is-promise' as a starter: ` + `no adapt_starter.json file found`); expect((err as any).oclif.exit).equals(2); }) .it("Should try to download from registry and only try gallery once", ({ stdout }) => { expect(trying(stdout)).eqls([ `git+https://gitlab.com/adpt/starters/is-promise#adapt-v0.0.3`, `is-promise@adapt-v0.0.3`, `is-promise@adapt-v0.0`, `is-promise@adapt-v0`, `is-promise`, ]); }); basicTestChain .command(["project:new", "--adaptVersion=0.0.4-next.0", testStarter, "project"]) .it("Should download prerelease version from adpt gallery with git tag", async ({ stdout, stderr }) => { expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkTestStarter("adapt-v0.0.4-next.0"); expect(trying(stdout)).eqls([ `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v0.0.4-next.0`, ]); }); basicTestChain .command(["project:new", "--adaptVersion=0.0.4-alpha", testStarter, "project"]) .it("Should download minor version from adpt gallery with git branch", async ({ stdout, stderr }) => { expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkTestStarter("adapt-v0.0"); expect(trying(stdout)).eqls([ `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v0.0.4-alpha`, `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v0.0.4`, `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v0.0`, ]); }); basicTestChain .command(["project:new", "--adaptVersion=0.1.4", testStarter, "project"]) .it("Should download major version from adpt gallery with git branch", async ({ stdout, stderr }) => { expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkTestStarter("adapt-v0"); expect(trying(stdout)).eqls([ `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v0.1.4`, `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v0.1`, `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v0`, ]); }); basicTestChain .command(["project:new", "--adaptVersion=1.0.0", testStarter, "project"]) .it("Should download master branch from adpt gallery", async ({ stdout, stderr }) => { expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkTestStarter("master"); expect(trying(stdout)).eqls([ `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v1.0.0`, `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v1.0`, `git+https://gitlab.com/adpt/starters/${testStarter}#adapt-v1`, `git+https://gitlab.com/adpt/starters/${testStarter}`, ]); }); basicTestChain .command(["project:new", "--adaptVersion=1.0.0", "@unboundedsystems/doesntexist", "project"]) .catch((err) => { expect(err.message).equals( `Unable to use '@unboundedsystems/doesntexist' as a starter: ` + `404 Not Found - GET https://registry.npmjs.org/@unboundedsystems%2fdoesntexist - Not found`); expect((err as any).oclif.exit).equals(2); }) .it("Should try non-existent npm package only once", async ({ stdout }) => { expect(trying(stdout)).eqls([ `@unboundedsystems/doesntexist@adapt-v1.0.0`, ]); }); }); /** * Because --sshHostKeyCheck manipulates the process environment variables AND * pacote (used by adapt project:new) caches the environment, we need to run * these tests in a separate process to get pacote to load the current env * each time. */ describe("project:new sshHostKeyCheck", () => { const cliBin = path.resolve("./bin/run"); mochaTmpdir.each("adapt-cli-test-new"); basicTestChain .withSshKey() .it("Should download private gitlab repo with SSH and add host key", async (ctx) => { const args = ["project:new", testAdaptVerCli, "--sshHostKeyCheck=no", testStarterPrivate, "project"]; const env = { GIT_SSH_COMMAND: `ssh -i ${ctx.withSshKeyFile} -o UserKnownHostsFile=/dev/null`, }; const out = await execa(cliBin, args, { env }); const { stdout, stderr } = out; expect(stderr).equals(""); expect(stdout).matches(/Downloading starter \[completed\]/); expect(stdout).matches(/Creating new project \[completed\]/); await checkAdaptVersion(testAdaptVerLabel); expect(trying(stdout)).eqls([ `${testStarterPrivate}#${testAdaptVerLabel}`, ]); }); basicTestChain .it("Should try only once on SSH host key verification failure", async () => { const args = ["project:new", "--adaptVersion=1.0.0", testStarterPrivate, "project"]; const env = { // Ensure we have no known hosts GIT_SSH_COMMAND: `ssh -o UserKnownHostsFile=/dev/null`, }; try { const ret = await execa(cliBin, args, { env }); // tslint:disable-next-line: no-console console.log(`Expected command to fail.\n${ret.stdout}\n${ret.stderr}`); throw new Error(`Expected command to fail`); } catch (err) { expect(err.exitCode).to.equal(2); expect(err.stderr).matches(/Host key verification failed/); expect(trying(err.stdout)).eqls([ `${testStarterPrivate}#adapt-v1.0.0`, ]); } }); }); describe("project:new scripts", () => { mochaTmpdir.each("adapt-cli-test-new"); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeJson("./starter/adapt_starter.json", { init: "echo newfile> newfile", }); }) .command(["project:new", "./starter", "project"]) .it("Should run script in project directory", async () => { const files = { newfile: `newfile${os.EOL}` }; await checkFiles(files, "project"); }); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeJson("./starter/adapt_starter.json", { // tslint:disable-next-line: no-invalid-template-strings init: "cross-env-shell bash ${ADAPT_STARTER_DIR}/setup.sh", }); await fs.writeFile("./starter/setup.sh", `echo Setup done > setup_done `); }) .command(["project:new", "./starter", "project"]) .it("Should provide starter environment variable and cross-env", async () => { const files = { setup_done: "Setup done\n" }; await checkFiles(files, "project"); }); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeJson("./starter/adapt_starter.json", { init: "badcommand", }); }) .command(["project:new", "./starter", "project"]) .catch((err) => { expect(err.message).equals( `Unable to use './starter' as a starter: ` + `Error running init script:\n` + `'badcommand' not found\n`); expect((err as any).oclif.exit).equals(2); }) .it("Should error on bad command"); basicTestChain .do(async () => { await fs.ensureDir("./starter"); await fs.writeFile("./starter/init.js", ` console.log("To stdout"); console.error("To stderr"); process.exit(2); `); await fs.writeJson("./starter/adapt_starter.json", { // tslint:disable-next-line: no-invalid-template-strings init: "cross-env-shell node ${ADAPT_STARTER_DIR}/init.js", }); }) .command(["project:new", "./starter", "project"]) .catch((err) => { expect(err.message).equals( `Unable to use './starter' as a starter: ` + `Error running init script:\n` + `Command failed with exit code 2: cross-env-shell node \${ADAPT_STARTER_DIR}/init.js\n` + `To stdout\n` + `To stderr\n`); expect((err as any).oclif.exit).equals(2); }) .it("Should error on non-zero exit code"); async function createArgsStarter(crossEnv = true) { const prefix = crossEnv ? "cross-env-shell bash " : ""; await fs.ensureDir("./starter"); // A little script that just outputs its args await fs.writeFile("./starter/init.sh", `#!/bin/sh echo -n > output arg="$1" while [ -n "$arg" ] ; do echo "$arg" >> output shift arg="$1" done `); await fs.chmod("./starter/init.sh", "0777"); await fs.writeJson("./starter/adapt_starter.json", { // tslint:disable-next-line: no-invalid-template-strings init: prefix + "${ADAPT_STARTER_DIR}/init.sh", }); } basicTestChain .do(createArgsStarter) .command(["project:new", "./starter", "project"]) .it("Should handle no args", async () => { const output = (await fs.readFile("./project/output")).toString(); expect(output).equals(""); }); basicTestChain .do(createArgsStarter) .command(["project:new", "./starter", "project", "arg1", "arg2"]) .it("Should handle simple args", async () => { const output = (await fs.readFile("./project/output")).toString(); expect(output).equals("arg1\narg2\n"); }); // Argument parsing on Windows is a mess, so only run this test on POSIX if (process.platform !== "win32") { const specialArgs = [ `arg one`, ` "arg2'`, ` ; arg3 | `, ` \\ arg4`, ]; basicTestChain .do(() => createArgsStarter(false)) .command(["project:new", "./starter", "project", ...specialArgs]) .it("Should handle args with special chars", async () => { const output = (await fs.readFile("./project/output")).toString(); expect(output).equals(specialArgs.join("\n") + "\n"); }); } });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_bookingalert_Information { interface Tabs { } interface Body { /** Type a description of the activity. */ Description: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Unique identifier of the user or team who owns the activity. */ OwnerId: DevKit.Controls.Lookup; /** Priority of the activity. */ PriorityCode: DevKit.Controls.OptionSet; /** Unique identifier of the object with which the activity is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Shows the list of assignees to be notified by alert. */ RequiredAttendees: DevKit.Controls.Lookup; /** Enter the scheduled end time of the activity. */ ScheduledEnd: DevKit.Controls.DateTime; /** Enter the subject associated with the activity. */ Subject: DevKit.Controls.String; } interface Footer extends DevKit.Controls.IFooter { /** Status of the activity. */ StateCode: DevKit.Controls.OptionSet; } interface Navigation { nav_msdyn_msdyn_bookingalert_msdyn_bookingalertstatus_BookingAlert: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } } class Formmsdyn_bookingalert_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_bookingalert_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_bookingalert_Information */ Body: DevKit.Formmsdyn_bookingalert_Information.Body; /** The Footer section of form msdyn_bookingalert_Information */ Footer: DevKit.Formmsdyn_bookingalert_Information.Footer; /** The Navigation of form msdyn_bookingalert_Information */ Navigation: DevKit.Formmsdyn_bookingalert_Information.Navigation; } class msdyn_bookingalertApi { /** * DynamicsCrm.DevKit msdyn_bookingalertApi * @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; /** Shows additional information provided by the external application as JSON. For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Shows the actual duration of the activity in minutes. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Shows the actual end time of the activity. */ ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the actual start time of the activity. */ ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** For internal use only. */ Community: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the activity was created. The date and time are displayed in the time zone selected in Microsoft Dynamics CRM options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the activity pointer on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Enter the date and time when the delivery of the activity was last attempted. */ DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Enter the priority of delivery of the activity to the email server. */ DeliveryPriorityCode: DevKit.WebApi.OptionSetValue; /** Type a description of the activity. */ Description: DevKit.WebApi.StringValue; /** The message id of activity which is returned from Exchange Server. */ ExchangeItemId: DevKit.WebApi.StringValue; /** Exchange rate for the currency associated with the activitypointer with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the web link of Activity of type email. */ ExchangeWebLink: DevKit.WebApi.StringValue; /** Shows the sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Information regarding whether the activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Shows whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information regarding whether the activity was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows whether a voice mail was left. */ LeftVoiceMail: DevKit.WebApi.BooleanValue; /** Unique identifier of user who last modified the activity. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the activity was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics CRM options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the activity pointer on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** 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 of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of the activity. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Shows the process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_account_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebooking_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebookingheader_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bulkoperation_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaign_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaignactivity_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contact_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contract_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlement_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlementtemplate_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_incident_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_new_interactionforemail_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_invoice_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgearticle_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgebaserecord_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_lead_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreement_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingdate_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingincident_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservice_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservicetask_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingsetup_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicedate_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicesetup_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingalertstatus_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingrule_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingtimestamp_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_customerasset_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_fieldservicesetting_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeservice_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustment_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryjournal_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventorytransfer_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_payment_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentdetail_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentmethod_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentterm_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_playbookinstance_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalbum_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalcode_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_processnotes_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_productinventory_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_projectteam_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorder_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderbill_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceipt_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseordersubstatus_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingincident_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservice_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservicetask_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_resourceterritory_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rma_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmaproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceipt_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceiptproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmasubstatus_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtv_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvsubstatus_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_shipvia_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_systemuserschedulersetting_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroup_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroupdetail_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timeoffrequest_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_warehouse_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorder_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workordercharacteristic_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderincident_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderproduct_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderresourcerestriction_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservice_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservicetask_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_opportunity_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_quote_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_salesorder_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_site_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_action_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_hostedapplication_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_nonhostedapplication_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_option_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_savedsession_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflowstep_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping_msdyn_bookingalert: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Enter the scheduled duration of the activity, in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the scheduled end time of the activity. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the scheduled start time of the activity. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the mailbox associated with the sender of the email message. */ SenderMailboxId: DevKit.WebApi.LookupValueReadonly; /** Enter the date and time when the activity was sent. */ SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows the ID of the recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of an associated service. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the case record. */ SLAId: DevKit.WebApi.LookupValue; /** Shows the last service level agreement (SLA) that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the stage. */ StageId: DevKit.WebApi.GuidValue; /** Status of the activity. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the activity. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Enter the subject associated with the activity. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the activitypointer. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Shows the time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace msdyn_bookingalert { enum Community { /** 5 */ Cortana, /** 6 */ Direct_Line, /** 8 */ Direct_Line_Speech, /** 9 */ Email, /** 1 */ Facebook, /** 10 */ GroupMe, /** 11 */ Kik, /** 3 */ Line, /** 7 */ Microsoft_Teams, /** 0 */ Other, /** 13 */ Skype, /** 14 */ Slack, /** 12 */ Telegram, /** 2 */ Twitter, /** 4 */ Wechat, /** 15 */ WhatsApp } enum DeliveryPriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open, /** 3 */ Scheduled } enum StatusCode { /** 3 */ Canceled, /** 2 */ Completed, /** 1 */ Open, /** 4 */ Scheduled } 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'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import 'vs/css!./media/editorplaceholder'; import { localize } from 'vs/nls'; import Severity from 'vs/base/common/severity'; import { IEditorOpenContext } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { Dimension, size, clearNode, $ } from 'vs/base/browser/dom'; import { CancellationToken } from 'vs/base/common/cancellation'; import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { assertIsDefined, assertAllDefined } from 'vs/base/common/types'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IWorkspaceContextService, isSingleFolderWorkspaceIdentifier, toWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace'; import { EditorOpenSource, IEditorOptions } from 'vs/platform/editor/common/editor'; import { computeEditorAriaLabel, EditorPaneDescriptor } from 'vs/workbench/browser/editor'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Link } from 'vs/platform/opener/browser/link'; import { SimpleIconLabel } from 'vs/base/browser/ui/iconLabel/simpleIconLabel'; import { editorErrorForeground, editorInfoForeground, editorWarningForeground } from 'vs/platform/theme/common/colorRegistry'; import { Codicon } from 'vs/base/common/codicons'; import { FileChangeType, FileOperationError, FileOperationResult, IFileService } from 'vs/platform/files/common/files'; import { isErrorWithActions, toErrorMessage } from 'vs/base/common/errorMessage'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; export interface IEditorPlaceholderContents { icon: string; label: string; actions: IEditorPlaceholderContentsAction[]; } export interface IEditorPlaceholderContentsAction { label: string; run: () => unknown; } export interface IErrorEditorPlaceholderOptions extends IEditorOptions { error?: Error; } export abstract class EditorPlaceholder extends EditorPane { private container: HTMLElement | undefined; private scrollbar: DomScrollableElement | undefined; private inputDisposable = this._register(new MutableDisposable()); constructor( id: string, @ITelemetryService telemetryService: ITelemetryService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IInstantiationService private readonly instantiationService: IInstantiationService ) { super(id, telemetryService, themeService, storageService); } protected createEditor(parent: HTMLElement): void { // Container this.container = document.createElement('div'); this.container.className = 'monaco-editor-pane-placeholder'; this.container.style.outline = 'none'; this.container.tabIndex = 0; // enable focus support from the editor part (do not remove) // Custom Scrollbars this.scrollbar = this._register(new DomScrollableElement(this.container, { horizontal: ScrollbarVisibility.Auto, vertical: ScrollbarVisibility.Auto })); parent.appendChild(this.scrollbar.getDomNode()); } override async setInput(input: EditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { await super.setInput(input, options, context, token); // Check for cancellation if (token.isCancellationRequested) { return; } // Render Input this.inputDisposable.value = await this.renderInput(input, options); } private async renderInput(input: EditorInput, options: IEditorOptions | undefined): Promise<IDisposable> { const [container, scrollbar] = assertAllDefined(this.container, this.scrollbar); // Reset any previous contents clearNode(container); // Delegate to implementation for contents const disposables = new DisposableStore(); const { icon, label, actions } = await this.getContents(input, options, disposables); // Icon const iconContainer = container.appendChild($('.editor-placeholder-icon-container')); const iconWidget = new SimpleIconLabel(iconContainer); iconWidget.text = icon; // Label const labelContainer = container.appendChild($('.editor-placeholder-label-container')); const labelWidget = document.createElement('span'); labelWidget.textContent = label; labelContainer.appendChild(labelWidget); // ARIA label container.setAttribute('aria-label', `${computeEditorAriaLabel(input, undefined, this.group, undefined)}, ${label}`); // Actions const actionsContainer = container.appendChild($('.editor-placeholder-actions-container')); for (const action of actions) { disposables.add(this.instantiationService.createInstance(Link, actionsContainer, { label: action.label, href: '' }, { opener: () => action.run() })); } // Adjust scrollbar scrollbar.scanDomNode(); return disposables; } protected abstract getContents(input: EditorInput, options: IEditorOptions | undefined, disposables: DisposableStore): Promise<IEditorPlaceholderContents>; override clearInput(): void { if (this.container) { clearNode(this.container); } this.inputDisposable.clear(); super.clearInput(); } layout(dimension: Dimension): void { const [container, scrollbar] = assertAllDefined(this.container, this.scrollbar); // Pass on to Container size(container, dimension.width, dimension.height); // Adjust scrollbar scrollbar.scanDomNode(); // Toggle responsive class container.classList.toggle('max-height-200px', dimension.height <= 200); } override focus(): void { const container = assertIsDefined(this.container); container.focus(); } override dispose(): void { this.container?.remove(); super.dispose(); } } export class WorkspaceTrustRequiredPlaceholderEditor extends EditorPlaceholder { static readonly ID = 'workbench.editors.workspaceTrustRequiredEditor'; private static readonly LABEL = localize('trustRequiredEditor', "Workspace Trust Required"); static readonly DESCRIPTOR = EditorPaneDescriptor.create(WorkspaceTrustRequiredPlaceholderEditor, WorkspaceTrustRequiredPlaceholderEditor.ID, WorkspaceTrustRequiredPlaceholderEditor.LABEL); constructor( @ITelemetryService telemetryService: ITelemetryService, @IThemeService themeService: IThemeService, @ICommandService private readonly commandService: ICommandService, @IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService, @IStorageService storageService: IStorageService, @IInstantiationService instantiationService: IInstantiationService ) { super(WorkspaceTrustRequiredPlaceholderEditor.ID, telemetryService, themeService, storageService, instantiationService); } override getTitle(): string { return WorkspaceTrustRequiredPlaceholderEditor.LABEL; } protected async getContents(): Promise<IEditorPlaceholderContents> { return { icon: '$(workspace-untrusted)', label: isSingleFolderWorkspaceIdentifier(toWorkspaceIdentifier(this.workspaceService.getWorkspace())) ? localize('requiresFolderTrustText', "The file is not displayed in the editor because trust has not been granted to the folder.") : localize('requiresWorkspaceTrustText', "The file is not displayed in the editor because trust has not been granted to the workspace."), actions: [ { label: localize('manageTrust', "Manage Workspace Trust"), run: () => this.commandService.executeCommand('workbench.trust.manage') } ] }; } } export class ErrorPlaceholderEditor extends EditorPlaceholder { private static readonly ID = 'workbench.editors.errorEditor'; private static readonly LABEL = localize('errorEditor', "Error Editor"); static readonly DESCRIPTOR = EditorPaneDescriptor.create(ErrorPlaceholderEditor, ErrorPlaceholderEditor.ID, ErrorPlaceholderEditor.LABEL); constructor( @ITelemetryService telemetryService: ITelemetryService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IInstantiationService instantiationService: IInstantiationService, @IFileService private readonly fileService: IFileService, @IDialogService private readonly dialogService: IDialogService ) { super(ErrorPlaceholderEditor.ID, telemetryService, themeService, storageService, instantiationService); } protected async getContents(input: EditorInput, options: IErrorEditorPlaceholderOptions, disposables: DisposableStore): Promise<IEditorPlaceholderContents> { const resource = input.resource; const group = this.group; const error = options.error; const isFileNotFound = (<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND; // Error Label let label: string; if (isFileNotFound) { label = localize('unavailableResourceErrorEditorText', "The editor could not be opened because the file was not found."); } else if (error) { label = localize('unknownErrorEditorTextWithError', "The editor could not be opened due to an unexpected error: {0}", toErrorMessage(error)); } else { label = localize('unknownErrorEditorTextWithoutError', "The editor could not be opened due to an unexpected error."); } // Actions let actions: IEditorPlaceholderContentsAction[] | undefined = undefined; if (isErrorWithActions(error) && error.actions.length > 0) { actions = error.actions.map(action => { return { label: action.label, run: () => { const result = action.run(); if (result instanceof Promise) { result.catch(error => this.dialogService.show(Severity.Error, toErrorMessage(error))); } } }; }); } else if (group) { actions = [ { label: localize('retry', "Try Again"), run: () => group.openEditor(input, { ...options, source: EditorOpenSource.USER /* explicit user gesture */ }) } ]; } // Auto-reload when file is added if (group && isFileNotFound && resource && this.fileService.hasProvider(resource)) { disposables.add(this.fileService.onDidFilesChange(e => { if (e.contains(resource, FileChangeType.ADDED, FileChangeType.UPDATED)) { group.openEditor(input, options); } })); } return { icon: '$(error)', label, actions: actions ?? [] }; } } registerThemingParticipant((theme, collector) => { // Editor Placeholder Error Icon const editorErrorIconForegroundColor = theme.getColor(editorErrorForeground); if (editorErrorIconForegroundColor) { collector.addRule(` .monaco-editor-pane-placeholder .editor-placeholder-icon-container ${Codicon.error.cssSelector} { color: ${editorErrorIconForegroundColor}; }`); } // Editor Placeholder Warning Icon const editorWarningIconForegroundColor = theme.getColor(editorWarningForeground); if (editorWarningIconForegroundColor) { collector.addRule(` .monaco-editor-pane-placeholder .editor-placeholder-icon-container ${Codicon.warning.cssSelector} { color: ${editorWarningIconForegroundColor}; }`); } // Editor Placeholder Info/Trust Icon const editorInfoIconForegroundColor = theme.getColor(editorInfoForeground); if (editorInfoIconForegroundColor) { collector.addRule(` .monaco-editor-pane-placeholder .editor-placeholder-icon-container ${Codicon.info.cssSelector}, .monaco-editor-pane-placeholder .editor-placeholder-icon-container ${Codicon.workspaceUntrusted.cssSelector} { color: ${editorInfoIconForegroundColor}; }`); } });
the_stack
import { Box, Separator, space, Spacer, Theme } from "@artsy/palette" import { Artwork_artworkAboveTheFold } from "__generated__/Artwork_artworkAboveTheFold.graphql" import { ArtworkAboveTheFoldQuery } from "__generated__/ArtworkAboveTheFoldQuery.graphql" import { ArtworkFullQuery, ArtworkFullQueryResponse } from "__generated__/ArtworkFullQuery.graphql" import { ArtworkMarkAsRecentlyViewedQuery } from "__generated__/ArtworkMarkAsRecentlyViewedQuery.graphql" import { RetryErrorBoundary } from "lib/Components/RetryErrorBoundary" import { defaultEnvironment } from "lib/relay/createEnvironment" import { SafeAreaInsets } from "lib/types/SafeAreaInsets" import { PlaceholderBox, PlaceholderRaggedText, PlaceholderText, ProvidePlaceholderContext, } from "lib/utils/placeholders" import { renderWithPlaceholder } from "lib/utils/renderWithPlaceholder" import { Schema, screenTrack } from "lib/utils/track" import { ProvideScreenDimensions, useScreenDimensions } from "lib/utils/useScreenDimensions" import React from "react" import { ActivityIndicator, FlatList, View } from "react-native" import { RefreshControl } from "react-native" import { Sentry } from "react-native-sentry" import { commitMutation, createFragmentContainer, fetchQuery, graphql, QueryRenderer, RelayProp } from "react-relay" import { AboutArtistFragmentContainer as AboutArtist } from "./Components/AboutArtist" import { AboutWorkFragmentContainer as AboutWork } from "./Components/AboutWork" import { ArtworkDetailsFragmentContainer as ArtworkDetails } from "./Components/ArtworkDetails" import { ArtworkHeaderFragmentContainer as ArtworkHeader } from "./Components/ArtworkHeader" import { ArtworkHistoryFragmentContainer as ArtworkHistory } from "./Components/ArtworkHistory" import { CommercialInformationFragmentContainer as CommercialInformation } from "./Components/CommercialInformation" import { ContextCardFragmentContainer as ContextCard } from "./Components/ContextCard" import { OtherWorksFragmentContainer as OtherWorks, populatedGrids } from "./Components/OtherWorks/OtherWorks" import { PartnerCardFragmentContainer as PartnerCard } from "./Components/PartnerCard" interface Props { artworkAboveTheFold: Artwork_artworkAboveTheFold isVisible: boolean relay: RelayProp } interface State { refreshing: boolean artworkFull: ArtworkFullQueryResponse["artwork"] | null } @screenTrack<Props>(props => ({ context_screen: Schema.PageNames.ArtworkPage, context_screen_owner_type: Schema.OwnerEntityTypes.Artwork, context_screen_owner_slug: props.artworkAboveTheFold.slug, context_screen_owner_id: props.artworkAboveTheFold.internalID, availability: props.artworkAboveTheFold.availability, acquireable: props.artworkAboveTheFold.is_acquireable, inquireable: props.artworkAboveTheFold.is_inquireable, offerable: props.artworkAboveTheFold.is_offerable, biddable: props.artworkAboveTheFold.is_biddable, })) export class Artwork extends React.Component<Props, State> { state = { refreshing: false, artworkFull: null, } shouldRenderDetails = () => { const { category, conditionDescription, signature, signatureInfo, certificateOfAuthenticity, framed, series, publisher, manufacturer, image_rights, } = this.state.artworkFull if ( category || conditionDescription || signature || signatureInfo || certificateOfAuthenticity || framed || series || publisher || manufacturer || image_rights ) { return true } else { return false } } componentDidMount() { this.markArtworkAsRecentlyViewed() this.loadFullArtwork() } componentDidUpdate(prevProps) { // If we are visible, but weren't, then we are re-appearing (not called on first render). if (this.props.isVisible && !prevProps.isVisible) { this.loadFullArtwork().then(() => { this.markArtworkAsRecentlyViewed() }) } } shouldRenderPartner = () => { const { partner, sale } = this.state.artworkFull if ((sale && sale.isBenefit) || (sale && sale.isGalleryAuction)) { return false } else if (partner && partner.type && partner.type !== "Auction House") { return true } else { return false } } shouldRenderOtherWorks = () => { const { contextGrids } = this.state.artworkFull const gridsToShow = populatedGrids(contextGrids) if (gridsToShow && gridsToShow.length > 0) { return true } else { return false } } onRefresh = async () => { if (this.state.refreshing) { return } this.setState({ refreshing: true }) try { await this.loadFullArtwork() } catch (e) { if (__DEV__) { console.error(e) } else { Sentry.captureMessage("failed to refresh artwork", { slug: this.props.artworkAboveTheFold.slug }) } } this.setState({ refreshing: false }) } markArtworkAsRecentlyViewed = () => { commitMutation<ArtworkMarkAsRecentlyViewedQuery>(this.props.relay.environment, { mutation: graphql` mutation ArtworkMarkAsRecentlyViewedQuery($input: RecordArtworkViewInput!) { recordArtworkView(input: $input) { artworkId } } `, variables: { input: { artwork_id: this.props.artworkAboveTheFold.slug, }, }, }) } sections(): ArtworkPageSection[] { const { artworkFull } = this.state const { artworkAboveTheFold } = this.props const sections: ArtworkPageSection[] = [] sections.push({ key: "header", element: <ArtworkHeader artwork={artworkAboveTheFold} />, excludePadding: true, }) sections.push({ key: "commercialInformation", element: <CommercialInformation artwork={artworkAboveTheFold} />, }) if (!artworkFull) { sections.push({ key: "belowTheFoldPlaceholder", element: <BelowTheFoldPlaceholder />, }) return sections } const { artist, context } = artworkFull if (artworkFull.description || artworkFull.additional_information) { sections.push({ key: "aboutWork", element: <AboutWork artwork={artworkFull} />, }) } if (this.shouldRenderDetails()) { sections.push({ key: "artworkDetails", element: <ArtworkDetails artwork={artworkFull} />, }) } if (artworkFull.provenance || artworkFull.exhibition_history || artworkFull.literature) { sections.push({ key: "history", element: <ArtworkHistory artwork={artworkFull} />, }) } if (artist && artist.biography_blurb) { sections.push({ key: "aboutArtist", element: <AboutArtist artwork={artworkFull} />, }) } if (this.shouldRenderPartner()) { sections.push({ key: "partnerCard", element: <PartnerCard artwork={artworkFull} />, }) } if (context && context.__typename === "Sale" && context.isAuction) { sections.push({ key: "contextCard", element: <ContextCard artwork={artworkFull} />, }) } if (this.shouldRenderOtherWorks()) { sections.push({ key: "otherWorks", element: <OtherWorks artwork={artworkFull} />, }) } return sections } async loadFullArtwork() { const result = await fetchQuery<ArtworkFullQuery>( this.props.relay.environment, graphql` query ArtworkFullQuery($artworkID: String!) { artwork(id: $artworkID) { additional_information: additionalInformation description provenance exhibition_history: exhibitionHistory literature partner { type id } artist { biography_blurb: biographyBlurb { text } } sale { id isBenefit isGalleryAuction } category conditionDescription { details } signature signatureInfo { details } certificateOfAuthenticity { details } framed { details } series publisher manufacturer image_rights: imageRights context { __typename ... on Sale { isAuction } } contextGrids { artworks: artworksConnection(first: 6) { edges { node { id } } } } ...PartnerCard_artwork ...AboutWork_artwork ...OtherWorks_artwork ...AboutArtist_artwork ...ArtworkDetails_artwork ...ContextCard_artwork ...ArtworkHistory_artwork # DO NOT DELETE this is needed to update the relay cache entries # for the above-the-fold content when the user refreshes (which in # turn updates the props.artworkAboveTheFold prop) ...Artwork_artworkAboveTheFold } } `, { artworkID: this.props.artworkAboveTheFold.internalID }, { force: true } ) this.setState({ artworkFull: result.artwork }) } render() { return ( <FlatList<ArtworkPageSection> data={this.sections()} ItemSeparatorComponent={() => ( <Box px={2} mx={2} my={3}> <Separator /> </Box> )} refreshControl={<RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh} />} contentInset={{ bottom: 40 }} renderItem={({ item }) => (item.excludePadding ? item.element : <Box px={2}>{item.element}</Box>)} /> ) } } interface ArtworkPageSection { key: string element: JSX.Element excludePadding?: boolean } export const ArtworkContainer = createFragmentContainer(Artwork, { artworkAboveTheFold: graphql` fragment Artwork_artworkAboveTheFold on Artwork { ...ArtworkHeader_artwork ...CommercialInformation_artwork slug internalID id is_acquireable: isAcquireable is_offerable: isOfferable is_biddable: isBiddable is_inquireable: isInquireable availability } `, }) export const ArtworkRenderer: React.SFC<{ artworkID: string; safeAreaInsets: SafeAreaInsets; isVisible: boolean }> = ({ artworkID, ...others }) => { return ( <RetryErrorBoundary render={({ isRetry }) => { return ( <Theme> <ProvideScreenDimensions> <QueryRenderer<ArtworkAboveTheFoldQuery> environment={defaultEnvironment} query={graphql` query ArtworkAboveTheFoldQuery($artworkID: String!) { artworkAboveTheFold: artwork(id: $artworkID) { ...Artwork_artworkAboveTheFold } } `} variables={{ artworkID }} cacheConfig={{ // Bypass Relay cache on retries. ...(isRetry && { force: true }), }} render={renderWithPlaceholder({ Container: ArtworkContainer, initialProps: others, renderPlaceholder: () => <AboveTheFoldPlaceholder />, })} /> </ProvideScreenDimensions> </Theme> ) }} /> ) } const AboveTheFoldPlaceholder: React.FC<{}> = ({}) => { const screenDimensions = useScreenDimensions() // The logic for artworkHeight comes from the zeplin spec https://zpl.io/25JLX0Q const artworkHeight = screenDimensions.width >= 375 ? 340 : 290 return ( <View style={{ flex: 1, padding: space(2) }}> {/* Artwork thumbnail */} <PlaceholderBox height={artworkHeight} /> <Spacer mb={2} /> {/* save/share buttons */} <View style={{ flexDirection: "row", justifyContent: "center" }}> <PlaceholderText width={50} marginHorizontal={space(1)} /> <PlaceholderText width={50} marginHorizontal={space(1)} /> <PlaceholderText width={50} marginHorizontal={space(1)} /> </View> <Spacer mb={2} /> {/* Artist name */} <PlaceholderText width={100} /> <Spacer mb={2} /> {/* Artwork tombstone details */} <View style={{ width: 130 }}> <PlaceholderRaggedText numLines={4} /> </View> <Spacer mb={3} /> {/* more junk */} <Separator /> <Spacer mb={3} /> <PlaceholderRaggedText numLines={3} /> <Spacer mb={2} /> {/* commerce button */} <PlaceholderBox height={60} /> </View> ) } const BelowTheFoldPlaceholder: React.FC<{}> = ({}) => { return ( <ProvidePlaceholderContext> <Separator /> <Spacer mb={3} /> {/* About the artwork title */} <PlaceholderText width={60} /> <Spacer mb={2} /> {/* About the artwork copy */} <PlaceholderRaggedText numLines={4} /> <Spacer mb={3} /> <Separator /> <Spacer mb={3} /> <ActivityIndicator /> <Spacer mb={3} /> </ProvidePlaceholderContext> ) }
the_stack
import {ColorModeRestriction, Destination, DestinationConnectionStatus, DestinationOrigin, DestinationType, DuplexModeRestriction, Margins, PrintPreviewModelElement, Size} from 'chrome://print/print_preview.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {PinModeRestriction} from 'chrome://print/print_preview.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; // </if> import {assertEquals} from 'chrome://webui-test/chai_assert.js'; import {getCddTemplate} from './print_preview_test_utils.js'; suite('ModelSettingsPolicyTest', function() { let model: PrintPreviewModelElement; function setupModel() { document.body.innerHTML = ''; model = document.createElement('print-preview-model'); document.body.appendChild(model); model.documentSettings = { hasCssMediaStyles: false, hasSelection: false, isModifiable: true, isScalingDisabled: false, fitToPageScaling: 100, pageCount: 3, isFromArc: false, title: 'title', }; model.pageSize = new Size(612, 792); model.margins = new Margins(72, 72, 72, 72); // Create a test destination. model.destination = new Destination( 'FooDevice', DestinationType.LOCAL, DestinationOrigin.LOCAL, 'FooName', DestinationConnectionStatus.ONLINE); model.set( 'destination.capabilities', getCddTemplate(model.destination.id).capabilities); } test('color managed', function() { [{ // Policy has no effect, setting unavailable colorCap: {option: [{type: 'STANDARD_COLOR', is_default: true}]}, colorPolicy: ColorModeRestriction.COLOR, colorDefault: ColorModeRestriction.COLOR, expectedValue: true, expectedAvailable: false, expectedManaged: false, expectedEnforced: true, }, { // Policy contradicts actual capabilities, setting unavailable. colorCap: {option: [{type: 'STANDARD_COLOR', is_default: true}]}, colorPolicy: ColorModeRestriction.MONOCHROME, colorDefault: ColorModeRestriction.MONOCHROME, expectedValue: true, expectedAvailable: false, expectedManaged: false, expectedEnforced: true, }, { // Policy overrides default. colorCap: { option: [ {type: 'STANDARD_MONOCHROME', is_default: true}, {type: 'STANDARD_COLOR'} ] }, colorPolicy: ColorModeRestriction.COLOR, // Default mismatches restriction and is ignored. colorDefault: ColorModeRestriction.MONOCHROME, expectedValue: true, expectedAvailable: true, expectedManaged: true, expectedEnforced: true, }, { // Default defined by policy but setting is modifiable. colorCap: { option: [ {type: 'STANDARD_MONOCHROME', is_default: true}, {type: 'STANDARD_COLOR'} ] }, colorDefault: ColorModeRestriction.COLOR, expectedValue: true, expectedAvailable: true, expectedManaged: false, expectedEnforced: false, }, { // Default defined by policy but setting is modifiable (same as the case // above but with swapped defaults). colorCap: { option: [ {type: 'STANDARD_MONOCHROME'}, {type: 'STANDARD_COLOR', is_default: true} ] }, colorDefault: ColorModeRestriction.MONOCHROME, expectedValue: false, expectedAvailable: true, expectedManaged: false, expectedEnforced: false, }].forEach(subtestParams => { setupModel(); // Remove color capability. const capabilities = getCddTemplate(model.destination.id).capabilities!; capabilities.printer!.color = subtestParams.colorCap; const policies = { color: { allowedMode: subtestParams.colorPolicy, defaultMode: subtestParams.colorDefault, } }; model.set('destination.capabilities', capabilities); model.setPolicySettings(policies); model.applyStickySettings(); assertEquals(subtestParams.expectedValue, model.getSettingValue('color')); assertEquals( subtestParams.expectedAvailable, model.settings.color.available); assertEquals(subtestParams.expectedManaged, model.settingsManaged); assertEquals( subtestParams.expectedEnforced, model.settings.color.setByPolicy); }); }); test('duplex managed', function() { [{ // Policy has no effect. duplexCap: {option: [{type: 'NO_DUPLEX', is_default: true}]}, duplexPolicy: DuplexModeRestriction.SIMPLEX, duplexDefault: DuplexModeRestriction.SIMPLEX, expectedValue: false, expectedAvailable: false, expectedManaged: false, expectedEnforced: true, expectedShortEdge: false, expectedShortEdgeAvailable: false, expectedShortEdgeEnforced: false, }, { // Policy contradicts actual capabilities and is ignored. duplexCap: {option: [{type: 'NO_DUPLEX', is_default: true}]}, duplexPolicy: DuplexModeRestriction.DUPLEX, duplexDefault: DuplexModeRestriction.LONG_EDGE, expectedValue: false, expectedAvailable: false, expectedManaged: false, expectedEnforced: true, expectedShortEdge: false, expectedShortEdgeAvailable: false, expectedShortEdgeEnforced: false, }, { // Policy overrides default. duplexCap: { option: [ {type: 'NO_DUPLEX', is_default: true}, {type: 'LONG_EDGE'}, {type: 'SHORT_EDGE'} ] }, duplexPolicy: DuplexModeRestriction.DUPLEX, // Default mismatches restriction and is ignored. duplexDefault: DuplexModeRestriction.SIMPLEX, expectedValue: true, expectedAvailable: true, expectedManaged: true, expectedEnforced: true, expectedShortEdge: false, expectedShortEdgeAvailable: true, expectedShortEdgeEnforced: false, }, { // Policy sets duplex type, overriding default. duplexCap: { option: [ {type: 'NO_DUPLEX'}, {type: 'LONG_EDGE', is_default: true}, {type: 'SHORT_EDGE'} ] }, duplexPolicy: DuplexModeRestriction.SHORT_EDGE, // Default mismatches restriction and is ignored. duplexDefault: DuplexModeRestriction.LONG_EDGE, expectedValue: true, expectedAvailable: true, expectedManaged: true, expectedEnforced: true, expectedShortEdge: true, expectedShortEdgeAvailable: true, expectedShortEdgeEnforced: true, }, { // Default defined by policy but setting is modifiable. duplexCap: { option: [ {type: 'NO_DUPLEX', is_default: true}, {type: 'LONG_EDGE'}, {type: 'SHORT_EDGE'} ] }, duplexDefault: DuplexModeRestriction.LONG_EDGE, expectedValue: true, expectedAvailable: true, expectedManaged: false, expectedEnforced: false, expectedShortEdge: false, expectedShortEdgeAvailable: true, expectedShortEdgeEnforced: false, }].forEach(subtestParams => { setupModel(); // Remove duplex capability. const capabilities = getCddTemplate(model.destination.id).capabilities!; capabilities.printer!.duplex = subtestParams.duplexCap; const policies = { duplex: { allowedMode: subtestParams.duplexPolicy, defaultMode: subtestParams.duplexDefault, } }; model.set('destination.capabilities', capabilities); model.setPolicySettings(policies); model.applyStickySettings(); assertEquals( subtestParams.expectedValue, model.getSettingValue('duplex')); assertEquals( subtestParams.expectedAvailable, model.settings.duplex.available); assertEquals(subtestParams.expectedManaged, model.settingsManaged); assertEquals( subtestParams.expectedEnforced, model.settings.duplex.setByPolicy); assertEquals( subtestParams.expectedShortEdge, model.getSettingValue('duplexShortEdge')); assertEquals( subtestParams.expectedShortEdgeAvailable, model.settings.duplexShortEdge.available); assertEquals( subtestParams.expectedShortEdgeEnforced, model.settings.duplexShortEdge.setByPolicy); }); }); // <if expr="chromeos_ash or chromeos_lacros"> test('pin managed', function() { [{ // No policies, settings is modifiable. pinCap: {supported: true}, expectedValue: false, expectedAvailable: true, expectedManaged: false, expectedEnforced: false, }, { // Policy has no effect, setting unavailable. pinCap: {}, pinPolicy: PinModeRestriction.PIN, pinDefault: PinModeRestriction.PIN, expectedValue: false, expectedAvailable: false, expectedManaged: false, expectedEnforced: true, }, { // Policy has no effect, setting is not supported. pinCap: {supported: false}, pinPolicy: PinModeRestriction.UNSET, pinDefault: PinModeRestriction.PIN, expectedValue: false, expectedAvailable: false, expectedManaged: false, expectedEnforced: false, }, { // Policy is UNSECURE, setting is not available. pinCap: {supported: true}, pinPolicy: PinModeRestriction.NO_PIN, expectedValue: false, expectedAvailable: false, expectedManaged: false, expectedEnforced: true, }, { // No restriction policy, setting is modifiable. pinCap: {supported: true}, pinPolicy: PinModeRestriction.UNSET, pinDefault: PinModeRestriction.NO_PIN, expectedValue: false, expectedAvailable: true, expectedManaged: false, expectedEnforced: false, }, { // Policy overrides default. pinCap: {supported: true}, pinPolicy: PinModeRestriction.PIN, // Default mismatches restriction and is ignored. pinDefault: PinModeRestriction.NO_PIN, expectedValue: true, expectedAvailable: true, expectedManaged: true, expectedEnforced: true, }, { // Default defined by policy but setting is modifiable. pinCap: {supported: true}, pinDefault: PinModeRestriction.PIN, expectedValue: true, expectedAvailable: true, expectedManaged: false, expectedEnforced: false, }].forEach(subtestParams => { setupModel(); // Make device enterprise managed since pin setting is available only on // managed devices. loadTimeData.overrideValues({isEnterpriseManaged: true}); // Remove pin capability. const capabilities = getCddTemplate(model.destination.id).capabilities!; capabilities.printer!.pin = subtestParams.pinCap; const policies = { pin: { allowedMode: subtestParams.pinPolicy, defaultMode: subtestParams.pinDefault, } }; model.set('destination.capabilities', capabilities); model.setPolicySettings(policies); model.applyStickySettings(); assertEquals(subtestParams.expectedValue, model.getSettingValue('pin')); assertEquals( subtestParams.expectedAvailable, model.settings.pin.available); assertEquals(subtestParams.expectedManaged, model.settingsManaged); assertEquals( subtestParams.expectedEnforced, model.settings.pin.setByPolicy); }); }); // </if> });
the_stack
import { Bounds, Extent, HSVColor, RGBAColor, RGBColor, Matrix, Matrix3x3, Range, Vector2, Vector3, Vector4 } from "../../../types"; /** * * @param {Number} size The size of the array. */ export function createArray(size?: number): number[]; /** * Get the number π. */ export function Pi(): number; /** * Convert degrees to radians. * @param {Number} deg The value in degrees. */ export function radiansFromDegrees(deg: number): number; /** * Convert radians to degrees. * @param {Number} rad The value in radians. */ export function degreesFromRadians(rad: number): number; /** * Same as Math.round(). * @param {Number} param1 The value to be rounded to the nearest integer. */ export function round(param1: number): number; /** * Same as Math.floor(). * @param {Number} param1 A numeric expression. */ export function floor(param1: number): number; /** * Same as Math.ceil(). * @param {Number} param1 A numeric expression. */ export function ceil(param1: number): number; /** * Get the minimum of the two arguments provided. If either argument is NaN, * the first argument will always be returned. * @param {Number} param1 The first numeric expression. * @param {Number} param2 The second numeric expression. */ export function min(param1: number, param2: number): number; /** * Get the maximum of the two arguments provided. If either argument is NaN, * the first argument will always be returned. * @param {Number} param1 The first numeric expression. * @param {Number} param2 The second numeric expression. */ export function max(param1: number, param2: number): number; /** * Get the minimum of the array. * @param {Number[]} arr The array. * @param {Number} offset The offset. * @param {Number} stride The stride. */ export function arrayMin(arr: number[], offset: number, stride: number): number; /** * Get the maximum of the array. * @param {Number[]} arr The array. * @param {Number} offset The offset. * @param {Number} stride The stride. */ export function arrayMax(arr: number[], offset: number, stride: number): number; /** * * @param {Number[]} arr The array. * @param {Number} offset The offset. * @param {Number} stride The stride. */ export function arrayRange(arr: number[], offset: number, stride: number): number[]; /** * Gives the exponent of the lowest power of two not less than x. * */ export function ceilLog2(): void; /** * Compute N factorial, N! = N*(N-1) * (N-2)...*3*2*1. */ export function factorial(): void; /** * Generate pseudo-random numbers distributed according to the standard normal * distribution. */ export function gaussian(): void; /** * Compute the nearest power of two that is not less than x. * @param {Number} xi A numeric expression. */ export function nearestPowerOfTwo(xi: number): number; /** * Returns true if integer is a power of two. * @param {Number} x A numeric expression. */ export function isPowerOfTwo(x: number): boolean; /** * The number of combinations of n objects from a pool of m objects (m>n). * @param {Number} m The first numeric expression. * @param {Number} n The second numeric expression. */ export function binomial(m: number, n: number): number; /** * Start iterating over "m choose n" objects. * @param {Number} [m] The first numeric expression. * @param {Number} [n] The second numeric expression. */ export function beginCombination(m?: number, n?: number): number; /** * Given m, n, and a valid combination of n integers in the range [0,m[, this * function alters the integers into the next combination in a sequence of all * combinations of n items from a pool of m. * @param {Number} m The first numeric expression. * @param {Number} n The second numeric expression. * @param {Number[]} r */ export function nextCombination(m: number, n: number, r: number[]): number; /** * Initialize seed value. * @param {Number} seed */ export function randomSeed(seed: number): void; /** * Return the current seed used by the random number generator. */ export function getSeed(): number; /** * Generate pseudo-random numbers distributed according to the uniform * distribution between min and max. * @param {Number} minValue * @param {Number} maxValue */ export function random(minValue: number, maxValue: number): number; /** * Addition of two 3-vectors. * @param {Vector3} a The first 3D vector. * @param {Vector3} b The second 3D vector. * @param {Vector3} out The output 3D vector. * @example * ```js * a[3] + b[3] => out[3] * ``` */ export function add(a: Vector3, b: Vector3, out: Vector3): Vector3; /** * Subtraction of two 3-vectors. * @param {Vector3} a The first 3D vector. * @param {Vector3} b The second 3D vector. * @param {Vector3} out The output 3D vector. * @example * ```js * a[3] - b[3] => out[3] * ``` */ export function subtract(a: Vector3, b: Vector3, out: Vector3): Vector3; /** * * @param {Vector3} vec * @param {Number} scalar * @example * ```js * vec[3] * scalar => vec[3] * ``` */ export function multiplyScalar(vec: Vector3, scalar: number): Vector3; /** * * @param {Vector2} vec * @param {Number} scalar * @example * ```js * vec[3] * scalar => vec[3] * ``` */ export function multiplyScalar2D(vec: Vector2, scalar: number): Vector2; /** * * @param {Vector3} a * @param {Vector3} b * @param {Number} scalar * @param {Vector3} out * @example * ```js * a[3] + b[3] * scalar => out[3] * ``` */ export function multiplyAccumulate(a: Vector3, b: Vector3, scalar: number, out: Vector3): Vector3; /** * * @param {Vector2} a * @param {Vector2} b * @param {Number} scalar * @param {Vector2} out * @example * ```js * a[2] + b[2] * scalar => out[2] * ``` */ export function multiplyAccumulate2D(a: Vector2, b: Vector2, scalar: number, out: Vector2): Vector2; /** * * @param {Vector3} x * @param {Vector3} y * @example * ```js * a[2] + b[2] * scalar => out[2] * ``` */ export function dot(x: Vector3, y: Vector3): number; /** * Outer product of two 3-vectors. * @param {Vector3} x The first 3D vector. * @param {Vector3} y The second 3D vector. * @param {Matrix3x3} out_3x3 The output 3x3 matrix. */ export function outer(x: Vector3, y: Vector3, out_3x3: Matrix3x3): void; /** * Computes cross product of 3D vectors x and y. * @param {Vector3} x The first 3D vector. * @param {Vector3} y The second 3D vector. * @param {Vector3} out The output 3D vector. */ export function cross(x: Vector3, y: Vector3, out: Vector3): Vector3; /** * * @param {Number[]} x * @param {Number} n */ export function norm(x: number[], n: number): number; /** * Normalize in place. Returns norm. * @param {Vector3} x The vector to normlize. */ export function normalize(x: Vector3): number; /** * Given a unit vector v1, find two unit vectors v2 and v3 such that v1 cross v2 = v3 * @param {Vector3} x The first vector. * @param {Vector3} y The second vector. * @param {Vector3} z The third vector. * @param {Number} theta */ export function perpendiculars(x: Vector3, y: Vector3, z: Vector3, theta: number): void; /** * * @param {Vector3} a * @param {Vector3} b * @param {Vector3} projection */ export function projectVector(a: Vector3, b: Vector3, projection: Vector3): boolean; /** * * @param {Vector2} x * @param {Vector2} y */ export function dot2D(x: Vector2, y: Vector2): number; /** * Compute the projection of 2D vector `a` on 2D vector `b` and returns the * result in projection vector. * @param {Vector2} a The first 2D vector. * @param {Vector2} b The second 2D vector. * @param {Vector2} projection The projection 2D vector. */ export function projectVector2D(a: Vector2, b: Vector2, projection: Vector2): boolean; /** * Compute distance squared between two points p1 and p2. * @param {Vector3} x The first 3D vector. * @param {Vector3} y The second 3D vector. */ export function distance2BetweenPoints(x: Vector3, y: Vector3): number; /** * Angle between 3D vectors. * @param {Vector3} v1 The first 3D vector. * @param {Vector3} v2 The second 3D vector. */ export function angleBetweenVectors(v1: Vector3, v2: Vector3): number; /** * Signed angle between v1 and v2 with regards to plane defined by normal vN. * angle between v1 and v2 with regards to plane defined by normal vN.Signed * angle between v1 and v2 with regards to plane defined by normal * vN.t3(mat_3x3, in_3, out_3) * @param {Vector3} v1 The first 3D vector. * @param {Vector3} v2 The second 3D vector. * @param {Vector3} vN */ export function signedAngleBetweenVectors(v1: Vector3, v2: Vector3, vN: Vector3): number; /** * Compute the amplitude of a Gaussian function with mean=0 and specified variance. * @param {Number} mean The mean value. * @param {Number} variance The variance value. * @param {Number} position The position value. */ export function gaussianAmplitude(mean: number, variance: number, position: number): number; /** * Compute the amplitude of an unnormalized Gaussian function with mean=0 and * specified variance. * @param {Number} mean The mean value. * @param {Number} variance The variance value. * @param {Number} position The position value. */ export function gaussianWeight(mean: number, variance: number, position: number): number; /** * Outer product of two 2-vectors. * @param {Vector2} x The first 2D vector. * @param {Vector2} y The second 2D vector. * @param {Matrix} out_2x2 The output 2x2 matrix. */ export function outer2D(x: Vector2, y: Vector2, out_2x2: Matrix): void; /** * Compute the norm of a 2-vector. * @param {Vector2} x2D x The 2D vector. */ export function norm2D(x2D: Vector2): number; /** * Normalize (in place) a 2-vector. * @param {Vector2} x The 2D vector. */ export function normalize2D(x: Vector2): number; /** * * @param {Number[][]|Number[]} args */ export function determinant2x2(args: number[][]|number[]): number; /** * LU Factorization of a 3x3 matrix. * @param {Matrix3x3} mat_3x3 * @param {Vector3} index_3 */ export function LUFactor3x3(mat_3x3: Matrix3x3, index_3: Vector3): void; /** * LU back substitution for a 3x3 matrix. * @param {Matrix3x3} mat_3x3 * @param {Vector3} index_3 * @param {Vector3} x_3 */ export function LUSolve3x3(mat_3x3: Matrix3x3, index_3: Vector3, x_3: Vector3): void; /** * Solve mat_3x3y_3 = x_3 for y and place the result in y. * @param {Matrix3x3} mat_3x3 * @param {Vector3} x_3 * @param {Vector3} y_3 */ export function linearSolve3x3(mat_3x3: Matrix3x3, x_3: Vector3, y_3: Vector3): void; /** * * @param {Matrix3x3} mat_3x3 * @param {Vector3} in_3 * @param {Vector3} out_3 */ export function multiply3x3_vect3(mat_3x3: Matrix3x3, in_3: Vector3, out_3: Vector3): void; /** * * @param {Matrix3x3} a_3x3 * @param {Matrix3x3} b_3x3 * @param {Matrix3x3} out_3x3 */ export function multiply3x3_mat3(a_3x3: Matrix3x3, b_3x3: Matrix3x3, out_3x3: Matrix3x3): void; /** * Multiply two matrices. * @param {Matrix} a * @param {Matrix} b * @param {Number} rowA * @param {Number} colA * @param {Number} rowB * @param {Number} colB * @param {Matrix} out_rowXcol */ export function multiplyMatrix(a: Matrix, b: Matrix, rowA: number, colA: number, rowB: number, colB: number, out_rowXcol: Matrix): void; /** * Transpose a 3x3 matrix. * @param {Matrix3x3} in_3x3 The input 3x3 matrix. * @param {Matrix3x3} outT_3x3 The output 3x3 matrix. */ export function transpose3x3(in_3x3: Matrix3x3, outT_3x3: Matrix3x3): void; /** * Invert a 3x3 matrix. * @param {Matrix3x3} in_3x3 The input 3x3 matrix. * @param {Matrix3x3} outI_3x3 The output 3x3 matrix. */ export function invert3x3(in_3x3: Matrix3x3, outI_3x3: Matrix3x3): void; /** * Set mat_3x3 to the identity matrix. * @param {Matrix3x3} mat_3x3 The input 3x3 matrix. */ export function identity3x3(mat_3x3: Matrix3x3): void; /** * Calculate the determinant of a 3x3 matrix. * @param {Matrix3x3} mat_3x3 The input 3x3 matrix. */ export function determinant3x3(mat_3x3: Matrix3x3): number; /** * * @param {Vector4} quat_4 * @param {Matrix3x3} mat_3x3 */ export function quaternionToMatrix3x3(quat_4: Vector4, mat_3x3: Matrix3x3): void; /** * Returns true if elements of both arrays are equals. * @param {Number[]} a An array of numbers (vector, point, matrix...) * @param {Number[]} b An array of numbers (vector, point, matrix...) * @param {Number} [eps] The tolerance value. */ export function areEquals(a: number[], b: number[], eps?: number): boolean; /** * * @param {Number} num * @param {Number} [digits] */ export function roundNumber(num: number, digits?: number): number; /** * * @param {Vector3} vector * @param {Vector3} [out] * @param {Number} [digits] */ export function roundVector(vector: Vector3, out?: Vector3, digits?: number): Vector3; /** * * @param {Matrix} a * @param {Number} n * @param {Number[]} w * @param {Number[]} v */ export function jacobiN(a: Matrix, n: number, w: number[], v: number[]): number; /** * * @param {Matrix3x3} mat_3x3 * @param {Vector4} quat_4 */ export function matrix3x3ToQuaternion(mat_3x3: Matrix3x3, quat_4: Vector4): void; /** * * @param {Vector4} quat_1 * @param {Vector4} quat_2 * @param {Vector4} quat_out */ export function multiplyQuaternion(quat_1: Vector4, quat_2: Vector4, quat_out: Vector4): void; /** * * @param {Matrix3x3} a_3x3 * @param {Matrix3x3} out_3x3 */ export function orthogonalize3x3(a_3x3: Matrix3x3, out_3x3: Matrix3x3): void; /** * * @param {Matrix3x3} a_3x3 * @param {Vector3} w_3 * @param {Matrix3x3} v_3x3 */ export function diagonalize3x3(a_3x3: Matrix3x3, w_3: Vector3, v_3x3: Matrix3x3): void; /** * * @param {Matrix3x3} a_3x3 * @param {Matrix3x3} u_3x3 * @param {Vector3} w_3 * @param {Matrix3x3} vT_3x3 */ export function singularValueDecomposition3x3(a_3x3: Matrix3x3, u_3x3: Matrix3x3, w_3: Vector3, vT_3x3: Matrix3x3): void; /** * * @param {Matrix} A * @param {Number[]} index * @param {Number} size */ export function luFactorLinearSystem(A: Matrix, index: number[], size: number): number; /** * * @param {Matrix} A * @param {Number[]} index * @param {Number[]} x * @param {Number} size */ export function luSolveLinearSystem(A: Matrix, index: number[], x: number[], size: number): void; /** * * @param {Matrix} A * @param {Number[]} x * @param {Number} size */ export function solveLinearSystem(A: Matrix, x: number[], size: number): number; /** * * @param {Matrix} A * @param {Matrix} AI * @param {Number} [size] * @param {Number[]} [index] * @param {Number[]} [column] */ export function invertMatrix(A: Matrix, AI: Matrix, size?: number, index?: number[], column?: number[]): number; /** * * @param {Matrix} A * @param {Number} size */ export function estimateMatrixCondition(A: Matrix, size: number): number; /** * * @param {Matrix3x3} a_3x3 * @param {Number[]} w * @param {Number[]} v */ export function jacobi(a_3x3: Matrix3x3, w: number[], v: number[]): number; /** * Solves for the least squares best fit matrix for the homogeneous equation * X'M' = 0'. Uses the method described on pages 40-41 of Computer Vision by * Forsyth and Ponce, which is that the solution is the eigenvector associated * with the minimum eigenvalue of T(X)X, where T(X) is the transpose of X. The * inputs and output are transposed matrices. Dimensions: X' is numberOfSamples * by xOrder, M' dimension is xOrder by yOrder. M' should be pre-allocated. All * matrices are row major. The resultant matrix M' should be pre-multiplied to * X' to get 0', or transposed and then post multiplied to X to get 0 * @param {Number} numberOfSamples * @param {Matrix} xt * @param {Number} xOrder * @param {Matrix} mt */ export function solveHomogeneousLeastSquares(numberOfSamples: number, xt: Matrix, xOrder: number, mt: Matrix): number; /** * Solves for the least squares best fit matrix for the equation X'M' = Y'. Uses * pseudoinverse to get the ordinary least squares. The inputs and output are * transposed matrices. Dimensions: X' is numberOfSamples by xOrder, Y' is * numberOfSamples by yOrder, M' dimension is xOrder by yOrder. M' should be * pre-allocated. All matrices are row major. The resultant matrix M' should be * pre-multiplied to X' to get Y', or transposed and then post multiplied to X * to get Y By default, this method checks for the homogeneous condition where * Y==0, and if so, invokes SolveHomogeneousLeastSquares. For better performance * when the system is known not to be homogeneous, invoke with * checkHomogeneous=0. * @param {Number} numberOfSamples * @param {Matrix} xt * @param {Number} xOrder * @param {Matrix} yt * @param {Number} yOrder * @param {Matrix} mt * @param {Boolean} [checkHomogeneous] */ export function solveLeastSquares(numberOfSamples: number, xt: Matrix, xOrder: number, yt: Matrix, yOrder: number, mt: Matrix, checkHomogeneous?: boolean): number; /** * * @param {String} hexStr * @param {Number[]} [outFloatArray] */ export function hex2float(hexStr: string, outFloatArray?: number[]): number[]; /** * * @param {RGBColor} rgb An Array of the RGB color. * @param {HSVColor} hsv An Array of the HSV color. */ export function rgb2hsv(rgb: RGBColor, hsv: HSVColor): void; /** * * @param {HSVColor} hsv An Array of the HSV color. * @param {RGBColor} rgb An Array of the RGB color. */ export function hsv2rgb(hsv: HSVColor, rgb: RGBColor): void; /** * * @param {Vector3} lab * @param {Vector3} xyz */ export function lab2xyz(lab: Vector3, xyz: Vector3): void; /** * * @param {Vector3} xyz * @param {Vector3} lab */ export function xyz2lab(xyz: Vector3, lab: Vector3): void; /** * * @param {Vector3} xyz * @param {RGBColor} rgb An Array of the RGB color. */ export function xyz2rgb(xyz: Vector3, rgb: RGBColor): void; /** * * @param {RGBColor} rgb An Array of the RGB color. * @param {Vector3} xyz */ export function rgb2xyz(rgb: RGBColor, xyz: Vector3): void; /** * * @param {RGBColor} rgb * @param {Vector3} lab */ export function rgb2lab(rgb: RGBColor, lab: Vector3): void; /** * * @param {Vector3} lab * @param {RGBColor} rgb An Array of the RGB color. */ export function lab2rgb(lab: Vector3, rgb: RGBColor): void; /** * Returns bounds. * @param {Bounds} bounds Output array that hold bounds, optionally empty. */ export function uninitializeBounds(bounds: Bounds): Bounds; /** * * @param {Bounds} bounds The bounds to check. */ export function areBoundsInitialized(bounds: Bounds): boolean; /** * Compute the bounds from points. * @param {Vector3} point1 The coordinate of the first point. * @param {Vector3} point2 The coordinate of the second point. * @param {Bounds} bounds Output array that hold bounds, optionally empty. */ export function computeBoundsFromPoints(point1: Vector3, point2: Vector3, bounds: Bounds): Bounds; /** * Clamp some value against a range. * @param {Number} value The value to clamp. * @param {Number} minValue The minimum value. * @param {Number} maxValue The maximum value. */ export function clampValue(value: number, minValue: number, maxValue: number): number; /** * Clamp some vector against a range. * @param {Vector3} vector The vector to clamp. * @param {Vector3} minVector The minimum vector. * @param {Vector3} maxVector The maximum vector. * @param {Vector3} out The output vector. */ export function clampVector(vector: Vector3, minVector: Vector3, maxVector: Vector3, out: Vector3): Vector3; /** * * @param {Vector3} vector * @param {Vector3} out */ export function roundVector(vector: Vector3, out: Vector3): Vector3; /** * * @param {Number} value * @param {Range} range */ export function clampAndNormalizeValue(value: number, range: Range): number; /** * Get the scalar type that is most likely to have enough precision to store a * given range of data once it has been scaled and shifted */ export function getScalarTypeFittingRange(): void; /** * */ export function getAdjustedScalarRange(): void; /** * Check if first 3D extent is within second 3D extent. * @param {Extent} extent1 The first extent. * @param {Extent} extent2 The second extent. */ export function extentIsWithinOtherExtent(extent1: Extent, extent2: Extent): number; /** * Check if first 3D bounds is within the second 3D bounds. * @param {Bounds} bounds1_6 The first bounds. * @param {Bounds} bounds2_6 The second bounds. * @param {Vector3} delta_3 The error margin along each axis. */ export function boundsIsWithinOtherBounds(bounds1_6: Bounds, bounds2_6: Bounds, delta_3: Vector3): number; /** * Check if point is within the given 3D bounds. * @param {Vector3} point_3 The coordinate of the point. * @param {Bounds} bounds_6 The bounds. * @param {Vector3} delta_3 The error margin along each axis. */ export function pointIsWithinBounds(point_3: Vector3, bounds_6: Bounds, delta_3: Vector3): number; /** * In Euclidean space, there is a unique circle passing through any given three * non-collinear points P1, P2, and P3. * * Using Cartesian coordinates to represent these points as spatial vectors, it * is possible to use the dot product and cross product to calculate the radius * and center of the circle. See: * http://en.wikipedia.org/wiki/Circumscribed_circle and more specifically the * section Barycentric coordinates from cross- and dot-products * @param {Vector3} p1 The coordinate of the first point. * @param {Vector3} p2 The coordinate of the second point. * @param {Vector3} p3 The coordinate of the third point. * @param {Vector3} center The coordinate of the center point. */ export function solve3PointCircle(p1: Vector3, p2: Vector3, p3: Vector3, center: Vector3): number; /** * Determines whether the passed value is a infinite number. * @param {Number} value The value to check. */ export function isInf(value: number): boolean; /** * */ export function createUninitializedBounds(): Bounds; /** * * @param {Number[]} vector */ export function getMajorAxisIndex(vector: number[]): number; /** * * @param {Number} value The value to convert. */ export function floatToHex2(value: number): string; /** * * @param {RGBColor} rgbArray * @param {string} [prefix] */ export function floatRGB2HexCode(rgbArray: RGBColor | RGBAColor, prefix?: string): string; /** * Convert RGB or RGBA color array to CSS representation * @param {RGBColor|RGBAColor} rgbArray The color array. */ export function float2CssRGBA(rgbArray: RGBColor | RGBAColor): string; /** * Determines whether the passed value is a NaN. * @param {Number} value The value to check. */ export function isNan(value: number): boolean; /** * Determines whether the passed value is a NaN. * @param {Number} value The value to check. */ export function isNaN(value: number): boolean; /** * Determines whether the passed value is a finite number. * @param value The value to check. */ export function isFinite(value: any): boolean; /** * vtkMath provides methods to perform common math operations. These include * providing constants such as Pi; conversion from degrees to radians; vector * operations such as dot and cross products and vector norm; matrix determinant * for 2x2 and 3x3 matrices; univariate polynomial solvers; and for random * number generation (for backward compatibility only). */ export declare const vtkMath: { createArray: typeof createArray; Pi: typeof Pi; radiansFromDegrees: typeof radiansFromDegrees; degreesFromRadians: typeof degreesFromRadians; round: typeof round; floor: typeof floor; ceil: typeof ceil; min: typeof min; max: typeof max; arrayMin: typeof arrayMin; arrayMax: typeof arrayMax; arrayRange: typeof arrayRange; ceilLog2: typeof ceilLog2; factorial: typeof factorial; gaussian: typeof gaussian; nearestPowerOfTwo: typeof nearestPowerOfTwo; isPowerOfTwo: typeof isPowerOfTwo; binomial: typeof binomial; beginCombination: typeof beginCombination; nextCombination: typeof nextCombination; randomSeed: typeof randomSeed; getSeed: typeof getSeed; random: typeof random; add: typeof add; subtract: typeof subtract; multiplyScalar: typeof multiplyScalar; multiplyScalar2D: typeof multiplyScalar2D; multiplyAccumulate: typeof multiplyAccumulate; multiplyAccumulate2D: typeof multiplyAccumulate2D; dot: typeof dot; outer: typeof outer; cross: typeof cross; norm: typeof norm; normalize: typeof normalize; perpendiculars: typeof perpendiculars; projectVector: typeof projectVector; dot2D: typeof dot2D; projectVector2D: typeof projectVector2D; distance2BetweenPoints: typeof distance2BetweenPoints; angleBetweenVectors: typeof angleBetweenVectors; gaussianAmplitude: typeof gaussianAmplitude; gaussianWeight: typeof gaussianWeight; outer2D: typeof outer2D; norm2D: typeof norm2D; normalize2D: typeof normalize2D; determinant2x2: typeof determinant2x2; LUFactor3x3: typeof LUFactor3x3; LUSolve3x3: typeof LUSolve3x3; linearSolve3x3: typeof linearSolve3x3; multiply3x3_vect3: typeof multiply3x3_vect3; multiply3x3_mat3: typeof multiply3x3_mat3; multiplyMatrix: typeof multiplyMatrix; transpose3x3: typeof transpose3x3; invert3x3: typeof invert3x3; identity3x3: typeof identity3x3; determinant3x3: typeof determinant3x3; quaternionToMatrix3x3: typeof quaternionToMatrix3x3; areEquals: typeof areEquals; areMatricesEqual: typeof areEquals; roundNumber: typeof roundNumber; roundVector: typeof roundVector; jacobiN: typeof jacobiN; matrix3x3ToQuaternion: typeof matrix3x3ToQuaternion; multiplyQuaternion: typeof multiplyQuaternion; orthogonalize3x3: typeof orthogonalize3x3; diagonalize3x3: typeof diagonalize3x3; singularValueDecomposition3x3: typeof singularValueDecomposition3x3; luFactorLinearSystem: typeof luFactorLinearSystem; luSolveLinearSystem: typeof luSolveLinearSystem; solveLinearSystem: typeof solveLinearSystem; invertMatrix: typeof invertMatrix; estimateMatrixCondition: typeof estimateMatrixCondition; jacobi: typeof jacobi; solveHomogeneousLeastSquares: typeof solveHomogeneousLeastSquares; solveLeastSquares: typeof solveLeastSquares; hex2float: typeof hex2float; rgb2hsv: typeof rgb2hsv; hsv2rgb: typeof hsv2rgb; lab2xyz: typeof lab2xyz; xyz2lab: typeof xyz2lab; xyz2rgb: typeof xyz2rgb; rgb2xyz: typeof rgb2xyz; rgb2lab: typeof rgb2lab; lab2rgb: typeof lab2rgb; uninitializeBounds: typeof uninitializeBounds; areBoundsInitialized: typeof areBoundsInitialized; computeBoundsFromPoints: typeof computeBoundsFromPoints; clampValue: typeof clampValue; clampVector: typeof clampVector; clampAndNormalizeValue: typeof clampAndNormalizeValue; getScalarTypeFittingRange: typeof getScalarTypeFittingRange; getAdjustedScalarRange: typeof getAdjustedScalarRange; extentIsWithinOtherExtent: typeof extentIsWithinOtherExtent; boundsIsWithinOtherBounds: typeof boundsIsWithinOtherBounds; pointIsWithinBounds: typeof pointIsWithinBounds; solve3PointCircle: typeof solve3PointCircle; isInf: typeof isInf; createUninitializedBounds: typeof createUninitializedBounds; getMajorAxisIndex: typeof getMajorAxisIndex; floatToHex2: typeof floatToHex2; floatRGB2HexCode: typeof floatRGB2HexCode; float2CssRGBA: typeof float2CssRGBA; inf: number; negInf: number; isNan: typeof isNaN, isNaN: typeof isNaN; isFinite: typeof isFinite } export default vtkMath;
the_stack
import { toTitleCase } from '../../util'; import ProcessedTable from '../../models/processedTable'; import IDBProvider from '../provider/dbProvider'; import ProcessedField from '../../models/processedField'; const tab = ` `; class TypeBuilder { private graphqlCode: string private typeSchemaCode: string private rootQueryCode: string private mutationCode: string constructor(private provider: IDBProvider) { this.graphqlCode = this.init(); this.typeSchemaCode = ''; this.rootQueryCode = `const RootQuery = new GraphQLObjectType({\n${tab}name: 'RootQueryType',\n${tab}fields: {\n`; this.mutationCode = `const Mutation = new GraphQLObjectType({\n${tab}name: 'Mutation',\n${tab}fields: {\n`; } build() { this.rootQueryCode += `\n${tab}}\n});\n\n`; this.mutationCode += `\n${tab}}\n});\n\n`; this.graphqlCode += this.typeSchemaCode + this.rootQueryCode + this.mutationCode; this.graphqlCode += this.provider.configureExport(); return this.graphqlCode; } addGraphqlTypeSchema(table: ProcessedTable, processedMetadata: { [key: number]: ProcessedTable }) { let subQuery = ''; let typeQuery = `const ${ table.displayName }Type = new GraphQLObjectType({\n${tab}name: '${ table.displayName }',\n${tab}fields: () => ({`; let firstLoop = true; for (const field of table.fields) { if (!firstLoop) typeQuery += ','; // check the field current name and give it a graphQL type typeQuery += `\n${tab.repeat(2)}${ field.name }: { type: ${this.tableDataTypeToGraphqlType(field.type)} }`; // later try to maintain the foreign key field to be the primary value?? NO if (field.inRelationship) { subQuery += `${this.createSubQuery(field, processedMetadata)}, `; } firstLoop = false; } if (subQuery !== '') typeQuery += ','; typeQuery += subQuery.slice(0, -2); typeQuery += `\n${tab}})\n});\n\n`; this.typeSchemaCode += typeQuery; return this; } private createSubQuery(column: ProcessedField, processedMetadata: { [key: number]: ProcessedTable }) { const subqueries = []; for (const rel in column.relation) { let subQuery = ''; const [relatedTableIdx, relatedColIdx] = rel.split('.').map(i => parseInt(i)); const { displayName: rtDisplayName, name: rtName } = processedMetadata[relatedTableIdx]; const relatedFieldName = processedMetadata[relatedTableIdx].fields[relatedColIdx].name; const relatedTableRelationType = column.relation[rel].refType; subQuery += `\n${tab.repeat(2)}${this.createSubQueryName( relatedTableRelationType, rtDisplayName )}: {\n${tab.repeat(3)}type: `; if (relatedTableRelationType === 'one to many') { subQuery += `new GraphQLList(${rtDisplayName}Type),`; } else { subQuery += `${rtDisplayName}Type,`; } subQuery += `\n${tab.repeat(3)}resolve(parent, args) {\n${tab.repeat(4)}`; subQuery += this.provider.selectWithWhere( rtName, relatedFieldName, `parent.${column.name}`, relatedTableRelationType === 'one to many' ); subQuery += '\n'; subQuery += `${tab.repeat(3)}}\n`; subQuery += `${tab.repeat(2)}}`; subqueries.push(subQuery); } return subqueries.join(', '); } addGraphqlRootCode(table: ProcessedTable) { let rootQuery = ''; rootQuery += this.createFindAllRootQuery(table); // primarykey id is not always the first field in our data for (const field of table.fields) { if (field.primaryKey) { rootQuery += this.createFindByIdQuery(table, field); } } this.rootQueryCode += rootQuery; return this; } private createFindAllRootQuery(table: ProcessedTable) { let rootQuery = `${tab.repeat(2)}every${toTitleCase( table.displayName )}: {\n${tab.repeat(3)}type: new GraphQLList(${ table.displayName }Type),\n${tab.repeat(3)}resolve() {\n${tab.repeat(4)}`; rootQuery += this.provider.select(table.name); return rootQuery += `\n${tab.repeat(3)}}\n${tab.repeat(2)}}`; } private createFindByIdQuery(table: ProcessedTable, idColumn: ProcessedField) { let rootQuery = `,\n${tab.repeat( 2 )}${table.displayName.toLowerCase()}: {\n${tab.repeat(3)}type: ${ table.displayName }Type,\n${tab.repeat(3)}args: {\n${tab.repeat(4)}${ idColumn.name }: { type: ${this.tableDataTypeToGraphqlType(idColumn.type)} }\n${tab.repeat( 3 )}},\n${tab.repeat(3)}resolve(parent, args) {\n${tab.repeat(4)}`; rootQuery += this.provider.selectWithWhere( table.name, idColumn.name, `args.${idColumn.name}`, false ); return rootQuery += `\n${tab.repeat(3)}}\n${tab.repeat(2)}}`; } addGraphqlMutationCode(table: ProcessedTable) { let mutationQuery = ``; mutationQuery += `${this.addMutation(table)}`; if (table.fields[0]) { mutationQuery += `,\n${this.updateMutation(table)},\n`; mutationQuery += `${this.deleteMutation(table)}`; } this.mutationCode += mutationQuery; return this; } private addMutation(table: ProcessedTable) { let mutationQuery = `${tab.repeat(2)}add${toTitleCase( table.displayName )}: {\n${tab.repeat(3)}type: ${table.displayName}Type,\n${tab.repeat( 3 )}args: {\n`; let fieldNames = ''; let argNames = ''; let firstLoop = true; for (const field of table.fields) { if (!firstLoop) mutationQuery += ',\n'; firstLoop = false; // dont need the ID for adding new row because generated in SQL if (!field.primaryKey) { mutationQuery += `${tab.repeat(4)}${field.name}: ${this.buildMutationArgType( field )}`; fieldNames += `${field.name}, `; argNames += `\${args.${field.name}}, `; } else { firstLoop = true; } } fieldNames = fieldNames.slice(0, -2); argNames = argNames.slice(0, -2); mutationQuery += `\n${tab.repeat(3)}},\n${tab.repeat( 3 )}resolve(parent, args) {\n${tab.repeat(4)}`; mutationQuery += this.loadBinaryDataToBuffer(table.fields); mutationQuery += this.provider.insert(table.name, fieldNames, argNames); return mutationQuery += `\n${tab.repeat(3)}}\n${tab.repeat(2)}}`; } private loadBinaryDataToBuffer(fields: ProcessedField[]) { return fields.reduce((acc, curr) => { if (curr.type === "IntegerList") { acc += `${tab.repeat(4)}args.${curr.name} ? args.${curr.name} = Buffer.from(args.${curr.name}) : undefined \n` } return acc }, "") } private updateMutation(table: ProcessedTable) { let idColumnName; for (const field of table.fields) { if (field.primaryKey) { idColumnName = field.name; } } let mutationQuery = `${tab.repeat(2)}update${toTitleCase( table.displayName )}: {\n${tab.repeat(3)}type: ${table.displayName}Type,\n${tab.repeat( 3 )}args: {\n`; let firstLoop = true; for (const field of table.fields) { if (!firstLoop) mutationQuery += ',\n'; firstLoop = false; mutationQuery += `${tab.repeat(4)}${field.name}: ${this.buildMutationArgType( field )}`; } mutationQuery += `\n${tab.repeat(3)}},\n${tab.repeat( 3 )}resolve(parent, args) {\n`; mutationQuery += `${tab.repeat( 4 )}const { ${idColumnName}, ...rest } = args;\n`; mutationQuery += this.loadBinaryDataToBuffer(table.fields) mutationQuery += this.provider.parameterize(table.fields); mutationQuery += `${tab.repeat(4)}${this.provider.update( table.name, idColumnName )}`; return mutationQuery += `\n${tab.repeat(3)}}\n${tab.repeat(2)}}`; } private deleteMutation(table: ProcessedTable) { let idColumn; for (const field of table.fields) { if (field.primaryKey) { idColumn = field; } } let mutationQuery = `${tab.repeat(2)}delete${toTitleCase( table.displayName )}: {\n${tab.repeat(3)}type: ${table.displayName}Type,\n${tab.repeat( 3 )}args: {\n${tab.repeat(4)}${ idColumn.name }: { type: ${this.tableDataTypeToGraphqlType(idColumn.type)} }\n${tab.repeat( 3 )}},\n${tab.repeat(3)}resolve(parent, args) {\n`; mutationQuery += `${tab.repeat(4)}${this.provider.delete( table.name, idColumn.name )}`; return mutationQuery += `\n${tab.repeat(3)}}\n${tab.repeat(2)}}`; } addNewLine(codeSegment: 'graphqlCode' | 'typeSchemaCode' | 'rootQueryCode' | 'mutationCode') { (<any>this)[codeSegment] += ',\n' } private createSubQueryName(relationType: string, relatedTable: string) { switch (relationType) { case 'one to one': return `related${toTitleCase(relatedTable)}`; case 'one to many': return `everyRelated${toTitleCase(relatedTable)}`; case 'many to one': return `related${toTitleCase(relatedTable)}`; default: return `everyRelated${toTitleCase(relatedTable)}`; } } private init() { let str = `const graphql = require('graphql');\nconst graphql_iso_date = require('graphql-iso-date');\n`; str += this.provider.connection(); str += `\nconst { GraphQLObjectType, GraphQLSchema, GraphQLID, GraphQLString, GraphQLInt, GraphQLBoolean, GraphQLList, GraphQLFloat, GraphQLNonNull } = graphql; \n`; str += `const { GraphQLDate, GraphQLTime, GraphQLDateTime } = graphql_iso_date; \n`; return str; } private tableDataTypeToGraphqlType(type: string) { switch (type) { case 'ID': return 'GraphQLID'; case 'String': return 'GraphQLString'; case 'Integer': return 'GraphQLInt'; case 'Float': return 'GraphQLFloat'; case 'Boolean': return 'GraphQLBoolean'; case 'Date': return 'GraphQLDate'; case 'Time': return 'GraphQLTime'; case 'DateTime': return 'GraphQLDateTime'; case 'IntegerList': return 'new GraphQLList(GraphQLInt)' default: return 'GraphQLString'; } } private buildMutationArgType(column: ProcessedField) { const mutationQuery = `{ type: ${this.checkifColumnRequired( column.required, 'front' )}${this.tableDataTypeToGraphqlType(column.type)}${this.checkifColumnRequired( column.required, 'back' )} }`; return mutationQuery; } private checkifColumnRequired(required: boolean, position: string) { if (required) { if (position === 'front') { return 'new GraphQLNonNull('; } return ')'; } return ''; } } export default TypeBuilder;
the_stack
// // var quat = new Quat(); // // document.write(quat.x + "") // // var segment = new Segment(v3(10, 20, 0), v3(100, 100, 0)); // // const distance = v.distanceSegment(segment); // // document.write(JSON.stringify(distance)) // const vs = ` // uniform mat4 u,worldViewProjection; // uniform vec3 u,lightWorldPos; // uniform mat4 u,world; // uniform mat4 u,viewInverse; // uniform mat4 u,worldInverseTranspose; // attribute vec4 position; // attribute vec3 normal; // attribute vec2 texcoord; // varying vec4 v,position; // varying vec2 v,texCoord; // varying vec3 v,normal; // varying vec3 v,surfaceToLight; // varying vec3 v,surfaceToView; // void main() { // v,texCoord = texcoord; // v,position = u,worldViewProjection * position; // v,normal = (u,worldInverseTranspose * vec4(normal, 0)).xyz; // v,surfaceToLight = u,lightWorldPos - (u,world * position).xyz; // v,surfaceToView = (u,viewInverse[3] - (u,world * position)).xyz; // gl,Position = v,position; // } // ` // const fs = ` // varying vec4 v,position; // varying vec2 v,texCoord; // varying vec3 v,normal; // varying vec3 v,surfaceToLight; // varying vec3 v,surfaceToView; // uniform vec4 u,lightColor; // uniform vec4 u,ambient; // uniform sampler2D u,diffuse; // uniform vec4 u,specular; // uniform float u,shininess; // uniform float u,specularFactor; // vec4 lit(float l, float h, float m) { // return vec4(1.0, // max(l, 0.0), // (l > 0.0) ? pow(max(0.0, h), m) : 0.0, // 1.0); // } // void main() { // vec4 diffuseColor = texture2D(u,diffuse, v,texCoord); // vec3 a,normal = normalize(v,normal); // vec3 surfaceToLight = normalize(v,surfaceToLight); // vec3 surfaceToView = normalize(v,surfaceToView); // vec3 halfVector = normalize(surfaceToLight + surfaceToView); // vec4 litR = lit(dot(a,normal, surfaceToLight), // dot(a,normal, halfVector), u,shininess); // vec4 outColor = vec4(( // u,lightColor * (diffuseColor * litR.y + diffuseColor * u,ambient + // u,specular * litR.z * u,specularFactor)).rgb, // diffuseColor.a); // gl,FragColor = outColor; // } // ` // const canvas = document.createElement('canvas'); // const renderer: WebGL2RenderingContext | WebGLRenderingContext = canvas.getContext("webgl2") || canvas.getContext("webgl")!; // const program = createProgram(renderer, { vertexShader: vs, fragmentShader: fs }) // const arrays = { // position: [1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1], // normal: [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1], // texcoord: [1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1], // indices: [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23], // }; // function render(time: number) { // requestAnimationFrame(render); // } // requestAnimationFrame(render) import * as cga from "./index" import { Vec3, v3 } from './math/Vec3'; import { GLView } from './glview'; import { Mesh, PlaneBufferGeometry, MeshBasicMaterial, DoubleSide, Vector3, LineSegments, LineBasicMaterial, MeshStandardMaterial, FrontSide, BufferGeometryUtils, WebGLRenderTarget, MeshNormalMaterial, MeshDepthMaterial, DepthTexture, MeshPhongMaterial, CanvasTexture, ShaderMaterial, } from 'three'; import { Delaunator } from './alg/delaunator'; import Delaunay from './alg/delaunay'; import { extrude, linkSides } from './alg/extrude'; import { Polyline } from './struct/3d/Polyline'; import { PI, PI_OVER_TWO, PI_TWO } from "./math/Math"; import { clone, scale, translate } from "./alg/common"; import { BufferGeometry } from "./render/geometry"; import { toGeoBuffer } from "./render/mesh"; // var a = Vec3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0); // console.log(a); var glv = new GLView({ container: document.body }); glv.run(); // var delaunay = new cga.Delaunay() // var vs = [] // var data = [] // for (let i = 0; i < 10000; i++) { // var x = Math.random() * 1000 - 500 // var y = Math.random() * 1000 - 500 // vs.push(new Vec3(x, y, 0)); // data.push(x, y); // } // // // var index = delaunay.triangulation(vs) // // var delaunator = Delaunay.from(data); // // // const delaunay1 = Delaunay.from(data); // // var index = delaunator.triangles; // // const voronoi = delaunator.voronoi([-520, -520, 520, 520]); // // var k = -1; // // var geometry = new Geometry(); // // while (k++ < 10000) { // // var vvs: any = voronoi._clip(k); // // debugger // // for (let i = 0; i < vvs.length; i++) { // // const e0 = vvs[i]; // // const e1 = vvs[(i + 1) % vvs.length]; // // geometry.vertices.push(new Vector3(e0[0], e0[1], 0)); // // geometry.vertices.push(new Vector3(e1[0], e1[1], 0)); // // } // // } // // var geo = toGeometryBuffer(vs, index) // // glv.add(new Mesh(geo, new MeshBasicMaterial({ wireframe: true, side: DoubleSide }))); // // glv.add(new LineSegments(geometry, new LineBasicMaterial({ color: 0xff0000 }))); // // var section = [-1, -1, -1, 1, 1, 1, 1, -1]; // // extrudeNext(section, path, { sectionClosed: true, pathClosed: false, vecdim: 2 }) // var pathx = [v3(-20, 0, 0), v3(-20, 0, 20), v3(20, 0, 20), v3(20, 0, 0)] // var polyline = new Polyline(pathx); // polyline.offset(1) const shape1: any = [new cga.Vec3(-10, -10, 0), new cga.Vec3(10, -10, 0), new cga.Vec3(10, 10, 0), new cga.Vec3(-10, 10, 0)] const path1: any = [new cga.Vec3(), new cga.Vec3(0, 0, 100)]; extrude({ shape: shape1, path: path1, enableSmooth: true }); var dizhu = (bottomR: number, topR: number, bh: number, gh: number, th: number) => { var bq: cga.Vec3[] = [] var tq: cga.Vec3[] = [] for (let i = 0; i < 33; i++) { var x = Math.cos(cga.PI_TWO / 32 * i) var z = Math.sin(cga.PI_TWO / 32 * i) bq.push(cga.v3(x, 0, z)); } tq = cga.clone(bq); cga.scale(bq, cga.v3(bottomR, 1, bottomR)) var bq1 = cga.clone(bq); cga.translate(bq1, cga.v3(0, bh, 0)) cga.scale(tq, cga.v3(topR, 1, topR)) var tq1 = cga.clone(tq); cga.translate(tq, cga.v3(0, bh + gh, 0)); cga.translate(tq1, cga.v3(0, bh + gh + th, 0)); var sides = [bq, bq1, cga.clone(bq1), tq, cga.clone(tq), tq1]; var index = { index: 0 }; var geo = cga.linkSides({ shapes: sides, index, orgShape: bq }); var geometry = cga.toGeometryBuffer(geo); return geometry; } var shape = [v3(-5, 0, 0), v3(5, 0, 0), v3(5, 0, 0), v3(5, 10, 0), v3(5, 10, 0), v3(-5, 10, 0), v3(-5, 10, 0)] var hole3 = [v3(-4, 5, 0), v3(-1, 5, 0), v3(-1, 5, 0), v3(-4, 9, 0), v3(-4, 9, 0), v3(-4, 5, 0)] var hole1 = [v3(1, 5, 0), v3(4, 5, 0), v3(4, 5, 0), v3(4, 9, 0), v3(4, 9, 0), v3(1, 9, 0), v3(1, 9, 0), v3(1, 5, 0)] var hole2 = [v3(-4, 1, 0), v3(4, 1, 0), v3(4, 1, 0), v3(4, 4, 0), v3(4, 4, 0), v3(-4, 4, 0), v3(-4, 4, 0), v3(-4, 1, 0)] var holes = [hole1, hole2, hole3] var path = []; var ia = Math.PI / 100; for (let i = 0; i <= 100; i++) { var x = Math.cos(ia * i) * 50 + 50; var y = Math.sin(ia * i) * 50; path.push(v3(x, y, 0)) } var geo = extrude({ shape: shape, path: path, right: Vec3.UnitZ, sealStart: true }) // var geo = dizhu(1.8, 0.9, 0.3, 0.5, 10); var geometry = cga.toGeometryBuffer(geo); geometry.computeVertexNormals(); import * as THREE from "three" import { diamondMaterial } from "./diamondMaterialShader"; import { BreathLight } from "./effect/breath-light"; import { Mat4 } from "./math/Mat4"; var tgeo = new THREE.BufferGeometry(); tgeo.setAttribute('position', new THREE.Float32BufferAttribute(geometry.getAttribute('position').array, 3)); tgeo.setAttribute('normal', new THREE.Float32BufferAttribute(geometry.getAttribute('normal').array, 3)); tgeo.setAttribute('uv', new THREE.Float32BufferAttribute(geometry.getAttribute('uv').array, 2)); tgeo.setIndex(new THREE.Uint16BufferAttribute(geometry.getIndex()!.array, 1)); var map = new THREE.TextureLoader().load("./assets/color.jpg"); map.repeat.set(0.4, 0.4) map.wrapT = map.wrapS = THREE.MirroredRepeatWrapping; var renderTarget = new WebGLRenderTarget(window.innerWidth, window.innerHeight, { depthTexture: new DepthTexture(window.innerWidth, window.innerHeight) }) var normalMaterial = new MeshNormalMaterial(); var mesh = new Mesh(tgeo, new MeshPhongMaterial({ map: map, side: FrontSide })); glv.add(mesh); // var mesh1 = new Mesh(new PlaneBufferGeometry(100, 100), new MeshBasicMaterial({ map: renderTarget.depthTexture, side: DoubleSide })); // glv.add(mesh1); // glv.addUpdates(() => { // glv.renderer.setRenderTarget(renderTarget); // glv.render(); // glv.renderer.setRenderTarget(null); // }) class LabelTexture { width: number; height: number; sideColor: string; areaColor: string; canvas: HTMLCanvasElement = document.createElement('canvas'); ctx: CanvasRenderingContext2D = this.canvas.getContext('2d')!; fontsize: number = 100; constructor(width: number = 1, height: number = 1, sideColor: string = "#1f9ccf", areaColor: string = "#1f9cff1f") { this.width = width; this.height = height; this.sideColor = sideColor; this.areaColor = areaColor } } glv.add(new BreathLight()) var label = new LabelTexture() var mesh1 = new Mesh(new PlaneBufferGeometry(100, 10), new MeshBasicMaterial({ map: new CanvasTexture(label.canvas), side: DoubleSide, transparent: true })); glv.add(mesh1); var shapeMaterial = new ShaderMaterial({ transparent: true, side: DoubleSide }); var planeGeo = new PlaneBufferGeometry(10, 10); planeGeo.translate(0, 5, -1) var mesh = new Mesh(planeGeo, shapeMaterial); glv.add(mesh) var m = new Mat4() var geo = extrude({ shape: shape, path: path, right: Vec3.UnitZ, sealStart: true }) var geometry = cga.toGeometryBuffer(geo); geometry.computeVertexNormals(); var tgeo = new THREE.BufferGeometry(); tgeo.setAttribute('position', new THREE.Float32BufferAttribute(geometry.getAttribute('position').array, 3)); tgeo.setAttribute('normal', new THREE.Float32BufferAttribute(geometry.getAttribute('normal').array, 3)); tgeo.setAttribute('uv', new THREE.Float32BufferAttribute(geometry.getAttribute('uv').array, 2)); tgeo.setIndex(new THREE.Uint16BufferAttribute(geometry.getIndex()!.array, 1)); var mesh = new Mesh(tgeo, new MeshPhongMaterial({}));
the_stack
import { DataQueryRequest, DataSourceApi, DataSourceInstanceSettings, TimeSeries, TableData, dateTime, TimeRange, TimeSeriesPoints, TimeSeriesValue, TIME_SERIES_TIME_FIELD_NAME, FieldType, MutableField, ArrayVector, MutableDataFrame, TIME_SERIES_VALUE_FIELD_NAME, MetricFindValue, } from '@grafana/data'; import StravaApi from './stravaApi'; import polyline from './polyline'; import { StravaActivityStat, StravaJsonData, StravaQuery, StravaQueryFormat, StravaActivityType, StravaQueryInterval, StravaQueryType, StravaActivityStream, StravaActivityData, StravaSplitStat, VariableQuery, } from './types'; import { smoothVelocityData, velocityDataToPace, velocityDataToSpeed, velocityToSpeed } from 'utils'; import { getTemplateSrv } from '@grafana/runtime'; const DEFAULT_RANGE = { from: dateTime(), to: dateTime(), raw: { from: 'now', to: 'now', }, }; export const DEFAULT_LIMIT = 100; export default class StravaDatasource extends DataSourceApi<StravaQuery, StravaJsonData> { type: any; datasourceId: number; apiUrl: string; stravaApi: StravaApi; activities: any[]; /** @ngInject */ constructor(instanceSettings: DataSourceInstanceSettings<StravaJsonData>) { super(instanceSettings); this.type = 'strava'; this.datasourceId = instanceSettings.id; this.apiUrl = instanceSettings.url!; this.stravaApi = new StravaApi(this.datasourceId); this.activities = []; } async query(options: DataQueryRequest<StravaQuery>) { const data: any[] = []; let activities = []; let queryActivities = options.targets.some((t) => t.queryType === StravaQueryType.Activities); if (queryActivities) { activities = await this.stravaApi.getActivities({ before: options.range?.to.unix(), after: options.range?.from.unix(), }); } for (const target of options.targets) { if (target.hide) { continue; } if (target.queryType === StravaQueryType.Activities) { const filteredActivities = this.filterActivities(activities, target.activityType); switch (target.format) { case StravaQueryFormat.Table: const tableData = this.transformActivitiesToTable(filteredActivities, target); data.push(tableData); break; case StravaQueryFormat.WorldMap: const wmData = this.transformActivitiesToWorldMap(filteredActivities, target); data.push(wmData); break; default: const tsData = this.transformActivitiesToTimeseries( filteredActivities, target, options.range || DEFAULT_RANGE ); data.push(tsData); break; } } else if (target.queryType === StravaQueryType.Activity) { const activityData = await this.queryActivity(options, target); data.push(activityData); } } return { data }; } async queryActivity(options: DataQueryRequest<StravaQuery>, target: StravaQuery) { const activityId = getTemplateSrv().replace(target.activityId?.toString()); const activity = await this.stravaApi.getActivity({ id: activityId, include_all_efforts: true, }); if (target.activityData === StravaActivityData.Stats) { return this.queryActivityStats(options, target, activity); } if (target.activityData === StravaActivityData.Splits) { return this.queryActivitySplits(options, target, activity); } let activityStream = target.activityGraph; if (activityStream === StravaActivityStream.Pace) { activityStream = StravaActivityStream.Velocity; } if (!activityStream) { return null; } const streams = await this.stravaApi.getActivityStreams({ id: activityId, streamType: activityStream, }); const timeFiled: MutableField<number> = { name: TIME_SERIES_TIME_FIELD_NAME, type: FieldType.time, config: { custom: {}, }, values: new ArrayVector(), }; const valueFiled: MutableField<number> = { name: activityStream, type: FieldType.number, config: { custom: {}, }, values: new ArrayVector(), }; const frame = new MutableDataFrame({ name: activity.name, refId: target.refId, fields: [], }); const stream = streams[activityStream]; if (!stream) { return frame; } let ts = dateTime(activity.start_date).unix(); if (target.fitToTimeRange) { ts = options.range.from.unix(); } let streamValues: number[] = []; for (let i = 0; i < stream.data.length; i++) { timeFiled.values.add(ts * 1000); streamValues.push(stream.data[i]); ts++; } if (activity.type === 'Run') { if (target.activityGraph === StravaActivityStream.Pace) { valueFiled.name = 'pace'; streamValues = velocityDataToPace(streamValues); } } else { if (target.activityGraph === StravaActivityStream.Velocity) { valueFiled.name = 'speed'; streamValues = velocityDataToSpeed(streamValues); } } // Smooth data if ( activityStream === StravaActivityStream.Velocity || activityStream === StravaActivityStream.HeartRate || activityStream === StravaActivityStream.GradeSmooth || activityStream === StravaActivityStream.WattsCalc || activityStream === StravaActivityStream.Watts ) { streamValues = smoothVelocityData(streamValues); } valueFiled.values = new ArrayVector(streamValues); frame.addField(timeFiled); frame.addField(valueFiled); return frame; } queryActivitySplits(options: DataQueryRequest<StravaQuery>, target: StravaQuery, activity: any) { const timeFiled: MutableField<number> = { name: TIME_SERIES_TIME_FIELD_NAME, type: FieldType.time, config: { custom: {}, }, values: new ArrayVector(), }; const splitStat = target.splitStat || ''; const valueFiled: MutableField<number> = { name: splitStat || TIME_SERIES_VALUE_FIELD_NAME, type: FieldType.number, config: { custom: {}, }, values: new ArrayVector(), }; const frame = new MutableDataFrame({ name: activity.name, refId: target.refId, fields: [], }); let ts = dateTime(activity.start_date).unix(); if (target.fitToTimeRange) { ts = options.range.from.unix(); } const splits: any[] = activity.splits_metric; for (let i = 0; i < splits.length; i++) { const split = splits[i]; timeFiled.values.add(ts * 1000); let value = split[splitStat]; if (splitStat === StravaSplitStat.Speed) { value = velocityToSpeed(value); } valueFiled.values.add(value); ts += split.moving_time; } frame.addField(timeFiled); frame.addField(valueFiled); return frame; } queryActivityStats(options: DataQueryRequest<StravaQuery>, target: StravaQuery, activity: any) { const stats = target.singleActivityStat || 'name'; const frame = new MutableDataFrame({ name: activity.name, refId: target.refId, fields: [{ name: 'time', type: FieldType.time }, { name: stats }], }); frame.add({ time: dateTime(activity.start_date), [stats]: activity[stats], }); return frame; } async metricFindQuery(query: VariableQuery, options?: any): Promise<MetricFindValue[]> { const limit = query.limit || DEFAULT_LIMIT; let activities = await this.stravaApi.getActivities({ limit }); activities = this.filterActivities(activities, query.activityType); const variableOptions: MetricFindValue[] = activities.map((a) => ({ value: a.id, text: a.name, })); return variableOptions; } async testDatasource() { const authCode = this.getAuthCode(); if (authCode) { // Exchange auth code for new refresh token if "Connect with Strava" button clicked try { await this.stravaApi.exchangeToken(authCode); } catch (err) { console.log(err); } } try { await this.stravaApi.getActivities({ per_page: 2, limit: 2 }); return { status: 'success', message: 'Data source is working' }; } catch (err) { return { status: 'error', message: 'Cannot connect to Strava API' }; } } getAuthCode() { const AuthCodePattern = /code=([\w]+)/; const result = AuthCodePattern.exec(window.location.search); const authCode = result && result.length && result[1]; return authCode; } filterActivities(activities: any[], activityType: StravaActivityType): any[] { if (!activityType) { // No filter, return all return activities; } return activities.filter((activity) => { if (activityType === 'Other') { return activity.type !== 'Run' && activity.type !== 'Ride'; } else { } return activity.type === activityType; }); } transformActivitiesToTimeseries(data: any[], target: StravaQuery, range: TimeRange): TimeSeries { let datapoints: any[] = []; for (const activity of data) { datapoints.push([activity[target.activityStat], dateTime(activity.start_date).valueOf()]); } datapoints.sort((dpA, dpB) => dpA[1] - dpB[1]); if (target.interval !== StravaQueryInterval.No) { const aggInterval = !target.interval || target.interval === StravaQueryInterval.Auto ? getAggregationInterval(range) : getAggregationIntervalFromTarget(target); if (aggInterval >= INTERVAL_4w) { datapoints = groupByMonthSum(datapoints, range); } else if (aggInterval === INTERVAL_1w) { datapoints = groupByWeekSum(datapoints, range); } else { datapoints = groupBySum(datapoints, range, aggInterval); } } const alias = `${target.activityType ? target.activityType + '_' : ''}${target.activityStat}`; return { target: alias, datapoints, }; } transformActivitiesToTable(data: any[], target: StravaQuery) { const frame = new MutableDataFrame({ refId: target.refId, fields: [ { name: 'time', type: FieldType.time }, { name: 'name', type: FieldType.string }, { name: 'distance', type: FieldType.number, config: { unit: 'lengthm' } }, { name: 'moving time', type: FieldType.number, config: { unit: 's' } }, { name: 'elapsed time', type: FieldType.number, config: { unit: 's' } }, { name: 'heart rate', type: FieldType.number, config: { unit: 'none', decimals: 0 } }, { name: 'elevation gain', type: FieldType.number, config: { unit: 'lengthm' } }, { name: 'kilojoules', type: FieldType.number, config: { unit: 'joule' } }, { name: 'type', type: FieldType.string }, { name: 'id', type: FieldType.string, config: { unit: 'none', custom: { hidden: true } } }, ], }); target.extendedStats?.forEach((stat) => { frame.addField({ name: stat }); }); for (let i = 0; i < data.length; i++) { const activity = data[i]; const dataRow: any = { time: dateTime(activity.start_date), name: activity.name, distance: activity.distance, 'moving time': activity.moving_time, 'elapsed time': activity.elapsed_time, 'heart rate': activity.average_heartrate, 'elevation gain': activity.total_elevation_gain, kilojoules: activity.kilojoules, type: activity.type, id: activity.id, }; target.extendedStats?.forEach((stat) => { dataRow[stat] = activity[stat]; }); frame.add(dataRow); } return frame; } transformActivitiesToWorldMap(data: any[], target: StravaQuery) { const unit = target.activityStat === StravaActivityStat.Distance || target.activityStat === StravaActivityStat.ElevationGain ? 'lengthm' : 's'; const table: TableData = { type: 'table', columns: [{ text: 'value', unit }, { text: 'name' }, { text: 'latitude' }, { text: 'longitude' }], rows: [], }; for (const activity of data) { const middlePoint = getActivityMiddlePoint(activity); const latitude = middlePoint ? middlePoint[0] : activity.start_latitude; const longitude = middlePoint ? middlePoint[1] : activity.start_longitude; const row = [activity[target.activityStat], activity.name, latitude, longitude]; if (activity.start_latitude && activity.start_longitude) { table.rows.push(row); } } return table; } } function getActivityMiddlePoint(activity: any): number[] | null { if (!activity.map || !activity.map.summary_polyline) { return null; } const summaryPolyline = activity.map.summary_polyline; const points = polyline.decode(summaryPolyline); if (points && points.length) { const middleIndex = Math.floor(points.length / 2); return points[middleIndex]; } else { return null; } } const INTERVAL_1h = 3600000; const INTERVAL_1d = 86400000; const INTERVAL_1w = 604800000; const INTERVAL_4w = 2419200000; function getAggregationInterval(range: TimeRange): number { const interval = range.to.unix() - range.from.unix(); const interval_ms = interval * 1000; switch (true) { // 4d case interval_ms <= 345600000: return INTERVAL_1h; // 1h // 90d case interval_ms <= 7776000000: return INTERVAL_1d; // 1d // 1y case interval_ms <= 31536000000: return INTERVAL_1w; // 1w default: return INTERVAL_4w; // 4w } } function getAggregationIntervalFromTarget(target: StravaQuery): number { switch (target.interval) { case StravaQueryInterval.Hour: return INTERVAL_1h; case StravaQueryInterval.Day: return INTERVAL_1d; case StravaQueryInterval.Week: return INTERVAL_1w; case StravaQueryInterval.Month: return INTERVAL_4w; default: return INTERVAL_4w; } } const POINT_VALUE = 0; const POINT_TIMESTAMP = 1; const AGG_SUM = (values: TimeSeriesValue[]) => { return values.reduce((acc, val) => acc! + val!); }; export function groupBySum(datapoints: TimeSeriesPoints, range: TimeRange, interval: number): TimeSeriesPoints { return groupByTime(datapoints, range, interval, getPointTimeFrame, getNextTimeFrame, AGG_SUM); } export function groupByWeekSum(datapoints: TimeSeriesPoints, range: TimeRange): TimeSeriesPoints { return groupByTime(datapoints, range, null, getClosestWeek, getNextWeek, AGG_SUM); } export function groupByMonthSum(datapoints: TimeSeriesPoints, range: TimeRange): TimeSeriesPoints { return groupByTime(datapoints, range, null, getClosestMonth, getNextMonth, AGG_SUM); } export function groupByTime( datapoints: any[], range: TimeRange, interval: number | null, intervalFn: any, nextIntervalFn: any, groupByFn: any ): any[] { if (datapoints.length === 0) { return []; } const time_from = range.from.unix() * 1000; const time_to = range.to.unix() * 1000; let grouped_series: any[] = []; let frame_values: any[] = []; let frame_value; let frame_ts = datapoints.length ? intervalFn(time_from, interval) : 0; let point_frame_ts = frame_ts; let point; for (let i = 0; i < datapoints.length; i++) { point = datapoints[i]; point_frame_ts = intervalFn(point[POINT_TIMESTAMP], interval); if (point_frame_ts === frame_ts) { frame_values.push(point[POINT_VALUE]); } else if (point_frame_ts > frame_ts) { frame_value = frame_values.length ? groupByFn(frame_values) : null; grouped_series.push([frame_value, frame_ts]); // Move frame window to next non-empty interval and fill empty by null frame_ts = nextIntervalFn(frame_ts, interval); while (frame_ts < point_frame_ts) { grouped_series.push([null, frame_ts]); frame_ts = nextIntervalFn(frame_ts, interval); } frame_values = [point[POINT_VALUE]]; } } frame_value = groupByFn(frame_values); grouped_series.push([frame_value, frame_ts]); // Move frame window to end of time range and fill empty by null frame_ts = nextIntervalFn(frame_ts, interval); while (frame_ts < time_to) { grouped_series.push([null, frame_ts]); frame_ts = nextIntervalFn(frame_ts, interval); } return grouped_series; } function getPointTimeFrame(timestamp: any, ms_interval: any) { return Math.floor(timestamp / ms_interval) * ms_interval; } function getNextTimeFrame(timestamp: any, ms_interval: any) { return timestamp + ms_interval; } function getClosestMonth(timestamp: any): number { const month_time = dateTime(timestamp).startOf('month'); return month_time.unix() * 1000; } function getNextMonth(timestamp: any): number { const next_month_time = dateTime(timestamp).add(1, 'month'); return next_month_time.unix() * 1000; } function getClosestWeek(timestamp: any): number { // The first Monday after the Unix Epoch begins on Jan 5, 1970, 00:00. // This is a UNIX timestamp of 96 hours or 345600000 ms const FIRST_MONDAY_MS = 345600000; const week_ts = timestamp - FIRST_MONDAY_MS; return Math.floor(week_ts / INTERVAL_1w) * INTERVAL_1w + FIRST_MONDAY_MS; } function getNextWeek(timestamp: any): number { return timestamp + INTERVAL_1w; }
the_stack
import * as ng1 from 'angular'; import { ILogService, IPromise, IQService } from 'angular'; import { convertSortToOrderBy, isGroupingFun } from './util'; import { assignPartialDeep } from '../shared'; import { Defaults } from './ngTableDefaults' import { NgTableEventsChannel } from './ngTableEventsChannel' import { SettingsPartial, Settings } from './ngTableSettings' import { DataResult, DataRowGroup, GetDataFunc } from './data'; import { FilterValues } from './filtering'; import { GetGroupFunc, Grouping, GroupingPartial, GroupValuesPartial, GroupingFunc, GroupSort, GroupValues } from './grouping'; import { SortDirection, SortingValues } from './sorting'; import { PageButton } from './paging'; /** * @private */ export interface InternalTableParams<T> extends NgTableParams<T> { isNullInstance: boolean } export type ParamValuesPartial<T> = Partial<Pick<ParamValues<T>, 'page' | 'count' | 'filter' | 'sorting'>> & { group?: string | GroupingPartial<T> }; /** * The runtime values for {@link NgTableParams} that determine the set of data rows and * how they are to be displayed in a table */ export class ParamValues<T> { /** * The index of the "slice" of data rows, starting at 1, to be displayed by the table. */ page = 1; /** * The number of data rows per page */ count = 10; /** * The filter that should be applied to restrict the set of data rows */ filter: FilterValues = {}; /** * The sort order that should be applied to the data rows. */ sorting: SortingValues = {}; /** * The grouping that should be applied to the data rows */ group: string | Grouping<T> = {}; } /** * @private */ function isNumber(n: any) { return !isNaN(parseFloat(n)) && isFinite(n); } /** * @private */ type Memento<T> = { params: ParamValues<T>; groupSortDirection?: string; }; /** * Parameters manager for an ngTable directive */ export class NgTableParams<T> { /** * The page of data rows currently being displayed in the table */ data: T[] = []; reloadPages: () => void; private defaultSettings = Settings.createWithOverrides<T>(); private errParamsMemento: Memento<T> | null; private isCommittedDataset = false; isNullInstance: boolean; private initialEvents: Function[] | null = []; private ngTableDefaults: Defaults private ngTableEventsChannel: NgTableEventsChannel; private prevParamsMemento: Memento<T>; private _params = new ParamValues<T>(); private _settings = this.defaultSettings; private $q: IQService; private $log: ILogService constructor(baseParameters: ParamValuesPartial<T> | boolean = {}, baseSettings: SettingsPartial<T> = {}) { // the ngTableController "needs" to create a dummy/null instance and it's important to know whether an instance // is one of these if (typeof baseParameters === "boolean") { this.isNullInstance = true; } this.reloadPages = (() => { let currentPages: PageButton[]; return () => { const oldPages = currentPages; const newPages = this.generatePagesArray(this.page(), this.total(), this.count()); if (!ng1.equals(oldPages, newPages)) { currentPages = newPages; this.ngTableEventsChannel.publishPagesChanged(this, newPages, oldPages); } } })(); assignPartialDeep(this._params, this.ngTableDefaults.params); this.settings(baseSettings); this.parameters(baseParameters, true); this.ngTableEventsChannel.publishAfterCreated(this); // run events during construction after the initial create event. That way a consumer // can subscribe to all events for a table without "dropping" an event ng1.forEach(this.initialEvents, event => { event(); }); this.initialEvents = null; } /** * Returns the number of data rows per page */ count(): number /** * Sets the number of data rows per page. * Changes to count will cause `isDataReloadRequired` to return true */ count(count: number): this count(count?: number) { // reset to first page because can be blank page return count !== undefined ? this.parameters({ 'count': count, 'page': 1 }) : this._params.count; } /** * Returns the current filter values used to restrict the set of data rows. * @param trim supply true to return the current filter minus any insignificant values * (null, undefined and empty string) */ filter(trim?: boolean): FilterValues /** * Sets filter values to the `filter` supplied; any existing filter will be removed * Changes to filter will cause `isDataReloadRequired` to return true and the current `page` to be set to 1 */ filter(filter: FilterValues): this filter(filter?: FilterValues | boolean) { if (filter != null && typeof filter === 'object') { return this.parameters({ 'filter': filter, 'page': 1 }); } else if (filter === true) { const keys = Object.keys(this._params.filter); const significantFilter: FilterValues = {}; for (let i = 0; i < keys.length; i++) { const filterValue = this._params.filter[keys[i]]; if (filterValue != null && filterValue !== '') { significantFilter[keys[i]] = filterValue; } } return significantFilter; } else { return this._params.filter; } } /** * Generate array of pages. * When no arguments supplied, the current parameter state of this `NgTableParams` instance will be used * @param currentPage Which page must be active * @param totalItems Total quantity of items * @param pageSize Quantity of items on page * @param maxBlocks Quantity of blocks for pagination * @returns Array of pages */ generatePagesArray(currentPage?: number, totalItems?: number, pageSize?: number, maxBlocks?: number) { if (!arguments.length) { currentPage = this.page(); totalItems = this.total(); pageSize = this.count(); } let maxPage: number, maxPivotPages: number, minPage: number, numPages: number; maxBlocks = maxBlocks && maxBlocks < 6 ? 6 : maxBlocks; const pages: PageButton[] = []; numPages = Math.ceil(totalItems / pageSize); if (numPages > 1) { pages.push({ type: 'prev', number: Math.max(1, currentPage - 1), active: currentPage > 1 }); pages.push({ type: 'first', number: 1, active: currentPage > 1, current: currentPage === 1 }); maxPivotPages = Math.round((this._settings.paginationMaxBlocks - this._settings.paginationMinBlocks) / 2); minPage = Math.max(2, currentPage - maxPivotPages); maxPage = Math.min(numPages - 1, currentPage + maxPivotPages * 2 - (currentPage - minPage)); minPage = Math.max(2, minPage - (maxPivotPages * 2 - (maxPage - minPage))); let i = minPage; while (i <= maxPage) { if ((i === minPage && i !== 2) || (i === maxPage && i !== numPages - 1)) { pages.push({ type: 'more', active: false }); } else { pages.push({ type: 'page', number: i, active: currentPage !== i, current: currentPage === i }); } i++; } pages.push({ type: 'last', number: numPages, active: currentPage !== numPages, current: currentPage === numPages }); pages.push({ type: 'next', number: Math.min(numPages, currentPage + 1), active: currentPage < numPages }); } return pages; } /** * Returns the current grouping used to group the data rows */ group(): Grouping<T> /** * Sets grouping to the `group` supplied; any existing grouping will be removed. * Changes to group will cause `isDataReloadRequired` to return true and the current `page` to be set to 1 */ group(group: GroupValuesPartial): this /** * Sets grouping to the `field` and `sortDirection` supplied; any existing grouping will be removed * Changes to group will cause `isDataReloadRequired` to return true and the current `page` to be set to 1 */ group(field: string, sortDirection?: GroupSort): this /** * Sets grouping to the `group` supplied; any existing grouping will be removed. * If `sortDirection` is supplied, this will be assigned to the sortDirection property of `group` * Changes to group will cause `isDataReloadRequired` to return true and the current `page` to be set to 1 */ group(group: GroupingFunc<T> | string, sortDirection?: GroupSort): this group(group?: GroupingPartial<T> | string, sortDirection?: GroupSort): string | Grouping<T> | this { if (group === undefined) { return this._params.group; } const newParameters: ParamValuesPartial<T> = { page: 1 }; if (isGroupingFun(group) && sortDirection !== undefined) { group.sortDirection = sortDirection; newParameters.group = group; } else if (typeof group === 'string' && sortDirection !== undefined) { newParameters.group = { [group]: sortDirection }; } else { newParameters.group = group; } this.parameters(newParameters); return this; } /** * Returns true when an attempt to `reload` the current `parameter` values have resulted in a failure. * This method will continue to return true until the `reload` is successfully called or when the * `parameter` values have changed */ hasErrorState() { return !!(this.errParamsMemento && ng1.equals(this.errParamsMemento, this.createComparableParams())); } /** * Returns true if `filter` has significant filter value(s) (any value except null, undefined, or empty string), * otherwise false */ hasFilter() { return Object.keys(this.filter(true)).length > 0; } /** * Return true when a change to `filters` require the `reload` method * to be run so as to ensure the data presented to the user reflects these filters */ hasFilterChanges() { const previousFilter = (this.prevParamsMemento && this.prevParamsMemento.params.filter); return !ng1.equals((this._params.filter), previousFilter) || this.hasGlobalSearchFieldChanges(); } /** * Returns true when at least one group has been set */ hasGroup(): boolean /** * Returns true when the `group` and when supplied, the `sortDirection` matches an existing group */ hasGroup(group: string | GroupingFunc<T>, sortDirection?: string): boolean hasGroup(group?: string | GroupingFunc<T>, sortDirection?: string) { if (group == null) { return isGroupingFun(this._params.group) || Object.keys(this._params.group).length > 0 } if (isGroupingFun(group)) { if (sortDirection == null) { return this._params.group === group; } else { return this._params.group === group && group.sortDirection === sortDirection; } } else { if (sortDirection == null) { return Object.keys(this._params.group).indexOf(group) !== -1; } else { return (this._params.group as GroupValues)[group] === sortDirection; } } } /** * Return true when a change to this instance should require the `reload` method * to be run so as to ensure the data rows presented to the user reflects the current state. * * Note that this method will return false when the `reload` method has run but fails. In this case * `hasErrorState` will return true. * * The built-in `ngTable` directives will watch for when this function returns true and will then call * the `reload` method to load its data rows */ isDataReloadRequired() { // note: using != as want to treat null and undefined the same return !this.isCommittedDataset || !ng1.equals(this.createComparableParams(), this.prevParamsMemento) || this.hasGlobalSearchFieldChanges(); } /** * Returns true if sorting by the field supplied. Where direction supplied * the field must also be sorted by that direction to return true */ isSortBy(field: string, direction?: string) { if (direction !== undefined) { return this._params.sorting[field] !== undefined && this._params.sorting[field] == direction; } else { return this._params.sorting[field] !== undefined; } } /** * Returns sorting values in a format that can be consumed by the angular `$orderBy` filter service */ orderBy() { return convertSortToOrderBy(this._params.sorting); } /** * Returns the index of the current "slice" of data rows */ page(): number /** * Sets the index of the current "slice" of data rows. The index starts at 1. * Changing the page number will cause `isDataReloadRequired` to return true */ page(page: number): this page(page?: number) { return page !== undefined ? this.parameters({ 'page': page }) : this._params.page; } parameters(): ParamValues<T> /** * Set new parameters */ parameters(newParameters?: ParamValuesPartial<T> | { [name: string]: string }, parseParamsFromUrl?: boolean): this parameters(newParameters?: ParamValuesPartial<T> | { [name: string]: string }, parseParamsFromUrl?: boolean): ParamValues<T> | this { if (newParameters === undefined) { return this._params; } // todo: move parsing of url like parameters into a seperate method parseParamsFromUrl = parseParamsFromUrl || false; for (const key in newParameters) { let value = newParameters[key]; if (parseParamsFromUrl && key.indexOf('[') >= 0) { const keys = key.split(/\[(.*)\]/).reverse() let lastKey = ''; for (let i = 0, len = keys.length; i < len; i++) { const name = keys[i]; if (name !== '') { const v = value; value = {}; value[lastKey = name] = (isNumber(v) ? parseFloat(v) : v); } } if (lastKey === 'sorting') { this._params[lastKey] = {}; } this._params[lastKey] = ng1.extend(this._params[lastKey] || {}, value[lastKey]); } else { if (newParameters[key] === undefined) { // skip } else if (key === 'group') { this._params[key] = this.parseGroup(newParameters[key]); } else { this._params[key] = (isNumber(newParameters[key]) ? parseFloat(newParameters[key]) : newParameters[key]); } } } this.log('ngTable: set parameters', this._params); return this; } /** * Trigger a reload of the data rows */ reload<TResult extends DataResult<T>>(): IPromise<TResult[]> { let pData: ng1.IPromise<any>; this._settings.$loading = true; this.prevParamsMemento = ng1.copy(this.createComparableParams()); this.isCommittedDataset = true; if (this.hasGroup()) { pData = this.runInterceptorPipeline(this.$q.when(this._settings.getGroups(this))); } else { const fn = this._settings.getData as GetDataFunc<T>; pData = this.runInterceptorPipeline(this.$q.when(fn(this))); } this.log('ngTable: reload data'); const oldData = this.data; return pData.then(data => { this._settings.$loading = false; this.errParamsMemento = null; this.data = data; // note: I think it makes sense to publish this event even when data === oldData // subscribers can always set a filter to only receive the event when data !== oldData this.ngTableEventsChannel.publishAfterReloadData(this, data, oldData); this.reloadPages(); return data; }).catch(reason => { this.errParamsMemento = this.prevParamsMemento; // "rethrow" return this.$q.reject(reason); }); } /** * Returns the settings for the table. */ settings(): Settings<T> /** * Sets the settings for the table; new setting values will be merged with the existing settings. * Supplying a new `dataset` will cause `isDataReloadRequired` to return true and the `ngTableEventsChannel` * to fire its `datasetChanged` event */ settings(newSettings: SettingsPartial<T>): this settings(newSettings?: SettingsPartial<T>): this | Settings<T> { if (newSettings === undefined) { return this._settings; } const settings = Settings.merge(this._settings, newSettings); const originalDataset = this._settings.dataset; this._settings = settings; // note: using != as want null and undefined to be treated the same const hasDatasetChanged = newSettings.hasOwnProperty('dataset') && (newSettings.dataset != originalDataset); if (hasDatasetChanged) { if (this.isCommittedDataset) { this.page(1); // reset page as a new dataset has been supplied } this.isCommittedDataset = false; const fireEvent = () => { this.ngTableEventsChannel.publishDatasetChanged(this, newSettings.dataset, originalDataset); }; if (this.initialEvents) { this.initialEvents.push(fireEvent); } else { fireEvent(); } } this.log('ngTable: set settings', this._settings); return this; } /** * Returns the current sorting used to order the data rows. * Changes to sorting will cause `isDataReloadRequired` to return true */ sorting(): SortingValues /** * Sets sorting values to the `sorting` supplied; any existing sorting will be removed. * Changes to sorting will cause `isDataReloadRequired` to return true */ sorting(sorting: SortingValues): this /** * Sets sorting to the `field` and `direction` supplied; any existing sorting will be removed */ sorting(field: string, direction?: string): this sorting(sorting?: SortingValues | string, direction?: SortDirection) { if (typeof sorting === 'string') { this.parameters({ 'sorting': { [sorting]: direction || this.settings().defaultSort } }); return this; } return sorting !== undefined ? this.parameters({ 'sorting': sorting }) : this._params.sorting; } /** * Returns the count of the data rows that match the current `filter` */ total(): number /** * Sets `settings().total` to the value supplied. * Typically you will need to set a `total` in the body of any custom `getData` function * you supply as a setting value to this instance. * @example * ```js * const tp = new NgTableParams({}, { getData: customGetData }) * function customGetData(params) { * const queryResult = // code to fetch current data rows and total // * params.total(queryResult.total); * return queryResult.dataRowsPage; * } * ``` */ total(total: number): this total(total?: number) { return total !== undefined ? this.settings({ 'total': total }) : this._settings.total; } /** * Returns the current parameter values uri-encoded. Set `asString` to * true for the parameters to be returned as an array of strings of the form 'paramName=value' * otherwise parameters returned as a key-value object */ url(asString = false) { const pairs: any[] | { [name: string]: string } = (asString ? [] : {}); for (const key in this._params) { if (this._params.hasOwnProperty(key)) { const item = (this._params as { [name: string]: any })[key], name = encodeURIComponent(key); if (typeof item === "object") { for (const subkey in item) { if (isSignificantValue(item[subkey], key)) { const pname = name + "[" + encodeURIComponent(subkey) + "]"; collectValue(item[subkey], pname); } } } else if (!ng1.isFunction(item) && isSignificantValue(item, key)) { collectValue(item, name); } } } return pairs; function collectValue(value: any, key: string) { if (isArray(pairs)) { pairs.push(key + "=" + encodeURIComponent(value)); } else { pairs[key] = encodeURIComponent(value); } } function isArray(pairs: any[] | {}): pairs is Array<any> { return asString; } function isSignificantValue(value: any, key: string) { return key === "group" ? true : typeof value !== undefined && value !== ""; } } private createComparableParams(): Memento<T> { const group = this._params.group; return { params: this._params, groupSortDirection: isGroupingFun(group) ? group.sortDirection : undefined }; } private hasGlobalSearchFieldChanges() { const currentVal = (this._params.filter && this._params.filter['$']); const previousVal = (this.prevParamsMemento && this.prevParamsMemento.params.filter && this.prevParamsMemento.params.filter['$']); return !ng1.equals(currentVal, previousVal); } private log(...args: any[]) { if (this._settings.debugMode && this.$log.debug) { this.$log.debug(...args); } } private parseGroup(group: string | Grouping<T>) { const defaultSort = this._settings.groupOptions.defaultSort; if (!group) { return group; } else if (isGroupingFun(group)) { if (group.sortDirection == null) { group.sortDirection = defaultSort; } return group; } else if (typeof group === 'object') { for (const key in group) { if (group[key] == null) { group[key] = defaultSort; } } return group; } else { return { [group]: defaultSort }; } } private runInterceptorPipeline(fetchedData: IPromise<any>) { return this._settings.interceptors.reduce((result, interceptor) => { const thenFn = (interceptor.response && interceptor.response.bind(interceptor)) || this.$q.when; const rejectFn = (interceptor.responseError && interceptor.responseError.bind(interceptor)) || this.$q.reject; return result.then(data => { return thenFn(data, this); }, reason => { return rejectFn(reason, this); }); }, fetchedData); } static init( $q: IQService, $log: ILogService, ngTableDefaults: Defaults, ngTableEventsChannel: NgTableEventsChannel) { ng1.extend(NgTableParams.prototype, { $q, $log, ngTableDefaults, ngTableEventsChannel }); } } NgTableParams.init.$inject = ['$q', '$log', 'ngTableDefaults', 'ngTableEventsChannel'];
the_stack
import assert from 'assert'; import * as net from 'net'; import { Connection, r } from '../src'; import config from './config'; import { uuid } from './util/common'; describe('accessing-reql', () => { let connection: Connection; // global connection let dbName: string; let tableName: string; beforeEach(async () => { connection = await r.connect(config); assert(connection.open); }); afterEach(async () => { if (!connection.open) { connection = await r.connect(config); assert(connection.open); } // remove any dbs created between each test case await r .dbList() .filter(db => r .expr(['rethinkdb', 'test']) .contains(db) .not() ) .forEach(db => r.dbDrop(db)) .run(connection); await connection.close(); assert(!connection.open); }); it('`run` should throw an error when called without connection', async () => { try { await r.expr(1).run(); assert.fail('shold throw an error'); } catch (e) { assert.equal( e.message, '`run` was called without a connection and no pool has been created after:\nr.expr(1)\n' ); } }); it('`run` should throw an error when called with a closed connection', async () => { try { connection.close(); assert(!connection.open); await r.expr(1).run(connection); assert.fail('should throw an error'); } catch (e) { assert.equal( e.message, '`run` was called with a closed connection after:\nr.expr(1)\n' ); } }); // tslint:disable-next-line:max-line-length it('should be able to create a db, a table, insert array into table, delete array from table, drop table and drop db', async () => { dbName = uuid(); tableName = uuid(); assert(connection.open); const result1 = await r.dbCreate(dbName).run(connection); assert.equal(result1.config_changes.length, 1); assert.equal(result1.dbs_created, 1); const result2 = await r .db(dbName) .tableCreate(tableName) .run(connection); assert.equal(result2.tables_created, 1); const result3 = await r .db(dbName) .table(tableName) .insert(new Array(100).fill({})) .run(connection); assert.equal(result3.inserted, 100); const result4 = await r .db(dbName) .table(tableName) .delete() .run(connection); assert.equal(result4.deleted, 100); const result5 = await r .db(dbName) .tableDrop(tableName) .run(connection); assert.equal(result5.config_changes.length, 1); assert.equal(result5.tables_dropped, 1); const result6 = await r.dbDrop(dbName).run(connection); assert.equal(result6.config_changes.length, 1); assert.equal(result6.dbs_dropped, 1); }); it('`run` should use the default database', async () => { dbName = uuid(); tableName = uuid(); const result1 = await r.dbCreate(dbName).run(connection); assert.equal(result1.dbs_created, 1); const result2 = await r .db(dbName) .tableCreate(tableName) .run(connection); assert.equal(result2.tables_created, 1); await connection.close(); assert(!connection.open); connection = await r.connect({ db: dbName, host: config.host, port: config.port, user: config.user, password: config.password }); assert(connection); const result = await r.tableList().run(connection); assert.deepEqual(result, [tableName]); }); it('`use` should work', async () => { dbName = uuid(); tableName = uuid(); const result1 = await r.dbCreate(dbName).run(connection); assert.equal(result1.dbs_created, 1); const result2 = await r .db(dbName) .tableCreate(tableName) .run(connection); assert.equal(result2.tables_created, 1); connection.use(dbName); const result3 = await r.tableList().run(connection); assert.deepEqual(result3, [tableName]); }); it('`reconnect` should work', async () => { await connection.close(); assert(!connection.open); connection = await connection.reconnect(); assert(connection.open); }); it('`reconnect` should work with options', async () => { assert(connection.open); connection = await connection.reconnect({ noreplyWait: true }); assert(connection.open); const result1 = await r.expr(1).run(connection); assert.equal(result1, 1); connection = await connection.reconnect({ noreplyWait: false }); assert(connection.open); const result2 = await r.expr(1).run(connection); assert.equal(result2, 1); connection = await connection.reconnect(); assert(connection); const result3 = await r.expr(1).run(connection); assert.equal(result3, 1); }); it('`noReplyWait` should throw', async () => { try { // @ts-ignore await connection.noReplyWait(); assert.fail('should throw an error'); } catch (e) { assert.equal(e.message, 'connection.noReplyWait is not a function'); } }); it('`noreplyWait` should work', async () => { dbName = uuid(); tableName = uuid(); const largeishObject = Array(10000) .fill(Math.random()) .map(random => r.expr({ random })); await r.dbCreate(dbName).run(connection); await r .db(dbName) .tableCreate(tableName) .run(connection); const result1 = await r .db(dbName) .table(tableName) .insert(largeishObject) .run(connection, { noreply: true }); assert.equal(result1, undefined); const result2 = await r .db(dbName) .table(tableName) .count() .run(connection); assert.equal(result2, 0); const result3 = await connection.noreplyWait(); assert.equal(result3, undefined); const result4 = await r .db(dbName) .table(tableName) .count() .run(connection); assert.equal(result4, 10000); }); it('`run` should take an argument', async () => { // @ts-ignore const result1 = await r.expr(1).run(connection, { readMode: 'primary' }); assert.equal(result1, 1); const result2 = await r.expr(1).run(connection, { readMode: 'majority' }); assert.equal(result2, 1); const result3 = await r.expr(1).run(connection, { profile: false }); assert.equal(result3, 1); const result4 = await r.expr(1).run(connection, { profile: true }); assert(result4.profile); assert.equal(result4.result, 1); const result5 = await r.expr(1).run(connection, { durability: 'soft' }); assert.equal(result5, 1); const result6 = await r.expr(1).run(connection, { durability: 'hard' }); assert.equal(result6, 1); }); it('`run` should throw on an unrecognized argument', async () => { try { // @ts-ignore await r.expr(1).run(connection, { foo: 'bar' }); assert.fail('should throw an error'); } catch (e) { assert.equal( e.message, 'Unrecognized global optional argument `foo` in:\nr.expr(1)\n^^^^^^^^^\n' ); } }); it('`r()` should be a shortcut for r.expr()', async () => { const result = await r(1).run(connection); assert.deepEqual(result, 1); }); it('`timeFormat` should work', async () => { const result1 = await r.now().run(connection); assert(result1 instanceof Date); const result2 = await r.now().run(connection, { timeFormat: 'native' }); assert(result2 instanceof Date); const result3 = await r.now().run(connection, { timeFormat: 'raw' }); // @ts-ignore assert.equal(result3.$reql_type$, 'TIME'); }); it('`binaryFormat` should work', async () => { const result = await r .binary(Buffer.from([1, 2, 3])) .run(connection, { binaryFormat: 'raw' }); // @ts-ignore assert.equal(result.$reql_type$, 'BINARY'); }); it('`groupFormat` should work', async () => { const result = await r .expr([ { name: 'Michel', grownUp: true }, { name: 'Laurent', grownUp: true }, { name: 'Sophie', grownUp: true }, { name: 'Luke', grownUp: false }, { name: 'Mino', grownUp: false } ]) .group('grownUp') .run(connection, { groupFormat: 'raw' }); assert.deepEqual(result, { $reql_type$: 'GROUPED_DATA', data: [ [ false, [{ grownUp: false, name: 'Luke' }, { grownUp: false, name: 'Mino' }] ], [ true, [ { grownUp: true, name: 'Michel' }, { grownUp: true, name: 'Laurent' }, { grownUp: true, name: 'Sophie' } ] ] ] }); }); it('`profile` should work', async () => { const result1 = await r.expr(true).run(connection, { profile: false }); assert(result1); const result2 = await r.expr(true).run(connection, { profile: true }); assert(result2.profile); assert.equal(result2.result, true); const result3 = await r.expr(true).run(connection, { profile: false }); assert.equal(result3, true); }); it('`timeout` option should work', async () => { let server: net.Server; let port: number; try { port = Math.floor(Math.random() * (65535 - 1025) + 1025); server = net.createServer().listen(port); connection = await r.connect({ port, timeout: 1 }); assert.fail('should throw an error'); } catch (err) { await server.close(); assert.equal( err.message, 'Failed to connect to localhost:' + port + ' in less than 1s.' ); } }); it('`server` should work', async () => { const response = await connection.server(); assert(typeof response.name === 'string'); assert(typeof response.id === 'string'); }); it('`grant` should work', async () => { const restrictedDbName = uuid(); const restrictedTableName = uuid(); const result1 = await r.dbCreate(restrictedDbName).run(connection); assert.equal(result1.config_changes.length, 1); assert.equal(result1.dbs_created, 1); const result2 = await r .db(restrictedDbName) .tableCreate(restrictedTableName) .run(connection); assert.equal(result2.tables_created, 1); const user = uuid(); const password = uuid(); const result3 = await r .db('rethinkdb') .table('users') .insert({ id: user, password }) .run(connection); const result4 = await r .db(restrictedDbName) .table(restrictedTableName) .grant(user, { read: true, write: true, config: true }) .run(connection); assert.deepEqual(result4, { granted: 1, permissions_changes: [ { new_val: { config: true, read: true, write: true }, old_val: null } ] }); }); it('If `servers` is specified, it cannot be empty', async () => { try { await r.connectPool({ servers: [] }); assert.fail('should throw an error'); } catch (e) { assert.equal( e.message, 'If `servers` is an array, it must contain at least one server.' ); } }); // tslint:disable-next-line:max-line-length it('should not throw an error (since 1.13, the token is now stored outside the query): `connection` should extend events.Emitter and emit an error if the server failed to parse the protobuf message', async () => { connection.addListener('error', () => assert.fail('should not throw')); const result = await Array(687) .fill(1) .reduce((acc, curr) => acc.add(curr), r.expr(1)) .run(connection); assert.equal(result, 688); }); });
the_stack
import type {Mutable, Proto, ObserverType} from "@swim/util"; import type {FastenerOwner, FastenerFlags} from "@swim/component"; import type {AnyView, View} from "./View"; import {ViewRelationInit, ViewRelationClass, ViewRelation} from "./ViewRelation"; /** @internal */ export type ViewSetType<F extends ViewSet<any, any>> = F extends ViewSet<any, infer V> ? V : never; /** @public */ export interface ViewSetInit<V extends View = View> extends ViewRelationInit<V> { extends?: {prototype: ViewSet<any, any>} | string | boolean | null; key?(view: V): string | undefined; compare?(a: V, b: V): number; sorted?: boolean; willSort?(parent: View | null): void; didSort?(parent: View | null): void; sortChildren?(parent: View): void; compareChildren?(a: View, b: View): number; } /** @public */ export type ViewSetDescriptor<O = unknown, V extends View = View, I = {}> = ThisType<ViewSet<O, V> & I> & ViewSetInit<V> & Partial<I>; /** @public */ export interface ViewSetClass<F extends ViewSet<any, any> = ViewSet<any, any>> extends ViewRelationClass<F> { /** @internal */ readonly SortedFlag: FastenerFlags; /** @internal @override */ readonly FlagShift: number; /** @internal @override */ readonly FlagMask: FastenerFlags; } /** @public */ export interface ViewSetFactory<F extends ViewSet<any, any> = ViewSet<any, any>> extends ViewSetClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ViewSetFactory<F> & I; define<O, V extends View = View>(className: string, descriptor: ViewSetDescriptor<O, V>): ViewSetFactory<ViewSet<any, V>>; define<O, V extends View = View>(className: string, descriptor: {observes: boolean} & ViewSetDescriptor<O, V, ObserverType<V>>): ViewSetFactory<ViewSet<any, V>>; define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown} & ViewSetDescriptor<O, V, I>): ViewSetFactory<ViewSet<any, V> & I>; define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ViewSetDescriptor<O, V, I & ObserverType<V>>): ViewSetFactory<ViewSet<any, V> & I>; <O, V extends View = View>(descriptor: ViewSetDescriptor<O, V>): PropertyDecorator; <O, V extends View = View>(descriptor: {observes: boolean} & ViewSetDescriptor<O, V, ObserverType<V>>): PropertyDecorator; <O, V extends View = View, I = {}>(descriptor: {implements: unknown} & ViewSetDescriptor<O, V, I>): PropertyDecorator; <O, V extends View = View, I = {}>(descriptor: {implements: unknown; observes: boolean} & ViewSetDescriptor<O, V, I & ObserverType<V>>): PropertyDecorator; } /** @public */ export interface ViewSet<O = unknown, V extends View = View> extends ViewRelation<O, V> { (view: AnyView<V>): O; /** @override */ get fastenerType(): Proto<ViewSet<any, any>>; /** @internal */ readonly views: {readonly [viewId: number]: V | undefined}; readonly viewCount: number; hasView(view: View): boolean; addView(view?: AnyView<V>, target?: View | null, key?: string): V; attachView(view?: AnyView<V>, target?: View | null): V; detachView(view: V): V | null; insertView(parent?: View | null, view?: AnyView<V>, target?: View | null, key?: string): V; removeView(view: V): V | null; deleteView(view: V): V | null; /** @internal @override */ bindView(view: View, target: View | null): void; /** @internal @override */ unbindView(view: View): void; /** @override */ detectView(view: View): V | null; /** @internal @protected */ key(view: V): string | undefined; get sorted(): boolean; /** @internal */ initSorted(sorted: boolean): void; sort(sorted?: boolean): this; /** @protected */ willSort(parent: View | null): void; /** @protected */ onSort(parent: View | null): void; /** @protected */ didSort(parent: View | null): void; /** @internal @protected */ sortChildren(parent: View): void; /** @internal */ compareChildren(a: View, b: View): number; /** @internal @protected */ compare(a: V, b: V): number; } /** @public */ export const ViewSet = (function (_super: typeof ViewRelation) { const ViewSet: ViewSetFactory = _super.extend("ViewSet"); Object.defineProperty(ViewSet.prototype, "fastenerType", { get: function (this: ViewSet): Proto<ViewSet<any, any>> { return ViewSet; }, configurable: true, }); ViewSet.prototype.hasView = function (this: ViewSet, view: View): boolean { return this.views[view.uid] !== void 0; }; ViewSet.prototype.addView = function <V extends View>(this: ViewSet<unknown, V>, newView?: AnyView<V>, target?: View | null, key?: string): V { if (newView !== void 0 && newView !== null) { newView = this.fromAny(newView); } else { newView = this.createView(); } if (target === void 0) { target = null; } let parent: View | null; if (this.binds && (parent = this.parentView, parent !== null)) { if (key === void 0) { key = this.key(newView); } this.insertChild(parent, newView, target, key); } const views = this.views as {[viewId: number]: V | undefined}; if (views[newView.uid] === void 0) { this.willAttachView(newView, target); views[newView.uid] = newView; (this as Mutable<typeof this>).viewCount += 1; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } return newView; }; ViewSet.prototype.attachView = function <V extends View>(this: ViewSet<unknown, V>, newView?: AnyView<V>, target?: View | null): V { if (newView !== void 0 && newView !== null) { newView = this.fromAny(newView); } else { newView = this.createView(); } const views = this.views as {[viewId: number]: V | undefined}; if (views[newView.uid] === void 0) { if (target === void 0) { target = null; } this.willAttachView(newView, target); views[newView.uid] = newView; (this as Mutable<typeof this>).viewCount += 1; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } return newView; }; ViewSet.prototype.detachView = function <V extends View>(this: ViewSet<unknown, V>, oldView: V): V | null { const views = this.views as {[viewId: number]: V | undefined}; if (views[oldView.uid] !== void 0) { this.willDetachView(oldView); (this as Mutable<typeof this>).viewCount -= 1; delete views[oldView.uid]; this.onDetachView(oldView); this.deinitView(oldView); this.didDetachView(oldView); return oldView; } return null; }; ViewSet.prototype.insertView = function <V extends View>(this: ViewSet<unknown, V>, parent?: View | null, newView?: AnyView<V>, target?: View | null, key?: string): V { if (newView !== void 0 && newView !== null) { newView = this.fromAny(newView); } else { newView = this.createView(); } if (parent === void 0 || parent === null) { parent = this.parentView; } if (target === void 0) { target = null; } if (key === void 0) { key = this.key(newView); } if (parent !== null && (newView.parent !== parent || newView.key !== key)) { this.insertChild(parent, newView, target, key); } const views = this.views as {[viewId: number]: V | undefined}; if (views[newView.uid] === void 0) { this.willAttachView(newView, target); views[newView.uid] = newView; (this as Mutable<typeof this>).viewCount += 1; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } return newView; }; ViewSet.prototype.removeView = function <V extends View>(this: ViewSet<unknown, V>, view: V): V | null { if (this.hasView(view)) { view.remove(); return view; } return null; }; ViewSet.prototype.deleteView = function <V extends View>(this: ViewSet<unknown, V>, view: V): V | null { const oldView = this.detachView(view); if (oldView !== null) { oldView.remove(); } return oldView; }; ViewSet.prototype.bindView = function <V extends View>(this: ViewSet<unknown, V>, view: View, target: View | null): void { if (this.binds) { const newView = this.detectView(view); const views = this.views as {[viewId: number]: V | undefined}; if (newView !== null && views[newView.uid] === void 0) { this.willAttachView(newView, target); views[newView.uid] = newView; (this as Mutable<typeof this>).viewCount += 1; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } } }; ViewSet.prototype.unbindView = function <V extends View>(this: ViewSet<unknown, V>, view: View): void { if (this.binds) { const oldView = this.detectView(view); const views = this.views as {[viewId: number]: V | undefined}; if (oldView !== null && views[oldView.uid] !== void 0) { this.willDetachView(oldView); (this as Mutable<typeof this>).viewCount -= 1; delete views[oldView.uid]; this.onDetachView(oldView); this.deinitView(oldView); this.didDetachView(oldView); } } }; ViewSet.prototype.detectView = function <V extends View>(this: ViewSet<unknown, V>, view: View): V | null { if (typeof this.type === "function" && view instanceof this.type) { return view as V; } return null; }; ViewSet.prototype.key = function <V extends View>(this: ViewSet<unknown, V>, view: V): string | undefined { return void 0; }; Object.defineProperty(ViewSet.prototype, "sorted", { get(this: ViewSet): boolean { return (this.flags & ViewSet.SortedFlag) !== 0; }, configurable: true, }); ViewSet.prototype.initInherits = function (this: ViewSet, sorted: boolean): void { if (sorted) { (this as Mutable<typeof this>).flags = this.flags | ViewSet.SortedFlag; } else { (this as Mutable<typeof this>).flags = this.flags & ~ViewSet.SortedFlag; } }; ViewSet.prototype.sort = function (this: ViewSet, sorted?: boolean): typeof this { if (sorted === void 0) { sorted = true; } const flags = this.flags; if (sorted && (flags & ViewSet.SortedFlag) === 0) { const parent = this.parentView; this.willSort(parent); this.setFlags(flags | ViewSet.SortedFlag); this.onSort(parent); this.didSort(parent); } else if (!sorted && (flags & ViewSet.SortedFlag) !== 0) { this.setFlags(flags & ~ViewSet.SortedFlag); } return this; }; ViewSet.prototype.willSort = function (this: ViewSet, parent: View | null): void { // hook }; ViewSet.prototype.onSort = function (this: ViewSet, parent: View | null): void { if (parent !== null) { this.sortChildren(parent); } }; ViewSet.prototype.didSort = function (this: ViewSet, parent: View | null): void { // hook }; ViewSet.prototype.sortChildren = function <V extends View>(this: ViewSet<unknown, V>, parent: View): void { parent.sortChildren(this.compareChildren.bind(this)); }; ViewSet.prototype.compareChildren = function <V extends View>(this: ViewSet<unknown, V>, a: View, b: View): number { const views = this.views; const x = views[a.uid]; const y = views[b.uid]; if (x !== void 0 && y !== void 0) { return this.compare(x, y); } else { return x !== void 0 ? 1 : y !== void 0 ? -1 : 0; } }; ViewSet.prototype.compare = function <V extends View>(this: ViewSet<unknown, V>, a: V, b: V): number { return a.uid < b.uid ? -1 : a.uid > b.uid ? 1 : 0; }; ViewSet.construct = function <F extends ViewSet<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { if (fastener === null) { fastener = function (newView: AnyView<ViewSetType<F>>): FastenerOwner<F> { fastener!.addView(newView); return fastener!.owner; } as F; delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name Object.setPrototypeOf(fastener, fastenerClass.prototype); } fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).views = {}; (fastener as Mutable<typeof fastener>).viewCount = 0; return fastener; }; ViewSet.define = function <O, V extends View>(className: string, descriptor: ViewSetDescriptor<O, V>): ViewSetFactory<ViewSet<any, V>> { let superClass = descriptor.extends as ViewSetFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const sorted = descriptor.sorted; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.sorted; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: ViewSet<any, any>}, fastener: ViewSet<O, V> | null, owner: O): ViewSet<O, V> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (sorted !== void 0) { fastener.initSorted(sorted); } return fastener; }; return fastenerClass; }; (ViewSet as Mutable<typeof ViewSet>).SortedFlag = 1 << (_super.FlagShift + 0); (ViewSet as Mutable<typeof ViewSet>).FlagShift = _super.FlagShift + 1; (ViewSet as Mutable<typeof ViewSet>).FlagMask = (1 << ViewSet.FlagShift) - 1; return ViewSet; })(ViewRelation);
the_stack
import { chain, externalSchematic, move, noop, Rule, SchematicContext, Tree, } from '@angular-devkit/schematics'; import { createOrUpdate, getWorkspace, getWorkspacePath, } from '@nrwl/workspace'; import { getJsonFromFile, getAppPaths, prerun, getNpmScope, getPrefix, getGroupByName, updateJsonFile, updateFile, } from '@nstudio/xplat-utils'; import { XplatHelpers, findNodes, ReplaceChange, insert, updateTsConfig, } from '@nstudio/xplat'; // import xplatAngular from '@nstudio/angular/src/schematics/xplat/index'; import * as ts from 'typescript'; import { join } from 'path'; import * as fs from 'fs'; export interface PackageNameMapping { [packageName: string]: string; } const options: XplatHelpers.Schema = {}; const oldDirectoriesToMove: Array<string> = []; const newDirectoriesToEmpty: Array<string> = []; let platforms: Array<string>; export default function (): Rule { return chain([ prerun( { framework: 'angular', }, true ), // generate new xplat libs // NOTE: this did not work with Nx 11 - // calling externalSchematic's from outside collections do not seem to work (not sure if expected or not from running Nx migrations) // This may have worked better being split into a migration by itself with no other rules in the chain // (tree: Tree, context: SchematicContext) => { // platforms = getCurrentlyUsedPlatforms(tree); // console.log('generating libs for platforms:', platforms); // if (platforms.length) { // return xplatAngular({ // platforms: platforms.join(','), // framework: 'angular', // npmScope: getNpmScope(), // prefix: getPrefix(), // skipFormat: true, // useXplat: true, // groupByName: getGroupByName(), // }); // } else { // return noop()(tree, context); // } // }, // clear the new libs and prepare to move existing into it emptyNewStructure(), // move old structure into new moveOldStructureToNew(), // update apps updateAppConfigs(), // update root deps updateRootDeps(), // cleanup gitignore cleanupGitIgnore(), // remove old nx projects (tree: Tree) => { const path = 'nx.json'; const nxJson = getJsonFromFile(tree, path); if (nxJson && nxJson.projects) { delete nxJson.projects['libs']; delete nxJson.projects['xplat']; return updateJsonFile(tree, path, nxJson); } else { return noop(); } }, // remove old workspace projects (tree: Tree) => { const workspacePath = getWorkspacePath(tree); const workspaceJson = getJsonFromFile(tree, workspacePath); if (workspaceJson && workspaceJson.projects) { delete workspaceJson.projects['libs']; delete workspaceJson.projects['xplat']; return updateJsonFile(tree, workspacePath, workspaceJson); } else { return noop(); } }, // remove old tsconfig settings (tree: Tree, context: SchematicContext) => { return updateTsConfig(tree, (tsConfig: any) => { if (tsConfig) { if (!tsConfig.compilerOptions) { tsConfig.compilerOptions = {}; } const npmScope = getNpmScope(); delete tsConfig.compilerOptions.paths[`@${npmScope}/*`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/electron`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/electron/*`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/ionic`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/ionic/*`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/nativescript`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/nativescript/*`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/web`]; delete tsConfig.compilerOptions.paths[`@${npmScope}/web/*`]; if (tsConfig.includes && tsConfig.includes.length) { // find index of xplat entries const xplatIndex = (<Array<string>>tsConfig.includes).findIndex( (v) => v.indexOf('xplat') > -1 ); if (xplatIndex > -1) { (<Array<string>>tsConfig.includes).splice(xplatIndex, 1); } } if (tsConfig.exclude && tsConfig.exclude.length) { // find index of xplat entries const xplatIndex = (<Array<string>>tsConfig.exclude).findIndex( (v) => v.indexOf('nativescript') > -1 ); if (xplatIndex > -1) { (<Array<string>>tsConfig.exclude).splice(xplatIndex, 1); } } } }); }, ]); } function emptyNewStructure() { return (tree: Tree, context: SchematicContext) => { platforms = getCurrentlyUsedPlatforms(tree); newDirectoriesToEmpty .map((dir) => tree.getDir(dir)) .forEach((projectDir) => { projectDir.visit((file) => { // console.log('emptyNewStructure', ' DELETE ', file); tree.delete(file); }); }); return tree; }; } function moveOldStructureToNew() { return (tree: Tree, context: SchematicContext) => { oldDirectoriesToMove .map((dir) => tree.getDir(dir)) .forEach((projectDir) => { projectDir.visit((file) => { let moveTo: string; let srcTarget = '/src'; if (file.indexOf('/scss') === -1) { srcTarget += '/lib'; } if (file.indexOf('/libs') === 0) { const pathTarget = projectDir.path.split('/').pop(); moveTo = file.replace( projectDir.path, `/libs/xplat/${pathTarget}${srcTarget}` ); } else if (file.indexOf('/xplat') === 0) { if (file.indexOf('/plugins') > -1) { moveTo = file.replace(projectDir.path, `/libs${projectDir.path}`); } else { moveTo = file.replace( projectDir.path, `/libs${projectDir.path}${srcTarget}` ); } } // console.log('moveOldStructureToNew', ' rename ', file); // console.log('moveOldStructureToNew', ' moveTo ', moveTo); tree.rename(file, moveTo); }); }); return tree; }; } function updateRootDeps() { return (tree: Tree, context: SchematicContext) => { if (tree.exists('tsconfig.json')) { tree.delete('tsconfig.json'); } const packagePath = 'package.json'; const packageJson = getJsonFromFile(tree, packagePath); const npmScope = getNpmScope(); delete packageJson.dependencies[`@${npmScope}/scss`]; packageJson.dependencies[`@${npmScope}/xplat-scss`] = 'file:libs/xplat/scss/src'; delete packageJson.devDependencies[`node-sass`]; packageJson.devDependencies['sass'] = '~1.30.0'; // look for file ref'd plugins from xplat and update path for (const packageName of Object.keys(packageJson.dependencies)) { const packageVersion = packageJson.dependencies[packageName]; if (packageVersion && packageVersion.indexOf('file:xplat') > -1) { packageJson.dependencies[packageName] = packageVersion.replace( 'file:xplat', 'file:libs/xplat' ); } } return updateJsonFile(tree, packagePath, packageJson); }; } function updateAppConfigs() { return (tree: Tree, context: SchematicContext) => { const webAppsPaths = getAppPaths(tree, 'web'); for (const dirPath of webAppsPaths) { const relativePath = dirPath .split('/') .filter((p) => !!p) .map((p) => '..') .join('/'); let customOptionsAppend = ''; if (tree.exists(`${dirPath}/tsconfig.json`)) { const tsConfig = getJsonFromFile(tree, `${dirPath}/tsconfig.json`); if (tsConfig.angularCompilerOptions) { customOptionsAppend = `,\n"angularCompilerOptions": ${JSON.stringify( tsConfig.angularCompilerOptions )}`; } } createOrUpdate( tree, `${dirPath}/tsconfig.json`, `{ "extends": "${relativePath}/tsconfig.base.json", "files": [], "include": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.spec.json" }, { "path": "./tsconfig.editor.json" } ] }` ); createOrUpdate( tree, `${dirPath}/tsconfig.app.json`, `{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "${relativePath}/dist/out-tsc", "types": [] }, "files": [ "src/main.ts", "src/polyfills.ts" ], "include": [ "src/test.ts" ], "exclude": [ "src/test-setup.ts", "**/*.spec.ts" ]${customOptionsAppend} } ` ); createOrUpdate( tree, `${dirPath}/tsconfig.editor.json`, `{ "extends": "./tsconfig.json", "include": ["**/*.ts"], "compilerOptions": { "types": ["jest", "node"] } } ` ); createOrUpdate( tree, `${dirPath}/tsconfig.spec.json`, `{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "${relativePath}/dist/out-tsc", "module": "commonjs", "types": ["jest", "node"] }, "files": ["src/test-setup.ts"], "include": ["**/*.spec.ts", "**/*.d.ts"] } ` ); } const nativeScriptAppsPaths = getAppPaths(tree, 'nativescript'); const npmScope = getNpmScope(); // update {N} apps and configs for (const dirPath of nativeScriptAppsPaths) { // console.log(dir); // console.log('{N} appDir:', dirPath); const relativePath = dirPath .split('/') .filter((p) => !!p) .map((p) => '..') .join('/'); const cwd = process.cwd(); const webpackConfigPath = join( cwd, 'node_modules/@nstudio/nativescript-angular/src/schematics/application/_files/webpack.config.js' ); // console.log('webpackConfigPath:', webpackConfigPath); const webpackConfig = fs.readFileSync(webpackConfigPath, { encoding: 'utf-8', }); createOrUpdate( tree, `${dirPath}/webpack.config.js`, webpackConfig.replace('<%= pathOffset %>', relativePath) ); // update {N} app deps const packagePath = `${dirPath}/package.json`; const packageJson = getJsonFromFile(tree, packagePath); if (packageJson) { packageJson.dependencies = packageJson.dependencies || {}; delete packageJson.dependencies[`@${npmScope}/scss`]; delete packageJson.dependencies[`@${npmScope}/nativescript-scss`]; delete packageJson.dependencies[`@${npmScope}/nativescript`]; const updatedDeps: any = {}; updatedDeps[ `@${npmScope}/xplat-nativescript-scss` ] = `file:${relativePath}/libs/xplat/nativescript/scss/src`; updatedDeps[ `@${npmScope}/xplat-scss` ] = `file:${relativePath}/libs/xplat/scss/src`; packageJson.dependencies = { ...packageJson.dependencies, ...updatedDeps, }; // look for file ref'd plugins from xplat and update path for (const packageName of Object.keys(packageJson.dependencies)) { const packageVersion = packageJson.dependencies[packageName]; if (packageVersion && packageVersion.indexOf('../xplat') > -1) { packageJson.dependencies[packageName] = packageVersion.replace( '../xplat', '../libs/xplat' ); } } // console.log('path:',path); // console.log('packageJson overwrite:', JSON.stringify(packageJson)); tree = updateJsonFile(tree, packagePath, packageJson); } const gitIgnorePath = `${dirPath}/.gitignore`; let gitIgnore = tree.get(gitIgnorePath).content.toString(); if (gitIgnore) { gitIgnore = gitIgnore.replace('*.js', '*.js\n!jest.config.js'); tree.overwrite(gitIgnorePath, gitIgnore); } if (tree.exists(`${dirPath}/src/app.android.scss`)) { let scssUpdate = tree .read(`${dirPath}/src/app.android.scss`)! .toString('utf-8'); scssUpdate = scssUpdate.replace( '/nativescript-scss', '/xplat-nativescript-scss' ); createOrUpdate(tree, `${dirPath}/src/app.android.scss`, scssUpdate); } if (tree.exists(`${dirPath}/src/app.ios.scss`)) { let scssUpdate = tree .read(`${dirPath}/src/app.ios.scss`)! .toString('utf-8'); scssUpdate = scssUpdate.replace( '/nativescript-scss', '/xplat-nativescript-scss' ); createOrUpdate(tree, `${dirPath}/src/app.ios.scss`, scssUpdate); } if (tree.exists(`${dirPath}/tsconfig.env.json`)) { tree.delete(`${dirPath}/tsconfig.env.json`); } createOrUpdate( tree, `${dirPath}/tsconfig.app.json`, `{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "${relativePath}/dist/out-tsc", "types": [] }, "files": [ "./references.d.ts", "./src/main.ts" ] }` ); createOrUpdate( tree, `${dirPath}/tsconfig.editor.json`, `{ "extends": "./tsconfig.json", "include": ["**/*.ts"], "compilerOptions": { "types": ["jest", "node"] } } ` ); createOrUpdate( tree, `${dirPath}/tsconfig.json`, `{ "extends": "${relativePath}/tsconfig.base.json", "files": [], "include": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.spec.json" }, { "path": "./tsconfig.editor.json" } ] } ` ); createOrUpdate( tree, `${dirPath}/tsconfig.spec.json`, `{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "${relativePath}/dist/out-tsc", "module": "commonjs", "types": ["jest", "node"] }, "files": ["src/test-setup.ts"], "include": ["**/*.spec.ts", "**/*.d.ts"] } ` ); createOrUpdate( tree, `${dirPath}/src/test-setup.ts`, `import 'jest-preset-angular';` ); createOrUpdate( tree, `${dirPath}/references.d.ts`, `/// <reference path="${relativePath}/references.d.ts" />` ); createOrUpdate( tree, `${dirPath}/jest.config.js`, `module.exports = { preset: '${relativePath}/jest.preset.js', setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'], globals: { 'ts-jest': { tsConfig: '<rootDir>/tsconfig.spec.json', stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', 'jest-preset-angular/build/StripStylesTransformer' ] } }, coverageDirectory: '${relativePath}/coverage${dirPath}', snapshotSerializers: [ 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js', 'jest-preset-angular/build/AngularSnapshotSerializer.js', 'jest-preset-angular/build/HTMLCommentSerializer.js' ], displayName: '${dirPath.split('/').pop()}' }; ` ); createOrUpdate( tree, `${dirPath}/.eslintrc.json`, `{ "extends": "${relativePath}/.eslintrc.json", "ignorePatterns": [ "!**/*" ], "overrides": [ { "files": [ "*.ts" ], "extends": [ "plugin:@nrwl/nx/angular", "plugin:@angular-eslint/template/process-inline-templates" ], "parserOptions": { "project": [ "${dirPath}/tsconfig.*?.json" ] }, "rules": { "@angular-eslint/directive-selector": [ "error", { "type": "attribute", "prefix": "nar", "style": "camelCase" } ], "@angular-eslint/component-selector": [ "error", { "type": "element", "prefix": "nar", "style": "kebab-case" } ] } }, { "files": [ "*.html" ], "extends": [ "plugin:@nrwl/nx/angular-template" ], "rules": {} } ] } ` ); } return tree; }; } function cleanupGitIgnore() { return (tree: Tree) => { const gitIgnorePath = '.gitignore'; let gitIgnore = tree.get(gitIgnorePath).content.toString(); if (gitIgnore) { gitIgnore = gitIgnore.replace('# libs', ''); gitIgnore = gitIgnore.replace('libs/**/*.js', ''); gitIgnore = gitIgnore.replace('libs/**/*.map', ''); gitIgnore = gitIgnore.replace('libs/**/*.d.ts', ''); gitIgnore = gitIgnore.replace('libs/**/*.metadata.json', ''); gitIgnore = gitIgnore.replace('libs/**/*.ngfactory.ts', ''); gitIgnore = gitIgnore.replace('libs/**/*.ngsummary.json', ''); gitIgnore = gitIgnore.replace('xplat/**/*.js', ''); gitIgnore = gitIgnore.replace('xplat/**/*.map', ''); gitIgnore = gitIgnore.replace('xplat/**/*.d.ts', ''); gitIgnore = gitIgnore.replace('xplat/**/*.metadata.json', ''); gitIgnore = gitIgnore.replace('xplat/**/*.ngfactory.ts', ''); gitIgnore = gitIgnore.replace('xplat/**/*.ngsummary.json', ''); } return updateFile(tree, gitIgnorePath, gitIgnore); }; } function getCurrentlyUsedPlatforms(tree: Tree) { const platforms = []; if ( tree.exists('/libs/core/index.ts') && tree.exists('/libs/features/index.ts') ) { const npmScope = getNpmScope(); if (!oldDirectoriesToMove.includes('/libs/core')) { oldDirectoriesToMove.push('/libs/core'); newDirectoriesToEmpty.push('/libs/xplat/core/src/lib'); } if (!oldDirectoriesToMove.includes('/libs/features')) { oldDirectoriesToMove.push('/libs/features'); newDirectoriesToEmpty.push('/libs/xplat/features/src/lib'); } if (!oldDirectoriesToMove.includes('/libs/scss')) { oldDirectoriesToMove.push('/libs/scss'); newDirectoriesToEmpty.push('/libs/xplat/scss/src'); createOrUpdate( tree, `/libs/scss/package.json`, `{ "name": "@${npmScope}/xplat-scss", "version": "1.0.0" }` ); } if (!oldDirectoriesToMove.includes('/libs/utils')) { oldDirectoriesToMove.push('/libs/utils'); newDirectoriesToEmpty.push('/libs/xplat/utils/src/lib'); } // collect which platforms were currently used if (tree.exists('/xplat/electron/index.ts')) { if (!platforms.includes('electron')) { platforms.push('electron'); } if (!oldDirectoriesToMove.includes('/xplat/electron')) { oldDirectoriesToMove.push('/xplat/electron'); newDirectoriesToEmpty.push('/libs/xplat/electron/core/src/lib'); } } if (tree.exists('/xplat/ionic/index.ts')) { if (!platforms.includes('ionic')) { platforms.push('ionic'); } if (!oldDirectoriesToMove.includes('/xplat/ionic/core')) { oldDirectoriesToMove.push('/xplat/ionic/core'); newDirectoriesToEmpty.push('/libs/xplat/ionic/core/src/lib'); } if (!oldDirectoriesToMove.includes('/xplat/ionic/features')) { oldDirectoriesToMove.push('/xplat/ionic/features'); newDirectoriesToEmpty.push('/libs/xplat/ionic/features/src/lib'); } if (!oldDirectoriesToMove.includes('/xplat/ionic/scss')) { oldDirectoriesToMove.push('/xplat/ionic/scss'); newDirectoriesToEmpty.push('/libs/xplat/ionic/scss/src'); createOrUpdate( tree, `/xplat/ionic/scss/package.json`, `{ "name": "@${npmScope}/xplat-ionic-scss", "version": "1.0.0" }` ); if (tree.exists(`/xplat/ionic/scss/_index.scss`)) { let scssUpdate = tree .read(`/xplat/ionic/scss/_index.scss`)! .toString('utf-8'); scssUpdate = scssUpdate.replace( `@${npmScope}/scss/index`, `@${npmScope}/xplat-scss/index` ); createOrUpdate(tree, `/xplat/ionic/scss/_index.scss`, scssUpdate); } } } if (tree.exists('/xplat/nativescript/index.ts')) { if (!platforms.includes('nativescript')) { platforms.push('nativescript'); } if (!oldDirectoriesToMove.includes('/xplat/nativescript/core')) { oldDirectoriesToMove.push('/xplat/nativescript/core'); newDirectoriesToEmpty.push('/libs/xplat/nativescript/core/src/lib'); } if (!oldDirectoriesToMove.includes('/xplat/nativescript/features')) { oldDirectoriesToMove.push('/xplat/nativescript/features'); newDirectoriesToEmpty.push('/libs/xplat/nativescript/features/src/lib'); } if (!oldDirectoriesToMove.includes('/xplat/nativescript/plugins')) { oldDirectoriesToMove.push('/xplat/nativescript/plugins'); } if (!oldDirectoriesToMove.includes('/xplat/nativescript/scss')) { oldDirectoriesToMove.push('/xplat/nativescript/scss'); newDirectoriesToEmpty.push('/libs/xplat/nativescript/scss/src'); createOrUpdate( tree, `/xplat/nativescript/scss/package.json`, `{ "name": "@${npmScope}/xplat-nativescript-scss", "version": "1.0.0" }` ); if (tree.exists(`/xplat/nativescript/scss/_common.scss`)) { let scssUpdate = tree .read(`/xplat/nativescript/scss/_common.scss`)! .toString('utf-8'); scssUpdate = scssUpdate.replace( `@${npmScope}/scss/index`, `@${npmScope}/xplat-scss/index` ); createOrUpdate( tree, `/xplat/nativescript/scss/_common.scss`, scssUpdate ); } } if (!oldDirectoriesToMove.includes('/xplat/nativescript/utils')) { oldDirectoriesToMove.push('/xplat/nativescript/utils'); newDirectoriesToEmpty.push('/libs/xplat/nativescript/utils/src/lib'); } } if (tree.exists('/xplat/web/index.ts')) { if (!platforms.includes('web')) { platforms.push('web'); } if (!oldDirectoriesToMove.includes('/xplat/web/core')) { oldDirectoriesToMove.push('/xplat/web/core'); newDirectoriesToEmpty.push('/libs/xplat/web/core/src/lib'); } if (!oldDirectoriesToMove.includes('/xplat/web/features')) { oldDirectoriesToMove.push('/xplat/web/features'); newDirectoriesToEmpty.push('/libs/xplat/web/features/src/lib'); } if (!oldDirectoriesToMove.includes('/xplat/web/plugins')) { oldDirectoriesToMove.push('/xplat/web/plugins'); } if (!oldDirectoriesToMove.includes('/xplat/web/scss')) { oldDirectoriesToMove.push('/xplat/web/scss'); newDirectoriesToEmpty.push('/libs/xplat/web/scss/src'); createOrUpdate( tree, `/xplat/web/scss/package.json`, `{ "name": "@${npmScope}/xplat-web-scss", "version": "1.0.0" }` ); if (tree.exists(`/xplat/web/scss/_index.scss`)) { let scssUpdate = tree .read(`/xplat/web/scss/_index.scss`)! .toString('utf-8'); scssUpdate = scssUpdate.replace( `@${npmScope}/scss/index`, `@${npmScope}/xplat-scss/index` ); createOrUpdate(tree, `/xplat/web/scss/_index.scss`, scssUpdate); } } } return platforms; } return platforms; }
the_stack
import { View, commitModel } from '@datx/core'; import { setMeta, mobx, IResponseHeaders } from '@datx/utils'; import { MODEL_PERSISTED_FIELD, MODEL_PROP_FIELD, MODEL_QUEUE_FIELD, MODEL_RELATED_FIELD, } from './consts'; import { isBrowser } from './helpers/utils'; import { ICollectionFetchOpts } from './interfaces/ICollectionFetchOpts'; import { IHeaders } from './interfaces/IHeaders'; import { IJsonapiCollection } from './interfaces/IJsonapiCollection'; import { IJsonapiModel } from './interfaces/IJsonapiModel'; import { IRawResponse } from './interfaces/IRawResponse'; import { IRequestOptions } from './interfaces/IRequestOptions'; import { ILink, IResponse } from './interfaces/JsonApi'; import { Response as LibResponse } from './Response'; import { CachingStrategy, ParamArrayType } from '@datx/network'; import { saveCache, getCache } from './cache'; export type FetchType = ( method: string, url: string, body?: object, requestHeaders?: IHeaders, fetchOptions?: object, ) => Promise<IRawResponse>; export type CollectionFetchType = <T extends IJsonapiModel>( options: ICollectionFetchOpts, ) => Promise<LibResponse<T>>; export interface IResponseObject { data: IResponse; error?: Error; headers: IResponseHeaders; requestHeaders: IHeaders; status: number; } export interface IConfigType { baseFetch: FetchType; baseUrl: string; cache: CachingStrategy; maxCacheAge: number; defaultFetchOptions: Record<string, any>; fetchReference?: typeof fetch; paramArrayType: ParamArrayType; encodeQueryString?: boolean; onError(IResponseObject): IResponseObject; transformRequest(options: ICollectionFetchOpts): ICollectionFetchOpts; transformResponse(response: IRawResponse): IRawResponse; } export const config: IConfigType = { // Base URL for all API calls baseUrl: '/', // Enable caching by default in the browser cache: isBrowser ? CachingStrategy.CacheFirst : CachingStrategy.NetworkOnly, maxCacheAge: Infinity, // Default options that will be passed to the fetch function defaultFetchOptions: { headers: { 'content-type': 'application/vnd.api+json', }, }, encodeQueryString: false, // Reference of the fetch method that should be used fetchReference: (isBrowser && 'fetch' in window && typeof window.fetch === 'function' && window.fetch.bind(window)) || undefined, // Determines how will the request param arrays be stringified paramArrayType: ParamArrayType.CommaSeparated, // As recommended by the spec /** * Base implementation of the fetch function (can be overridden) * * @param {string} method API call method * @param {string} url API call URL * @param {object} [body] API call body * @param {IHeaders} [requestHeaders] Headers that will be sent * @param {object} [fetchOptions] Options that can be passed from the fetch function call * @returns {Promise<IRawResponse>} Resolves with a raw response object */ baseFetch( method: string, url: string, body?: object, requestHeaders?: IHeaders, _fetchOptions?: object, ): Promise<IRawResponse> { let data: IResponse; let status: number; let headers: IResponseHeaders; const request: Promise<void> = Promise.resolve(); const uppercaseMethod = method.toUpperCase(); const isBodySupported = uppercaseMethod !== 'GET' && uppercaseMethod !== 'HEAD'; return request .then(() => { const defaultHeaders = config.defaultFetchOptions.headers || {}; const reqHeaders: IHeaders = Object.assign({}, defaultHeaders, requestHeaders) as IHeaders; const options = Object.assign({}, config.defaultFetchOptions, { body: (isBodySupported && JSON.stringify(body)) || undefined, headers: reqHeaders, method, }); if (this.fetchReference) { return this.fetchReference(url, options); } throw new Error('Fetch reference needs to be defined before using the network'); }) .then((response: Response) => { status = response.status; headers = response.headers; return response.json(); }) .catch((error: Error) => { if (status === 204) { return null; } throw error; }) .then((responseData: IResponse) => { data = responseData; if (status >= 400) { throw { message: `Invalid HTTP status: ${status}`, status, }; } return { data, headers, requestHeaders, status }; }) .catch((error) => { return this.onError({ data, error, headers, requestHeaders, status }); }); }, onError(resp: IResponseObject) { return resp; }, transformRequest(options: ICollectionFetchOpts): ICollectionFetchOpts { return options; }, transformResponse(response: IRawResponse): IRawResponse { return response; }, }; function getLocalNetworkError<T extends IJsonapiModel>( message: string, reqOptions: ICollectionFetchOpts, collection?: IJsonapiCollection, ): LibResponse<T> { const ResponseConstructor: typeof LibResponse = reqOptions.options?.fetchOptions?.['Response'] || LibResponse; return new ResponseConstructor<T>( { error: new Error(message), // collection, requestHeaders: reqOptions.options?.networkConfig?.headers, }, collection, reqOptions.options, ); } function makeNetworkCall<T extends IJsonapiModel>( params: ICollectionFetchOpts, fetchOptions?: object, doCacheResponse = false, existingResponse?: LibResponse<T>, ): Promise<LibResponse<T>> { const ResponseConstructor: typeof LibResponse = fetchOptions?.['Response'] || LibResponse; return config .baseFetch(params.method, params.url, params.data, params?.options?.networkConfig?.headers, fetchOptions) .then((response: IRawResponse) => { const collectionResponse = Object.assign({}, response, { collection: params.collection }); const payload = config.transformResponse(collectionResponse); if (existingResponse) { existingResponse.update(payload, params.views); return existingResponse; } return new ResponseConstructor<T>( payload, params.collection, params.options, undefined, params.views, ); }) .then((response: LibResponse<T>) => { if (doCacheResponse) { saveCache(params.url, response); } return response; }); } /** * Base implementation of the stateful fetch function (can be overridden) * * @param {ICollectionFetchOpts} reqOptions API request options * @returns {Promise<Response>} Resolves with a response object */ function collectionFetch<T extends IJsonapiModel>( reqOptions: ICollectionFetchOpts, ): Promise<LibResponse<T>> { const ResponseConstructor: typeof LibResponse = reqOptions.options?.fetchOptions?.['Response'] || LibResponse; const params = config.transformRequest(reqOptions); // const { url, options, data, method = 'GET', collection, views } = params; const staticCollection = (params?.collection?.constructor as unknown) as { maxCacheAge?: number; cache: CachingStrategy; }; const collectionCache = staticCollection && staticCollection.cache; const isCacheSupported = params.method.toUpperCase() === 'GET'; const cacheStrategy = reqOptions.options?.cacheOptions?.skipCache || !isCacheSupported ? CachingStrategy.NetworkOnly : reqOptions.options?.cacheOptions?.cachingStrategy || collectionCache || config.cache; let maxCacheAge: number = config.maxCacheAge || Infinity; if (staticCollection && staticCollection.maxCacheAge !== undefined) { maxCacheAge = staticCollection.maxCacheAge; } if (reqOptions.options?.cacheOptions?.maxAge !== undefined) { maxCacheAge = reqOptions.options?.cacheOptions?.maxAge; } // NetworkOnly - Ignore cache if (cacheStrategy === CachingStrategy.NetworkOnly) { return makeNetworkCall<T>(params, reqOptions.options?.fetchOptions); } const cacheContent: { response: LibResponse<T> } | undefined = (getCache( params.url, maxCacheAge, ResponseConstructor, ) as unknown) as { response: LibResponse<T> } | undefined; // NetworkFirst - Fallback to cache only on network error if (cacheStrategy === CachingStrategy.NetworkFirst) { return makeNetworkCall<T>(params, reqOptions.options?.fetchOptions, true).catch((errorResponse) => { if (cacheContent) { return cacheContent.response; } throw errorResponse; }); } // StaleWhileRevalidate - Use cache and update it in background if (cacheStrategy === CachingStrategy.StaleWhileRevalidate) { const network = makeNetworkCall<T>(params, reqOptions.options?.fetchOptions, true); if (cacheContent) { network.catch(() => { // Ignore the failure }); return Promise.resolve(cacheContent.response); } return network; } // CacheOnly - Fail if nothing in cache if (cacheStrategy === CachingStrategy.CacheOnly) { if (cacheContent) { return Promise.resolve(cacheContent.response); } return Promise.reject( getLocalNetworkError('No cache for this request', reqOptions, params?.collection), ); } // PREFER_CACHE - Use cache if available if (cacheStrategy === CachingStrategy.CacheFirst) { return cacheContent ? Promise.resolve(cacheContent.response) : makeNetworkCall<T>(params, reqOptions.options?.fetchOptions, true); } // StaleAndUpdate - Use cache and update response once network is complete if (cacheStrategy === CachingStrategy.StaleAndUpdate) { const existingResponse = cacheContent?.response?.clone() as LibResponse<T>; const network = makeNetworkCall<T>(params, reqOptions.options?.fetchOptions, true, existingResponse); if (existingResponse) { network.catch(() => { // Ignore the failure }); return Promise.resolve(existingResponse); } return network; } return Promise.reject( getLocalNetworkError('Invalid caching strategy', reqOptions, params?.collection), ); } export function libFetch<T extends IJsonapiModel = IJsonapiModel>( options: ICollectionFetchOpts, ): Promise<LibResponse<T>> { return collectionFetch<T>(options); } /** * API call used to get data from the server * * @export * @param {IJsonapiCollection} collection Related collection * @param {string} url API call URL * @param {IRequestOptions} [options] Server options * @param {Array<View>} [views] Request view * @returns {Promise<Response>} Resolves with a Response object */ export function read<T extends IJsonapiModel = IJsonapiModel>( url: string, collection?: IJsonapiCollection, options?: IRequestOptions, views?: Array<View>, ): Promise<LibResponse<T>> { return collectionFetch<T>({ collection, data: undefined, method: 'GET', options, url, views, }); } /** * API call used to create data on the server * * @export * @param {IJsonapiCollection} collection Related collection * @param {string} url API call URL * @param {object} [data] Request body * @param {IRequestOptions} [options] Server options * @param {Array<View>} [views] Request view * @returns {Promise<Response>} Resolves with a Response object */ export function create<T extends IJsonapiModel = IJsonapiModel>( url: string, data?: object, collection?: IJsonapiCollection, options?: IRequestOptions, views?: Array<View>, ): Promise<LibResponse<T>> { return collectionFetch<T>({ collection, data, method: 'POST', options, url, views, }); } /** * API call used to update data on the server * * @export * @param {IJsonapiCollection} collection Related collection * @param {string} url API call URL * @param {object} [data] Request body * @param {IRequestOptions} [options] Server options * @param {Array<View>} [views] Request view * @returns {Promise<Response>} Resolves with a Response object */ export function update<T extends IJsonapiModel = IJsonapiModel>( url: string, data?: object, collection?: IJsonapiCollection, options?: IRequestOptions, views?: Array<View>, ): Promise<LibResponse<T>> { return collectionFetch<T>({ collection, data, method: 'PATCH', options, url, views, }); } /** * API call used to remove data from the server * * @export * @param {IJsonapiCollection} collection Related collection * @param {string} url API call URL * @param {IRequestOptions} [options] Server options * @param {Array<View>} [views] Request view * @returns {Promise<Response>} Resolves with a Response object */ export function remove<T extends IJsonapiModel = IJsonapiModel>( url: string, collection?: IJsonapiCollection, options?: IRequestOptions, views?: Array<View>, ): Promise<LibResponse<T>> { return collectionFetch<T>({ collection, data: undefined, method: 'DELETE', options, url, views, }); } /** * Fetch a link from the server * * @export * @param {JsonApi.ILink} link Link URL or a link object * @param {IJsonapiCollection} collection Store that will be used to save the response * @param {IRequestOptions} [options] Server options * @param {Array<View>} [views] Request view * @returns {Promise<LibResponse>} Response promise */ export function fetchLink<T extends IJsonapiModel = IJsonapiModel>( link: ILink, collection?: IJsonapiCollection, options?: IRequestOptions, views?: Array<View>, ResponseConstructor: typeof LibResponse = LibResponse, ): Promise<LibResponse<T>> { if (link) { const href: string = typeof link === 'object' ? link.href : link; if (href) { return read<T>(href, collection, options, views); } } return Promise.resolve(new ResponseConstructor({ data: undefined }, collection)); } export function handleResponse<T extends IJsonapiModel = IJsonapiModel>( record: T, prop?: string, ): (response: LibResponse<T>) => T { return mobx.action( (response: LibResponse<T>): T => { if (response.error) { throw response.error; } if (response.status === 204) { setMeta(record, MODEL_PERSISTED_FIELD, true); return record; } if (response.status === 202) { const responseRecord = response.data as T; setMeta(responseRecord, MODEL_PROP_FIELD, prop); setMeta(responseRecord, MODEL_QUEUE_FIELD, true); setMeta(responseRecord, MODEL_RELATED_FIELD, record); return responseRecord; } setMeta(record, MODEL_PERSISTED_FIELD, true); const data = response.replaceData(record).data as T; commitModel(data); return data; }, ); }
the_stack
import {useCallback, useEffect, useMemo, useRef, useState} from "react"; import {QueryClient, useMutation, useQuery, useQueryClient} from "react-query"; import {FieldPath, FirebaseFirestore, Query} from "@firebase/firestore-types"; import {useFirestore} from "./Provider"; import {collectionCache} from "./Cache"; import { CollectionQueryType, Document, empty, Options, OrderByArray, OrderByType, WhereArray, WhereType, Optional, } from "./types"; import {parseDates} from "./utils"; const createFirestoreRef = ( firestore: FirebaseFirestore, path: string, { where, orderBy, limit, startAt, endAt, startAfter, endBefore, isCollectionGroup, }: CollectionQueryType, ) => { let ref: Query = firestore.collection(path); if (isCollectionGroup) { ref = firestore.collectionGroup(path); } if (where) { function multipleConditions(w: WhereType): w is WhereArray { return !!(w as WhereArray) && Array.isArray(w[0]); } if (multipleConditions(where)) { where.forEach((w) => { ref = ref.where(w[0] as string | FieldPath, w[1], w[2]); }); } else if ( typeof where[0] === "string" && typeof where[1] === "string" ) { ref = ref.where(where[0], where[1], where[2]); } } if (orderBy) { if (typeof orderBy === "string") { ref = ref.orderBy(orderBy); } else if (Array.isArray(orderBy)) { function multipleOrderBy(o: OrderByType): o is OrderByArray[] { return Array.isArray((o as OrderByArray[])[0]); } if (multipleOrderBy(orderBy)) { orderBy.forEach(([order, direction]) => { ref = ref.orderBy(order as string | FieldPath, direction); }); } else { const [order, direction] = orderBy; ref = ref.orderBy(order as string | FieldPath, direction); } } } if (startAt) { ref = ref.startAt(startAt); } if (endAt) { ref = ref.endAt(endAt); } if (startAfter) { ref = ref.startAfter(startAfter); } if (endBefore) { ref = ref.endBefore(endBefore); } if (limit) { ref = ref.limit(limit); } return ref; }; type ListenerReturnType<Doc extends Document = Document> = { initialData: Doc[]; unsubscribe: () => void; }; const createListenerAsync = async <Doc extends Document = Document>( firestore: FirebaseFirestore, queryClient: QueryClient, path: string | undefined = undefined, queryString: string, ignoreFirestoreDocumentSnapshotField: boolean, setHasNextPage: (value: boolean) => void, ): Promise<ListenerReturnType<Doc>> => { return new Promise((resolve, reject) => { if (!path) { return resolve({ initialData: [], unsubscribe: empty.function, }); } const query: CollectionQueryType = JSON.parse(queryString) ?? {}; const ref = createFirestoreRef(firestore, path, query); const unsubscribe = ref.onSnapshot( {includeMetadataChanges: true}, { next: (querySnapshot) => { const data: Doc[] = []; querySnapshot.forEach((doc) => { const docData = doc.data() ?? empty.object; parseDates(docData); const docToAdd = { ...docData, id: doc.id, exists: doc.exists, hasPendingWrites: doc.metadata.hasPendingWrites, __snapshot: ignoreFirestoreDocumentSnapshotField ? undefined : doc, } as Doc; // update individual docs in the cache queryClient.setQueryData(doc.ref.path, docToAdd); data.push(docToAdd); }); setHasNextPage(!querySnapshot.empty); // resolve initial data resolve({ initialData: data, unsubscribe, }); // update on listener fire queryClient.setQueryData([path, queryString], data); }, error: reject, }, ); }); }; /** * Call a Firestore Collection * @template Doc * @param path String if the document is ready. If it's not ready yet, pass `null`, and the request won't start yet. * @param [query] - Dictionary with options to query the collection. * @param [options] - takes any of useQuery options. */ export const useCollection = <Data, TransData = unknown>( path?: string, options?: Options<Document<Data>[], Optional<Document<TransData>, "id">[]>, query?: CollectionQueryType<Document<Data>> & { ignoreFirestoreDocumentSnapshotField?: boolean; }, ) => { const [isFetchingNextPage, setIsFetchingNextPage] = useState(false); const [hasNextPage, setHasNextPage] = useState(true); const {firestore} = useFirestore(); const queryClient = useQueryClient(); const unsubscribeRef = useRef<ListenerReturnType["unsubscribe"] | null>( null, ); const { where, endAt, endBefore, startAfter, startAt, orderBy, limit, isCollectionGroup, ignoreFirestoreDocumentSnapshotField = true, } = query || {}; // why not just put this into the ref directly? // so that we can use the useEffect down below that triggers revalidate() const memoQueryString = useMemo( () => JSON.stringify({ where, endAt, endBefore, startAfter, startAt, orderBy, limit, isCollectionGroup, }), [ endAt, endBefore, isCollectionGroup, limit, orderBy, startAfter, startAt, where, ], ); async function fetch() { if (unsubscribeRef.current) { unsubscribeRef.current(); unsubscribeRef.current = null; } const {unsubscribe, initialData} = await createListenerAsync< Document<Data> >( firestore, queryClient, path, memoQueryString, ignoreFirestoreDocumentSnapshotField, setHasNextPage, ); unsubscribeRef.current = unsubscribe; return initialData; } const {data, status, error} = useQuery< Document<Data>[], Error, Optional<Document<TransData>, "id">[] >([path, memoQueryString], fetch, { ...options, notifyOnChangeProps: "tracked", }); const {mutateAsync} = useMutation< Document<Data>[], Error, {data: Data | Data[]; subPath?: string} >( async ({data: newData, subPath}) => { if (!path) return Promise.resolve([]); const newPath = subPath ? path + "/" + subPath : path; const dataArray = Array.isArray(newData) ? newData : [newData]; const ref = firestore.collection(newPath); const docsToAdd: Document<Data>[] = dataArray.map((doc) => ({ ...doc, // generate IDs we can use that in the local cache that match the server id: ref.doc().id, })); // add to network const batch = firestore.batch(); docsToAdd.forEach(({id, ...doc}) => { // take the ID out of the document batch.set(ref.doc(id), doc); }); await batch.commit(); return Promise.resolve(docsToAdd); }, { // Always refetch after error or success: onSettled: () => { queryClient.invalidateQueries([path, memoQueryString]); }, }, ); useEffect(() => { //should it go before the useQuery? return () => { // clean up listener on unmount if it exists if (unsubscribeRef.current) { unsubscribeRef.current(); unsubscribeRef.current = null; } }; // should depend on the path, queyr being the same... }, [path, memoQueryString]); // add the collection to the cache, // so that we can mutate it from document calls later useEffect(() => { if (path) collectionCache.addCollectionToCache(path, memoQueryString); }, [path, memoQueryString]); /** * `add(data, subPath?)`: Extends the Firestore document [`add` function](https://firebase.google.com/docs/firestore/manage-data/add-data). * - It also updates the local cache using react-query's `setQueryData`. This will prove highly convenient over the regular `add` function provided by Firestore. * - If the second argument is defined it will be concatinated to path arg as a prefix */ const add = async (newData: Data | Data[], subPath?: string) => mutateAsync({data: newData, subPath}); const setCache = useCallback( (cachedData: TransData[]) => { queryClient.setQueryData<TransData[]>( [path, memoQueryString], (prevState) => { if (!prevState) return []; return [...prevState, ...cachedData]; }, ); }, // eslint-disable-next-line react-hooks/exhaustive-deps [path, memoQueryString], ); const fetchNextPage = async () => { if (!path || !data?.length) return; setIsFetchingNextPage(true); // get the snapshot of last document we have right now in our query const startAfterDocument = data[data.length - 1].__snapshot; const ref = createFirestoreRef( firestore, path, JSON.parse(memoQueryString), ); // get more documents, after the most recent one we have const querySnapshot = await ref.startAfter(startAfterDocument).get(); setHasNextPage(!querySnapshot.empty); const moreDocs: TransData[] = []; querySnapshot.docs.forEach((doc) => { const docData = doc.data() ?? empty.object; const docToAdd = { ...docData, id: doc.id, exists: doc.exists, hasPendingWrites: doc.metadata.hasPendingWrites, __snapshot: ignoreFirestoreDocumentSnapshotField ? undefined : doc, } as Document<TransData>; // update individual docs in the cache queryClient.setQueryData(doc.ref.path, docToAdd); moreDocs.push(docToAdd); }); // mutate our local cache, adding the docs we just added setCache(moreDocs); setIsFetchingNextPage(false); }; return { data, status, error, add, setCache, fetchNextPage, isFetchingNextPage, hasNextPage, /** * A function that, when called, unsubscribes the Firestore listener. * * The function can be null, so make sure to check that it exists before calling it. * * Note: This is not necessary to use. `useCollection` already unmounts the listener for you. This is only intended if you want to unsubscribe on your own. */ unsubscribe: unsubscribeRef.current, }; };
the_stack
import { CharSet } from "refa"; import { visitRegExpAST, AST } from "regexpp"; import { Alternative, Assertion, LookaroundAssertion, Backreference, CapturingGroup, Character, CharacterClass, CharacterClassElement, CharacterSet, Group, Quantifier, Element, Node, Pattern, EscapeCharacterSet, UnicodePropertyCharacterSet, BranchNode, CharacterClassRange, RegExpLiteral, EdgeAssertion, } from "regexpp/ast"; import { allCharSet, emptyCharSet, lineTerminatorCharSet, toCharSet } from "./char-util"; import { assertNever, Simple } from "./util"; type Flags = Partial<Readonly<AST.Flags>>; /** * Returns whether the given node is constant meaning that it can only match one string and what this string is. * If the node is constant, it will return the constant string. */ export function getConstant(node: Node, flags: Flags): false | { word: string } { switch (node.type) { case "Alternative": { let word = ""; for (const element of node.elements) { const elementResult = getConstant(element, flags); if (elementResult === false) { return false; } else { word += elementResult.word; } } return { word }; } case "Assertion": case "Flags": { // Assertions are constant because the only affect whether a string matches. // Flags are trivially constant return { word: "" }; } case "Backreference": { if (isEmptyBackreference(node)) { return { word: "" }; } else { // only constant if the expression of the capturing group is constant return getConstant(node.resolved, flags); } } case "CapturingGroup": case "Group": case "Pattern": { if (node.alternatives.length == 0) { return { word: "" }; } else if (node.alternatives.length == 1) { return getConstant(node.alternatives[0], flags); } else { let word: string | false = false; for (const alt of node.alternatives) { const altResult = getConstant(alt, flags); if (altResult === false) { return false; } else if (word === false) { word = altResult.word; } else if (word !== altResult.word) { return false; } } return word === false ? false : { word }; } } case "Character": { const string = String.fromCodePoint(node.value); if (flags.ignoreCase && string.toLowerCase() !== string.toUpperCase()) { return false; } return { word: string }; } case "CharacterClass": { // Here's a question is the empty character class (`[]` or `[^\s\S]`) constant? // I say, no it isn't. if (node.negate) { // negated character classes are 1) really hard to check and 2) very unlikely to be constant return false; } let word: false | string = false; for (const element of node.elements) { const elementResult = getConstant(element, flags); if (elementResult === false) { return false; } else if (word === false) { word = elementResult.word; } else if (word !== elementResult.word) { return false; } } return word === false ? false : { word }; } case "CharacterClassRange": { return node.min.value == node.max.value && getConstant(node.min, flags); } case "CharacterSet": { // for themselves, character sets like \w, ., \s are not constant return false; } case "Quantifier": { if (node.max === 0) { return { word: "" }; } const elementResult = getConstant(node.element, flags); if (elementResult !== false) { if (elementResult.word === "") { return elementResult; } else if (node.min === node.max) { let word = ""; for (let i = node.min; i > 0; i--) { word += elementResult.word; } return { word }; } } return false; } case "RegExpLiteral": { return getConstant(node.pattern, flags); } default: return false; } } /** * Returns whether all paths of the given element don't move the position of the automaton. */ export function isZeroLength(element: Element | Alternative | Alternative[]): boolean { if (Array.isArray(element)) { return element.every(a => isZeroLength(a)); } switch (element.type) { case "Alternative": return element.elements.every(e => isZeroLength(e)); case "Assertion": return true; case "Character": case "CharacterClass": case "CharacterSet": return false; case "Quantifier": return element.max === 0 || isZeroLength(element.element); case "Backreference": return isEmptyBackreference(element); case "CapturingGroup": case "Group": return isZeroLength(element.alternatives); default: throw assertNever(element); } } /** * Returns whether at least one path of the given element does not move the position of the automation. */ export function isPotentiallyZeroLength(element: Element | Alternative | Alternative[]): boolean { if (Array.isArray(element)) { return element.some(a => isPotentiallyZeroLength(a)); } switch (element.type) { case "Alternative": return element.elements.every(e => isPotentiallyZeroLength(e)); case "Assertion": return true; case "Backreference": if (isEmptyBackreference(element)) { return true; } return isPotentiallyZeroLength(element.resolved); case "Character": case "CharacterClass": case "CharacterSet": return false; case "CapturingGroup": case "Group": return isPotentiallyZeroLength(element.alternatives); case "Quantifier": return element.min === 0 || isPotentiallyZeroLength(element.element); default: throw assertNever(element); } } /** * Returns whether all paths of the given element does not move the position of the automation and accept * regardless of prefix and suffix. * * @param {Element | Alternative | Alternative[]} element */ export function isEmpty(element: Element | Alternative | Alternative[]): boolean { if (Array.isArray(element)) { return element.every(isEmpty); } switch (element.type) { case "Alternative": return element.elements.every(isEmpty); case "Assertion": // assertion do not consume characters but they do usually reject some pre- or suffixes if (element.kind === "lookahead" || element.kind === "lookbehind") { if (!element.negate && isPotentiallyEmpty(element.alternatives)) { // if a positive lookaround is potentially empty, it will trivially accept all pre- or suffixes return true; } } return false; case "Backreference": if (isEmptyBackreference(element)) { return true; } return isEmpty(element.resolved); case "Character": case "CharacterClass": case "CharacterSet": return false; case "CapturingGroup": case "Group": return isEmpty(element.alternatives); case "Quantifier": return element.max === 0 || isEmpty(element.element); default: throw assertNever(element); } } export interface IsPotentiallyEmptyOptions { /** * If `true`, then backreferences that aren't guaranteed to always be replaced with the empty string will be * assumed to be non-empty. */ backreferencesAreNonEmpty?: boolean; } /** * Returns whether at least one path of the given element does not move the position of the automation and accepts * regardless of prefix and suffix. * * This basically means that it can match the empty string and that it does that at any position in any string. * Lookarounds do not affect this as (as mentioned above) all prefixes and suffixes are accepted. */ export function isPotentiallyEmpty( element: Element | Alternative | Alternative[], options: Readonly<IsPotentiallyEmptyOptions> = {} ): boolean { if (Array.isArray(element)) { return element.some(a => isPotentiallyEmpty(a, options)); } switch (element.type) { case "Alternative": return element.elements.every(e => isPotentiallyEmpty(e, options)); case "Assertion": // assertion do not consume characters but they do usually reject some pre- or suffixes if (element.kind === "lookahead" || element.kind === "lookbehind") { if (!element.negate && isPotentiallyEmpty(element.alternatives, options)) { // if a positive lookaround is potentially empty, it will trivially accept all pre- or suffixes return true; } } return false; case "Backreference": if (isEmptyBackreference(element)) { return true; } if (options.backreferencesAreNonEmpty) { return false; } else { return !backreferenceAlwaysAfterGroup(element) || isPotentiallyEmpty(element.resolved, options); } case "Character": case "CharacterClass": case "CharacterSet": return false; case "CapturingGroup": case "Group": return isPotentiallyEmpty(element.alternatives, options); case "Quantifier": return element.min === 0 || isPotentiallyEmpty(element.element, options); default: throw assertNever(element); } } /** * Returns whether any of the ancestors of the given node fulfills the given condition. * * The ancestors will be iterated in the order from closest to farthest. * The condition function will not be called on the given node. */ export function hasSomeAncestor(node: Node, conditionFn: (ancestor: BranchNode) => boolean): boolean { let parent: Node["parent"] = node.parent; while (parent) { if (conditionFn(parent)) { return true; } parent = parent.parent; } return false; } export type Descendants<T> = T | (T extends Node ? RealDescendants<T> : never); type RealDescendants<T extends Node> = T extends | Alternative | CapturingGroup | Group | LookaroundAssertion | Quantifier | Pattern ? Element | CharacterClassElement : never | T extends CharacterClass ? CharacterClassElement : never | T extends CharacterClassRange ? Character : never | T extends RegExpLiteral ? Flags | Pattern | Element | CharacterClassElement : never; /** * Returns whether any of the descendants of the given node fulfill the given condition. * * The descendants will be iterated in a DFS top-to-bottom manner from left to right with the first node being the * given node. * * This function is short-circuited, so as soon as any `conditionFn` returns `true`, `true` will be returned. * * @param node * @param conditionFn * @param descentConditionFn An optional function to decide whether the descendant of the given node will be checked as * well. */ export function hasSomeDescendant<T extends Node>( node: T & Node, conditionFn: (descendant: Descendants<T>) => boolean, descentConditionFn?: (descendant: Descendants<T>) => boolean ): boolean { if (conditionFn(node)) { return true; } if (descentConditionFn && !descentConditionFn(node)) { return false; } switch (node.type) { case "Alternative": return node.elements.some(e => hasSomeDescendant(e, conditionFn, descentConditionFn)); case "Assertion": if (node.kind === "lookahead" || node.kind === "lookbehind") { return node.alternatives.some(a => hasSomeDescendant(a, conditionFn, descentConditionFn)); } return false; case "CapturingGroup": case "Group": case "Pattern": return node.alternatives.some(a => hasSomeDescendant(a, conditionFn, descentConditionFn)); case "CharacterClass": return node.elements.some(e => hasSomeDescendant(e, conditionFn, descentConditionFn)); case "CharacterClassRange": return ( hasSomeDescendant(node.min, conditionFn, descentConditionFn) || hasSomeDescendant(node.max, conditionFn, descentConditionFn) ); case "Quantifier": return hasSomeDescendant(node.element, conditionFn, descentConditionFn); case "RegExpLiteral": return ( hasSomeDescendant(node.pattern, conditionFn, descentConditionFn) || hasSomeDescendant(node.flags, conditionFn, descentConditionFn) ); } return false; } /** * Returns whether the given node is or contains a capturing group. * * This function is justified because it's extremely important to check for capturing groups when providing fixers. * * @param node */ export function hasCapturingGroup(node: Node): boolean { return hasSomeDescendant(node, d => d.type === "CapturingGroup"); } /** * Returns whether two nodes are semantically equivalent. */ export function areEqual(x: Node | null, y: Node | null): boolean { if (x == y) { return true; } if (!x || !y || x.type != y.type) { return false; } function manyAreEqual(a: Node[], b: Node[]): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (!areEqual(a[i], b[i])) { return false; } } return true; } function alternativesAreEqual(a: { alternatives: Alternative[] }, b: { alternatives: Alternative[] }): boolean { return manyAreEqual(a.alternatives, b.alternatives); } switch (x.type) { case "Alternative": { const other = y as Alternative; return manyAreEqual(x.elements, other.elements); } case "Assertion": { const other = y as Assertion; if (x.kind === other.kind) { if (x.kind === "lookahead" || x.kind === "lookbehind") { const otherLookaround = y as LookaroundAssertion; return x.negate === otherLookaround.negate && alternativesAreEqual(x, otherLookaround); } else { return x.raw === other.raw; } } return false; } case "Backreference": { const other = y as Backreference; return areEqual(x.resolved, other.resolved); } case "CapturingGroup": { const other = y as CapturingGroup; const p1 = getPattern(x); const p2 = getPattern(other); if (p1 && p2) { const n1 = getCapturingGroupNumber(p1, x); const n2 = getCapturingGroupNumber(p2, other); if (n1 && n2) { return n1 === n2 && alternativesAreEqual(x, other); } } return false; } case "Character": { const other = y as Character; return x.value === other.value; } case "CharacterClass": { const other = y as CharacterClass; return x.negate === other.negate && manyAreEqual(x.elements, other.elements); } case "CharacterClassRange": { const other = y as CharacterClassRange; return areEqual(x.min, other.min) && areEqual(x.max, other.max); } case "CharacterSet": { const other = y as CharacterSet; if (x.kind === "property" && other.kind === "property") { return x.negate === other.negate && x.key === other.key; } else { return x.raw === other.raw; } } case "Flags": { const other = y as Flags; return ( x.dotAll === other.dotAll && x.global === other.global && x.ignoreCase === other.ignoreCase && x.multiline === other.multiline && x.sticky === other.sticky && x.unicode === other.unicode ); } case "Group": case "Pattern": { const other = y as Group; return alternativesAreEqual(x, other); } case "Quantifier": { const other = y as Quantifier; return ( x.min === other.min && x.max === other.max && x.greedy === other.greedy && areEqual(x.element, other.element) ); } case "RegExpLiteral": { const other = y as RegExpLiteral; return areEqual(x.flags, other.flags) && areEqual(x.pattern, other.pattern); } default: throw assertNever(x); } } export function getCapturingGroupNumber(pattern: Pattern, group: CapturingGroup): number | null { let found = 0; try { visitRegExpAST(pattern, { onCapturingGroupEnter(node) { found++; if (node === group) { // throw an error to end early throw new Error(); } }, }); return null; } catch (error) { return found; } } export function getPattern(node: Node): Pattern | null { switch (node.type) { case "Pattern": return node; case "RegExpLiteral": return node.pattern; case "Flags": return node.parent ? node.parent.pattern : null; default: return getPattern(node.parent); } } /** * Returns the minimal hexadecimal escape sequence of a given code point. * * This will use one of the following formats: `\xFF`, `\uFFFF`, or `\u{10FFFF}`. */ export function minimalHexEscape(codePoint: number): string { if (codePoint <= 0xff) { return "\\x" + codePoint.toString(16).padStart(2, "0"); } else if (codePoint <= 0xffff) { return "\\u" + codePoint.toString(16).padStart(4, "0"); } else { return "\\u{" + codePoint.toString(16) + "}"; } } /** * Returns whether the given character is written as an octal escape sequence (e.g. `\0`, `\12`). */ export function isOctalEscapeSequence(node: Character): boolean { return /^\\[0-7]+$/.test(node.raw); } /** * Returns whether the given character is written as a control escape sequence (e.g. `\cI`). */ export function isControlEscapeSequence(node: Character): boolean { return /^\\c[A-Za-z]$/.test(node.raw); } /** * Returns whether the given character is written as a hexadecimal escape sequence (e.g. `\xFF` `\u00FFF` `\u{FF}`). */ export function isHexadecimalEscapeSequence(node: Character): boolean { return /^\\(?:x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]+\})$/.test(node.raw); } /** * Returns whether the given node is a escape sequence. * * This includes octal escapes (e.g. `\31`), hexadecimal escapes (e.g. `\xFF` `\u00FFF` `\u{FF}`), control character * escapes (e.g. `\cI`), and other escape sequences like `\n` and `\t`. * * This does not include the character-class-exclusive `\b` escape for backspace. * * This does not include literal escapes where the escaped character is equal to the character after the backslash * (e.g. `\G`, `\\`, `\?`) and character sequences. */ export function isEscapeSequence(node: Character): boolean { return ( isOctalEscapeSequence(node) || // octal isHexadecimalEscapeSequence(node) || // hexadecimal isControlEscapeSequence(node) || // control character /^\\[fnrtv]$/.test(node.raw) // form feed, new line, carrier return, tab, vertical tab ); } export function nodeAt(root: Node, index: number): Node | undefined { if (index < root.start || root.end >= index) { return undefined; } if (root.start == index) { return root; } switch (root.type) { case "Assertion": case "CapturingGroup": case "Group": case "Pattern": if (root.type === "Assertion" && !(root.kind === "lookahead" || root.kind === "lookbehind")) { break; } for (const alt of root.alternatives) { if (alt.end >= index) { break; } const result = nodeAt(alt, index); if (result) { return result; } } break; case "Quantifier": { const res = nodeAt(root.element, index); if (res) { return res; } break; } case "RegExpLiteral": { let res = nodeAt(root.flags, index); if (res) { return res; } res = nodeAt(root.pattern, index); if (res) { return res; } break; } default: break; } return root; } export interface Quant { min: number; max: number; greedy?: boolean; } /** * Returns the string representation of the given quantifier. */ export function quantToString(quant: Readonly<Quant>): string { if ( quant.max < quant.min || quant.min < 0 || !Number.isInteger(quant.min) || !(Number.isInteger(quant.max) || quant.max === Infinity) ) { throw new Error(`Invalid quantifier { min: ${quant.min}, max: ${quant.max} }`); } let value; if (quant.min === 0 && quant.max === 1) { value = "?"; } else if (quant.min === 0 && quant.max === Infinity) { value = "*"; } else if (quant.min === 1 && quant.max === Infinity) { value = "+"; } else if (quant.min === quant.max) { value = `{${quant.min}}`; } else if (quant.max === Infinity) { value = `{${quant.min},}`; } else { value = `{${quant.min},${quant.max}}`; } if (!quant.greedy) { return value + "?"; } else { return value; } } export function quantAdd(quant: Readonly<Quant>, other: number | Readonly<Quant>): Quant { if (typeof other === "number") { return { min: quant.min + other, max: quant.max + other, greedy: quant.greedy, }; } else { if (quant.greedy === other.greedy || quant.greedy === undefined || other.greedy === undefined) { return { min: quant.min + other.min, max: quant.max + other.max, greedy: quant.greedy ?? other.greedy, }; } else { throw Error("The `greedy` property of the given quants is not compatible."); } } } /** * Returns the raw string of the negated character set. * * I.e. for a given `\S` is will return `"\s"`. * * This __does not__ support the dot character set. */ export function negateCharacterSetRaw(charSet: Readonly<EscapeCharacterSet | UnicodePropertyCharacterSet>): string { let type = charSet.raw[1]; if (type.toLowerCase() === type) { type = type.toUpperCase(); } else { type = type.toLowerCase(); } return `\\${type}${charSet.raw.substr(2)}`; } /** * Returns the string representation of the given character class elements in a character class. */ export function elementsToCharacterClass(elements: Readonly<Simple<CharacterClassElement>>[], negate = false): string { // This won't do any optimization. // Its ONLY job is to generate a valid character class from the given elements. // Optimizations can be done by the optimize-character-class rule. let result = ""; elements.forEach((e, i) => { switch (e.type) { case "Character": if (e.raw === "-") { if (i === 0 || i === elements.length - 1) { result += "-"; } else { result += "\\-"; } } else if (e.raw === "^") { if (i === 0) { result += "\\^"; } else { result += "^"; } } else if (e.raw === "]") { result += "\\]"; } else { result += e.raw; } break; case "CharacterClassRange": if (e.min.raw === "^" && i === 0) { result += "\\^-" + e.max.raw; } else { result += e.min.raw + "-" + e.max.raw; } break; case "CharacterSet": result += e.raw; break; default: throw assertNever(e); } }); return "[" + (negate ? "^" : "") + result + "]"; } /** * Returns whether the given backreference will always be replaced with the empty string. */ export function isEmptyBackreference(backreference: Backreference): boolean { const group = backreference.resolved; if (hasSomeAncestor(backreference, a => a === group)) { // if the backreference is element of the referenced group return true; } if (isZeroLength(group)) { // If the referenced group can only match doesn't consume characters, then it can only capture the empty // string. return true; } // Now for the hard part: // If there exists a path through the regular expression which connect the group and the backreference, then // the backreference can capture the group iff we only move up, down, or right relative to the group. function findBackreference(node: Element): boolean { const parent = node.parent; switch (parent.type) { case "Alternative": { // if any elements right to the given node contain or are the backreference, we found it. const index = parent.elements.indexOf(node); // we have to take the current matching direction into account let next; if (matchingDirection(node) === "ltr") { // the next elements to match will be right to the given node next = parent.elements.slice(index + 1); } else { // the next elements to match will be left to the given node next = parent.elements.slice(0, index); } if (next.some(e => hasSomeDescendant(e, d => d === backreference))) { return true; } // no luck. let's go up! const parentParent = parent.parent; if (parentParent.type === "Pattern") { // can't go up. return false; } else { return findBackreference(parentParent); } } case "Quantifier": return findBackreference(parent); default: throw new Error("What happened?"); } } return !findBackreference(group); } /** * Returns whether the given backreference is always matched __after__ the referenced group was matched. * * If there exists any accepting path which goes through the backreference but not through the referenced group, * this will return `false`. */ export function backreferenceAlwaysAfterGroup(backreference: Backreference): boolean { const group = backreference.resolved; if (hasSomeAncestor(backreference, a => a === group)) { // if the backreference is element of the referenced group return false; } function findBackreference(node: Element): boolean { const parent = node.parent; switch (parent.type) { case "Alternative": { // if any elements right to the given node contain or are the backreference, we found it. const index = parent.elements.indexOf(node); // we have to take the current matching direction into account let next; if (matchingDirection(node) === "ltr") { // the next elements to match will be right to the given node next = parent.elements.slice(index + 1); } else { // the next elements to match will be left to the given node next = parent.elements.slice(0, index); } if (next.some(e => hasSomeDescendant(e, d => d === backreference))) { return true; } // no luck. let's go up! const parentParent = parent.parent; if (parentParent.type === "Pattern") { // can't go up. return false; } else { if (parentParent.alternatives.length > 1) { // e.g.: (?:a|(a))+b\1 return false; } return findBackreference(parentParent); } } case "Quantifier": if (parent.min === 0) { // e.g.: (a+)?b\1 return false; } return findBackreference(parent); default: throw new Error("What happened?"); } } return findBackreference(group); } /** * Returns the raw string of the quantifier without the quantified element. * * E.g. for `a+?`, `+?` will be returned. */ export function getQuantifierRaw(quantifier: Quantifier): string { return quantifier.raw.substr(quantifier.element.end - quantifier.start); } export type MatchingDirection = "ltr" | "rtl"; /** * Returns the direction which which the given node will be matched relative to the closest parent alternative. */ export function matchingDirection(node: Node): MatchingDirection { let closestLookaround: LookaroundAssertion | undefined; hasSomeAncestor(node, a => { if (a.type === "Assertion") { closestLookaround = a; return true; } return false; }); if (closestLookaround !== undefined && closestLookaround.kind === "lookbehind") { // the matching direction in a lookbehind is right to left return "rtl"; } // the standard matching direction is left to right return "ltr"; } /** * `lookahead` is here equivalent to `ltr` and `lookbehind` is equivalent to `rtl`. */ export function invertMatchingDirection(direction: LookaroundAssertion["kind"] | MatchingDirection): MatchingDirection { return direction === "ltr" || direction === "lookahead" ? "rtl" : "ltr"; } export function assertionKindToMatchingDirection( kind: LookaroundAssertion["kind"] | EdgeAssertion["kind"] ): MatchingDirection { return kind === "end" || kind === "lookahead" ? "ltr" : "rtl"; } /** * Returns whether the given element contains or is an assertion that looks into the given direction. * * `lookahead` is here equivalent to `ltr` and `lookbehind` is equivalent to `rtl`. */ export function hasAssertionWithDirection( element: Element, direction: LookaroundAssertion["kind"] | MatchingDirection ): boolean { return hasSomeDescendant(element, d => { if (d.type === "Assertion") { if (d.kind === "word") { // word is both a lookahead and a lookbehind return true; } if (isPotentiallyEmpty(element)) { // we can generally completely ignore empty lookarounds, they are just dead code return false; } if (direction === "lookahead" || direction === "ltr") { return d.kind === "lookahead" || d.kind === "end"; } else { return d.kind === "lookbehind" || d.kind === "start"; } } return false; }); } /** * Returns how many characters the given element can consume at most and has to consume at least. * * If `undefined`, then the given element can't consume any characters. */ export function getLengthRange( element: Element | Alternative | Alternative[] ): { min: number; max: number } | undefined { if (Array.isArray(element)) { let min = Infinity; let max = 0; for (const e of element) { const eRange = getLengthRange(e); if (eRange) { min = Math.min(min, eRange.min); max = Math.max(max, eRange.max); } } if (min > max) { return undefined; } else { return { min, max }; } } switch (element.type) { case "Assertion": return { min: 0, max: 0 }; case "Character": case "CharacterClass": case "CharacterSet": return { min: 1, max: 1 }; case "Quantifier": { if (element.max === 0) { return { min: 0, max: 0 }; } const elementRange = getLengthRange(element.element); if (!elementRange) { return element.min === 0 ? { min: 0, max: 0 } : undefined; } if (elementRange.max === 0) { return { min: 0, max: 0 }; } elementRange.min *= element.min; elementRange.max *= element.max; return elementRange; } case "Alternative": { let min = 0; let max = 0; for (const e of element.elements) { const eRange = getLengthRange(e); if (!eRange) { return undefined; } min += eRange.min; max += eRange.max; } return { min, max }; } case "CapturingGroup": case "Group": return getLengthRange(element.alternatives); case "Backreference": { if (isEmptyBackreference(element)) { return { min: 0, max: 0 }; } const resolvedRange = getLengthRange(element.resolved); if (!resolvedRange) { return backreferenceAlwaysAfterGroup(element) ? undefined : { min: 0, max: 0 }; } if (resolvedRange.min > 0 && !backreferenceAlwaysAfterGroup(element)) { resolvedRange.min = 0; } return resolvedRange; } default: throw assertNever(element); } } export interface FirstLookChar { /** * A super set of the first character. * * We can usually only guarantee a super set because lookaround in the pattern may narrow down the actual character * set. */ char: CharSet; /** * If `true`, then the first character can be the start/end of the string. */ edge: boolean; /** * If `true`, then `char` is guaranteed to be exactly the first character and not just a super set of it. */ exact: boolean; } export type FirstConsumedChar = FirstFullyConsumedChar | FirstPartiallyConsumedChar; /** * This is equivalent to a regex fragment `[char]`. */ export interface FirstFullyConsumedChar { /** * A super set of the first character. * * We can usually only guarantee a super set because lookaround in the pattern may narrow down the actual character * set. */ char: CharSet; /** * If `true`, then the first character also includes the empty word. */ empty: false; /** * If `true`, then `char` is guaranteed to be exactly the first character and not just a super set of it. */ exact: boolean; } /** * This is equivalent to a regex fragment `[char]|(?=[look.char])` or `[char]|(?=[look.char]|$)` depending on * `look.edge`. */ export interface FirstPartiallyConsumedChar { /** * A super set of the first character. * * We can usually only guarantee a super set because lookaround in the pattern may narrow down the actual character * set. */ char: CharSet; /** * If `true`, then the first character also includes the empty word. */ empty: true; /** * If `true`, then `char` is guaranteed to be exactly the first character and not just a super set of it. */ exact: boolean; /** * A set of characters that may come after the consumed character */ look: FirstLookChar; } /** * If a character is returned, it guaranteed to be a super set of the actual character. If the given element is * always of zero length, then the empty character set will be returned. * * If `exact` is `true` then it is guaranteed that the returned character is guaranteed to be the actual * character at all times if this element is not influenced by lookarounds outside itself. */ export function getFirstCharConsumedBy( element: Element | Alternative | Alternative[], direction: MatchingDirection, flags: Flags ): FirstConsumedChar { if (Array.isArray(element)) { return firstConsumedCharUnion( element.map(e => getFirstCharConsumedBy(e, direction, flags)), flags ); } switch (element.type) { case "Assertion": switch (element.kind) { case "word": return misdirectedAssertion(); case "end": case "start": if (assertionKindToMatchingDirection(element.kind) === direction) { if (flags.multiline) { return lineAssertion(); } else { return edgeAssertion(); } } else { return misdirectedAssertion(); } case "lookahead": case "lookbehind": if (assertionKindToMatchingDirection(element.kind) === direction) { if (element.negate) { // we can only meaningfully analyse negative lookarounds of the form `(?![a])` if (hasSomeDescendant(element, d => d !== element && d.type === "Assertion")) { return misdirectedAssertion(); } const firstChar = getFirstCharConsumedBy(element.alternatives, direction, flags); const range = getLengthRange(element.alternatives); if (firstChar.empty || !range) { // trivially rejecting return { char: emptyCharSet(flags), empty: false, exact: true }; } if (!firstChar.exact || range.max !== 1) { // the goal to to convert `(?![a])` to `(?=[^a]|$)` but this negation is only correct // if the characters are exact and if the assertion asserts at most one character // E.g. `(?![a][b])` == `(?=$|[^a]|[a][^b])` return misdirectedAssertion(); } else { return emptyWord({ char: firstChar.char.negate(), edge: true, exact: true }); } } else { const firstChar = getFirstCharConsumedBy(element.alternatives, direction, flags); return emptyWord(firstConsumedToLook(firstChar)); } } else { return misdirectedAssertion(); } default: throw assertNever(element); } case "Character": case "CharacterSet": case "CharacterClass": return { char: toCharSet(element, flags), empty: false, exact: true }; case "Quantifier": { if (element.max === 0) { return emptyWord(); } const firstChar = getFirstCharConsumedBy(element.element, direction, flags); if (element.min === 0) { return firstConsumedCharUnion([emptyWord(), firstChar], flags); } else { return firstChar; } } case "Alternative": { let elements = element.elements; if (direction === "rtl") { elements = [...elements]; elements.reverse(); } return firstConsumedCharConcat( (function* (): Iterable<FirstConsumedChar> { for (const e of elements) { yield getFirstCharConsumedBy(e, direction, flags); } })(), flags ); } case "CapturingGroup": case "Group": return getFirstCharConsumedBy(element.alternatives, direction, flags); case "Backreference": { if (isEmptyBackreference(element)) { return emptyWord(); } const resolvedChar = getFirstCharConsumedBy(element.resolved, direction, flags); // the resolved character is only exact if it is only a single character. // i.e. /(\w)\1/ here the (\w) will capture exactly any word character, but the \1 can only match // one word character and that is the only (\w) matched. resolvedChar.exact = resolvedChar.exact && resolvedChar.char.size <= 1; if (backreferenceAlwaysAfterGroup(element)) { return resolvedChar; } else { // there is at least one path through which the backreference will (possibly) be replaced with the // empty string return firstConsumedCharUnion([resolvedChar, emptyWord()], flags); } } default: throw assertNever(element); } /** * The result for an assertion that (partly) assert for the wrong matching direction. */ function misdirectedAssertion(): FirstPartiallyConsumedChar { return emptyWord({ char: allCharSet(flags), edge: true, // This is the important part. // Since the allowed chars depend on the previous chars, we don't know which will be allowed. exact: false, }); } function edgeAssertion(): FirstPartiallyConsumedChar { return emptyWord(firstLookCharEdgeAccepting(flags)); } function lineAssertion(): FirstPartiallyConsumedChar { return emptyWord({ char: lineTerminatorCharSet(flags), edge: true, exact: true, }); } function emptyWord(look?: FirstLookChar): FirstPartiallyConsumedChar { return firstConsumedCharEmptyWord(flags, look); } } /** * Returns first-look-char that is equivalent to a trivially-accepting lookaround. */ function firstLookCharTriviallyAccepting(flags: Flags): FirstLookChar { return { char: allCharSet(flags), edge: true, exact: true }; } /** * Returns first-look-char that is equivalent to `/$/`. */ function firstLookCharEdgeAccepting(flags: Flags): FirstLookChar { return { char: emptyCharSet(flags), edge: true, exact: true }; } /** * Returns first-consumed-char that is equivalent to consuming nothing (the empty word) followed by a trivially * accepting lookaround. */ function firstConsumedCharEmptyWord(flags: Flags, look?: FirstLookChar): FirstPartiallyConsumedChar { return { char: emptyCharSet(flags), empty: true, exact: true, look: look ?? firstLookCharTriviallyAccepting(flags), }; } class CharUnion { char: CharSet; exact: boolean; private constructor(char: CharSet) { this.char = char; this.exact = true; } add(char: CharSet, exact: boolean): void { // basic idea here is that the union or an exact superset with an inexact subset will be exact if (this.exact && !exact && !this.char.isSupersetOf(char)) { this.exact = false; } else if (!this.exact && exact && char.isSupersetOf(this.char)) { this.exact = true; } this.char = this.char.union(char); } static emptyFromFlags(flags: Flags): CharUnion { return new CharUnion(emptyCharSet(flags)); } static emptyFromMaximum(maximum: number): CharUnion { return new CharUnion(CharSet.empty(maximum)); } } function firstConsumedCharUnion(iter: Iterable<Readonly<FirstConsumedChar>>, flags: Flags): FirstConsumedChar { const union = CharUnion.emptyFromFlags(flags); const looks: FirstLookChar[] = []; for (const itemChar of iter) { union.add(itemChar.char, itemChar.exact); if (itemChar.empty) { looks.push(itemChar.look); } } if (looks.length > 0) { // This means that the unioned elements look something like this: // (a|(?=g)|b?|x) // // Adding the trivially accepting look after all all alternatives that can be empty, we'll get: // (a|(?=g)|b?|x) // (a|(?=g)|b?(?=[^]|$)|x) // (a|(?=g)|b(?=[^]|$)|(?=[^]|$)|x) // // Since we are only interested in the first character, the look in `b(?=[^]|$)` can be removed. // (a|(?=g)|b|(?=[^]|$)|x) // (a|b|x|(?=g)|(?=[^]|$)) // ([abx]|(?=g)|(?=[^]|$)) // // To union the looks, we can simply use the fact that `(?=a)|(?=b)` == `(?=a|b)` // ([abx]|(?=g)|(?=[^]|$)) // ([abx]|(?=g|[^]|$)) // ([abx]|(?=[^]|$)) // // And with that we are done. This is exactly the form of a first partial char. Getting the exactness of the // union of normal chars and look chars follows the same rules. const lookUnion = CharUnion.emptyFromFlags(flags); let edge = false; for (const look of looks) { lookUnion.add(look.char, look.exact); edge = edge || look.edge; } return { char: union.char, exact: union.exact, empty: true, look: { char: lookUnion.char, exact: lookUnion.exact, edge }, }; } else { return { char: union.char, exact: union.exact, empty: false }; } } function firstConsumedCharConcat(iter: Iterable<Readonly<FirstConsumedChar>>, flags: Flags): FirstConsumedChar { const union = CharUnion.emptyFromFlags(flags); let look = firstLookCharTriviallyAccepting(flags); for (const item of iter) { union.add(item.char.intersect(look.char), look.exact && item.exact); if (item.empty) { // This is the hard case. We need to convert the expression // (a|(?=b))(c|(?=d)) // into an expression // e|(?=f) // (we will completely ignore edge assertions for now) // // To do that, we'll use the following idea: // (a|(?=b))(c|(?=d)) // a(c|(?=d))|(?=b)(c|(?=d)) // ac|a(?=d)|(?=b)c|(?=b)(?=d) // // Since we are only interested in the first char, we can remove the `c` in `ac` and the `(?=d)` in // `a(?=d)`. Furthermore, `(?=b)c` is a single char, so let's call it `C` for now. // ac|a(?=d)|(?=b)c|(?=b)(?=d) // a|a|C|(?=b)(?=d) // [aC]|(?=b)(?=d) // [aC]|(?=(?=b)d) // // This is *almost* the desired form. We now have to convert `(?=(?=b)d)` to an expression of the form // `(?=f)`. This is the point where we can't ignore edge assertions any longer. Let's look at all possible // cases and see how it plays out. Also, let `D` be the char intersection of `b` and `d`. // (1) (?=(?=b)d) // (?=D) // // (2) (?=(?=b)(d|$)) // (?=(?=b)d|(?=b)$) // (?=D) // // (3) (?=(?=b|$)d) // (?=((?=b)|$)d) // (?=(?=b)d|$d) // (?=D) // // (4) (?=(?=b|$)(d|$)) // (?=((?=b)|$)(d|$)) // (?=(?=b)(d|$)|$(d|$)) // (?=(?=b)d|(?=b)$|$d|$$) // (?=D|$) // // As we can see, the look char is always `D` and the edge is only accepted if it's accepted by both. const charIntersection = look.char.intersect(item.look.char); look = { char: charIntersection, exact: (look.exact && item.look.exact) || charIntersection.isEmpty, edge: look.edge && item.look.edge, }; } else { return { char: union.char, exact: union.exact, empty: false }; } } return { char: union.char, exact: union.exact, empty: true, look }; } /** * This wraps the first-consumed-char object in a look. */ function firstConsumedToLook(first: Readonly<FirstConsumedChar>): FirstLookChar { if (first.empty) { // We have 2 cases: // (1) (?=a|(?=b)) // (?=a|b) // (?=[ab]) // (2) (?=a|(?=b|$)) // (?=a|b|$) // (?=[ab]|$) const union = CharUnion.emptyFromMaximum(first.char.maximum); union.add(first.char, first.exact); union.add(first.look.char, first.look.exact); return { char: union.char, exact: union.exact, edge: first.look.edge, }; } else { // It's already in the correct form: // (?=a) return { char: first.char, exact: first.exact, edge: false, }; } } export interface FollowOperations<S> { /** * Split off a new path from the given one. * * The given state should not be modified. If the state is immutable, then `fork` may be implemented as the identify * function in regard to `state`. */ fork(state: S, direction: MatchingDirection): S; /** * Joins any number but of paths to create a combined path. */ join(states: S[], direction: MatchingDirection): S; /** * This function is called when dealing to general lookarounds (it will __not__ be called for predefined assertion - * `^`, `$`, `\b`, `\B`). */ assert?: (state: S, direction: MatchingDirection, assertion: S, assertionDirection: MatchingDirection) => S; enter?: (element: Element, state: S, direction: MatchingDirection) => S; leave?: (element: Element, state: S, direction: MatchingDirection) => S; endPath?: (state: S, direction: MatchingDirection, reason: "pattern" | "assertion") => S; /** * Whether the current path should go into the given element (return `true`) or whether it should be skipped * (return `false`). If the element is skipped, the given state will not be changed and passed as-is to the `leave` * function. * * You shouldn't modify state in this function. Modify state in the `enter` function instead. */ continueInto?: (element: Element, state: S, direction: MatchingDirection) => boolean; /** * Whether the current path should continue after the given element (return `true`) or whether all elements that * follow this element should be skipped (return `false`). * * If the current path is a fork path, then only the elements until the fork is joined will be skipped. A stopped * fork path will be joined with all other forks like normal. * * You shouldn't modify state in this function. Modify state in the `leave` function instead. */ continueAfter?: (element: Element, state: S, direction: MatchingDirection) => boolean; } /** * This function goes to all elements reachable from the given `start`. * * ## Paths * * The function uses _paths_ for this. A path is an [execution path](https://en.wikipedia.org/wiki/Symbolic_execution) * that is described by a sequence of regex elements. * * I.e. there are two paths to go from `a` to `b` in the pattern `/a(\w|dd)b/`. The first path is `a \w b` and the * second path is `a d d b`. * * However, the problem with paths is that there can be exponentially many because of combinatorial explosion (e.g. the * pattern `/(a|b)(a|b)(a|b)(a|b)(a|b)/` has 32 paths). To solve this problem, this function will _join_ paths together * again. * * I.e. In the pattern `/a(\w|dd)b/`, first element of all paths will be `a`. After `a`, the path splits into two. We * call each of the split paths a _fork_. The two forks will be `a ( \w` and `a ( d d`. The `(` is used to indicate that * a fork was made. Since both paths come together after the group ends, they will be _joined_. The joined path of * `a ( \w` and `a ( d d` will be written as `a ( \w | d d )`. The `)` is used to indicate that forks have been joined. * The final path will be `a ( \w | d d ) b`. * * This method of forking and joining works for alternations but it won't work for quantifiers. This is why quantifiers * will be treated as single elements that can be entered. By default, a quantifier `q` will be interpreted as `( q | )` * if its minimum is zero and as `( q )` otherwise. * * ### State * * Paths are thought of as a sequence of elements and they are represented by state (type parameter `S`). All operations * that fork, join, or assert paths will operate on state and not a sequence of elements. * * State allows flow operations to be implemented more efficiently and ensures that only necessary data is passed * around. Flow analysis for paths usually tracks properties and analyses how these properties change, the current * values of these properties is state. * * ## Flow operations * * Flow operations are specific to the type of the state and act upon the state. The define how the state of paths * changes when encountering elements and how paths fork, join, and continue. * * ### Operation sequence * * To follow all paths, two operations are necessary: one operations that enters elements and one that determines the * next element. These operations will be called `Enter` and `Next` respectively. The operation will call the given * flow operations like this: * * ```txt * function Enter(element, state): * operations.enter * if operations.continueInto: * if elementType == GROUP: * operations.join( * alternatives.map(e => Enter(e, operations.fork(state))) * ) * if elementType == QUANTIFIER: * if quantifierMin == 0: * operations.join([ * state, * Enter(quantifier, operations.fork(state)) * ]) * if elementType == LOOKAROUND: * operations.assert( * state, * operations.join( * alternatives.map(e => Enter(e, operations.fork(state))) * ) * ) * operations.leave * Next(element, state) * * function Next(element, state): * if operations.continueAfter: * if noNextElement: * operations.endPath * else: * Enter(nextElement, state) * ``` * * (This is just simplified pseudo code but the general order of operations will be the same.) * * ## Runtime * * If `n` elements can be reached from the given starting element, then the average runtime will be `O(n)` and the * worst-case runtime will be `O(n^2)`. * * @param start * @param startMode If "enter", then the first element to be entered will be the starting element. If "leave", then the * first element to continue after will be the starting element. * @param initialState * @param operations * @param direction */ export function followPaths<S>( start: Element, startMode: "enter" | "next", initialState: NonNullable<S>, operations: FollowOperations<NonNullable<S>>, direction?: MatchingDirection ): NonNullable<S> { function opEnter(element: Element, state: NonNullable<S>, direction: MatchingDirection): NonNullable<S> { state = operations.enter?.(element, state, direction) ?? state; const continueInto = operations.continueInto?.(element, state, direction) ?? true; if (continueInto) { switch (element.type) { case "Assertion": { if (element.kind === "lookahead" || element.kind === "lookbehind") { const assertionDirection = assertionKindToMatchingDirection(element.kind); const assertion = operations.join( element.alternatives.map(a => enterAlternative(a, operations.fork(state, direction), assertionDirection) ), assertionDirection ); state = operations.endPath?.(state, assertionDirection, "assertion") ?? state; state = operations.assert?.(state, direction, assertion, assertionDirection) ?? state; } break; } case "Group": case "CapturingGroup": { state = operations.join( element.alternatives.map(a => enterAlternative(a, operations.fork(state, direction), direction) ), direction ); break; } case "Quantifier": { if (element.max === 0) { // do nothing } else if (element.min === 0) { state = operations.join( [state, opEnter(element.element, operations.fork(state, direction), direction)], direction ); } else { state = opEnter(element.element, state, direction); } break; } } } state = operations.leave?.(element, state, direction) ?? state; return state; } function enterAlternative( alternative: Alternative, state: NonNullable<S>, direction: MatchingDirection ): NonNullable<S> { let i = direction === "ltr" ? 0 : alternative.elements.length - 1; const increment = direction === "ltr" ? +1 : -1; let element: Element | undefined; for (; (element = alternative.elements[i]); i += increment) { state = opEnter(element, state, direction); const continueAfter = operations.continueAfter?.(element, state, direction) ?? true; if (!continueAfter) { break; } } return state; } function opNext(element: Element, state: NonNullable<S>, direction: MatchingDirection): NonNullable<S> { type NextElement = false | Element | "pattern" | "assertion" | [Quantifier, NextElement]; function getNextElement(element: Element): NextElement { const parent = element.parent; if (parent.type === "CharacterClass" || parent.type === "CharacterClassRange") { throw new Error("The given element cannot be part of a character class."); } const continuePath = operations.continueAfter?.(element, state, direction) ?? true; if (!continuePath) { return false; } if (parent.type === "Quantifier") { // This is difficult. // The main problem is that paths coming out of the quantifier might loop back into itself. This means that // we have to consider the path that leaves the quantifier and the path that goes back into the quantifier. if (parent.max <= 1) { // Can't loop, so we only have to consider the path going out of the quantifier. return getNextElement(parent); } else { return [parent, getNextElement(parent)]; } } else { const nextIndex = parent.elements.indexOf(element) + (direction === "ltr" ? +1 : -1); const nextElement: Element | undefined = parent.elements[nextIndex]; if (nextElement) { return nextElement; } else { const parentParent = parent.parent; if (parentParent.type === "Pattern") { return "pattern"; } else if (parentParent.type === "Assertion") { return "assertion"; } else if (parentParent.type === "CapturingGroup" || parentParent.type === "Group") { return getNextElement(parentParent); } throw assertNever(parentParent); } } } // eslint-disable-next-line no-constant-condition while (true) { let after = getNextElement(element); while (Array.isArray(after)) { const [quant, other] = after; state = operations.join( [state, opEnter(quant, operations.fork(state, direction), direction)], direction ); after = other; } if (after === false) { return state; } else if (after === "assertion" || after === "pattern") { state = operations.endPath?.(state, direction, after) ?? state; return state; } else { state = opEnter(after, state, direction); element = after; } } } if (!direction) { direction = matchingDirection(start); } if (startMode === "enter") { initialState = opEnter(start, initialState, direction); } return opNext(start, initialState, direction); } export interface FirstConsumedCharAfter { char: FirstConsumedChar; elements: Element[]; } export function getFirstConsumedCharAfter( afterThis: Element, direction: MatchingDirection, flags: Flags ): FirstConsumedCharAfter { type State = Readonly<FirstConsumedCharAfter>; const result = followPaths<State>( afterThis, "next", { char: firstConsumedCharEmptyWord(flags), elements: [] }, { fork(state): State { return state; }, join(states): State { const elements = new Set<Element>(); states.forEach(s => s.elements.forEach(e => elements.add(e))); return { char: firstConsumedCharUnion( states.map(s => s.char), flags ), elements: [...elements], }; }, enter(element, state, direction): State { const first = getFirstCharConsumedBy(element, direction, flags); return { char: firstConsumedCharConcat([state.char, first], flags), elements: [...state.elements, element], }; }, continueInto(): boolean { return false; }, continueAfter(_, state): boolean { return state.char.empty; }, }, direction ); return { char: result.char, elements: result.elements }; } export interface FirstCharAfter { /** * The first character after the given element. */ char: FirstLookChar; /** * A list of elements that all contributed to the result. All sub-elements of the listed elements also contribute. */ elements: Element[]; } /** * Returns the first character after the given element. * * What "after" means depends the on the given direction which will be interpreted as the current matching * direction. You can use this to get the previous character of an element as well. */ export function getFirstCharAfter(afterThis: Element, direction: MatchingDirection, flags: Flags): FirstCharAfter { const result = getFirstConsumedCharAfter(afterThis, direction, flags); return { char: firstConsumedToLook(result.char), elements: [...result.elements] }; } export interface SingleConsumedChar { char: CharSet; exact: boolean; empty: boolean; } /** * If the given element can, via some path, consume only a single character, this character will be returned. If the * element always consume zero or more than one character, an empty character set will be returned. * * If the element, via some path, can consume zero characters, it will be returned as `empty: true`. * * @param element * @param ignoreAssertions * @param flags */ export function getSingleConsumedChar( element: Element | Alternative | Alternative[], ignoreAssertions: boolean, flags: Flags ): SingleConsumedChar { if (Array.isArray(element)) { let empty = false; const union = CharUnion.emptyFromFlags(flags); for (const a of element) { const single = getSingleConsumedChar(a, ignoreAssertions, flags); empty = empty || single.empty; union.add(single.char, single.exact); } return { char: union.char, exact: union.exact, empty }; } function multipleChars(): SingleConsumedChar { return { char: emptyCharSet(flags), exact: true, empty: false }; } function zeroChars(): SingleConsumedChar { return { char: emptyCharSet(flags), exact: true, empty: true }; } switch (element.type) { case "Alternative": { // e.g. /a?b?c?/ => /[abc]?/, /a?bc?/ => /[b]/, /abc?/ => /[]/ let nonEmptyResult: SingleConsumedChar | undefined = undefined; const emptyUnion = CharUnion.emptyFromFlags(flags); for (const e of element.elements) { const single = getSingleConsumedChar(e, ignoreAssertions, flags); if (nonEmptyResult === undefined) { if (single.empty) { emptyUnion.add(single.char, single.exact); } else { nonEmptyResult = single; } } else { if (single.empty) { // ignore } else { return multipleChars(); } } } if (nonEmptyResult) { return nonEmptyResult; } else { return { char: emptyUnion.char, exact: emptyUnion.exact, empty: true }; } } case "Assertion": { return { char: emptyCharSet(flags), exact: false, empty: ignoreAssertions }; } case "Character": case "CharacterClass": case "CharacterSet": { return { char: toCharSet(element, flags), exact: true, empty: false }; } case "CapturingGroup": case "Group": { return getSingleConsumedChar(element.alternatives, ignoreAssertions, flags); } case "Backreference": { if (isEmptyBackreference(element)) { return zeroChars(); } const resolvedSingle = getSingleConsumedChar(element.resolved, ignoreAssertions, flags); // the resolved character is only exact if it is only a single character. // i.e. /(\w)\1/ here the (\w) will capture exactly any word character, but the \1 can only match // one word character and that is the only (\w) matched. resolvedSingle.exact = resolvedSingle.exact && resolvedSingle.char.size <= 1; // there is at least one path through which the backreference will (possibly) be replaced with the // empty string resolvedSingle.empty = resolvedSingle.empty || !backreferenceAlwaysAfterGroup(element); return resolvedSingle; } case "Quantifier": { if (element.max === 0) { return zeroChars(); } const single = getSingleConsumedChar(element.element, ignoreAssertions, flags); if (!single.empty) { if (element.min === 0) { single.empty = true; } else if (element.min >= 2) { // we will always consume at least 2 chars, so there is no *single* consumed char return multipleChars(); } } return single; } default: throw assertNever(element); } } /** * Returns how many times the regex engine may match the given node against a string. */ export function effectiveQuantifierMax(node: Node | null): number { if (node == null) { return 1; } else { const parent = effectiveQuantifierMax(node.parent); if (node.type === "Quantifier") { if (node.max === 0 || parent === 0) { return 0; } else { return parent * node.max; } } else { return parent; } } } /** * Returns whether the given node either is or is under an effectively star quantifier. * * All quantifiers with a max larger than a certain threshold are assumed to have a max of infinity. */ export function underAStar(node: Node): boolean { return effectiveQuantifierMax(node) > 20; } /** * Returns the content prefix and suffix of the given parent node. */ export function getParentPrefixAndSuffix( parent: Pattern | CapturingGroup | Group | LookaroundAssertion ): [string, string] { switch (parent.type) { case "Assertion": return ["(?" + (parent.kind === "lookahead" ? "" : "<") + (parent.negate ? "!" : "="), ")"]; case "CapturingGroup": if (parent.name !== null) { return ["(?<" + parent.name + ">", ")"]; } else { return ["(", ")"]; } case "Group": return ["(?:", ")"]; case "Pattern": return ["", ""]; default: throw assertNever(parent); } }
the_stack
import { Duck } from '../..'; import degToRadians from '../../utils/degToRadians'; import clamp from './clamp'; /** * @class Vector2 * @classdesc Creates a Vector2 * @description The Vector2 Class. Represents a point * @since 2.0.0 */ export default class Vector2 { /** * @constructor Vector2 * @description Creates a Vector2 instance * @param {number} [x=0] X position, optional -> defaults: 0 * @param {number} [y=0] Y position, optional -> defaults: 0 * @since 2.0.0 */ constructor(public x = 0, public y = 0) {} /** * @memberof Vector2 * @description Sets the values of the Vector2 * @param {number} x X position to setValue of * @param {number} y Y position to setValue of * @returns Vector2 * @since 2.0.0 */ public setValues(x: number, y: number) { this.x = x; this.y = y; return this; } /** * @memberof Vector2 * @description Sets the values of the Vector2 based on another Vector2 * @param {number} vector Vector2 to use to set the position * @returns Vector2 * @since 2.0.0 */ public setValuesVec(vector: Vector2) { this.x = vector.x; this.y = vector.y; return this; } /** * @memberof Vector2 * @description Adds a Vector2 * @param {Vector2} vector Vector2 to be added to * @returns Vector2 * @since 2.0.0 */ public add(vector: Vector2) { this.x += vector.x; this.y += vector.y; return this; } /** * @memberof Vector2 * @description Adds a number to the x and y properties * @param {number} number Number to add to x and y properties * @returns Vector2 * @since 2.0.0 */ public addNumber(number: number) { this.x += number; this.y += number; return this; } /** * @memberof Vector2 * @description Subtracts a Vector2 * @param {Vector2} vector Vector2 to be subtracted to * @returns Vector2 * @since 2.0.0 */ public subtract(vector: Vector2) { this.x -= vector.x; this.y -= vector.y; return this; } /** * @memberof Vector2 * @description Subtracts a number from the x and y properties * @param {number} number Number to subtract from x and y properties * @returns Vector2 * @since 2.0.0 */ public subtractNumber(number: number) { this.x -= number; this.y -= number; return this; } /** * @memberof Vector2 * @description Multiplies a Vector2 * @param {Vector2} vector Vector2 to be multiplied to * @returns Vector2 * @since 2.0.0 */ public multiply(vector: Vector2) { this.x *= vector.x; this.y *= vector.y; return this; } /** * @memberof Vector2 * @description Multiplies a number to the x and y properties * @param {number} number Number to multiply to x and y properties * @returns Vector2 * @since 2.0.0 */ public multiplyNumber(number: number) { this.x *= number; this.y *= number; return this; } /** * @memberof Vector2 * @description Divides a Vector2 * @param {Vector2} vector Vector2 to be divided to * @returns Vector2 * @since 2.0.0 */ public divide(vector: Vector2) { this.x /= vector.x; this.y /= vector.y; return this; } /** * @memberof Vector2 * @description Divides a number to the x and y properties * @param {number} number Number to divide to x and y properties * @returns Vector2 * @since 2.0.0 */ public divideNumber(number: number) { this.x /= number; this.y /= number; return this; } /** * @memberof Vector2 * @description Rounds the Vector2 * @returns Vector2 * @since 2.0.0 */ public round() { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; } /** * @memberof Vector2 * @description Gets the angle between two Vector2s * @param {Vector2} vector A Vector2 to get the angle between from * @returns number * @since 2.0.0 */ public angleBetween(vector: Vector2) { return Math.atan2( this.x * vector.y - this.y * vector.x, this.x * vector.x + this.y * vector.y ); } /** * @memberof Vector2 * @description Gets the angle to two Vector2s * @param {Vector2} vector A Vector2 to get the angle to from * @returns number * @since 2.0.0 */ public angleTo(vector: Vector2) { return Math.atan2(vector.y - this.y, vector.x - this.x); } /** * @memberof Vector2 * @description Clones the current Vector2 * @returns Vector2 * @since 2.0.0 */ public clone() { return new Vector2(this.x, this.y); } /** * @memberof Vector2 * @description Gets the distance from another Vector2 * @param {Vector2} vector A Vector2 to get the distance from * @returns number * @since 2.0.0 */ public distance(vector: Vector2) { return Math.sqrt( (vector.x - this.x) * (vector.x - this.x) + (vector.y - this.y) * (vector.y - this.y) ); } /** * @memberof Vector2 * @description Gets the distance squared from another Vector2 * @param {Vector2} vector A Vector2 to get the distance from * @returns number * @since 2.0.0 */ public distanceSqr(vector: Vector2) { return ( (vector.x - this.x) * (vector.x - this.x) + (vector.y - this.y) * (vector.y - this.y) ); } /** * @memberof Vector2 * @description Gets the dot product with another Vector2 * @param {Vector2} vector A Vector2 to get the dot product from * @returns number * @since 2.0.0 */ public dot(vector: Vector2) { return this.x * vector.x + this.y * vector.y; } /** * @memberof Vector2 * @description Gets the cross dot product with another Vector2 * @param {Vector2} vector A Vector2 to get the cross dot product from * @returns number * @since 2.0.0 */ public crossProduct(vector: Vector2) { return this.x * vector.y - this.y * vector.x; } /** * @memberof Vector2 * @description Checks if another Vector2 is equal on both axises * @param {Vector2} vector A Vector2 to compare with * @returns boolean * @since 2.0.0 */ public equals(vector: Vector2) { return this.x === vector.x && this.y === vector.y; } /** * @memberof Vector2 * @description Gets the perpendicular values of the Vector2 * @param {Vector2} [resultVector] The new Vector2 to save the value to, optional -> defaults: new Vector2 * @returns Vector2 * @since 2.0.0 */ public perpendicular(resultVector?: Vector2) { resultVector = resultVector || new Vector2(); return resultVector.setValues(-this.y, this.x); } /** * @memberof Vector2 * @description Gradually interpolates the Vector2 towards another Vector2 by an amount * @param {Vector2} current The Current Vector * @param {Vector2} target The Target Vector2 * @param {number} maxDistanceDelta The amount to increase by * @returns Vector2 * @since 2.0.0 */ public moveTowards( current: Vector2, target: Vector2, maxDistanceDelta: number ) { const toVector_x = target.x - current.x; const toVector_y = target.y - current.y; const sqDist = toVector_x * toVector_x + toVector_y * toVector_y; if ( sqDist === 0 || (maxDistanceDelta >= 0 && sqDist <= maxDistanceDelta * maxDistanceDelta) ) { return target; } const dist = Math.sqrt(sqDist); const newX = current.x + (toVector_x / dist) * maxDistanceDelta; const newY = current.y + (toVector_y / dist) * maxDistanceDelta; return new Vector2(newX, newY); } /** * @memberof Vector2 * @description Normalizes the Vector2 * @returns Vector2 * @since 2.0.0 */ public normalize() { const mag = this.magnitude(); if (mag > 0) { this.divideNumber(mag); } return this; } /** * @memberof Vector2 * @description Gets the normal value of the Vector2 and another Vector2 * @param * @param {Vector2} [resultVector] The new Vector2 to save the value to, optional -> defaults: new Vector2 * @returns Vector2 * @since 2.0.0 */ public getNormal(vector: Vector2, resultVector?: Vector2) { resultVector = resultVector || new Vector2(); return resultVector .setValues(vector.y - this.y, this.x - vector.x) .normalize(); } /** * @memberof Vector2 * @description Determines if Vector2.x and Vector2.y are both equal to 0 * @returns boolean * @since 2.0.0 */ public isZero() { return this.x === 0 && this.y === 0; } /** * @memberof Vector * @description Scales the Vector2 by a scalar Vector2 * @param {Vector2} scalar A Vector2 that is used to scale the current Vector2 * @returns Vector * @since 2.0.0 */ public scale(scalar: Vector2) { this.x *= scalar.x; this.y *= scalar.y; return this; } /** * @memberof Vector2 * @description Sets Vector2.x and Vector2.y to their negative values * @returns Vector2 * @since 2.0.0 */ public negate() { this.x = -this.x; this.y = -this.y; return this; } /** * @memberof Vector2 * @description Returns the magnitude or length of the Vector2 * @returns number * @since 2.0.0 */ public magnitude() { return Math.sqrt(this.x * this.x + this.y * this.y); } /** * @memberof Vector2 * @description Returns the magnitude/lenth squared of the Vector2 * @returns number * @since 2.0.0 */ public magnitudeSqr() { return this.x * this.x + this.y * this.y; } /** * @memberof Vector2 * @description Scales the Vector2 by the magnitude or length * @param magnitude The magnitude or length of the Vector2 * @returns Vector2 * @since 2.0.0 */ public scaleToMagnitude(magnitude: number) { const k = magnitude / this.magnitude(); this.x *= k; this.y *= k; return this; } /** * @memberof Vector2 * @description Returns the string version of the Vector2 * @example console.log(new Vector2(0, 0).toString()) // Vector2(0, 0) * @returns string * @since 2.0.0 */ public toString() { return `Vector2(${this.x}, ${this.y})`; } /** * @memberof Vector2 * @description Sets the values to be precise by using Number.toPrecision * @param {number} precision The precision * @returns Vector2 * @since 2.0.0 */ public toPrecision(precision: number) { this.x = Number(this.x.toPrecision(precision)); this.y = Number(this.y.toPrecision(precision)); return this; } /** * @memberof Vector2 * @description Adds to the Vector2 by an amount * @param {number} dx Delta x, the amount to increase the x value by * @param {number} dy Delta y, the amount to increase the y value by * @returns Vector2 * @since 2.0.0 */ public translate(dx: number, dy: number) { this.x += dx; this.y += dy; return this; } /** * @memberof Vector2 * @description Adds to the Vector2.x by an amount * @param {number} dx Delta x, the amount to increase the x value by * @returns Vector2 * @since 2.0.0 */ public translateX(dx: number) { this.x += dx; return this; } /** * @memberof Vector2 * @description Adds to the Vector2.y by an amount * @param {number} dy Delta y, the amount to increase the y value by * @returns Vector2 * @since 2.0.0 */ public translateY(dy: number) { this.x += dy; return this; } /** * @memberof Vector2 * @description Gets the dot product using three different Vector2s * @param {Vector2} a A Vector2 * @param {Vector2} b A Vector2 * @param {Vector2} c A Vector2 * @param {Vector2} [resultVector=Vector2] A Vector2 that the result is saved in, optional -> defaults: new Vector2 * @returns Vector2 * @since 2.0.0 */ public tripleProduct( a: Vector2, b: Vector2, c: Vector2, resultVector?: Vector2 ) { resultVector = resultVector || new Vector2(); const ac = a.dot(c); const bc = b.dot(c); return resultVector.setValues(b.x * ac - a.x * bc, b.y * ac - a.y * bc); } /** * @memberof Vector2 * @description Clamps the values to a min and max * @param {number} min The min value * @param {number} max The max value * @returns Vector2 * @since 2.0.0 */ public clamp(min: number, max: number) { this.x = clamp(this.x, min, max); this.y = clamp(this.y, min, max); return this; } /** * @memberof Vector2 * @description Clamps the values to a min * @param {number} min The min value * @returns Vector2 * @since 2.0.0 */ public clampMin(min: number) { if (this.x < min) { this.x = min; } if (this.y < min) { this.y = min; } return this; } /** * @memberof Vector2 * @description Clamps the values to a max * @param {number} max The max value * @returns Vector2 * @since 2.0.0 */ public clampMax(max: number) { if (this.x > max) { this.x = max; } if (this.y > max) { this.y = max; } return this; } /** * @memberof Vector2 * @description Rotates the Vector2 based on degrees * @param {number} degrees The angle in degrees * @param {Vector2} [center] The center Vector relative to the Vector, optional -> defaults: Vector2.ZERO * @returns Vector2 * @since 2.0.0 */ public rotate(degrees: number, center = Vector2.ZERO) { const radians = degToRadians(degrees); const cx = center.x || 0; const cy = center.y || 0; const c = Math.cos(radians), s = Math.sin(radians); const x = this.x - cx; const y = this.y - cy; this.x = x * c - y * s + cx; this.y = x * s + y * c + cy; return this; } /** * @memberof Vector2 * @description Reflects the Vector2, returns the opposite value on a number line * * @example new Vector2(100, 50).reflect() // Vector2(-100, -50) * * @returns Vector2 * @since 2.0.0 */ public reflect() { this.x *= -1; this.y *= -1; return this; } /** * @memberof Vector2 * @description Gets the absolute value of the vector * @returns Vector2 * @since 2.0.0 */ public abs() { this.x = Math.abs(this.x); this.y = Math.abs(this.y); return this; } // STATIC /** * @memberof Vector2 * @static * @description Returns a Vector2 with 0 set as x and y * @returns Vector2 * @since 2.0.0 */ public static get ZERO() { return new Vector2(0, 0); } /** * @memberof Vector2 * @static * @description Returns a Vector2 with 0 set as x and -1 set as y * @returns Vector2 * @since 2.0.0 */ public static get UP() { return new Vector2(0, -1); } /** * @memberof Vector2 * @static * @description Returns a Vector2 with 0 set as x and 1 set as y * @returns Vector2 * @since 2.0.0 */ public static get DOWN() { return new Vector2(0, 1); } /** * @memberof Vector2 * @static * @description Returns a Vector2 with -1 set as x and 0 set as y * @returns Vector2 * @since 2.0.0 */ public static get LEFT() { return new Vector2(-1, 0); } /** * @memberof Vector2 * @static * @description Returns a Vector2 with 1 set as x and 0 set as y * @returns Vector2 * @since 2.0.0 */ public static get RIGHT() { return new Vector2(1, 0); } /** * @memberof Vector2 * @static * @description Returns a Vector2 with passed parameters, if no parameters are passed, a Vector2.ZERO is returned * @param {number} [x] X position, optional -> defaults: 0 * @param {number} [y] Y position, optional -> defaults: 0 * @returns Vector2 * @since 2.0.0 */ public static CREATE(x?: number, y?: number) { if (!x && !y) return this.ZERO; // none if (x && !y) return new Vector2(x); // only x if (!x && y) return new Vector2(0, y); // only y return new Vector2(x, y); // both } /** * @memberof Vector2 * @static * @description Returns a Vector2 with passed vector2Like object * @param {Duck.Types.Math.Vector2Like} vector2Like An object with x and y properties * @returns Vector2 * @since 2.0.0 */ public static fromVector2Like(vector2Like: Duck.Types.Math.Vector2Like) { return new Vector2(vector2Like.x, vector2Like.y); } /** * @memberof Vector2 * @static * @description Returns a Vector2Like object with passed Vector2 * @param {Vector2} vector2 A Vector2 to convert to Vector2Like object * @returns Vector2 * @since 2.0.0 */ public static toVector2Like(vector2: Vector2) { return { x: vector2.x, y: vector2.y, }; } /** * @memberof Vector2 * @static * @description Returns a Vector2 with values from a passed Vector2 * @param {Vector2} vector Vector2 to create a Vector2 from * @returns Vector2 * @since 2.0.0 */ public static fromVec(vector: Vector2) { return new Vector2(vector.x, vector.y); } }
the_stack
import { Array } from "@siteimprove/alfa-array"; import { Cache } from "@siteimprove/alfa-cache"; import { Element } from "@siteimprove/alfa-dom"; import { Equatable } from "@siteimprove/alfa-equatable"; import { Serializable } from "@siteimprove/alfa-json"; import { Real } from "@siteimprove/alfa-math"; import { Option } from "@siteimprove/alfa-option"; import { Predicate } from "@siteimprove/alfa-predicate"; import { Sequence } from "@siteimprove/alfa-sequence"; import * as json from "@siteimprove/alfa-json"; import { Cell } from "./cell"; import { Column } from "./column"; import { Row } from "./row"; import { Group } from "./group"; import { Slot } from "./slot"; import { Scope } from "./scope"; const { isNaN } = Number; const { clamp } = Real; const { not, equals } = Predicate; const { hasName, isElement } = Element; /** * {@link https://html.spec.whatwg.org/#concept-table} * * @public */ export class Table implements Equatable, Serializable<Table.JSON> { public static of( element: Element, cells: Iterable<Cell>, groups: Iterable<Group> ): Table { return new Table( element, Array.sort(Array.copy(Array.from(cells))), Array.sort(Array.copy(Array.from(groups))) ); } public static empty(element: Element): Table { return new Table(element, [], []); } private readonly _element: Element; private readonly _cells: Array<Cell>; private readonly _groups: Array<Group>; private constructor( element: Element, cells: Array<Cell>, groups: Array<Group> ) { this._element = element; this._cells = cells; this._groups = groups; } public get element(): Element { return this._element; } public get cells(): Sequence<Cell> { return Sequence.from(this._cells); } public get groups(): Sequence<Group> { return Sequence.from(this._groups); } public isEmpty(): boolean { return this._cells.length === 0; } public equals(table: Table): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Table && value._element.equals(this._element) && Array.equals(value._cells, this._cells) ); } public toJSON(): Table.JSON { return { element: this._element.path(), cells: Array.toJSON(this._cells), groups: Array.toJSON(this._groups), }; } } /** * @public */ export namespace Table { export interface JSON { [key: string]: json.JSON; element: string; cells: Array<Cell.JSON>; groups: Array<Group.JSON>; } const cache = Cache.empty<Element, Table>(); export function from(element: Element): Table { return cache.get(element, () => formTable(element)); } /** * {@link https://html.spec.whatwg.org/#forming-a-table} */ function formTable(element: Element): Table { // 1 let xWidth = 0; // 2 let yHeight = 0; // 3 const footers: Array<Element> = []; // 4 const cells: Array<Cell> = []; const groups: Array<Group> = []; // We model tables as an array of rows with each row containing an array of // columns and each column containing an array of cell indices. // // Tables are indexed first by row and then by column. This way, rows are // aligned vertically and columns horizontally: // // table = [ // /* row 1 */ [/* column 1 */, /* column 2 */], // /* row 2 */ [/* column 1 */, /* column 2 */], // ] // // This makes it considerably easier to debug table construction by not // having to rotate your screen 90 degrees to make sense of things. const table: Array<Array<Array<number>>> = []; // Keep track of which columns and rows have data cells. This information is // used when determining the scope of header cells. // // Consider the following table, with letters indicating headers and numbers // indicating data: // // +---+---+---+ // | | A | B | // +---+---+---+ // | C | 1 | 2 | // +---+---+---+ // // For this table, the following `data` object would be constructed: // // data = { // x: Set { 1, 2 } // y: Set { 1 } // } // // This tells us that across the x-axis column 1 and 2 contain data, and // across the y-axis row 1 contains data. Empty cells never count as data. // // For the headers "A" and "B" we can therefore determine that these should // be column headers as row 0 contains no data. For the header "C" we can // determine that this should be a row header as column 0 has no data. const data = { x: new Set<number>(), y: new Set<number>() }; // Keep track of headings along rows and columns. This information is used // when determining implicitly assigned header cells. // // Consider the following table, with letters indicating headers and numbers // indicating data: // // +---+---+---+ // | | A | B | // +---+---+---+ // | C | 1 | 2 | // +---+---+---+ // // For this table, the following `jumps` object would be constructed: // // jumps = { // x: Map { // 0 => [ 1 ] // 1 => [ 0 ], // 2 => [ 0 ], // }, // y: Map { // 0 => [ 1, 2 ], // 1 => [ 0 ] // } // } // // This tells us that across the x-axis, column 0 contains a header at row 1 // while columns 1 and 2 contain headers at row 0. Across the y-axis, row 0 // contains headers at column 1 and 2 while row 1 contains a header at // column 0. // // For the cell "2" on row 1 we can therefore determine that we can jump // directly to x-coordinate 0 when scanning for row headers as this is the // only column with a header on row 1. This saves us from having to visit // cell "1" just to determine that it's a data cell. const jumps = { x: new Map<number, Array<number>>(), y: new Map<number, Array<number>>(), }; // Keep track of cells that can be indexed by element ID. This information // is used when determining explicitly assigned header cells. const index = new Map<string, number>(); // Keep track of the groups associated with columns and rows. This // information is used when determining implicitly assigned header cells. const groupings = { x: new Map<number, number>(), y: new Map<number, number>(), }; // 5 if (element.children().isEmpty()) { return Table.of(element, cells, groups); } // 6 // Nothing to do // 7 let children = element.children().filter(isElement); // 8 skip(not(hasName("colgroup", "thead", "tbody", "tfoot", "tr"))); // 9 while (current().some(hasName("colgroup"))) { // 9.1 // As this step contains several substeps inlined in the algorithm, its // substeps have been extracted into a function of their own. processColumnGroup(current().get()); // 9.2 advance(); // 9.3 skip(not(hasName("colgroup", "thead", "tbody", "tfoot", "tr"))); // 9.4 // Nothing to do } // 10 let yCurrent = 0; // 11 let downwardGrowing: Array<[cell: Cell, index: number]> = []; // Steps 12-18 are repeated for as long as there are children left in the // table. while (current().isSome()) { // 12 skip(not(hasName("thead", "tbody", "tfoot", "tr"))); if (current().isNone()) { break; } // 13 if (current().some(hasName("tr"))) { processRow(current().get()); advance(); continue; } // 14 endRowGroup(); // 15 if (current().some(hasName("tfoot"))) { footers.push(current().get()); advance(); continue; } // 16 processRowGroup(current().get()); // 17 advance(); // 18 // Nothing to do } // 19 footers.forEach(processRowGroup); // 20 // Nothing to do // 21 // Before returning the final table, we go through all cells and assign them // scopes and headers, if any. cells.forEach(assignScope); cells.forEach(assignHeaders); return Table.of(element, cells, groups); /** * Ensure that the given position is available in the table. */ function ensure(x: number, y: number): void { for (let i = table.length - 1; i < y; i++) { table.push([]); } const row = table[y]; for (let i = row.length - 1; i < x; i++) { row.push([]); } } /** * Get the cells at the given position. */ function get(x: number, y: number): Array<number> { ensure(x, y); // Keep in mind that tables are indexed first by row and then by column. return table[y][x]; } /** * Check if the table has cells at the given position. */ function has(x: number, y: number): boolean { return get(x, y).length > 0; } /** * Add a cell at the given position. */ function add(x: number, y: number, i: number): number { const cell = cells[i]; if (cell.isHeader()) { if (jumps.x.has(x)) { jumps.x.get(x)!.push(y); } else { jumps.x.set(x, [y]); } if (jumps.y.has(y)) { jumps.y.get(y)!.push(x); } else { jumps.y.set(y, [x]); } } else if (!cell.isEmpty()) { data.x.add(x); data.y.add(y); } ensure(x, y); // Keep in mind that tables are indexed first by row and then by column. return table[y][x].push(i); } /** * Determine the last position among the candidates that is less than or * equal to the given initial position `i`. That is, the last value in * `candidates` that is `<= i`. If no suitable candidate is found, -1 is * returned. */ function jump(i: number, candidates: Array<number> = []): number { for (let j = candidates.length - 1; j >= 0; j--) { const candidate = candidates[j]; if (candidate <= i) { return candidate; } } return -1; } /** * Get the current child element of the table. */ function current(): Option<Element> { return children.first(); } /** * Advance to the next child element of the table. */ function advance(): Option<Element> { children = children.rest(); return current(); } /** * Skip child elements of the table while the predicate holds. */ function skip(predicate: Predicate<Element>): void { while (current().some(predicate)) { advance(); } } /** * {@link https://html.spec.whatwg.org/#algorithm-for-processing-row-groups} */ function processRowGroup(element: Element): void { // 1 const yStart = yHeight; // 2 element .children() .filter(isElement) .filter(hasName("tr")) .forEach(processRow); // 3 if (yHeight > yStart) { const group = Row.group(element, yStart, yHeight - yStart); const i = groups.length; groups.push(group); for (let y = group.y, n = y + group.height; y < n; y++) { groupings.y.set(y, i); } } // 4 endRowGroup(); } /** * {@link https://html.spec.whatwg.org/#algorithm-for-ending-a-row-group} */ function endRowGroup(): void { // 1 while (yCurrent < yHeight) { // 1.1 growCells(); // 1.2 yCurrent++; } // 2 downwardGrowing = []; } /** * {@link https://html.spec.whatwg.org/#algorithm-for-processing-rows} */ function processRow(element: Element): void { // 1 if (yHeight === yCurrent) { yHeight++; } // 2 let xCurrent = 0; // 3 growCells(); // 4 let children = element .children() .filter(isElement) .filter(hasName("td", "th")); if (children.isEmpty()) { yCurrent++; return; } // 5 // Nothing to do // Steps 6-18 are repeated for as long as there are children left in the // row. while (current().isSome()) { // 6 while (xCurrent < xWidth && has(xCurrent, yCurrent)) { xCurrent++; } // 7 if (xCurrent === xWidth) { xWidth++; } // 8 let colspan = integerValue( current().get(), "colspan", 1 /* lower */, 1000 /* upper */ ); // 9 let rowspan = integerValue( current().get(), "rowspan", 0 /* lower */, 65534 /* upper */, 1 /* missing */ ); // 10 let growsDownward: boolean; if (rowspan === 0) { growsDownward = true; rowspan = 1; } else { growsDownward = false; } // 11 if (xWidth < xCurrent + colspan) { xWidth = xCurrent + colspan; } // 12 if (yHeight < yCurrent + rowspan) { yHeight = yCurrent + rowspan; } // 13 let cell: Cell; if (current().some(hasName("th"))) { cell = Cell.header( current().get(), Slot.of(xCurrent, yCurrent), colspan, rowspan ); } else { cell = Cell.data( current().get(), Slot.of(xCurrent, yCurrent), colspan, rowspan ); } const i = cells.length; cells.push(cell); for (const id of cell.element.id) { index.set(id, i); } for (let x = xCurrent, n = x + colspan; x < n; x++) { for (let y = yCurrent, n = y + rowspan; y < n; y++) { add(x, y, i); } } // 14 if (growsDownward) { downwardGrowing.push([cell, i]); } // 15 xCurrent += colspan; // 16 if (advance().isNone()) { yCurrent++; return; } // 17 // Nothing to do // 18 // Nothing to do } /** * Get the current child element of the row. */ function current(): Option<Element> { return children.first(); } /** * Advance to the next child element of the row. */ function advance(): Option<Element> { children = children.rest(); return current(); } } /** * Carry out step 9.1 of the table forming algorithm. * * {@link https://html.spec.whatwg.org/#forming-a-table} */ function processColumnGroup(element: Element): void { let children = element .children() .filter(isElement) .filter(hasName("col")); let group: Group; let i: number; if (!children.isEmpty()) { // 1 const xStart = xWidth; // 2 // Nothing to do // Steps 3-6 are repeated for as long as there are children left in the // column group. while (current().isSome()) { // 3 const span = integerValue( current().get(), "span", 1 /* lower */, 1000 /* upper */ ); // 4 xWidth += span; // 5 // Nothing to do // 6 advance(); } // 7 group = Column.group(element, xStart, xWidth - xStart); i = groups.length; } else { // 1 const span = integerValue( element, "span", 1 /* lower */, 1000 /* upper */ ); // 2 xWidth += span; // 3 group = Column.group(element, xWidth - span, span); i = groups.length; } groups.push(group); for (let x = group.x, n = x + group.width; x < n; x++) { groupings.x.set(x, i); } /** * Get the current child element of the column group. */ function current(): Option<Element> { return children.first(); } /** * Advance to the next child element of the column group. */ function advance(): Option<Element> { children = children.rest(); return current(); } } /** * For all downwards growing cells, extend their height to the current * y-coordinate. * * {@link https://html.spec.whatwg.org/#algorithm-for-growing-downward-growing-cells} */ function growCells(): void { for (const [cell, i] of downwardGrowing) { const height = yCurrent - cell.y + 1; for (let x = cell.x, n = x + cell.width; x < n; x++) { for (let y = cell.y + cell.height, n = cell.y + height; y < n; y++) { add(x, y, i); } } if (cell.isHeader()) { cells[i] = Cell.header(cell.element, cell.anchor, cell.width, height); } else { cells[i] = Cell.data(cell.element, cell.anchor, cell.width, height); } } } /** * {@link https://html.spec.whatwg.org/#algorithm-for-assigning-header-cells} */ function assignHeaders(cell: Cell, i: number): void { // 1 const headers: Array<Cell> = []; // 2 // Nothing to do // 3 const ids = cell.element .attribute("headers") .map((attribute) => attribute.tokens()); if (ids.isSome()) { // 3.1 // Nothing to do // 3.2 // Keep in mind that not just <th> elements but also <td> elements can // be referenced as headers. headers.push( ...ids .get() .collect((id) => Option.from(index.get(id)).map((i) => cells[i])) ); } else { // 1 // Nothing to do // 2 // Nothing to do // 3 for (let y = cell.y, n = y + cell.height; y < n; y++) { scanHeaderCells(cell, headers, cell.x, y, -1, 0); } // 4 for (let x = cell.x, n = x + cell.width; x < n; x++) { scanHeaderCells(cell, headers, x, cell.y, 0, -1); } // 5 const i = groupings.y.get(cell.y); if (i !== undefined) { const group = groups[i] as Row.Group; for (let x = cell.x + cell.width - 1; x >= 0; x--) { for (let y = group.y, n = cell.y + cell.height; y < n; y++) { x = jump(x, jumps.y.get(y)); if (x < 0) { break; } headers.push( ...get(x, y) .map((i) => cells[i]) .filter((cell) => cell.isHeader() && isRowGroupHeader(cell)) ); } } } // 6 const j = groupings.x.get(cell.x); if (j !== undefined) { const group = groups[j] as Column.Group; for (let y = cell.y + cell.height - 1; y >= 0; y--) { for (let x = group.x, n = cell.x + cell.width; x < n; x++) { y = jump(y, jumps.x.get(x)); if (y < 0) { break; } headers.push( ...get(x, y) .map((i) => cells[i]) .filter( (cell) => cell.isHeader() && isColumnGroupHeader(cell) ) ); } } } } const filtered = Sequence.from(headers) // 4 .reject((cell) => cell.isEmpty()) // 5 .distinct() // 6 .reject(equals(cell)); const anchors = filtered.map((cell) => cell.anchor); // 7 if (cell.isHeader()) { cells[i] = Cell.header( cell.element, cell.anchor, cell.width, cell.height, anchors, cell.scope ); } else { cells[i] = Cell.data( cell.element, cell.anchor, cell.width, cell.height, anchors ); } } /** * {@link https://html.spec.whatwg.org/#internal-algorithm-for-scanning-and-assigning-header-cells} */ function scanHeaderCells( principal: Cell, headers: Array<Cell>, initialX: number, initialY: number, deltaX: number, deltaY: number ): void { // 1 let x = initialX; // 2 let y = initialY; // 3 const opaque: Array<Cell> = []; // 4 let inHeader = principal.isHeader(); let currentHeaders = inHeader ? [principal] : []; // Steps 5-10 are repeated for as long as the position (x, y) is within // bounds of the table. while (true) { // 5 x += deltaX; y += deltaY; // Fast path: Based on the current position and direction, jump to the // next available heading. This ensures that we don't need to linearly // scan over a bunch of data cells before finding a header. if (deltaX === 0) { y = jump(y, jumps.x.get(x)); } else { x = jump(x, jumps.y.get(y)); } // 6 if (x < 0 || y < 0) { return; } // 7 const neighbour = get(x, y); if (neighbour.length !== 1) { continue; } // 8 const cell = cells[neighbour[0]]; // 9 if (cell.isHeader()) { // 9.1 inHeader = true; // 9.2 currentHeaders.push(cell); // 9.3 let blocked = false; // 9.4 if (deltaX === 0) { if ( opaque.some( (header) => header.x === cell.x && header.width === cell.width ) || !isColumHeader(cell) ) { blocked = true; } } else { if ( opaque.some( (header) => header.y === cell.y && header.height === cell.height ) || !isRowHeader(cell) ) { blocked = true; } } // 9.5 if (!blocked) { headers.push(cell); } } else if (inHeader) { inHeader = false; opaque.push(...currentHeaders); currentHeaders = []; } // 10 // Nothing to do } } /** * {@link https://html.spec.whatwg.org/#attr-th-scope} */ function assignScope(cell: Cell, i: number): void { if (!cell.isHeader()) { return; } let scope: Scope; if (isColumHeader(cell)) { scope = "column"; } else if (isColumnGroupHeader(cell)) { scope = "column-group"; } else if (isRowHeader(cell)) { scope = "row"; } else if (isRowGroupHeader(cell)) { scope = "row-group"; } else { return; } cells[i] = Cell.header( cell.element, cell.anchor, cell.width, cell.height, cell.headers, scope ); } /** * {@link https://html.spec.whatwg.org/#column-header} */ function isColumHeader(cell: Cell.Header): boolean { if (cell.scope === "column") { return true; } switch (Scope.from(cell.element)) { case "column": return true; case "auto": for (let y = cell.y, n = y + cell.height; y < n; y++) { if (data.y.has(y)) { return false; } } return true; } return false; } /** * {@link https://html.spec.whatwg.org/#column-group-header} */ function isColumnGroupHeader(cell: Cell.Header): boolean { return ( cell.scope === "column-group" || Scope.from(cell.element) === "column-group" ); } /** * {@link https://html.spec.whatwg.org/#row-header} */ function isRowHeader(cell: Cell.Header): boolean { if (cell.scope === "row") { return true; } switch (Scope.from(cell.element)) { case "row": return true; case "auto": for (let x = cell.x, n = x + cell.width; x < n; x++) { if (data.x.has(x)) { return false; } } return true; } return false; } /** * {@link https://html.spec.whatwg.org/#row-group-header} */ function isRowGroupHeader(cell: Cell.Header): boolean { return ( cell.scope === "row-group" || Scope.from(cell.element) === "row-group" ); } } function integerValue( element: Element, attribute: string, lower: number, upper: number, missing: number = lower ): number { return clamp( element .attribute(attribute) .map((attribute) => parseInt(attribute.value)) .reject(isNaN) .getOr(missing), lower, upper ); } }
the_stack
import { AddressSpace, IHistoricalDataNodeOptions, UAVariable } from "node-opcua-address-space"; import { StatusCode, StatusCodes } from "node-opcua-status-code"; import { AggregateConfigurationOptions, AggregateConfigurationOptionsEx, installAggregateConfigurationOptions } from "../.."; import { makeDataValue } from "./helpers"; function addHistory(node: UAVariable, time: string, value: number | boolean | null, statusCode: StatusCode): void { (node as any)._historyPush(makeDataValue(time, value, statusCode)); } /// Example 1 : Example Aggregate data – Historian 1 // For the purposes of Historian 1 examples consider a source historian with the following data: // // Timestamp Value StatusCode Notes // 12:00:00 - BadNoData First archive entry, Point created // 12:00:10 10 Raw, Good // 12:00:20 20 Raw, Good // 12:00:30 30 Raw, Good // 12:00:40 40 Raw, Bad ANNOTATION: Operator 1 // Jan-02-2012 8:00:00 Scan failed, Bad data entered // ANNOTATION: // Jan-04-2012 7:10:00 Value cannot be verified // 12:00:50 50 Raw, Good ANNOTATION: Engineer1 // Jan-04-2012 7:00:00 Scanner fixed // 12:01:00 60 Raw, Good // 12:01:10 70 Raw, Uncertain ANNOTATION: Technician_1 // Jan-02-2012 8:00:00 Value flagged as questionable // 12:01:20 80 Raw, Good // 12:01:30 90 Raw, Good // null No Data No more entries, awaiting next scan // The example historian also has Annotations associated with three data point // // 1) TreatUncertainAsBad = False. Therefore Uncertain values are included in Aggregate calls. // 2) Stepped Attribute = False. Therefore SlopedInterpolation is used between // data points. // 3) UseSlopedExtrapolation = False. Therefore SteppedExtrapolation is used at end // boundary conditions. // 4) PercentBad = 100, PercentGood = 100. Therefore if all values are Good then the // quality will be Good, or if all values are Bad then the quality will be Bad, but if there is // some Good and some Bad then the quality will be Uncertain // // ---------------------------------------------------------------------------- export function createHistorian1(addressSpace: AddressSpace): UAVariable { const node = addressSpace.getOwnNamespace().addVariable({ browseName: "History1", dataType: "Float" }); const options: AggregateConfigurationOptionsEx & IHistoricalDataNodeOptions = { historian: undefined, percentDataBad: 100, percentDataGood: 100, // Therefore if all values are Good then the // quality will be Good, or if all values are Bad then the quality will be Bad, but if there is // some Good and some Bad then the quality will be Uncertain stepped: false, // Therefore SlopedInterpolation is used between data points. treatUncertainAsBad: false, // Therefore Uncertain values are included in Aggregate calls. useSlopedExtrapolation: false // Therefore SteppedExtrapolation is used at end boundary conditions. }; addressSpace.installHistoricalDataNode(node, options); installAggregateConfigurationOptions(node, options); // 12:00:00 - BadNoData First archive entry, Point created addHistory(node, "12:00:00", null, StatusCodes.BadNoData); // 12:00:10 10 Raw, Good addHistory(node, "12:00:10", 10, StatusCodes.Good); // 12:00:20 20 Raw, Good addHistory(node, "12:00:20", 20, StatusCodes.Good); // 12:00:30 30 Raw, Good addHistory(node, "12:00:30", 30, StatusCodes.Good); // 12:00:40 40 Raw, Bad ANNOTATION: Operator 1 // Jan-02-2012 8:00:00 Scan failed, Bad data entered // ANNOTATION: // Jan-04-2012 7:10:00 Value cannot be verified addHistory(node, "12:00:40", 40, StatusCodes.Bad); // 12:00:50 50 Raw, Good ANNOTATION: Engineer1 // Jan-04-2012 7:00:00 Scanner fixed addHistory(node, "12:00:50", 50, StatusCodes.Good); // 12:01:00 60 Raw, Good addHistory(node, "12:01:00", 60, StatusCodes.Good); // 12:01:10 70 Raw, Uncertain ANNOTATION: Technician_1 // Jan-02-2012 8:00:00 Value flagged as questionable addHistory(node, "12:01:10", 70, StatusCodes.Uncertain); // 12:01:20 80 Raw, Good addHistory(node, "12:01:20", 80, StatusCodes.Good); // 12:01:30 90 Raw, Good addHistory(node, "12:01:30", 90, StatusCodes.Good); return node; } export function createHistorian2(addressSpace: AddressSpace): UAVariable { const node = addressSpace.getOwnNamespace().addVariable({ browseName: "History2", dataType: "Double" }); const options = {}; addressSpace.installHistoricalDataNode(node, options); // 12:00:00 - Bad_NoData First archive entry, Point created addHistory(node, "12:00:00", 10, StatusCodes.BadNoData); // 12:00:02 10 Raw, Good addHistory(node, "12:00:02", 10, StatusCodes.Good); // 12:00:25 20 Raw, Good addHistory(node, "12:00:25", 20, StatusCodes.Good); // 12:00:28 25 Raw, Good addHistory(node, "12:00:28", 25, StatusCodes.Good); // 12:00:39 30 Raw, Good addHistory(node, "12:00:39", 30, StatusCodes.Good); // 12:00:42 - Raw, Bad Bad quality data received, Bad data entered addHistory(node, "12:00:42", null, StatusCodes.BadDataLost); // 12:00:48 40 Raw, Good Received Good StatusCode value addHistory(node, "12:00:48", 40, StatusCodes.Good); // 12:00:52 50 Raw, Good addHistory(node, "12:00:52", 50, StatusCodes.Good); // 12:01:12 60 Raw, Good addHistory(node, "12:01:12", 60, StatusCodes.Good); // 12:01:17 70 Raw, Uncertain Value is flagged as questionable addHistory(node, "12:01:17", 70, StatusCodes.UncertainNoCommunicationLastUsableValue); // 12:01:23 70 Raw, Good addHistory(node, "12:01:23", 70, StatusCodes.Good); // 12:01:26 80 Raw, Good addHistory(node, "12:01:26", 80, StatusCodes.Good); // 12:01:30 90 Raw, Good addHistory(node, "12:01:30", 90, StatusCodes.Good); // - No Data No more entries, awaiting next Value return node; } // This example is included to illustrate non-periodic data. For the purposes of Historian 2 // examples consider a source historian with the following data: // Timestamp Value StatusCode Notes // 12:00:00 - Bad_NoData First archive entry, Point created // 12:00:02 10 Raw, Good // 12:00:25 20 Raw, Good // 12:00:28 25 Raw, Good // 12:00:39 30 Raw, Good // 12:00:42 - Raw, Bad Bad quality data received, Bad data entered // 12:00:48 40 Raw, Good Received Good StatusCode value // 12:00:52 50 Raw, Good // 12:01:12 60 Raw, Good // 12:01:17 70 Raw, Uncertain Value is flagged as questionable // 12:01:23 70 Raw, Good // 12:01:26 80 Raw, Good // 12:01:30 90 Raw, Good // - No Data No more entries, awaiting next Value // // For the purposes of all Historian 2 examples: // 1) TreatUncertainAsBad = True. Therefore Uncertain values are treated as Bad, and not // included in the Aggregate call. // 2) Stepped Attribute = False. Therefore SlopedInterpolation is used between data points. // 3) UseSlopedExtrapolation = False. Therefore SteppedExtrapolation is used at end // boundary conditions. // 4) PercentBad = 100, PercentGood = 100. Therefore unless if all values are Good then // the quality will be Good, or if all values are Bad then the quality will be Bad, but if // there is some Good and some Bad then the quality will be Uncertain. // ------------------------------------------------------------------------------------ // A.1.3 Example Aggregate data – Historian 3 // This example is included to illustrate stepped data. For the purposes of Historian 3 examples // consider a source historian with the following data: // // Timestamp Value StatusCode Notes // 12:00:00 - Bad_NoData First archive entry, Point created // 12:00:02 10 Raw, Good // 12:00:25 20 Raw, Good // 12:00:28 25 Raw, Good // 12:00:39 30 Raw, Good // 12:00:42 - Raw, Bad Bad quality data received, Bad data entered // 12:00:48 40 Raw, Good Received Good StatusCode value // 12:00:52 50 Raw, Good // 12:01:12 60 Raw, Good // 12:01:17 70 Raw, Uncertain Value is flagged as questionable // 12:01:23 70 Raw, Good // 12:01:26 80 Raw, Good // 12:01:30 90 Raw, Good // - No Data No more entries, awaiting next Value // // For the purposes of all Historian 3 examples: // 1) TreatUncertainAsBad = True. Therefore Uncertain values are treated as Bad, and not // included in the Aggregate call. // 2) Stepped Attribute = True. Therefore SteppedInterpolation is used between data points. // 3) UseSlopedExtrapolation = False. Therefore SteppedExtrapolation is used at end // boundary conditions. // 4) PercentBad = 50, PercentGood = 50. Therefore data will be either Good or Bad quality. // Uncertain should not happen since a value is either Good or Bad // export function createHistorian3(addressSpace: AddressSpace): UAVariable { const node = addressSpace.getOwnNamespace().addVariable({ browseName: "History3", dataType: "Double" }); const options: AggregateConfigurationOptionsEx & IHistoricalDataNodeOptions = { percentDataBad: 50, percentDataGood: 50, stepped: true, // therefore SteppedInterpolation is used between data points treatUncertainAsBad: true, // therefore Uncertain values are treated as Bad, // and not included in the Aggregate call. useSlopedExtrapolation: false // therefore SteppedExtrapolation is used at end boundary conditions. }; addressSpace.installHistoricalDataNode(node, options); installAggregateConfigurationOptions(node, options); // 12:00:00 - Bad_NoData First archive entry, Point created addHistory(node, "12:00:00", 10, StatusCodes.BadNoData); // 12:00:02 10 Raw, Good addHistory(node, "12:00:02", 10, StatusCodes.Good); // 12:00:25 20 Raw, Good addHistory(node, "12:00:25", 20, StatusCodes.Good); // 12:00:28 25 Raw, Good addHistory(node, "12:00:28", 25, StatusCodes.Good); // 12:00:39 30 Raw, Good addHistory(node, "12:00:39", 30, StatusCodes.Good); // 12:00:42 - Raw, Bad Bad quality data received, Bad data entered addHistory(node, "12:00:42", null, StatusCodes.BadDataLost); // 12:00:48 40 Raw, Good Received Good StatusCode value addHistory(node, "12:00:48", 40, StatusCodes.Good); // 12:00:52 50 Raw, Good addHistory(node, "12:00:52", 50, StatusCodes.Good); // 12:01:12 60 Raw, Good addHistory(node, "12:01:12", 60, StatusCodes.Good); // 12:01:17 70 Raw, Uncertain Value is flagged as questionable addHistory(node, "12:01:17", 70, StatusCodes.UncertainLastUsableValue); // 12:01:23 70 Raw, Good addHistory(node, "12:01:23", 70, StatusCodes.Good); // 12:01:26 80 Raw, Good addHistory(node, "12:01:26", 80, StatusCodes.Good); // 12:01:30 90 Raw, Good addHistory(node, "12:01:30", 90, StatusCodes.Good); // - No Data No more entries, awaiting next Value return node; } /// ------------------------------------------------------------------------------ // A.1.4 Example Aggregate data – Historian 4 // This example is included to illustrate Boolean data. For the purposes of Historian 4 examples // consider a source historian with the following data: // Timestamp Value StatusCode Notes // 12:00:00 - Bad_NoData First archive entry, Point created // 12:00:02 TRUE Raw, Good // 12:00:25 FALSE Raw, Good // 12:00:28 TRUE Raw, Good // 12:00:39 TRUE Raw, Good // 12:00:42 - Raw, Bad Bad quality data received, Bad data entered // 12:00:48 TRUE Raw, Good Received Good StatusCode value // 12:00:52 FALSE Raw, Good // 12:01:12 FALSE Raw, Good // 12:01:17 TRUE Raw, Uncertain Value is flagged as questionable // 12:01:23 TRUE Raw, Good // 12:01:26 FALSE Raw, Good // 12:01:30 TRUE Raw, Good // - No Data No more entries, awaiting next Value // For the purposes of all Historian 4 examples: // 1) TreatUncertainAsBad = True. Therefore Uncertain values are treated as Bad, and not // included in the Aggregate call. // 2) Stepped Attribute = True. Therefore SteppedInterpolation is used between data points. // 3) UseSlopedExtrapolation = False. Therefore SteppedExtrapolation is used at end // boundary conditions. // 4) PercentGood = 100, PercentBad = 100. // For Boolean data interpolation and extrapolation shall always be stepped. export function createHistorian4(addressSpace: AddressSpace): UAVariable { const node = addressSpace.getOwnNamespace().addVariable({ browseName: "History4", dataType: "Boolean" }); const options = {}; addressSpace.installHistoricalDataNode(node, options); // 12:00:00 - Bad_NoData First archive entry, Point created addHistory(node, "12:00:00", null, StatusCodes.BadNoData); // 12:00:02 TRUE Raw, Good addHistory(node, "12:00:02", true, StatusCodes.Good); // 12:00:25 FALSE Raw, Good addHistory(node, "12:00:25", false, StatusCodes.Good); // 12:00:28 TRUE Raw, Good addHistory(node, "12:00:28", true, StatusCodes.Good); // 12:00:39 TRUE Raw, Good addHistory(node, "12:00:39", true, StatusCodes.Good); // 12:00:42 - Raw, Bad Bad quality data received, Bad data entered addHistory(node, "12:00:42", true, StatusCodes.BadDataLost); // 12:00:48 TRUE Raw, Good Received Good StatusCode value addHistory(node, "12:00:48", true, StatusCodes.Good); // 12:00:52 FALSE Raw, Good addHistory(node, "12:00:52", false, StatusCodes.Good); // 12:01:12 FALSE Raw, Good addHistory(node, "12:01:12", true, StatusCodes.Good); // 12:01:17 TRUE Raw, Uncertain Value is flagged as questionable addHistory(node, "12:01:17", true, StatusCodes.UncertainLastUsableValue); // 12:01:23 TRUE Raw, Good addHistory(node, "12:01:23", true, StatusCodes.Good); // 12:01:26 FALSE Raw, Good addHistory(node, "12:01:26", false, StatusCodes.Good); // 12:01:30 TRUE Raw, Good addHistory(node, "12:01:30", true, StatusCodes.Good); return node; }
the_stack
import * as React from 'react'; import { mount } from 'enzyme'; import { pluginDepsToComponents, setupConsole } from '@devexpress/dx-testing'; import { TABLE_DATA_TYPE, TABLE_REORDERING_TYPE, orderedColumns, getTableTargetColumnIndex, changeColumnOrder, draftOrder, } from '@devexpress/dx-grid-core'; import { PluginHost, Template, TemplatePlaceholder, TemplateConnector, DragDropProvider, } from '@devexpress/dx-react-core'; import { TableColumnReordering } from './table-column-reordering'; jest.mock('@devexpress/dx-grid-core', () => ({ TABLE_DATA_TYPE: 'd', TABLE_REORDERING_TYPE: 'r', orderedColumns: jest.fn(), getTableTargetColumnIndex: jest.fn(), changeColumnOrder: jest.fn(args => args), tableHeaderRowsWithReordering: jest.fn(), draftOrder: jest.fn(args => args), })); /* eslint-disable react/prop-types */ const getBoundingClientRect = jest.fn(node => node.getBoundingClientRect()); const defaultProps = { tableContainerComponent: ({ children }) => ( <div> {children} </div> ), rowComponent: () => null, cellComponent: ( { getCellDimensions }, ) => <div ref={node => getCellDimensions(() => getBoundingClientRect(node))} />, }; /* eslint-enable react/prop-types */ const defaultDeps = { getter: { tableColumns: [ { key: `${TABLE_DATA_TYPE}_a`, type: TABLE_DATA_TYPE, column: { name: 'a' } }, { key: `${TABLE_DATA_TYPE}_b`, type: TABLE_DATA_TYPE, column: { name: 'b' } }, ], tableHeaderRows: [], }, template: { table: {}, }, plugins: ['Table'], }; const defaultClientOffset = { clientOffset: { x: 180 } }; describe('TableColumnReordering', () => { let resetConsole; beforeAll(() => { resetConsole = setupConsole({ ignore: ['validateDOMNesting'] }); }); afterAll(() => { resetConsole(); }); afterEach(() => { jest.clearAllMocks(); }); // tslint:disable-next-line: max-line-length it('should apply the column order specified in the "defaultOrder" property in uncontrolled mode', () => { mount(( <DragDropProvider> <PluginHost> {pluginDepsToComponents(defaultDeps)} <TableColumnReordering {...defaultProps} defaultOrder={['b', 'a']} /> </PluginHost> </DragDropProvider> )); expect(orderedColumns) .toHaveBeenCalledTimes(1); expect(orderedColumns) .toHaveBeenCalledWith(defaultDeps.getter.tableColumns, ['b', 'a']); }); it('should apply the column order specified in the "order" property in controlled mode', () => { mount(( <DragDropProvider> <PluginHost> {pluginDepsToComponents(defaultDeps)} <TableColumnReordering {...defaultProps} order={['b', 'a']} /> </PluginHost> </DragDropProvider> )); expect(orderedColumns) .toHaveBeenCalledTimes(1); expect(orderedColumns) .toHaveBeenCalledWith(defaultDeps.getter.tableColumns, ['b', 'a']); }); it('should apply the column order in uncontrolled mode when drag-and-drop is disabled', () => { mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <TableColumnReordering {...defaultProps} defaultOrder={['b', 'a']} /> </PluginHost> )); expect(orderedColumns) .toHaveBeenCalledTimes(1); expect(orderedColumns) .toHaveBeenCalledWith(defaultDeps.getter.tableColumns, ['b', 'a']); }); it('should apply the column order in controlled mode when drag-and-drop is disabled', () => { mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <TableColumnReordering {...defaultProps} order={['b', 'a']} /> </PluginHost> )); expect(orderedColumns) .toHaveBeenCalledTimes(1); expect(orderedColumns) .toHaveBeenCalledWith(defaultDeps.getter.tableColumns, ['b', 'a']); }); it('should render the "table" template', () => { const tree = mount(( <DragDropProvider> <PluginHost> {pluginDepsToComponents(defaultDeps)} <TableColumnReordering {...defaultProps} order={['b', 'a']} /> </PluginHost> </DragDropProvider> )); expect(tree.find(defaultProps.tableContainerComponent).props()) .toEqual({ onOver: expect.any(Function), onLeave: expect.any(Function), onDrop: expect.any(Function), children: expect.any(Object), }); }); describe('drag\'n\'drop reordering', () => { // eslint-disable-next-line react/prop-types const TableMock = ({ children }) => ( <div> {children} </div> ); const mountWithCellTemplates = ({ defaultOrder, onOrderChange, }, deps = {}) => mount(( <DragDropProvider> <PluginHost> <Template name="table"> <div> <TemplateConnector> {({ tableColumns }) => ( <div> {tableColumns.map(tableColumn => tableColumn.type === TABLE_DATA_TYPE && ( <TemplatePlaceholder key={tableColumn.column.name} name="tableCell" params={{ tableColumn, tableRow: { key: TABLE_REORDERING_TYPE, type: TABLE_REORDERING_TYPE }, }} /> ))} </div> )} </TemplateConnector> </div> </Template> {pluginDepsToComponents(defaultDeps, deps)} <TableColumnReordering {...defaultProps} onOrderChange={onOrderChange} defaultOrder={defaultOrder} tableContainerComponent={props => <TableMock {...props} />} /> </PluginHost> </DragDropProvider> )); beforeEach(() => { orderedColumns.mockImplementation(() => defaultDeps.getter.tableColumns); }); it('should preview column order while dragging', () => { getTableTargetColumnIndex .mockImplementationOnce(() => 1) .mockImplementationOnce(() => 1) .mockImplementationOnce(() => 0); const onOver = mountWithCellTemplates({ defaultOrder: ['a', 'b'] }) .find(TableMock) .prop('onOver'); orderedColumns.mockClear(); onOver({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); expect(draftOrder) .toHaveBeenLastCalledWith(['a', 'b'], 0, 1); onOver({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); expect(draftOrder) .toHaveBeenLastCalledWith(['a', 'b'], 0, 1); expect(orderedColumns) .toHaveBeenCalledTimes(1); getTableTargetColumnIndex.mockImplementationOnce(() => 0); onOver({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); expect(draftOrder) .toHaveBeenLastCalledWith(['a', 'b'], 0, 0); }); it('should revert column order when source moves out', () => { getTableTargetColumnIndex.mockImplementation(() => 1); const { onOver, onLeave } = mountWithCellTemplates({ defaultOrder: ['a', 'b'] }) .find(TableMock) .props(); onOver({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); onLeave({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); expect(orderedColumns) .toHaveBeenLastCalledWith(defaultDeps.getter.tableColumns, ['a', 'b']); }); it('should change column order on drop', () => { getTableTargetColumnIndex.mockImplementation(() => 1); const { onOver, onDrop } = mountWithCellTemplates({ defaultOrder: ['a', 'b'] }) .find(TableMock) .props(); onOver({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); onDrop({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); expect(changeColumnOrder) .toBeCalledWith(['a', 'b'], { sourceColumnName: 'a', targetColumnName: 'b' }); }); it('should not fail while dragging a column when non-data type columns are present', () => { const deps = { getter: { tableColumns: [ ...defaultDeps.getter.tableColumns, { key: 'test_c', type: 'test', column: { name: 'c' } }, ], }, }; orderedColumns.mockImplementation(() => deps.getter.tableColumns); getTableTargetColumnIndex.mockImplementation(() => 1); const onOver = mountWithCellTemplates({ defaultOrder: ['a', 'b'] }) .find(TableMock) .prop('onOver'); expect(() => { onOver({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); }).not.toThrow(); }); it('should preview column order correctly when non-data columns are present', () => { const deps = { getter: { tableColumns: [ { key: 'test_c', type: 'test', column: { name: 'c' } }, ...defaultDeps.getter.tableColumns, ], }, }; orderedColumns.mockImplementation(() => deps.getter.tableColumns); getTableTargetColumnIndex.mockImplementation(() => 1); const onOver = mountWithCellTemplates({ defaultOrder: ['c', 'a', 'b'] }, deps) .find(TableMock) .prop('onOver'); onOver({ payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }); expect(draftOrder) .toHaveBeenLastCalledWith(['c', 'a', 'b'], 1, 2); }); it('should reset cell dimensions after leave and drop events', () => { const onOverArg = { payload: [{ type: 'column', columnName: 'a' }], ...defaultClientOffset }; const { onOver, onLeave, onDrop } = mountWithCellTemplates({ defaultOrder: ['a', 'b'] }) .find(TableMock) .props(); getBoundingClientRect.mockClear(); onOver(onOverArg); onOver(onOverArg); onOver(onOverArg); onLeave(); onOver(onOverArg); onOver(onOverArg); onOver(onOverArg); onDrop(); onOver(onOverArg); onOver(onOverArg); onOver(onOverArg); expect(getBoundingClientRect) .toHaveBeenCalledTimes(defaultDeps.getter.tableColumns.length * 3); }); it('should work correctly if table columns are changed', () => { const changedTableColumns = [ { key: `${TABLE_DATA_TYPE}_a`, type: TABLE_DATA_TYPE, column: { name: 'a' } }, { key: `${TABLE_DATA_TYPE}_c`, type: TABLE_DATA_TYPE, column: { name: 'c' } }, ]; const tree = mount(( <DragDropProvider> <PluginHost> <Template name="table"> {changedTableColumns.map(tableColumn => tableColumn.type === TABLE_DATA_TYPE && ( <TemplatePlaceholder key={tableColumn.column.name} name="tableCell" params={{ tableColumn, tableRow: { key: TABLE_REORDERING_TYPE, type: TABLE_REORDERING_TYPE }, }} /> ))} </Template> {pluginDepsToComponents(defaultDeps)} <TableColumnReordering {...defaultProps} defaultOrder={['a', 'b']} tableContainerComponent={props => <TableMock {...props} />} /> </PluginHost> </DragDropProvider> )); const { cellDimensionGetters } = tree.find(TableColumnReordering).childAt(0).instance(); expect(Object.keys(cellDimensionGetters)).toEqual(['a']); }); it('should not change column order if target is moved from outside', () => { const onOrderChangeMock = jest.fn(); const { onLeave, onDrop } = mountWithCellTemplates( { defaultOrder: ['a', 'b'], onOrderChange: onOrderChangeMock }, ) .find(TableMock) .props(); onLeave(); onDrop(); expect(changeColumnOrder).not.toBeCalled(); expect(onOrderChangeMock).not.toBeCalled(); }); }); });
the_stack
import cp = require('child_process'); import path = require('path'); export var resolve: typeof Promise.resolve = Promise.resolve.bind(Promise); /** * The main function you should call from master */ export function startWorker<TWorker>(config:{ workerPath: string, workerContract: TWorker, masterImplementation: any, /** * We automatially restart the worker if it crashes * After that is done, you can do reinitialization in this if you want */ onCrashRestart?: ()=>any, }): { parent: Parent; worker: TWorker } { var parent = new Parent(); parent.startWorker(config.workerPath, showError, [], config.onCrashRestart || (()=>null)); function showError(error: Error) { if (error) { console.error('Failed to start a worker:', error); } } var worker = parent.sendAllToIpc(config.workerContract); parent.registerAllFunctionsExportedFromAsResponders(config.masterImplementation); return { parent, worker }; } /** * The main function you should call from worker */ export function runWorker<TMaster>(config:{workerImplementation: any, masterContract: TMaster}): { child: Child; master: TMaster } { var child = new Child(); child.registerAllFunctionsExportedFromAsResponders(config.workerImplementation); let master = child.sendAllToIpc(config.masterContract); return { child, master }; } // Parent makes queries<T> // Child responds<T> export interface Message<T> { message: string; id: string; data?: T; error?: { method: string; message: string; stack: string; details: any; }; /** Is this message a request or a response */ request: boolean; } /** Query Response function */ export interface QRFunction<Query, Response> { (query: Query): Promise<Response>; } /** Creates a Guid (UUID v4) */ function createId(): string { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } /** Used by parent and child for keepalive */ var orphanExitCode = 100; class RequesterResponder { /** Must be implemented in children */ protected sendTarget: { (): { send?: <T>(message: Message<T>) => any } }; ///////////////////////////////// REQUESTOR ///////////////////////// private currentListeners: { [message: string]: { [id: string]: PromiseDeferred<any> } } = {}; /** Only relevant when we only want the last of this type */ private currentLastOfType: { [message: string]: { data: any; defer: PromiseDeferred<any>; } } = {}; private pendingRequests: string[] = []; public pendingRequestsChanged = (pending: string[]) => null; /** process a message from the child */ protected processResponse(m: any) { var parsed: Message<any> = m; this.pendingRequests.shift(); this.pendingRequestsChanged(this.pendingRequests.slice()); if (!parsed.message || !parsed.id) { console.log('PARENT ERR: Invalid JSON data from child:', m); } else if (!this.currentListeners[parsed.message] || !this.currentListeners[parsed.message][parsed.id]) { console.log('PARENT ERR: No one was listening:', parsed.message, parsed.data); } else { // Alright nothing *weird* happened if (parsed.error) { this.currentListeners[parsed.message][parsed.id].reject(parsed.error); console.log(parsed.error); console.log(`======================= STACK (${parsed.error.method}) ==========================`); console.log(parsed.error.stack); } else { this.currentListeners[parsed.message][parsed.id].resolve(parsed.data); } delete this.currentListeners[parsed.message][parsed.id]; // If there is current last one queued then that needs to be resurrected if (this.currentLastOfType[parsed.message]) { let last = this.currentLastOfType[parsed.message]; delete this.currentLastOfType[parsed.message]; let lastPromise = this.sendToIpcHeart(last.data, parsed.message); lastPromise.then((res) => last.defer.resolve(res), (rej) => last.defer.reject(rej)); } } } /** * This is used by both the request and the reponse */ private sendToIpcHeart = (data, message) => { // If we don't have a child exit if (!this.sendTarget()) { console.log('PARENT ERR: no child when you tried to send :', message); return <any>Promise.reject(new Error("No worker active to recieve message: " + message)); } // Initialize if this is the first call of this type if (!this.currentListeners[message]) this.currentListeners[message] = {}; // Create an id unique to this call and store the defered against it var id = createId(); const promise = new Promise((resolve,reject)=>{ this.currentListeners[message][id] = { resolve, reject, promise }; }); // Send data to worker this.pendingRequests.push(message); this.pendingRequestsChanged(this.pendingRequests); this.sendTarget().send({ message: message, id: id, data: data, request: true }); return promise; } /** * Send all the member functions to IPC */ sendAllToIpc<TWorker>(contract: TWorker): TWorker { var toret = {} as TWorker; Object.keys(contract).forEach(key => { toret[key] = this.sendToIpc(contract[key], key); }); return toret; } /** * Takes a sync named function * and returns a function that will execute this function by name using IPC * (will only work if the process on the other side has this function as a registered responder) */ sendToIpc<Query, Response>(func: QRFunction<Query, Response>, name?: string): QRFunction<Query, Response> { name = func.name || name; if (!name) { console.error('NO NAME for function', func.toString()); throw new Error('Name not specified for function: \n' + func.toString()); } return (data) => this.sendToIpcHeart(data, name); } /** * If there are more than one pending then we only want the last one as they come in. * All others will get the default value */ sendToIpcOnlyLast<Query, Response>(func: QRFunction<Query, Response>, defaultResponse: Response): QRFunction<Query, Response> { return (data) => { var message = func.name; // If we don't have a child exit if (!this.sendTarget()) { console.log('PARENT ERR: no child when you tried to send :', message); return <any>Promise.reject(new Error("No worker active to recieve message: " + message)); } // Allow if this is the only call of this type if (!Object.keys(this.currentListeners[message] || {}).length) { return this.sendToIpcHeart(data, message); } else { // Note: // The last needs to continue once the current one finishes // That is done in our response handler // If there is already something queued as last. // Then it is no longer last and needs to be fed a default value if (this.currentLastOfType[message]) { this.currentLastOfType[message].defer.resolve(defaultResponse); } // this needs to be the new last const promise = new Promise<Response>((resolve,reject)=>{ this.currentLastOfType[message] = { data: data, defer: {promise,resolve,reject} } }); return promise; } }; } ////////////////////////////////// RESPONDER //////////////////////// private responders: { [message: string]: (query: any) => Promise<any> } = {}; protected processRequest = (m: any) => { var parsed: Message<any> = m; if (!parsed.message || !this.responders[parsed.message]) { // TODO: handle this error scenario. Either the message is invalid or we do not have a registered responder return; } var message = parsed.message; var responsePromise: Promise<any>; try { responsePromise = this.responders[message](parsed.data); } catch (err) { responsePromise = Promise.reject({ method: message, message: err.message, stack: err.stack, details: err.details || {} }); } responsePromise .then((response) => { // console.log('I have the response for:',parsed.message) this.sendTarget().send({ message: message, /** Note: to process a request we just pass the id as we recieve it */ id: parsed.id, data: response, error: null, request: false }); // console.log('I sent the response', parsed.message); }) .catch((error) => { this.sendTarget().send({ message: message, /** Note: to process a request we just pass the id as we recieve it */ id: parsed.id, data: null, error: error, request: false }); }); } private addToResponders<Query, Response>(func: (query: Query) => Promise<Response>, name?: string) { name = func.name || name; if (!name) { console.error('NO NAME for function', func.toString()); throw new Error('Name not specified for function: \n' + func.toString()); } this.responders[name] = func; } registerAllFunctionsExportedFromAsResponders(aModule: any) { Object.keys(aModule) .filter((funcName) => typeof aModule[funcName] == 'function') .forEach((funcName) => this.addToResponders(aModule[funcName], funcName)); } } /** The parent */ export class Parent extends RequesterResponder { private child: cp.ChildProcess; private node = process.execPath; /** If we get this error then the situation if fairly hopeless */ private gotENOENTonSpawnNode = false; protected sendTarget = () => this.child; private stopped = false; /** start worker */ startWorker( childJsPath: string, terminalError: (e: Error) => any, customArguments: string[] = [], onCrashRestart: () => any ) { try { const fileName = path.basename(childJsPath); this.child = cp.fork( childJsPath, customArguments, { cwd: path.dirname(childJsPath), env: process.env } ); this.child.on('error', (error) => { const err = error as any; if (err.code === "ENOENT" && err.path === this.node) { this.gotENOENTonSpawnNode = true; } console.log('CHILD ERR ONERROR:', err.message, err.stack, err); this.child = null; }); this.child.on('message', (message: Message<any>) => { // console.log('PARENT: A child asked me', message.message) if (message.request) { this.processRequest(message); } else { this.processResponse(message); } }); this.child.on('close', (code) => { if (this.stopped) { return; } // Handle process dropping // If orphaned then Definitely restart if (code === orphanExitCode) { this.startWorker(childJsPath, terminalError, customArguments, onCrashRestart); onCrashRestart(); } // If we got ENOENT. Restarting will not help. else if (this.gotENOENTonSpawnNode) { terminalError(new Error('gotENOENTonSpawnNode')); } // We haven't found a reson to not start worker yet else { console.log(`${fileName} worker restarting. Don't know why it stopped with code:`, code); this.startWorker(childJsPath, terminalError, customArguments, onCrashRestart); onCrashRestart(); } }); } catch (err) { terminalError(err); } } /** stop worker */ stopWorker() { this.stopped = true; if (!this.child) return; try { this.child.kill('SIGTERM'); } catch (ex) { console.error('failed to kill worker child'); } this.child = null; } } export class Child extends RequesterResponder { protected sendTarget = () => process; private connected = true; constructor() { super(); // Keep alive this.keepAlive(); process.on('exit', () => this.connected = false); // Start listening process.on('message', (message: Message<any>) => { // console.error('--------CHILD: parent told me :-/', message.message) if (message.request) { this.processRequest(message); } else { this.processResponse(message); } }); } /** keep the child process alive while its connected and die otherwise */ private keepAlive() { setInterval(() => { // We have been orphaned if (!this.connected) { process.exit(orphanExitCode); } }, 1000); } }
the_stack
import _defaultsDeep from 'lodash.defaultsdeep'; import { DeepPartial, NotInitializedError, OperatingSystemDetector, VoidListener } from '..'; import { EventListenerMap, TypedEventEmitter } from '../utilities/TypedEventEmitter'; interface AudioRecorderNodes { inputStream?: MediaStreamAudioSourceNode; analyser?: AnalyserNode; inputGain?: GainNode; processor?: ScriptProcessorNode; destination?: AudioDestinationNode; } export interface AudioRecorderResult { data: Float32Array; sampleRate: number; } export interface AudioRecorderProcessingData { bufferLength: number; data: Uint8Array; } export enum AudioRecorderEvent { Start = 'start', Processing = 'processing', StartDetected = 'start-detected', SilenceDetected = 'silenced-detected', Timeout = 'timeout', Abort = 'abort', Stop = 'stop', } export interface AudioRecorderEventListenerMap extends EventListenerMap { [AudioRecorderEvent.Stop]: (result: AudioRecorderResult) => void; [AudioRecorderEvent.Processing]: (data: AudioRecorderProcessingData) => void; [AudioRecorderEvent.Start]: VoidListener; [AudioRecorderEvent.Abort]: VoidListener; [AudioRecorderEvent.StartDetected]: VoidListener; [AudioRecorderEvent.SilenceDetected]: VoidListener; [AudioRecorderEvent.Timeout]: VoidListener; } export interface AudioRecorderDetectionConfig { enabled: boolean; /** Value between 0 and 1 */ threshold: number; timeoutInMs: number; } export interface AudioRecorderAnalyserConfig extends Required<Omit<AnalyserOptions, keyof AudioNodeOptions | 'fftSize'>> { bufferSize: number; } export interface AudioRecorderConfig { sampleRate: number; audioConstraints: MediaTrackConstraints; analyser: AudioRecorderAnalyserConfig; startDetection: AudioRecorderDetectionConfig; silenceDetection: AudioRecorderDetectionConfig; } export class AudioRecorder extends TypedEventEmitter<AudioRecorderEventListenerMap> { static getDefaultConfig(): AudioRecorderConfig { return { sampleRate: 16000, audioConstraints: { echoCancellation: true, noiseSuppression: true, }, analyser: { bufferSize: 2048, maxDecibels: -10, minDecibels: -90, smoothingTimeConstant: 0.85, }, startDetection: { enabled: true, timeoutInMs: 3000, threshold: 0.2, }, silenceDetection: { enabled: true, timeoutInMs: 1500, threshold: 0.2, }, }; } readonly config: AudioRecorderConfig; private readonly audioNodes: AudioRecorderNodes = {}; private audioContext: AudioContext | null = null; private mediaStream: MediaStream | null = null; private initialized = false; private recording = false; private recordingStartedAt?: Date; private startThresholdPassed = false; private chunks: Float32Array[] = []; private chunkLength = 0; constructor(config?: DeepPartial<AudioRecorderConfig>) { super(); window.AudioContext = window.AudioContext || window.webkitAudioContext; const defaultConfig = AudioRecorder.getDefaultConfig(); this.config = config ? _defaultsDeep(config, defaultConfig) : defaultConfig; } get isInitialized(): boolean { return this.initialized; } get isRecording(): boolean { return this.recording; } get startDetectionEnabled(): boolean { return !!( this.config.startDetection.enabled && this.config.startDetection.threshold && this.config.startDetection.timeoutInMs ); } get silenceDetectionEnabled(): boolean { return !!( this.config.silenceDetection.enabled && this.config.silenceDetection.threshold && this.config.silenceDetection.timeoutInMs ); } /** * Initialize the AudioRecorder. This needs to be called synchronously in a click-event handler for Safari in order to properly work. */ initialize(): void { if (this.initialized) { return; } this.checkForBrowserCompatibility(); const ctx = new AudioContext(); this.audioNodes.inputGain = ctx.createGain(); const analyser = ctx.createAnalyser(); analyser.minDecibels = this.config.analyser.minDecibels; analyser.maxDecibels = this.config.analyser.maxDecibels; analyser.smoothingTimeConstant = this.config.analyser.smoothingTimeConstant; this.audioNodes.analyser = analyser; this.audioNodes.processor = ctx.createScriptProcessor(); this.audioNodes.processor.onaudioprocess = this.doProcessing.bind(this); this.audioNodes.destination = ctx.destination; this.audioContext = ctx; this.initialized = true; } async start(): Promise<void> { this.checkForInitialization(); if (this.recording) { return; } this.checkForBrowserCompatibility(); if (OperatingSystemDetector.isWindows()) { if (!this.mediaStream) { this.mediaStream = await this.getUserMediaStream(); } return this.startRecording(this.mediaStream!); } const stream = await this.getUserMediaStream(); return this.startRecording(stream); } stop(): void { this.checkForInitialization(); if (!this.recording) { return; } this.stopRecording(); const data = this.mergeChunks(this.chunks, this.chunkLength); const result: AudioRecorderResult = { data, sampleRate: this.config.sampleRate, }; this.emit(AudioRecorderEvent.Stop, result); } abort(): void { this.checkForInitialization(); if (!this.recording) { return; } this.stopRecording(); this.emit(AudioRecorderEvent.Abort); } private startRecording(stream: MediaStream) { if (!this.audioContext) { throw new NotInitializedError('AudioRecorder'); } this.chunks = []; this.chunkLength = 0; this.startThresholdPassed = false; this.mediaStream = stream; const nodes = this.audioNodes as Required<AudioRecorderNodes>; nodes.inputStream = this.audioContext.createMediaStreamSource(stream); this.audioContext = nodes.inputStream.context as AudioContext; this.config.sampleRate = this.audioContext.sampleRate; nodes.inputStream.connect(nodes.inputGain); nodes.inputGain.gain.setValueAtTime(1.0, this.audioContext.currentTime); nodes.inputGain.connect(nodes.analyser); nodes.inputGain.connect(nodes.processor); nodes.processor.connect(nodes.destination); this.recordingStartedAt = new Date(); this.recording = true; if (this.startDetectionEnabled) { this.initializeStartDetection(); } this.emit(AudioRecorderEvent.Start); } private initializeStartDetection() { setTimeout(() => { if (!this.startThresholdPassed && this.startDetectionEnabled) { this.onTimeout(); } }, this.config.startDetection.timeoutInMs); } private stopRecording() { this.audioNodes.processor?.disconnect(); this.audioNodes.analyser?.disconnect(); this.audioNodes.inputGain?.disconnect(); this.audioNodes.inputStream?.disconnect(); if (this.mediaStream && !OperatingSystemDetector.isWindows) { this.mediaStream.getTracks().forEach((track) => { track.stop(); }); this.mediaStream = null; } this.recording = false; } private onTimeout() { if (!this.recording) { return; } this.stopRecording(); this.emit(AudioRecorderEvent.Timeout); } private doProcessing(evt: AudioProcessingEvent) { if (!this.recording) { return; } this.chunks.push(new Float32Array(evt.inputBuffer.getChannelData(0))); this.chunkLength += this.audioNodes.processor!.bufferSize; const analyser = this.audioNodes.analyser as AnalyserNode; analyser.fftSize = this.audioNodes.processor!.bufferSize; const bufferLength = analyser.frequencyBinCount; const data = new Uint8Array(bufferLength); analyser.getByteTimeDomainData(data); const eventData: AudioRecorderProcessingData = { bufferLength, data, }; this.emit(AudioRecorderEvent.Processing, eventData); if (this.startDetectionEnabled && !this.startThresholdPassed) { return this.detectStart(bufferLength, data); } if (this.silenceDetectionEnabled && this.startThresholdPassed) { return this.detectSilence(bufferLength, data); } } private detectStart(bufferLength: number, data: Uint8Array) { for (let i = 0; i < bufferLength; i++) { const current = data[i] / 128 - 1.0; if (this.startThresholdPassed) { return; } if ( current >= this.config.startDetection.threshold || current <= -1 * this.config.startDetection.threshold ) { this.startThresholdPassed = true; this.emit(AudioRecorderEvent.StartDetected); return; } } } private detectSilence(bufferLength: number, data: Uint8Array) { for (let i = 0; i < bufferLength; i++) { // normalize const current = data[i] / 128 - 1.0; if ( current > this.config.silenceDetection.threshold || current < -1 * this.config.silenceDetection.threshold ) { this.recordingStartedAt = new Date(); } } const newTime = new Date(); const elapsedTime = newTime.getTime() - (this.recordingStartedAt?.getTime() || newTime.getTime()); if (elapsedTime > this.config.silenceDetection.timeoutInMs) { this.emit(AudioRecorderEvent.SilenceDetected); this.stop(); } } private mergeChunks(chunks: Float32Array[], chunkLength: number): Float32Array { const merged = new Float32Array(chunkLength); let offset = 0; for (const chunk of chunks) { merged.set(chunk, offset); offset += chunk.length; } return merged; } private checkForInitialization() { if (!this.initialized) { throw new NotInitializedError('AudioRecorder'); } } private checkForBrowserCompatibility() { // if (location.hostname !== 'localhost' && location.protocol !== 'https:') { // throw new Error('Recording is only allowed on https-sites except for localhost.'); // } if (!navigator || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { throw new Error( '`navigator.mediaDevices.getUserMedia` is not available - recording is not supported', ); } } private getUserMediaStream(): Promise<MediaStream> { return navigator.mediaDevices.getUserMedia({ audio: this.config.audioConstraints, }); } }
the_stack
import ChainedPromise from '../src/index'; describe('ChainedPromise', function() { describe('createPromiseCallbackPair', function() { it('creates ChainedPromise and callback functions', function(done) { const dataCollected: Array<number> = []; const [promise, callback] = ChainedPromise.createPromiseCallbackPair<number>(); callback(1); callback(2); callback(3); promise .forEach((v) => { dataCollected.push(v.data); if (dataCollected.length === 3) { expect(dataCollected).toEqual([1, 2, 3]); done(); } }) .catch(done); }); }); it('creates error function which rejectes the promise', function(done) { const dataCollected: Array<number> = []; const [promise, callback, error] = ChainedPromise.createPromiseCallbackPair<number>(); callback(1); callback(2); error('Error!'); promise .forEach(({data}) => { dataCollected.push(data); }) .catch((err) => { expect(dataCollected).toEqual([1, 2]); expect(err).toEqual('Error!'); done(); }); }); describe('forEach', function() { it('runs function on each value', function(done) { const dataCollected: Array<number> = []; const thirdPromise = Promise.resolve({data: 3, next: {[ChainedPromise.DONE]: 'done'}}); const secondPromise = Promise.resolve({data: 2, next: thirdPromise}); const testChainedPromise = new ChainedPromise<{data: number}>((resolver) => { resolver({data: 1, next: secondPromise}); }); testChainedPromise .forEach((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([1, 2, 3]); done(); }) .catch(done); }); }); it('bubbles up error', function(done) { const dataCollected: Array<number> = []; const testChainedPromise = ChainedPromise.from(Promise.resolve({ data: 1, next: Promise.resolve({data: 2, next: Promise.reject('Error!')}) })); testChainedPromise .forEach(({data}) => { dataCollected.push(data); }) .catch((err) => { expect(dataCollected).toEqual([1, 2]); expect(err).toEqual('Error!'); done(); }); }); describe('flatMap', function() { it('composes flat map functions', function(done) { const addOnePromise = function(v) { return Promise.resolve(Object.assign(v, {data: v.data + 1})); }; const doublePromise = function(v) { return Promise.resolve(Object.assign(v, {data: v.data * 2})); }; const dataCollected: Array<number> = []; const thirdPromise = Promise.resolve({data: 3, next: {[ChainedPromise.DONE]: 'done'}}); const secondPromise = Promise.resolve({data: 2, next: thirdPromise}); const testChainedPromise = new ChainedPromise((resolver) => { resolver({data: 1, next: secondPromise}); }); testChainedPromise.flatMap(addOnePromise) .flatMap(doublePromise) .forEach((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([4, 6, 8]); done(); }) .catch(done); }); }); describe('map', function() { it('composes map functions', function(done) { const addOneFunction = (v) => Object.assign(v, {data: v.data + 1}); const doubleFunction = (v) => Object.assign(v, {data: v.data * 2}); const dataCollected: Array<number> = []; const thirdPromise = Promise.resolve({data: 3, next: {[ChainedPromise.DONE]: 'done'}}); const secondPromise = Promise.resolve({data: 2, next: thirdPromise}); const testChainedPromise = new ChainedPromise((resolver) => { resolver({data: 1, next: secondPromise}); }); testChainedPromise.map(addOneFunction) .map(doubleFunction) .forEach((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([4, 6, 8]); done(); }) .catch(done); }); }); describe('then', function() { it('bypasses composition when registering reject handler only', function(done) { const testChainedPromise = new ChainedPromise<number>((resolver) => { resolver(1); }); testChainedPromise.flatMap((v) => Promise.resolve(v * 2)); testChainedPromise.then(undefined, console.error); testChainedPromise.then((v) => { expect(v).toEqual(2); // i.e. flatMapped function should have been // invoked only once. done(); }); }); }); describe('accumulate', function() { it('accumulates values', function(done) { const dataCollected: Array<number> = []; const thirdPromise = Promise.resolve({data: 3, next: {[ChainedPromise.DONE]: 'done'}}); const secondPromise = Promise.resolve({data: 2, next: thirdPromise}); const testChainedPromise = new ChainedPromise((resolver) => { resolver({data: 1, next: secondPromise}); }); testChainedPromise .accumulate( (prevSum, newValue) => { return Promise.resolve(Object.assign( newValue, {data: prevSum.data + newValue.data})); }, {data: 0}) .forEach((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([1, 3, 6]); done(); }) .catch(done); }); }); describe('join', function() { it('extracts field', function(done) { type raw = {name: string, ref: number}; type joined = {name: string, ref: string}; const dataCollected: Array<joined> = []; const secondPromise = new ChainedPromise<{data: raw}>((resolver) => { resolver({ data: {name: 'Test Person 2', ref: 43}, next: {[ChainedPromise.DONE]: 'done'} }); }); const testChainedPromise = new ChainedPromise<{data: raw}>((resolver) => { resolver({data: {name: 'Test Person', ref: 42}, next: secondPromise}); }); testChainedPromise .join<{data: joined}>( {data: {ref: (v) => new Promise((res) => res('Reference ' + v))}}) .forEach<string>((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([ {name: 'Test Person', ref: 'Reference 42'}, {name: 'Test Person 2', ref: 'Reference 43'} ]); done(); }) .catch(done); }); it('supports multiple fields', function(done) { type raw = {name: string, book: {ref: number}, car: {ref: number}}; type joined = {name: string, book: {ref: string}, car: {ref: string}}; const dataCollected: Array<joined> = []; const testChainedPromise = new ChainedPromise<{data: raw}>((resolver) => { resolver({ data: {name: 'Test Person', book: {ref: 42}, car: {ref: 43}}, next: {[ChainedPromise.DONE]: 'done'} }); }); testChainedPromise .join<{data: joined}>({ data: { book: { ref: (v) => new Promise((res) => res('Book reference ' + v)) }, car: { ref: (v) => new Promise((res) => res('Car reference ' + v)) } } }) .forEach<string>((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([{ name: 'Test Person', book: {ref: 'Book reference 42'}, car: {ref: 'Car reference 43'} }]); done(); }) .catch(done); }); it('maps array of values', function(done) { type raw = {name: string, book: {ref: number}, car: {ref: number}}; type joined = {name: string, book: {ref: string}, car: {ref: string}}; const dataCollected: Array<joined> = []; const secondPromise = new ChainedPromise<{data: raw}>((resolver) => { resolver({ data: {name: 'Test Person 2', ref: [44, 45]}, next: {[ChainedPromise.DONE]: 'done'} }); }); const testChainedPromise = new ChainedPromise((resolver) => { resolver( {data: {name: 'Test Person', ref: [42, 43]}, next: secondPromise}); }); testChainedPromise .join<{data: joined}>({ data: {ref: [(v) => new Promise((res) => res('Reference ' + v))]} }) .forEach((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([ {name: 'Test Person', ref: ['Reference 42', 'Reference 43']}, {name: 'Test Person 2', ref: ['Reference 44', 'Reference 45']} ]); done(); }) .catch(done); }); it('supports object specification inside an array', function(done) { type raw = {name: string, book: [{ref: number}], car: [{ref: number}]}; type joined = {name: string, book: [{ref: string}], car: [{ref: string}]}; const dataCollected: Array<joined> = []; const secondPromise = new ChainedPromise((resolver) => { resolver({ data: {name: 'Test Person 2', refs: [{book: 44}, {book: 45}]}, next: {[ChainedPromise.DONE]: 'done'} }); }); const testChainedPromise = new ChainedPromise<{data: raw}>((resolver) => { resolver({ data: {name: 'Test Person', refs: [{book: 42}, {book: 43}]}, next: secondPromise }); }); testChainedPromise .join<{data: joined}>({ data: { refs: [ {book: (v) => new Promise((res) => res('Reference ' + v))} ] } }) .forEach<string>((v) => { dataCollected.push(v.data); }) .then((v) => { expect(v).toEqual('done'); expect(dataCollected).toEqual([ { name: 'Test Person', refs: [{book: 'Reference 42'}, {book: 'Reference 43'}] }, { name: 'Test Person 2', refs: [{book: 'Reference 44'}, {book: 'Reference 45'}] } ]); done(); }) .catch(done); }); it('throws when the given spec is illegal', function(done) { const testChainedPromise = new ChainedPromise((resolver) => { resolver({ data: {name: 'Test Person', ref: 42}, next: {[ChainedPromise.DONE]: 'done'} }); }); testChainedPromise.join({data: {name: 'hello'}}) .then((v) => { done(v); }) .catch(() => { done(); }); }); }); describe('collect', function() { it('collects result in an array', function(done) { const thirdPromise = Promise.resolve({data: 3, next: {[ChainedPromise.DONE]: 'done'}}); const secondPromise = Promise.resolve({data: 2, next: thirdPromise}); const testChainedPromise = new ChainedPromise<{data: number}>((resolver) => { resolver({data: 1, next: secondPromise}); }); testChainedPromise.collect<{data: number}, string>() .then((result) => { expect((result[0] as {data: number}).data).toEqual(1); expect((result[1] as {data: number}).data).toEqual(2); expect((result[2] as {data: number}).data).toEqual(3); expect(result[3]).toEqual('done'); expect(result.length).toEqual(4); done(); }) .catch(done); }); it('transforms data before collecting into an array', function(done) { const thirdPromise = Promise.resolve({data: 3, next: {[ChainedPromise.DONE]: 'done'}}); const secondPromise = Promise.resolve({data: 2, next: thirdPromise}); const testChainedPromise = new ChainedPromise<{data: number}>((resolver) => { resolver({data: 1, next: secondPromise}); }); testChainedPromise.collect<number, string>((v) => v.data) .then((result) => { expect(result).toEqual([1, 2, 3, 'done']); done(); }) .catch(done); }); }); describe('filter', () => { it('skips data', (done) => { const thirdPromise = Promise.resolve({data: 3, next: {[ChainedPromise.DONE]: 'done'}}); const secondPromise = Promise.resolve({data: 2, next: thirdPromise}); const testChainedPromise = new ChainedPromise<{data: number}>((resolver) => { resolver({data: 1, next: secondPromise}); }); testChainedPromise .map((v) => ({...v, data: v.data + 1})) // [2, 3, 4] .filter((v) => v.data % 2 == 0) // [2, 4] .map((v) => ({...v, data: v.data * 2})) // [4, 8] .collect<{data: number}, string>() .then((result) => { expect((result[0] as {data: number}).data).toEqual(4); expect((result[1] as {data: number}).data).toEqual(8); expect(result[2]).toEqual('done'); expect(result.length).toEqual(3); done(); }); }); }); });
the_stack
import ko = require('knockout'); import $ = require('jquery'); import chitu = require('chitu'); export let config = { imageBaseUrl: '', storeName: '', ajaxTimeoutSeconds: 10 } //===================================================================== // 说明:实现数据格式化 Number.prototype['toFormattedString'] = function (format) { var reg = new RegExp('^C[0-9]+'); if (reg.test(format)) { var num = format.substr(1); return this.toFixed(num); } return this; }; Date.prototype['toFormattedString'] = function (format) { switch (format) { case 'd': return chitu.Utility.format("{0}-{1}-{2}", this.getFullYear(), this.getMonth() + 1, this.getDate()); case 'g': return chitu.Utility.format("{0}-{1}-{2} {3}:{4}", this.getFullYear(), this.getMonth() + 1, this.getDate(), this.getHours(), this.getMinutes()); case 'G': return chitu.Utility.format("{0}-{1}-{2} {3}:{4}:{5}", this.getFullYear(), this.getMonth() + 1, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()); case 't': return chitu.Utility.format("{0}:{1}", this.getHours(), this.getMinutes()); case 'T': return chitu.Utility.format("{0}:{1}:{2}", this.getHours(), this.getMinutes(), this.getSeconds()); } return this.toString(); }; var formatString = function (useLocale, args) { //TODO: 验证数组 for (var i = 1; i < args.length; i++) { args[i] = ko.unwrap(args[i]); } var result = ''; var format = args[0]; for (var i = 0; ;) { var open = format.indexOf('{', i); var close = format.indexOf('}', i); if ((open < 0) && (close < 0)) { result += format.slice(i); break; } if ((close > 0) && ((close < open) || (open < 0))) { if (format.charAt(close + 1) !== '}') { throw new Error('format,Sys.Res.stringFormatBraceMismatch'); } result += format.slice(i, close + 1); i = close + 2; continue; } result += format.slice(i, open); i = open + 1; if (format.charAt(i) === '{') { result += '{'; i++; continue; } if (close < 0) throw new Error('format,Sys.Res.stringFormatBraceMismatch'); var brace = format.substring(i, close); var colonIndex = brace.indexOf(':'); var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1; if (isNaN(argNumber)) throw new Error('format,Sys.Res.stringFormatInvalid'); var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1); var arg = args[argNumber]; if (typeof (arg) === "undefined" || arg === null) { arg = ''; } if (arg.toFormattedString) { result += arg.toFormattedString(argFormat); } else if (useLocale && arg.localeFormat) { result += arg.localeFormat(argFormat); } else if (arg.format) { result += arg.format(argFormat); } else result += arg.toString(); i = close + 1; } return result; } var money = function (element, valueAccessor) { var str; var value = valueAccessor(); if (value < 0) { str = formatString(true, ['-¥{0:C2}', Math.abs(value)]); } else { str = formatString(true, ['¥{0:C2}', value]); } element.innerHTML = str; }; ko.bindingHandlers['money'] = { init: function (element, valueAccessor) { money(element, valueAccessor); }, update: function (element, valueAccessor) { money(element, valueAccessor); } }; var text = function (element: HTMLElement, valueAccessor) { var value = valueAccessor(); var str = $.isArray(value) ? formatString(true, value) : ko.unwrap(value); //debugger; element.innerText = str; //ko.utils.setTextContent(element, str); } ko.bindingHandlers.text = { init: function (element, valueAccessor) { return text(element, valueAccessor); }, update: function (element, valueAccessor) { return text(element, valueAccessor); } }; var href = function (element, valueAccessor) { var value = valueAccessor(); if ($.isArray(value)) { var str = formatString(true, value); $(element).attr('href', str); } else { $(element).attr('href', value); } }; ko.bindingHandlers['href'] = { init: function (element, valueAccessor) { href(element, valueAccessor); }, update: function (element, valueAccessor) { href(element, valueAccessor); } }; //=============================================================================== //=============================================================================== // 说明:实现对话框 var ToastDialogHtml = '<div class="modal fade"> \ <div class="modal-dialog"> \ <div class="modal-content"> \ <div class="modal-body"> \ <h5 data-bind="html:text"></h5> \ </div> \ </div> \ </div> \ </div>'; var ConfirmDialogHtml = '<div class="modal fade"> \ <div class="modal-dialog"> \ <div class="modal-content"> \ <div class="modal-body"> \ <h5 data-bind="html:text"></h5> \ </div> \ <div class="modal-footer"> \ <button data-bind="click:cancel" type="button" class="btn btn-default" data-dismiss="modal">取消</button> \ <button data-bind="click:ok" type="button" class="btn btn-primary">确认</button> \ </div> \ </div> \ </div> \ </div>'; function getDialogConfig(element, name) { var dlg = $(element).attr(name); var config; if (dlg) { config = eval('(function(){return {' + dlg + '};})()'); } else { config = {}; } return config; } function translateClickAccessor(element, valueAccessor, allBindings, viewModel, bindingContext) { var value = ko.unwrap(valueAccessor()); if (value == null) { return valueAccessor; } return $.proxy(function () { var element = this._element; var valueAccessor = this._valueAccessor; var allBindings = this._allBindings; var viewModel = this._viewModel; var bindingContext = this._bindingContext; var value = this._value; return function (viewModel) { var deferred: JQueryPromise<any> = $.Deferred<any>().resolve(); var dialog_config = getDialogConfig(element, 'data-dialog'); if (dialog_config.confirm) { var content = dialog_config.confirm; deferred = deferred.pipe(function () { var result = $.Deferred(); var html = ConfirmDialogHtml; var node = $(html).appendTo(document.body)['modal']()[0]; var model = { text: content, ok: function () { $(node)['modal']('hide'); result.resolve(); }, cancel: function () { result.reject(); } } ko.applyBindings(model, node); return result; }); } deferred = deferred.pipe(function () { var result = $.isFunction(value) ? (<Function>value).apply(viewModel, [viewModel, event]) : value; if (result && $.isFunction(result.always)) { $(element).attr('disabled', 'disabled'); $(element).addClass('disabled'); result.element = element; result.always(function () { $(element).removeAttr('disabled'); $(element).removeClass('disabled'); }); //=============================================== // 超时去掉按钮禁用,防止 always 不起作用。 setTimeout($.proxy(function () { $(this._element).removeAttr('disabled'); $(this._element).removeClass('disabled'); }, { _element: element }), 1000 * config.ajaxTimeoutSeconds); //=============================================== result.done(function () { if (dialog_config.toast) { var content = dialog_config.toast; var html = ToastDialogHtml; var node = $(html).appendTo(document.body)['modal']()[0]; var model = { text: content } window.setTimeout(function () { $(node)['modal']('hide'); $(node).remove(); }, 1000); ko.applyBindings(model, node); } }); } return result; }); return deferred; }; }, { _element: element, _valueAccessor: valueAccessor, _allBindings: allBindings, _viewModel: viewModel, _bindingContext: bindingContext, _value: value }); } var _click = ko.bindingHandlers.click; ko.bindingHandlers.click = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { valueAccessor = translateClickAccessor(element, valueAccessor, allBindings, viewModel, bindingContext); return _click.init(element, valueAccessor, allBindings, viewModel, bindingContext); } }; //=============================================================================== //=============================================================================== // 说明:处理图片的懒加载。 // TODO:在窗口内的图片才显示,使用 getClientRects 或 getBoundingClientRect 可以获得图片的位置,或 jquery offset。 function getImageUrl(src) { // 说明:替换图片路径 if (src.substr(0, 1) == '/') { src = config.imageBaseUrl + src; } return src; } function getPreviewImage(img_width, img_height) { var scale = (img_height / img_width).toFixed(2); var img_name = 'img_log' + scale; var img_src = localStorage.getItem(img_name); if (img_src) return img_src; var MAX_WIDTH = 320; var width = MAX_WIDTH; var height = width * new Number(scale).valueOf(); var canvas = document.createElement('canvas'); canvas.width = width; //img_width; canvas.height = height; //img_height; var ctx = canvas.getContext('2d'); ctx.fillStyle = 'whitesmoke'; ctx.fillRect(0, 0, canvas.width, canvas.height); // 设置字体 ctx.font = "Bold 40px Arial"; // 设置对齐方式 ctx.textAlign = "left"; // 设置填充颜色 ctx.fillStyle = "#999"; // 设置字体内容,以及在画布上的位置 ctx.fillText(config.storeName, canvas.width / 2 - 75, canvas.height / 2); img_src = canvas.toDataURL('/png'); localStorage.setItem(img_name, img_src); return img_src; } var _attr = ko.bindingHandlers.attr; ko.bindingHandlers.attr = (function () { return { 'update': function (element, valueAccessor, allBindings) { var result = _attr.update(element, valueAccessor, allBindings); if (element.tagName == 'IMG') { var value = ko.utils.unwrapObservable(valueAccessor()) || {}; ko.utils['objectForEach'](value, function (attrName, attrValue) { var src = ko.unwrap(attrValue); if (attrName == 'src' && src != null) { processImageElement(element); return false; } }); } return result; } } })(); function processImageElement(element: HTMLElement) { var PREVIEW_IMAGE_DEFAULT_WIDTH = 200; var PREVIEW_IMAGE_DEFAULT_HEIGHT = 200; var src = $(element).attr('src'); $(element).addClass('img-full'); var img_width = PREVIEW_IMAGE_DEFAULT_WIDTH; var img_height = PREVIEW_IMAGE_DEFAULT_HEIGHT; var match = src.match(/_\d+_\d+/); if (match && match.length > 0) { var arr = match[0].split('_'); img_width = new Number(arr[1]).valueOf(); img_height = new Number(arr[2]).valueOf(); } $(element).attr('width', img_width + 'px'); $(element).attr('height', img_height + 'px'); var src_replace = getPreviewImage(img_width, img_height); $(element).attr('src', src_replace); var image = new Image(); image['element'] = element; image['updateScrollView'] = match == null || match.length == 0; image.onload = function () { $(this['element']).attr('src', (this as HTMLImageElement).src); if (image['updateScrollView'] == true) tryUpdateScrollView(this['element']); }; image.src = getImageUrl(src); } var _html = ko.bindingHandlers.html; ko.bindingHandlers.html = { 'update': function (element, valueAccessor, allBindings) { var result = _html.update(element, valueAccessor, allBindings); var $img = $(element).find('img'); $img.each(function () { processImageElement(this); }); return result; } } //=============================================================================== // 说明:实现 IScrollView 的刷新 var html_update = ko.bindingHandlers.html.update; ko.bindingHandlers.html.update = function (element, valueAccessor, allBindings) { var result = html_update.apply(ko.bindingHandlers.html, [element, valueAccessor, allBindings]); tryUpdateScrollView(element); return result; } var foreach_update = ko.bindingHandlers.foreach.update; ko.bindingHandlers.foreach.update = function (element, valueAccessor, allBindings, viewModel, bindingContext) { tryUpdateScrollView(element); var result = foreach_update.apply(ko.bindingHandlers.foreach, [element, valueAccessor, allBindings, viewModel, bindingContext]); return result; } var visible_update = ko.bindingHandlers.visible.update; ko.bindingHandlers.visible.update = function (element, valueAccessor) { tryUpdateScrollView(element); var result = visible_update.apply(ko.bindingHandlers.visible, [element, valueAccessor]); return result; } function tryUpdateScrollView(element: HTMLElement) { if (element == null) new Error('Argument element is null.'); var $scroll_view = $(element).parents('scroll-view'); if ($scroll_view.length > 0) { var scroll_view = <any>$scroll_view.data('control'); if (scroll_view instanceof chitu.IScrollView) { refreshScrollView(<chitu.IScrollView>scroll_view); } } } function refreshScrollView(scroll_view: chitu.IScrollView) { var timeid = <any>$(scroll_view.element).data('timeid'); if (timeid != null) { window.clearTimeout(<number>timeid); } timeid = window.setTimeout(function () { scroll_view.refresh(); }, 60); $(scroll_view.element).data('timeid', timeid); } ko.bindingHandlers['tap'] = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { valueAccessor = translateClickAccessor(element, valueAccessor, allBindings, viewModel, bindingContext); $(element).on("tap", $.proxy(function (event) { this._valueAccessor()(viewModel, event); }, { _valueAccessor: valueAccessor })); } }
the_stack
import * as React from 'react'; // Custom styles import styles from './OneDriveTab.module.scss'; // Office Fabric import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog'; import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/components/Button'; import { Spinner } from 'office-ui-fabric-react/lib/Spinner'; import { FocusZone } from 'office-ui-fabric-react/lib/FocusZone'; import { List, IPageProps } from 'office-ui-fabric-react/lib/List'; import { css, IRenderFunction, IRectangle } from 'office-ui-fabric-react/lib/Utilities'; import { SelectionZone } from 'office-ui-fabric-react/lib/Selection'; import { Breadcrumb, IBreadcrumbItem } from 'office-ui-fabric-react/lib/Breadcrumb'; import { CommandBar, ICommandBarItemProps } from 'office-ui-fabric-react/lib/CommandBar'; import { IContextualMenuItem } from 'office-ui-fabric-react/lib/ContextualMenu'; import { DetailsList, DetailsListLayoutMode, Selection, SelectionMode, IColumn, IDetailsRowProps, DetailsRow } from 'office-ui-fabric-react/lib/DetailsList'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; // Used to read JSON string as JSON import { unescape } from '@microsoft/sp-lodash-subset'; // Custom props and states import { IOneDriveTabProps, IOneDriveTabState, IOneDriveFile, ViewType } from './OneDriveTab.types'; // Localized resources import * as strings from 'PropertyPaneFilePickerStrings'; // Used to get OneDrive data import { IGetListDataAsStreamResult, IRow, IParentFolderInfo } from '../../../services/OneDriveServices/IGetListDataAsStreamResult'; import { OneDriveServices, IDimensions } from '../../../services/OneDriveServices'; // Used to render custom tiles import { FolderTile } from './FolderTile/FolderTile'; import { DocumentTile } from './DocumentTile/DocumentTile'; import { FormatBytes, GetAbsoluteDomainUrl } from '../../../CommonUtils'; /** * Rows per page */ const ROWS_PER_PAGE: number = 3; /** * Maximum row height */ const MAX_ROW_HEIGHT: number = 250; /** * Maximum number of cells per page */ const CELLS_PER_PAGE: number = 100; /** * Standard tile margin */ const STANDARD_TILE_MARGIN: number = 4; /** * Standard left and right padding */ const TILE_HORZ_PADDING: number = 32; /** * Standard bottom margin */ const BOTTOM_MARGIN: number = 36; const LAYOUT_STORAGE_KEY: string = 'comparerOneDriveLayout'; /** * This tab uses a different approach than the SiteFilePickerTab because, * unlike it, all requests are made to a separate site collection and separate domain. * Unfortuntely, we couldn't use the PnP libraries to make the API calls * and had to use RemoteWeb to allow retrieving content across domains. * */ export default class OneDriveTab extends React.Component<IOneDriveTabProps, IOneDriveTabState> { private _columnCount: number; private _columnWidth: number; private _rowHeight: number; private _selection: Selection; private _listElem: List = undefined; private _pageWidth: number; private _oneDriveService: OneDriveServices = undefined; constructor(props: IOneDriveTabProps) { super(props); // If possible, load the user's favourite layout const lastLayout: ViewType = localStorage ? localStorage.getItem(LAYOUT_STORAGE_KEY) as ViewType : 'tiles' as ViewType; // Set the columns we'll use for the list views const columns: IColumn[] = [ { key: 'colIcon', name: 'Type', ariaLabel: strings.TypeAriaLabel, iconName: 'Page', isIconOnly: true, fieldName: 'docIcon', headerClassName: styles.iconColumnHeader, minWidth: 16, maxWidth: 16, onColumnClick: this._onColumnClick, onRender: (item: IOneDriveFile) => { // Get the icon const folderIcon: string = strings.FolderIconUrl; const iconUrl: string = strings.PhotoIconUrl; // Insert file type into localized string const altText: string = item.isFolder ? strings.FolderAltText : strings.ImageAltText.replace('{0}', item.fileType); //TODO: This will have to change if we add support for non-image fiels return <div className={styles.fileTypeIcon}> <img src={item.isFolder ? folderIcon : iconUrl} className={styles.fileTypeIconIcon} alt={altText} title={altText} /> </div>; } }, { key: 'colName', name: strings.NameField, fieldName: 'fileLeafRef', minWidth: 200, isRowHeader: true, isResizable: true, isSorted: true, isSortedDescending: false, sortAscendingAriaLabel: strings.SortedAscending, sortDescendingAriaLabel: strings.SortedDescending, onColumnClick: this._onColumnClick, data: 'string', isPadded: true, onRender: (item: IOneDriveFile) => { // If this is a folder, browse to that folder if (item.isFolder) { return <span className={styles.folderItem} onClick={(_event) => this._handleOpenLibrary(item)}>{item.name}</span>; } else { // Just show the file name return <span className={styles.fileItem}>{item.name}</span>; } }, }, { key: 'colModified', name: strings.ODModifiedField, fieldName: 'modified', minWidth: 120, isResizable: true, onColumnClick: this._onColumnClick, data: 'number', onRender: (item: IOneDriveFile) => { //aria-label="Modified column, March 9, 2017" const ariaLabel: string = strings.AriaCellValue.replace('{0}', strings.ODModifiedField).replace('{1}', item.modified); // Modified date already returns localized and formatted return <span aria-label={ariaLabel} >{item.modified}</span>; }, isPadded: true }, { key: 'colEditor', name: strings.ModifiedByField, fieldName: 'modifiedBy', minWidth: 100, isResizable: true, data: 'string', onColumnClick: this._onColumnClick, onRender: (item: IOneDriveFile) => { return <span>{item.modifiedBy}</span>; }, isPadded: true }, { key: 'colSize', name: strings.FileSizeField, fieldName: 'fileSizeDisplay', minWidth: 100, isResizable: true, data: 'number', onColumnClick: this._onColumnClick, onRender: (item: IOneDriveFile) => { // Format the size into a nice human-friendly format. return <span>{item.fileSizeDisplay ? FormatBytes(item.fileSizeDisplay, 1) : undefined}</span>; } }, { key: 'colShared', name: strings.SharingField, fieldName: 'principalCount', minWidth: 100, isResizable: true, data: 'string', onColumnClick: this._onColumnClick, onRender: (item: IOneDriveFile) => { // Can't find any references here, but I'm pretty sure that // if there are no other principals, nobody else is allowed to see it // but anything above zero means we shared with at least one person/group. const cellValue: string = item.isShared ? strings.SharingShared : strings.SharingPrivate; const ariaLabel: string = strings.AriaCellValue.replace('{0}', strings.SharingField).replace('{1}', cellValue); return <span aria-label={ariaLabel}> {item.isShared && <span> <Icon iconName="People" /> <span>&nbsp;</span> </span>} {cellValue} </span>; } } ]; this._selection = new Selection( { selectionMode: SelectionMode.single, onSelectionChanged: () => { // Get the selected item const selectedItems = this._selection.getSelection(); if (selectedItems && selectedItems.length > 0) { const selectedKey: IOneDriveFile = selectedItems[0] as IOneDriveFile; if (!selectedKey.isFolder) { // Save the selected file this.setState({ fileUrl: selectedKey.absoluteUrl }); } } else { // Remove any selected file this.setState({ fileUrl: undefined }); } if (this._listElem) { // Force the list to update to show the selection check this._listElem.forceUpdate(); } } }); this.state = { isLoading: true, files: [], hideDialog: true, parentFolderInfo: [], selectedView: lastLayout, columns: columns }; } /** * Gets the OneDrive files */ public componentDidMount(): void { // Initialize the OneDrive services this._oneDriveService = new OneDriveServices(this.props.context, this.props.accepts); // Get the items at the root of the OneDrive folder this._getListItems(); } /** * Handle if we change the relative folder we're browsing */ public componentDidUpdate(_prevProps: IOneDriveTabProps, prevState: IOneDriveTabState): void { // Update the list of items if the folder changes if (prevState.serverRelativeFolderUrl !== this.state.serverRelativeFolderUrl) { this._getListItems(); } } /** * Gets the list of items to display */ private _getListItems = (): Promise<void> => { // We're loading! this.setState({ isLoading: true }); return this._oneDriveService.GetListDataAsStream(this.state.serverRelativeFolderUrl).then((listDataStream: IGetListDataAsStreamResult) => { // Get the thumbnail URL template -- stored in the list schema const thumbnailUrlTemplate: string = listDataStream.ListSchema[".thumbnailUrl"] .replace("{.mediaBaseUrl}", listDataStream.ListSchema[".mediaBaseUrl"]) .replace("{.callerStack}", listDataStream.ListSchema[".callerStack"]) .replace("{.driveAccessToken}", "encodeFailures=1&ctag={.ctag}"); // Map every item to a OneDrive file const files: IOneDriveFile[] = listDataStream.ListData.Row.map((item: IRow) => { // Build the thumbnail URL from the template // The template is stored in the schema (see above) and contains list-specific // replacement tokens (which we already replaced above) and item-specific // tokens, which we're replacing right. now. const thumbnail: string = thumbnailUrlTemplate .replace('{.spItemUrl}', item[".spItemUrl"]) .replace('{.ctag}', encodeURIComponent(item[".ctag"])) .replace('{.fileType}', item[".fileType"]); // Get the modified date const modifiedParts: string[] = item["Modified.FriendlyDisplay"]!.split('|'); let modified: string = item.Modified; // If there is a friendly modified date, use that // The friendly dates seem to be a lot smarter than what I have here. // For example, it seems to use a different structure for dates that are on the same // day, within a few days, etc. // For this example, we just handle the regular friendly-dates, but if we // turn this into a PnP control, we'll want to handle all sorts of friendly dates if (modifiedParts.length === 2) { modified = modifiedParts[1]; } // Parse media metadata to see if we can get known dimensions // Dimensions are stored as HTML-encoded JSON from media services. // If it is available, get the JSON structure and parse it. const media: any = item.MediaServiceFastMetadata && JSON.parse(unescape(item.MediaServiceFastMetadata)); const dimensions: IDimensions = media && media.photo && { width: media.photo.width, height: media.photo.height }; // Create a nice OneDriveFile interface so we're not saving all that extra metadata that // gets returned from SharePoint in our state. const file: IOneDriveFile = { key: item.UniqueId, name: item.FileLeafRef, absoluteUrl: this._buildOneDriveAbsoluteUrl(listDataStream.HttpRoot, item.FileRef), serverRelativeUrl: item.FileRef, isFolder: item.FSObjType === "1", modified: modified, modifiedBy: item.Editor[0].title, fileType: item.File_x0020_Type, fileIcon: item["HTML_x0020_File_x0020_Type.File_x0020_Type.mapico"], fileSizeDisplay: item.FileSizeDisplay, totalFileCount: +item.SMTotalFileCount, // quickly converts string to number thumbnail: thumbnail, dimensions: dimensions, isShared: parseInt(item.PrincipalCount) > 0 }; return file; }); // Set the selection items so that we know what item we're selecting this._selection.setItems(files); // Store the files and stop the loading icon this.setState({ files: files, isLoading: false, // we're done loading parentFolderInfo: listDataStream.ParentInfo.ParentFolderInfo // remember where we are }); }); } /** * Renders the tab */ public render(): React.ReactElement<IOneDriveTabProps> { const { isLoading, files, selectedView, fileUrl } = this.state; return ( <div className={css(styles.tabContainer)}> <div className={styles.tabHeaderContainer}> {this._onRenderHeader()} {this._onRenderCommandBar()} </div> <div className={styles.tab}> {isLoading && <Spinner label={strings.Loading} />} {!isLoading && files!.length > 0 && selectedView !== 'tiles' && this._renderListLayout()} {!isLoading && files!.length > 0 && selectedView === 'tiles' && this._renderTileLayout()} {!isLoading && files!.length < 1 && this._renderEmptyFolder() } </div> <div className={styles.actionButtonsContainer}> <div className={styles.actionButtons}> <PrimaryButton disabled={!fileUrl} onClick={() => this._handleSaveConfirm()} className={styles.actionButton}>{strings.OpenButtonLabel}</PrimaryButton> <DefaultButton onClick={() => this._handleClose()} className={styles.actionButton}>{strings.CancelButtonLabel}</DefaultButton> </div> </div> {this._onRenderConfirmDialog()} </div> ); } /** * Gratuitous sorting */ private _onColumnClick = (event: React.MouseEvent<HTMLElement>, column: IColumn): void => { const { columns } = this.state; let { files } = this.state; let isSortedDescending = column.isSortedDescending; // If we've sorted this column, flip it. if (column.isSorted) { isSortedDescending = !isSortedDescending; } // Sort the items. files = files!.concat([]).sort((a, b) => { const firstValue = a[column.fieldName || '']; const secondValue = b[column.fieldName || '']; if (isSortedDescending) { return firstValue > secondValue ? -1 : 1; } else { return firstValue > secondValue ? 1 : -1; } }); // Reset the items and columns to match the state. this._selection.setItems(files); this.setState({ files: files, columns: columns!.map(col => { col.isSorted = col.key === column.key; if (col.isSorted) { col.isSortedDescending = isSortedDescending; } return col; }) }); } /** * Renders a tile */ private _renderTileLayout = (): JSX.Element => { const { files } = this.state; return (<SelectionZone selection={this._selection} onItemInvoked={(item: IOneDriveFile) => this._handleItemInvoked(item)} > <FocusZone> <List ref={this._linkList} className={styles.folderList} items={files} getItemCountForPage={this._getItemCountForPage} getPageHeight={this._getPageHeight} renderedWindowsAhead={4} onRenderPage={(pageProps: IPageProps, defaultRender?: IRenderFunction<IPageProps>) => this._onRenderPage(pageProps, defaultRender)} /> </FocusZone> </SelectionZone>); } /** * Renders a list or a compact list */ private _renderListLayout = (): JSX.Element => { const { files, selectedView, columns } = this.state; return ( <DetailsList items={files} compact={selectedView === 'compact'} columns={columns} selectionMode={SelectionMode.single} setKey="set" layoutMode={DetailsListLayoutMode.justified} isHeaderVisible={true} selection={this._selection} selectionPreservedOnEmptyClick={true} onActiveItemChanged={(item: IOneDriveFile, index: number, ev: React.FormEvent<Element>) => this._itemChangedHandler(item, index, ev)} enterModalSelectionOnTouch={true} onRenderRow={this._onRenderRow} /> ); } /** * Renders a row in a detailed list */ private _onRenderRow = (props: IDetailsRowProps): JSX.Element => { const fileItem: IOneDriveFile = props.item; return <DetailsRow getRowAriaLabel={(item: IOneDriveFile) => this._getRowAriaLabel(item)} {...props} className={fileItem.isFolder ? styles.folderRow : styles.fileRow} />; } /** * Gets called on every row to provide an ARIA label describing the data in the row. */ private _getRowAriaLabel = (item: IOneDriveFile): string => { //Attachments, Folder, Modified March 9, 2017, edited by Hugo Bernier, 0 items, Private //me.png, .png Image, Modified December 12, 2017, edited by Hugo Bernier, 86.5 KB, Shared //"{0}, {1}, Modified {2}, edited by {3}, {4}, {5}" const fileType: string = item.isFolder ? strings.FolderAltText : strings.ImageAltText.replace('{0}', item.fileType); const sharingValue: string = item.isShared ? strings.SharingShared : strings.SharingPrivate; const ariaLabel: string = strings.ODRowArialLabelTemplate.replace('{0}', item.name) .replace('{1}', fileType) .replace('{2}', item.modified) .replace('{3}', item.modifiedBy) .replace('{4}', item.fileSizeDisplay) .replace('{5}', sharingValue); return ariaLabel; } /** * Renders the command bar above the list/grid */ private _onRenderCommandBar = (): JSX.Element => { return (<div className={styles.itemPickerTopBar}> <CommandBar items={this._getToolbarItems()} farItems={this.getFarItems()} /> </div>); } /** * Display an annoying pop-up saying you should make sure * that you shared this file otherwise people won't see it */ private _onRenderConfirmDialog = (): JSX.Element => { return (<Dialog hidden={this.state.hideDialog} dialogContentProps={{ type: DialogType.normal, title: strings.OneDriveConfirmDialogTitle, subText: strings.OneDriveConfirmDialogBody }} modalProps={{ isBlocking: true, containerClassName: styles.dialogMainOverride }} > <DialogFooter> <PrimaryButton onClick={(_ev) => this._handleSave()} text={strings.Yes} /> <DefaultButton onClick={(_ev) => this._handleClose()} text={strings.No} /> </DialogFooter> </Dialog>); } /** * Render a heading or a breadcrumb (depending on how many levels deep we're in) */ private _onRenderHeader = (): JSX.Element => { const { parentFolderInfo } = this.state; // If we don't have parent info, or we're only 2 levels deep, don't render breadcrumbs. // just render a heading. // also, render a header until we're fully loaded, otherwise the breadcrumb starts // flickering. if (parentFolderInfo === undefined || parentFolderInfo.length < 2 || this.state.isLoading) { return (<h2 className={styles.tabHeader}>{this.state.folderName ? this.state.folderName : strings.OneDriveRootFolderName}</h2>); } // Get the breadcrumb path const breadCrumbItems: IBreadcrumbItem[] = []; // Parent info comes in reversed, so reverse it to render the breadcrumbs in the right order parentFolderInfo.reverse().forEach((parentFolder: IParentFolderInfo, index: number) => { // Anything after the first level is a link if (index > 1) { const folderName: string = this._getFolderName(parentFolder.ServerRelativeUrl); breadCrumbItems.push({ text: folderName, key: folderName, onClick: () => this._handleOpenLibraryByPath(parentFolder.ServerRelativeUrl, folderName) }); } else if (index === 1) { // First level is always a link to the OneDrive root breadCrumbItems.push({ text: strings.OneDriveRootFolderName, key: strings.OneDriveRootFolderName, onClick: () => this._handleOpenLibraryByPath(parentFolder.ServerRelativeUrl, strings.OneDriveRootFolderName) }); } }); // List breadcrumb node is the current folder breadCrumbItems.push({ text: this.state.folderName, key: this.state.folderName, isCurrentItem: true }); return <Breadcrumb className={styles.standaloneListBreadcrumb} items={breadCrumbItems} />; } /** * Renders a custom list page */ private _onRenderPage = (pageProps: IPageProps, _defaultRender?: IRenderFunction<IPageProps>): JSX.Element => { const { page, className: pageClassName, ...divProps } = pageProps; const { items } = page; return <div {...divProps} className={css(pageClassName, styles.listPage)}> <div className={styles.grid} style={{ width: this._pageWidth, marginTop: -STANDARD_TILE_MARGIN, marginBottom: BOTTOM_MARGIN, marginLeft: -STANDARD_TILE_MARGIN, marginRight: -STANDARD_TILE_MARGIN }} > {items.map((item: IOneDriveFile, index: number) => { return this._onRenderCell(item, index); })} </div> </div>; } /** * Renders a placeholder to indicate that the folder is empty */ private _renderEmptyFolder = (): JSX.Element => { return (<div className={styles.emptyFolder}> <div className={styles.emptyFolderImage}> <img className={styles.emptyFolderImageTag} src={strings.OneDriveEmptyFolderIconUrl} alt={strings.OneDriveEmptyFolderAlt} /> </div> <div role="alert"> <div className={styles.emptyFolderTitle}> {strings.OneDriveEmptyFolderTitle} </div> <div className={styles.emptyFolderSubText}> <span className={styles.emptyFolderPc}> {strings.OneDriveEmptyFolderDescription} </span> {/* Removed until we add support to upload */} {/* <span className={styles.emptyFolderMobile}> Tap <Icon iconName="Add" className={styles.emptyFolderIcon} /> to add files here. </span> */} </div> </div> </div>); } /** * Get the list of toolbar items on the left side of the toolbar. * We leave it empty for now, but we may add the ability to upload later. */ private _getToolbarItems = (): ICommandBarItemProps[] => { return [ // This space for rent ]; } private getFarItems = (): ICommandBarItemProps[] => { const { selectedView } = this.state; let viewIconName: string = undefined; let viewName: string = undefined; switch (this.state.selectedView) { case 'list': viewIconName = 'List'; viewName = strings.ListLayoutList; break; case 'compact': viewIconName = 'AlignLeft'; viewName = strings.ListLayoutCompact; break; default: viewIconName = 'GridViewMedium'; viewName = strings.ListLayoutTile; } const farItems: ICommandBarItemProps[] = [ { key: 'listOptions', className: styles.commandBarNoChevron, title: strings.ListOptionsTitle, ariaLabel: strings.ListOptionsAlt.replace('{0}', viewName), iconProps: { iconName: viewIconName }, iconOnly: true, subMenuProps: { items: [ { key: 'list', name: strings.ListLayoutList, iconProps: { iconName: 'List' }, canCheck: true, checked: this.state.selectedView === 'list', ariaLabel: strings.ListLayoutAriaLabel.replace('{0}', strings.ListLayoutList).replace('{1}', selectedView === 'list' ? strings.Selected : undefined), title: strings.ListLayoutListDescrition, onClick: (_ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => this._handleSwitchLayout(item) }, { key: 'compact', name: strings.ListLayoutCompact, iconProps: { iconName: 'AlignLeft' }, canCheck: true, checked: this.state.selectedView === 'compact', ariaLabel: strings.ListLayoutAriaLabel.replace('{0}', strings.ListLayoutCompact).replace('{1}', selectedView === 'compact' ? strings.Selected : undefined), title: strings.ListLayoutCompactDescription, onClick: (_ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => this._handleSwitchLayout(item) }, { key: 'tiles', name: 'Tiles', iconProps: { iconName: 'GridViewMedium' }, canCheck: true, checked: this.state.selectedView === 'tiles', ariaLabel: strings.ListLayoutAriaLabel.replace('{0}', strings.ListLayoutTile).replace('{1}', selectedView === 'tiles' ? strings.Selected : undefined), title: strings.ListLayoutTileDescription, onClick: (_ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => this._handleSwitchLayout(item) } ] } } ]; return farItems; } /** * Called when users switch the view */ private _handleSwitchLayout = (item?: IContextualMenuItem) => { if (item) { // Store the user's favourite layout if (localStorage) { localStorage.setItem(LAYOUT_STORAGE_KEY, item.key); } this.setState({ selectedView: item.key as ViewType }); } } /** * Gets called what a file is selected. */ private _handleItemInvoked = (item: IOneDriveFile) => { // If a file is selected, open the library if (item.isFolder) { this._handleOpenLibrary(item); } else { // Otherwise, remember it was selected this._selection.setKeySelected(item.key, true, true); } } /** * When user selects an item, save selection */ private _itemChangedHandler = (item: IOneDriveFile, _index: number, _ev): void => { // When we highlight a folder, do nothing (except set the selection to blank) if (item.isFolder) { this.setState({ fileUrl: undefined }); return; } // set the item selected this._selection.setKeySelected(item.key, true, true); } /** * Calculates how many items there should be in the page */ private _getItemCountForPage = (itemIndex: number, surfaceRect: IRectangle): number => { if (itemIndex === 0) { this._columnCount = Math.ceil(surfaceRect.width / MAX_ROW_HEIGHT); this._columnWidth = Math.floor(surfaceRect.width / this._columnCount); this._rowHeight = this._columnWidth; this._pageWidth = surfaceRect.width; } // Get the list of items const { files } = this.state; const isFolder: boolean = files[itemIndex].isFolder; // Group items by folders and files let pageLength: number = 0; for (let index = itemIndex; index < files.length; index++) { const element = files[index]; if (element.isFolder === isFolder) { pageLength++; } else { break; } } // Return the page lenght, up to the maximum number of cells per page return Math.min(pageLength, CELLS_PER_PAGE); } /** Calculates the list "page" height (a.k.a. row) */ private _getPageHeight = (): number => { return this._rowHeight * ROWS_PER_PAGE; } /** * Renders a file folder cover */ private _onRenderCell = (item: IOneDriveFile, index: number | undefined): JSX.Element => { let isSelected: boolean = false; if (this._selection && index !== undefined) { isSelected = this._selection.isIndexSelected(index); } // I know this is a lot of divs and spans inside of each other, but my // goal was to mimic the HTML and style of the out-of-the-box file picker // to the best of my ability. return ( <div className={styles.listCell} data-item-index={index} style={{ flexBasis: this._columnWidth, maxWidth: this._columnWidth, margin: STANDARD_TILE_MARGIN, borderStyle: "none", borderWidth: 0 }} > <div role="presentation" className={styles.cell} // I don't agree with this magic number. Where does this come from? style={{ paddingTop: "97.16%" }} > <div role="presentation" className={styles.cellContent}> {item.isFolder ? <FolderTile item={item} index={index} isSelected={isSelected} pageWidth={this._pageWidth} tileDimensions={{ width: this._columnWidth - TILE_HORZ_PADDING, height: this._rowHeight - TILE_HORZ_PADDING }} onItemInvoked={(itemInvoked: IOneDriveFile) => this._handleItemInvoked(itemInvoked)} /> : <DocumentTile item={item} index={index} isSelected={isSelected} pageWidth={this._pageWidth} tileDimensions={{ width: this._columnWidth - TILE_HORZ_PADDING, height: this._rowHeight - TILE_HORZ_PADDING }} onItemInvoked={(itemInvoked: IOneDriveFile) => this._handleItemInvoked(itemInvoked)} />} </div> </div> </div> ); } /** * Creates an absolute URL */ private _buildOneDriveAbsoluteUrl = (root: string, relativeUrl: string) => { const siteUrl: string = GetAbsoluteDomainUrl(root); return siteUrl + relativeUrl; } /** * Calls parent when library is opened */ private _handleOpenLibrary = (library: IOneDriveFile) => { this.setState({ serverRelativeFolderUrl: library.serverRelativeUrl, folderName: library.name }); } /** * Gets called when someone clicks on a breadcrumb * In this case, we only have the path to work with, not the full * reference to the OneDrive file */ private _handleOpenLibraryByPath = (serverRelativeUrl: string, libraryName: string) => { this.setState({ serverRelativeFolderUrl: serverRelativeUrl, folderName: libraryName }); } /** * Prompt user with dialog before they can save */ private _handleSaveConfirm = () => { this.setState({ hideDialog: false }); } /** * Called when user saves */ private _handleSave = () => { this.props.onSave(encodeURI(this.state.fileUrl)); } /** * Called when user closes tab */ private _handleClose = () => { this.props.onClose(); } /** * Creates a ref to the list */ private _linkList = (e: any) => { this._listElem = e; } /** * Extracts the last part of the path to get the folder name */ private _getFolderName = (folderPath: string): string => { // break the folder path into its sub-folders const pathSegments: string[] = folderPath.split('/'); return pathSegments.pop(); } }
the_stack
import { fail, strictEqual, throws, deepEqual, notEqual } from "assert" import { userInfo } from "os" const Nodehun = require('bindings')('Nodehun') const fs = require('fs') const path = require('path') const enUS = { affix: fs.readFileSync(path.resolve(__dirname, './dictionaries/en_us.aff')), dictionary: fs.readFileSync(path.resolve(__dirname, './dictionaries/en_us.dic')) } const enGB = { affix: fs.readFileSync(path.resolve(__dirname, './dictionaries/en_gb.aff')), dictionary: fs.readFileSync(path.resolve(__dirname, './dictionaries/en_gb.dic')) } const fr = { dictionary: fs.readFileSync(path.resolve(__dirname, './dictionaries/fr.dic')) } const nl = { affix: fs.readFileSync(path.resolve(__dirname, './dictionaries/nl.aff')), dictionary: fs.readFileSync(path.resolve(__dirname, './dictionaries/nl.dic')) } describe('Nodehun(affixBuffer, dictionaryBuffer)', () => { it(`should export a function`, () => { strictEqual(typeof Nodehun, 'function') }) it(`should throw when 'new' operator isn't used`, () => { throws(() => Nodehun()) }) it(`should throw when no arguments are given`, () => { throws(() => new Nodehun()) }) it(`should throw when 1 arguments are given`, () => { throws(() => new Nodehun(1)) }) it(`should throw when 3 arguments are given`, () => { throws(() => new Nodehun(1, 2, 3)) }) it(`should throw when the first argument isn't a buffer`, () => { throws(() => new Nodehun(1, 2)) }) it(`should throw when the second argument isn't a buffer`, () => { throws(() => new Nodehun(enUS.affix, 2)) }) it(`should successfully construct an object when two buffers are given`, () => { new Nodehun(enUS.affix, enUS.dictionary) }) // FIXME // it(`should construct an object of type Nodehun`, () => { // const nodehun = new Nodehun(enUS.affix, enUS.dictionary) // strictEqual(nodehun instanceof Nodehun, true) // }) }) describe('Nodehun#spell(word)', () => { let nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary); it(`should be a function`, async () => { strictEqual(typeof nodehun.spell, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.spell() .then(() => { }) .catch(() => { }) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when 0 arguments are given`, async () => { try { await nodehun.spell() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, async () => { try { await nodehun.spell(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.spell(123456) fail() } catch { // success } }) it(`should return true when the word is spelled correctly`, async () => { strictEqual(await nodehun.spell('color'), true) }) it(`should return false when the word is not spelled correctly`, async () => { strictEqual(await nodehun.spell('colour'), false) }) it(`should not throw when spellchecking emojis ☀`, async () => { await nodehun.spell('😀') await nodehun.spell('☀') }) }) describe('Nodehun#spellSync(word)', () => { let nodehun = new Nodehun(enUS.affix, enUS.dictionary) let nodehunNL = new Nodehun(nl.affix, nl.dictionary) it(`should be a function`, async () => { strictEqual(typeof nodehun.spellSync, 'function') }) it(`should throw when 0 arguments are given`, () => { try { nodehun.spellSync() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, () => { try { nodehun.spellSync(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.spellSync(123456) fail() } catch { // success } }) it(`should return 'false' when a word is not correctly spelled`, () => { strictEqual(nodehun.spellSync('colour'), false) }) it(`should return 'true' when a word is correctly spelled (1)`, () => { strictEqual(nodehun.spellSync('color'), true) }) it(`should return 'true' when a word is correctly spelled (2)`, () => { strictEqual(nodehun.spellSync('c'), true) }) it(`should return 'true' without word`, () => { strictEqual(nodehun.spellSync(' '), true) }) it(`should return 'true' for non-words`, () => { strictEqual(nodehun.spellSync('.'), true) }) it(`should check for sentence-case when upper-case (ok)`, () => { strictEqual(nodehun.spellSync('ABDUL'), true) }) it(`should check for sentence-case when upper-case (not ok)`, () => { strictEqual(nodehun.spellSync('COLOUR'), false) }) it(`should check for lower-case (ok)`, () => { strictEqual(nodehun.spellSync('Color'), true) }) it(`should check for lower-case (not ok)`, () => { strictEqual(nodehun.spellSync('Colour'), false) }) it(`should check for lower-case (not ok)`, () => { strictEqual(nodehun.spellSync('Colour'), false) }) it(`should not check upper-case for sentence-case when KEEPCASE`, () => { strictEqual(nodehunNL.spellSync('DVD'), false) }) it(`should not check other casing for lower-case when KEEPCASE`, () => { strictEqual(nodehunNL.spellSync('dVd'), false) }) it(`should support ONLYINCOMPOUND (ok)`, () => { strictEqual(nodehunNL.spellSync('eierlevendbarend'), true) }) it(`should support ONLYINCOMPOUND (not ok)`, () => { strictEqual(nodehunNL.spellSync('eier'), false) }) it(`should support compounds (1)`, () => { strictEqual(nodehun.spellSync('21st'), true) }) it(`should support compounds (2)`, () => { strictEqual(nodehun.spellSync('20st'), false) }) it(`should support compounds (3)`, () => { strictEqual(nodehun.spellSync('20th'), true) }) it(`should support compounds (4)`, () => { strictEqual(nodehun.spellSync('23st'), false) }) it(`should support compounds (5)`, () => { strictEqual(nodehun.spellSync('23th'), false) }) it(`should support compounds (6)`, () => { strictEqual(nodehun.spellSync('23rd'), true) }) it(`should support compounds (7)`, () => { strictEqual(nodehun.spellSync('12th'), true) }) it(`should support compounds (8)`, () => { strictEqual(nodehun.spellSync('22nd'), true) }) it(`should not throw when spellchecking emojis ☀`, () => { nodehun.spellSync('😀') nodehun.spellSync('☀') }) }) describe('Nodehun#suggestSync(word)', () => { let nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.suggestSync, 'function') }) it(`should throw when 0 arguments are given`, () => { try { nodehun.suggestSync() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, () => { try { nodehun.suggestSync(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.suggestSync(123456) fail() } catch { // success } }) it(`should return null when correct (1)`, () => { deepEqual(nodehun.suggestSync('color'), null) }); it(`should return null when correct (2)`, () => { deepEqual( nodehun.suggestSync('c'), null ) }); it(`should suggest alternatives`, () => { deepEqual( nodehun.suggestSync('colour').slice(0, 5), ['color', 'co lour', 'co-lour', 'col our', 'col-our'] ) }); it(`should suggest alternatives`, () => { deepEqual( nodehun.suggestSync('propper').slice(0, 5), ['proper', 'popper', 'prosper', 'cropper', 'propped'] ) }); it(`should return null for empty values`, () => { deepEqual( nodehun.suggestSync(' '), null ) }); it(`should return null for non-words`, () => { deepEqual( nodehun.suggestSync('.'), null ) }); it(`should suggest alternatives for sentence-case`, () => { deepEqual( nodehun.suggestSync('Colour').slice(0, 5), ['Co lour', 'Co-lour', 'Col our', 'Col-our', 'Color'] ) }); it(`should suggest alternatives for upper-case`, () => { deepEqual( nodehun.suggestSync('COLOUR').slice(0, 5), ['COLOR', 'CO LOUR', 'CO-LOUR', 'COL OUR', 'COL-OUR'] ) }); it(`should suggest alternatives for funky-case`, () => { deepEqual( nodehun.suggestSync('coLOUR').slice(0, 5), ['col Our', 'co Lour', 'color', 'co-lour', 'col-our'] ) }); it(`should suggest uppercase versions`, () => { deepEqual( nodehun.suggestSync('html'), ['HTML', 'ht ml', 'ht-ml'] ) }); it(`should suggest removals`, () => { deepEqual( nodehun.suggestSync('collor').slice(0, 5), ['color', 'collar', 'coll or', 'coll-or', 'collator'] ) }); it(`should suggest additions`, () => { notEqual( nodehun.suggestSync('coor').indexOf('color'), -1 ) }); it(`should suggest switches`, () => { const suggestions: Array<string> = nodehun.suggestSync('cloor') strictEqual(suggestions.includes('color'), true) }); it(`should suggest insertions`, () => { const suggestions: Array<string> = nodehun.suggestSync('coor') strictEqual(suggestions.includes('color'), true) }); it(`should not suggest alternatives marked with 'NOSUGGEST'`, () => { const suggestions: Array<string> = nodehun.suggestSync('bulshit') strictEqual(suggestions.includes('bullshit') || suggestions.includes('Bullshit'), false) }); it(`should suggest based on replacements`, () => { const suggestions: Array<string> = nodehun.suggestSync('consize') strictEqual(suggestions.includes('concise'), true) }); // it(`should not throw when suggesting for emojis ☀`, () => { // nodehun.suggestSync('😀') // nodehun.suggestSync('☀') // }) it(`should not overflow on too long values`, () => { const word = 'npmnpmnpmnpmnpmnpmnpmnpmnpmnpmnpmnpmnpmnpmnpm' deepEqual(nodehun.suggestSync(word), []) }); }) describe('Nodehun#suggest(word)', () => { let nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary); it(`should be a function`, async () => { strictEqual(typeof nodehun.suggest, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.suggest() .then(() => { }) .catch(() => { }) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when 0 arguments are given`, async () => { try { await nodehun.suggest() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, async () => { try { await nodehun.suggest(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.suggest(123456) fail() } catch { // success } }) it(`should return null when the word is spelled correctly`, async () => { strictEqual(await nodehun.suggest('color'), null) }) it(`should return an array when the word is not spelled correctly`, async () => { const value = await nodehun.suggest('colour') strictEqual(typeof value, 'object') strictEqual(typeof value.length, 'number') }) it(`should return appropriate suggestions when a word is spelled incorrectly`, async () => { const value = await nodehun.suggest('colour') deepEqual(value.splice(0, 3), ['color', 'co lour', 'co-lour']) }) // it(`should not throw when suggesting for emojis ☀`, async () => { // await nodehun.suggest('😀') // await nodehun.suggest('☀') // }) }) describe('Nodehun#add(word)', () => { let nodehun: Nodehun beforeEach(() => { // clear changes before each test nodehun = new Nodehun(enUS.affix, enUS.dictionary) }) it(`should be a function`, async () => { strictEqual(typeof nodehun.add, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.add() .then(() => { }) .catch(() => { }) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when 0 arguments are given`, async () => { try { await nodehun.add() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, async () => { try { await nodehun.add(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.add(123456) fail() } catch { // success } }) it(`should now mark as correct`, async () => { const word = 'npm' strictEqual(await nodehun.spell(word), false) await nodehun.add('npm') strictEqual(await nodehun.spell(word), true) }) it(`should no longer receive suggestions`, async () => { const word = 'npm' notEqual(await nodehun.suggest(word), null) await nodehun.add(word) strictEqual(await nodehun.suggest(word), null) }) }) describe('Nodehun#addSync(value)', () => { let nodehun: Nodehun beforeEach(() => { // clear changes before each test nodehun = new Nodehun(enUS.affix, enUS.dictionary) }) it(`should be a function`, () => { strictEqual(typeof nodehun.addSync, 'function') }) it(`should throw when 0 arguments are given`, () => { try { nodehun.addSync() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, () => { try { nodehun.addSync(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.addSync(123456) fail() } catch { // success } }) it(`should now mark as correct`, () => { const word = 'npm' strictEqual(nodehun.spellSync(word), false) nodehun.addSync(word) strictEqual(nodehun.spellSync(word), true) }) it(`should no longer receive suggestions`, () => { const word = 'npm' notEqual(nodehun.suggestSync(word), null) nodehun.addSync(word) strictEqual(nodehun.suggestSync(word), null) }) }) describe('Nodehun#remove(word)', () => { let nodehun: Nodehun beforeEach(() => { // clear changes before each test nodehun = new Nodehun(enUS.affix, enUS.dictionary) }) it(`should be a function`, async () => { strictEqual(typeof nodehun.remove, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.remove() .then(() => { }) .catch(() => { }) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when 0 arguments are given`, async () => { try { await nodehun.remove() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, async () => { try { await nodehun.remove(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.remove(123456) fail() } catch { // success } }) it(`should now mark as correct`, async () => { const word = 'npm' await nodehun.add(word) strictEqual(await nodehun.spell(word), true) await nodehun.remove('npm') strictEqual(await nodehun.spell(word), false) }) it(`should no longer receive suggestions`, async () => { const word = 'npm' await nodehun.add(word) strictEqual(await nodehun.suggest(word), null) await nodehun.remove(word) notEqual(await nodehun.suggest(word), null) }) }) describe('Nodehun#removeSync(value)', () => { let nodehun: Nodehun beforeEach(() => { // clear changes before each test nodehun = new Nodehun(enUS.affix, enUS.dictionary) }) it(`should be a function`, () => { strictEqual(typeof nodehun.removeSync, 'function') }) it(`should throw when 0 arguments are given`, () => { try { nodehun.removeSync() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, () => { try { nodehun.removeSync(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.removeSync(123456) fail() } catch { // success } }) it(`should now mark as correct`, () => { const word = 'npm' nodehun.addSync(word) strictEqual(nodehun.spellSync(word), true) nodehun.removeSync(word) strictEqual(nodehun.spellSync(word), false) }) it(`should no longer receive suggestions`, () => { const word = 'npm' nodehun.addSync(word) strictEqual(nodehun.suggestSync(word), null) nodehun.removeSync(word) notEqual(nodehun.suggestSync(word), null) }) }) // t.test('Nodehun#addSync(value, model)', function (st) { // /* `azc` is a Dutch word only properly spelled // * in its lower-case form. */ // st.strictEqual( // nl.addSync('npm', 'azc'), // nl, // 'should return the context object' // ); // // st.strictEqual(nl.spellSync('npm'), true, 'should match affixes (1)'); // st.strictEqual(nl.spellSync('NPM'), false, 'should match affixes (2)'); // st.strictEqual(nl.spellSync('Npm'), false, 'should match affixes (3)'); // // nl.removeSync('npm'); // // st.end(); // }); describe('Nodehun#analyze(word: string): Promise<string[]>;', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.analyze, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.analyze() .then(() => {}) .catch(() => {}) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when no arguments are given`, async () => { try { await nodehun.analyze() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, async () => { try { await nodehun.analyze(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.analyze(1) fail() } catch { // success } }) it(`should return morphological analysis`, async () => { const morphologicalAnalysis = await nodehun.analyze('telling') deepEqual( morphologicalAnalysis, [' st:telling ts:0', ' st:tell ts:0 al:told is:Vg'] ) }) it(`should return an empty array when it isn't available`, async () => { deepEqual( await nodehun.analyze('npmnpmnpmnpmnpmnpmnpmnpm'), [] ) }) }) describe('Nodehun#analyzeSync(word: string): string[];', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.analyzeSync, 'function') }) it(`should throw when no arguments are given`, () => { try { nodehun.analyzeSync() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, () => { try { nodehun.analyzeSync(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.analyzeSync(1) fail() } catch { // success } }) it(`should return morphological analysis`, async () => { const morphologicalAnalysis = nodehun.analyzeSync('telling') deepEqual( morphologicalAnalysis, [' st:telling ts:0', ' st:tell ts:0 al:told is:Vg'] ) }) it(`should return an empty array when it isn't available`, async () => { deepEqual( nodehun.analyzeSync('npmnpmnpmnpmnpmnpmnpmnpm'), [] ) }) }) describe('Nodehun#stem(word: string): Promise<string[]>;', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.stem, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.stem() .then(() => {}) .catch(() => {}) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when no arguments are given`, async () => { try { await nodehun.stem() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, async () => { try { await nodehun.stem(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.stem(1) fail() } catch { // success } }) it(`should return roots`, async () => { const roots = await nodehun.stem('telling') deepEqual( roots, ['telling', 'tell'] ) }) it(`should return an empty array when not available`, async () => { deepEqual( await nodehun.stem('npmnpmnpmnpmnpmnpmnpmnpm'), [] ) }) }) describe('Nodehun#stemSync(word: string): string[];', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.stemSync, 'function') }) it(`should throw when no arguments are given`, () => { try { nodehun.stemSync() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, () => { try { nodehun.stemSync(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.stemSync(1) fail() } catch { // success } }) it(`should return roots`, async () => { const roots = nodehun.stemSync('telling') deepEqual( roots, ['telling', 'tell'] ) }) it(`should return an empty array when not available`, async () => { deepEqual( nodehun.stemSync('npmnpmnpmnpmnpmnpmnpmnpm'), [] ) }) }) describe('Nodehun#generate(word: string, example: string): Promise<string[]>;', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.generate, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.generate() .then(() => {}) .catch(() => {}) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when no arguments are given`, async () => { try { await nodehun.generate() fail() } catch { // success } }) it(`should throw when 3 arguments are given`, async () => { try { await nodehun.generate(1, 2, 3) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.generate(1) fail() } catch { // success } }) it(`should throw when the second argument isn't a string`, async () => { try { await nodehun.generate('abc', 1) fail() } catch { // success } }) it(`should return variations based on example`, async () => { deepEqual( await nodehun.generate('telling', 'ran'), [ 'told' ] ) }) it(`should return variations based on example (2)`, async () => { deepEqual( await nodehun.generate('told', 'run'), [ 'tell' ] ) }) it(`should return an empty array when not computable`, async () => { deepEqual( await nodehun.generate('told', 'npmnpmnpmnpm'), [] ) }) it(`should return an empty array when not computable (2)`, async () => { deepEqual( await nodehun.generate('npmnpmnpmnpm', 'npmnpmnpmnpm'), [] ) }) it(`should return an empty array when not computable (3)`, async () => { deepEqual( await nodehun.generate('npmnpmnpmnpm', 'run'), [] ) }) }) describe('Nodehun#generateSync(word: string): string[];', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.generateSync, 'function') }) it(`should throw when no arguments are given`, () => { try { nodehun.generateSync() fail() } catch { // success } }) it(`should throw when 3 arguments are given`, async () => { try { nodehun.generateSync(1, 2, 3) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { nodehun.generateSync(1) fail() } catch { // success } }) it(`should throw when the second argument isn't a string`, async () => { try { nodehun.generateSync('abc', 1) fail() } catch { // success } }) it(`should return variations based on example`, async () => { deepEqual( nodehun.generateSync('telling', 'ran'), [ 'told' ] ) }) it(`should return variations based on example (2)`, async () => { deepEqual( nodehun.generateSync('told', 'run'), [ 'tell' ] ) }) it(`should return an empty array when not computable`, async () => { deepEqual( nodehun.generateSync('told', 'npmnpmnpmnpm'), [] ) }) it(`should return an empty array when not computable (2)`, async () => { deepEqual( nodehun.generateSync('npmnpmnpmnpm', 'npmnpmnpmnpm'), [] ) }) it(`should return an empty array when not computable (3)`, async () => { deepEqual( nodehun.generateSync('npmnpmnpmnpm', 'run'), [] ) }) }) describe('Nodehun#addDictionary(dictionary: Buffer): Promise<void>;', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.addDictionary, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.addDictionary() .then(() => {}) .catch(() => {}) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when no arguments are given`, async () => { try { await nodehun.addDictionary() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, async () => { try { await nodehun.addDictionary(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.addDictionary(1) fail() } catch { // success } }) it(`should mark correct after dictionary is added`, async () => { await nodehun.addDictionary(fr.dictionary) strictEqual(await nodehun.spell('bonjour'), true) }) }) describe('Nodehun#addDictionarySync(dictionary: Buffer): void;', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.addDictionarySync, 'function') }) it(`should throw when no arguments are given`, () => { try { nodehun.addDictionarySync() fail() } catch { // success } }) it(`should throw when 2 arguments are given`, () => { try { nodehun.addDictionarySync(1, 2) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.addDictionarySync(1) fail() } catch { // success } }) it(`should mark correct after dictionary is added`, async () => { nodehun.addDictionarySync(fr.dictionary) strictEqual(nodehun.spellSync('bonjour'), true) }) }) describe('Nodehun#addWithAffix(word: string, example: string): Promise<void>;', () => { let nodehun: Nodehun beforeEach(() => { // clear changes before every test nodehun = new Nodehun(enUS.affix, enUS.dictionary) }) it(`should be a function`, () => { strictEqual(typeof nodehun.addWithAffix, 'function') }) it(`should return a promise`, async () => { let success = false await nodehun.addWithAffix() .then(() => {}) .catch(() => {}) .finally(() => { success = true }) strictEqual(success, true) }) it(`should throw when no arguments are given`, async () => { try { await nodehun.addWithAffix() fail() } catch { // success } }) it(`should throw when 3 arguments are given`, async () => { try { await nodehun.addWithAffix(1, 2, 3) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, async () => { try { await nodehun.addWithAffix(1) fail() } catch { // success } }) it(`should throw when the second argument isn't a string`, async () => { try { await nodehun.addWithAffix('abc', 1) fail() } catch { // success } }) it(`should mark correct`, async () => { await nodehun.addWithAffix('colour', 'color') strictEqual(await nodehun.spell('colouring'), true) }) }) describe('Nodehun#addWithAffixSync(word: string, example: string): void;', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary) it(`should be a function`, () => { strictEqual(typeof nodehun.addWithAffixSync, 'function') }) it(`should throw when no arguments are given`, () => { try { nodehun.addWithAffixSync() fail() } catch { // success } }) it(`should throw when 3 arguments are given`, () => { try { nodehun.addWithAffixSync(1, 2,3) fail() } catch { // success } }) it(`should throw when the first argument isn't a string`, () => { try { nodehun.addWithAffixSync(1) fail() } catch { // success } }) it(`should throw when the second argument isn't a string`, () => { try { nodehun.addWithAffixSync('abc', 2) fail() } catch { // success } }) it(`should mark correct`, async () => { nodehun.addWithAffixSync('colour', 'color') strictEqual(nodehun.spellSync('colouring'), true) }) }) describe('Nodehun#getWordCharacters()', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary); const nodehunGB: Nodehun = new Nodehun(enGB.affix, enGB.dictionary); it(`should return the defined word-characters`, () => { strictEqual(nodehun.getWordCharacters(), `0123456789'.-’`) }) it(`should return 'undefined' when not defined`, () => { strictEqual(nodehunGB.getWordCharacters(), undefined) }) }); describe('Nodehun#getWordCharactersUTF16()', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary); const nodehunGB: Nodehun = new Nodehun(enGB.affix, enGB.dictionary); it(`should return the defined word-characters`, () => { strictEqual(nodehun.getWordCharactersUTF16(), `'-.0123456789’`) }) it(`should return 'undefined' when not defined`, () => { strictEqual(nodehunGB.getWordCharactersUTF16(), undefined) }) }); describe('Nodehun#getDictionaryEncoding()', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary); it(`should return encoding as a string when known`, () => { strictEqual(nodehun.getDictionaryEncoding(), 'UTF-8') }) }) describe('Nodehun#getVersion()', () => { const nodehun: Nodehun = new Nodehun(enUS.affix, enUS.dictionary); it(`should return 'undefined' when not defined`, () => { strictEqual(nodehun.getVersion(), undefined) }) })
the_stack
import { Injectable, OnInit } from '@angular/core'; import { Http, URLSearchParams, Response, Headers, RequestOptionsArgs } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { Store } from '@ngrx/store'; import { Claim } from '../store/claim/claim.model'; import { ClaimRebuttal } from '../store/claim-rebuttal/claim-rebuttal.model'; import { Comment } from '../store/comment/comment.model'; import { Contact } from '../store/contact/contact.model'; import { Crisis } from '../store/crisis/crisis.model'; import { Hero } from '../store/hero/hero.model'; import { Note } from '../store/note/note.model'; import { Rebuttal } from '../store/rebuttal/rebuttal.model'; import { AppConfig } from '../../app.config'; import { DataService } from './data.service'; import { RootState } from '../store'; import { Entity } from '../store/entity/entity.model'; import * as SliceActions from '../store/slice/slice.actions'; import * as EntityActions from '../store/entity/entity.actions'; import { completeAssign, QueryPayload } from '../store/util'; import * as config from '../../app.config'; type APIConfig = { method?: ((entity?: any, state?: RootState) => string) | string, url?: ((entity?: any, state?: RootState, query?: QueryPayload, slice?: keyof RootState) => string) | string, options?: (entity?: any, state?: RootState, query?: QueryPayload) => RequestOptionsArgs, response?: (resp: any, entity?: any, state?: RootState, query?: QueryPayload) => any } type EntityConfig = { url?: ((entity?: any, state?: RootState, query?: QueryPayload) => string) | string, options?: (entity?: any, state?: RootState, query?: QueryPayload) => RequestOptionsArgs, getEntity?: APIConfig, getEntities?: APIConfig, update?: APIConfig, remove?: APIConfig, add?: APIConfig, } const GOOGLE_ROOT = 'https://www.googleapis.com/books/v1/volumes'; const apis: { [entity: string]: EntityConfig } = { article: { url: 'articles', update: { url: (article, state) => { const slug = state.article.entities[article.id].slug; if (article.favorited === true || article.favorited === false) { return `${config.apiUrl}/articles/${slug}/favorite`; } return `${config.apiUrl}/articles/${slug}`; }, method: (article, state) => { if (article.favorited === true) { return 'post'; } if (article.favorited === false) { return 'delete'; } return 'put'; }, options: (article, state, query) => (typeof article.favorited !== 'undefined') ? null : article, response: (resp, article) => ({ id: article.id, ...resp }) // the slug could be different if the title changed }, // getEntity: { // url: (article, state) => { // const slug = article.id; // return `${config.apiUrl}/articles/${slug}`; // } // }, getEntities: { url: (article, state: RootState) => { return `${config.apiUrl}/articles` + ((state.layout.blogPage.type === 'feed') ? '/feed' : ''); }, options: (article, state, query) => ({ params: getParamsFromQuery(query) }) } }, claim: { url: 'claims' }, claimRebuttal: { url: 'claim-rebuttals', getEntities: { response: (resp, claimRebuttal, state, query) => { return ({ ...resp, entities: resp.entities.map((cr) => ({ ...cr, id: '' + cr.id, claimId: '' + cr.claimId, rebuttalId: '' + cr.rebuttalId })) }); } } }, comment: { url: 'comments', add: { url: (comment: Comment, state: RootState) => { const slug = comment.articleId; return `${config.apiUrl}/articles/${slug}/comments`; }, options: (entity, state, query) => ({ body: entity.body }), response: (resp, comment) => ({ ...resp, articleId: comment.articleId }) }, remove: { url: (comment: Comment, state: RootState) => { const slug = comment.articleId; return `${config.apiUrl}/articles/${slug}/comments/${comment.id}`; } }, getEntities: { url: (comment: Comment, state: RootState, query: QueryPayload) => { const slug = query['slug']; return `${config.apiUrl}/articles/${slug}/comments`; }, response: (resp, comment, state, query) => { return ({ ...resp, entities: resp.entities.map((comment) => ({ articleId: query['slug'], ...comment })) }); } } }, contact: { url: 'contacts' }, crisis: { url: 'crises' }, hero: { url: 'heroes' }, note: { url: 'notes' }, profile: { url: 'profiles', update: { method: (profile, state) => { if (profile.following === true) { return 'post'; } if (profile.following === false) { return 'delete'; } return 'put'; }, url: (profile, state) => { const username = state.profile.entities[profile.id].username; if (profile.following === true || profile.following === false) { return `${config.apiUrl}/profiles/${username}/follow`; } return `${config.apiUrl}/profiles`; }, options: (profile, state, query) => (typeof profile.following !== 'undefined') ? null : profile }, getEntities: { url: (profile, state, query) => { const id = query['id']; return `${config.apiUrl}/profiles/${id}`; } } }, rebuttal: { url: 'rebuttals' }, search: { url: 'books', getEntity: { url: (book, state, query) => { return `${GOOGLE_ROOT}/${book.id}`; } }, getEntities: { url: (book, state, query) => { if (typeof query === 'object') { throw new Error(`Invalid parameter [query] passed to book getEntities: ${query}`); } return `${GOOGLE_ROOT}?q=${query}`; }, response: (resp, entity) => resp.items } }, tag: { url: 'tags', getEntities: { response: (resp) => resp.map((tag) => { return { id: tag, name: tag }; }) } }, talk: { url: 'talks' }, defaults: { options: (entity, state, query) => entity, add: { method: 'post', url: (entity, state, query, slice) => `${config.apiUrl}/${apis[slice].url}` }, update: { method: 'put', url: (entity, state, query, slice) => `${config.apiUrl}/${apis[slice].url}` }, getEntity: { url: (entity, state, query, slice) => `${config.apiUrl}/${apis[slice].url}/${entity.id}` }, getEntities: { url: (entity, state, query, slice) => `${config.apiUrl}/${apis[slice].url}` }, remove: { url: (entity, state, query, slice) => `${config.apiUrl}/${apis[slice].url}/${entity.id}` } } } const getParamsFromQuery = (query: QueryPayload) => { const params: URLSearchParams = new URLSearchParams(); if (query && typeof query === 'object') { Object.keys(query) .forEach((key) => { if (query[key] !== null) { params.set(key, '' + query[key]); } }); } return params; } @Injectable() export class RESTService implements DataService { constructor(private http: Http, private config: AppConfig) { } private getUrl(slice: keyof RootState, state: RootState, entity: any, query: QueryPayload, job: string): string { return apis[slice][job] && (typeof apis[slice][job].url === 'function') && apis[slice][job].url(entity, state, query) || (typeof apis.defaults[job].url === 'function') && apis.defaults[job].url(entity, state, query, slice); } private getOptions(slice: keyof RootState, state: RootState, entity: any, query: QueryPayload, job: string): RequestOptionsArgs { // remove the infrastructure parts of the entity const newEntity = { ...this.prepareEntity(entity) }; return apis[slice][job] && (typeof apis[slice][job].options === 'function') && apis[slice][job].options(newEntity, state, query) || (typeof apis.defaults[job].options === 'function') && apis.defaults[job].options(newEntity, state, query) || (typeof apis.defaults.options === 'function') && apis.defaults.options(newEntity, state, query); } private getMethod(slice: keyof RootState, state: RootState, entity: any, query: QueryPayload, job: string): string { return apis[slice][job] && (typeof apis[slice][job].method === 'function') && apis[slice][job].method(entity, state) || apis.defaults[job].method; } private getResponse(slice: keyof RootState, state: RootState, entity: any, query: QueryPayload, job: string): any { return (resp: any) => { return apis[slice][job] && (typeof apis[slice][job].response === 'function') && apis[slice][job].response(resp, entity, state, query) || resp; } } getEntities(slice: keyof RootState, query: QueryPayload = null, state: RootState): Observable<any[]> { const url = this.getUrl(slice, state, null, query, 'getEntities'); const options = this.getOptions(slice, state, null, query, 'getEntities'); return this.http.get(url, options) .map(this.extractData) .map(this.getResponse(slice, state, null, query, 'getEntities')) .catch(this.handleError); } getEntity(slice: keyof RootState, id: string, state: RootState): Observable<any> { const url = this.getUrl(slice, state, { id }, null, 'getEntity'); const options = this.getOptions(slice, state, null, null, 'getEntity'); return this.http.get(url, options) .map(this.extractData) .map(this.getResponse(slice, state, null, null, 'getEntity')) .catch(this.handleError); } add(slice: keyof RootState, entity: Entity, state: RootState, store: Store<RootState>): Observable<any> { const url = this.getUrl(slice, state, entity, null, 'add'); const options = this.getOptions(slice, state, entity, null, 'add'); return this.http.post(url, options) .map((result) => { let oldObject = {}; const newObject = this.extractData(result); const tempEntity = state[slice].entities[EntityActions.TEMP]; if (tempEntity) { oldObject = completeAssign({}, ...tempEntity); if (typeof oldObject['id'] !== 'undefined') { delete oldObject['id']; } store.dispatch(new EntityActions.DeleteTemp(slice)); } return completeAssign(oldObject, newObject); }) .map(this.getResponse(slice, state, entity, null, 'add')) .catch((error: Response | any) => { if (state[slice].entities[EntityActions.TEMP]) { store.dispatch(new EntityActions.RestoreTemp(slice)); } return this.handleError(error); }); } get(route: string): Observable<any> { return this.http.get(`${this.config.apiUrl}/${route}`) .map(this.extractData) .catch(this.handleError); } post(route: string, object: any): Observable<any> { return this.http.post(`${this.config.apiUrl}/${route}`, this.prepareEntity(object)) .map(this.extractData) .catch(this.handleError); } update(slice: keyof RootState, entity: Entity, state: RootState, store: Store<RootState>): Observable<any> { const url = this.getUrl(slice, state, entity, null, 'update'); const method = this.getMethod(slice, state, entity, null, 'update'); const options = this.getOptions(slice, state, entity, null, 'update'); return this.http[method](url, options) .map(this.extractData) .catch(this.handleError); } remove(slice: keyof RootState, entity: Entity, state: RootState, store: Store<RootState>): Observable<any> { const url = this.getUrl(slice, state, entity, null, 'remove'); return this.http.delete(url) .map(this.extractData) .catch(this.handleError); } /** * Remove all the utility parts of the entity */ prepareEntity(entity: any) { const newEntity = { ...entity }; delete newEntity.dirty; delete newEntity.loading; delete newEntity.slice; return newEntity; } extractData(res: any) { if (res.status < 200 || res.status >= 300) { throw new Error('Bad response status: ' + res.status); } let obj = (res && !!res._body && res.json()) || res.data || { id: res.url.match(/[^\/]+$/)[0] }; if (Array.isArray(obj)) { obj = { entities: obj, totalItems: +res.headers.get('X-Total-Count') } } return obj; } handleError(error: Response | any) { // In a real world app, we might use a remote logging infrastructure let errMsg: string; if (error instanceof Response) { const body = error.json() || ''; const err = body.error || JSON.stringify(body); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); const id = error.url.match(/[^\/]+$/)[0]; // if DELETE_FAIL, get id from resp.url return Observable.throw({ errMsg, id }) } }
the_stack
import m from 'mithril'; import prop from 'mithril/stream'; import _ from 'underscore'; import projectVM from './project-vm'; import addressVM from './address-vm'; import models from '../models'; import h from '../h'; import { getCurrentUserCached } from '../shared/services/user/get-current-user-cached'; const I18nScope = _.partial(h.i18nScope, 'projects.contributions.edit.errors'); const paymentInfoId = prop(); const { commonPayment, commonSubscriptionUpgrade, commonPaymentInfo, commonCreditCard, commonCreditCards, rechargeSubscription } = models; const sendPaymentRequest = data => commonPayment.postWithToken( { data: _.extend({}, data, { payment_id: paymentInfoId() }) }, null, (h.isDevEnv() ? { 'X-forwarded-For': '127.0.0.1' } : {}) ) .catch((error) => { h.captureException(error); throw error; }); const sendSubscriptionUpgrade = data => commonSubscriptionUpgrade.postWithToken( { data }, null, (h.isDevEnv() ? { 'X-forwarded-For': '127.0.0.1' } : {}) ) .catch((error) => { h.captureException(error); throw error; }); const saveCreditCard = creditCardHash => commonCreditCard .postWithToken({ data: { card_hash: creditCardHash } }) .catch((error) => { h.captureException(error); throw error; });; const updateUser = user => m.request({ method: 'PUT', url: `/users/${user.id}.json`, data: { user }, config: h.setCsrfToken }) .catch((error) => { h.captureException(error); throw error; }); const userPayload = (customer, address) => ({ id: getCurrentUserCached().id, cpf: customer.ownerDocument(), name: customer.completeName(), address_attributes: { country_id: address.country_id, state_id: address.state_id, address_street: address.address_street, address_neighbourhood: address.address_neighbourhood, address_number: address.address_number, address_zip_code: address.address_zip_code, address_city: address.address_city, address_state: address.address_state, address_complement: address.address_complement, phone_number: address.phone_number } }); const displayError = fields => (exception) => { const errorMsg = exception.message || window.I18n.t('submission.encryption_error', I18nScope()); fields.isLoading(false); fields.submissionError(window.I18n.t('submission.error', I18nScope({ message: errorMsg }))); m.redraw(); h.captureException(exception); }; const paymentInfo = paymentId => commonPaymentInfo .postWithToken({ id: paymentId }, null, (h.isDevEnv() ? { 'X-forwarded-For': '127.0.0.1' } : {})) .catch((error) => { h.captureException(error); throw error; }); const creditCardInfo = creditCard => commonCreditCards .getRowWithToken(h.idVM.id(creditCard.id).parameters()) .catch((error) => { h.captureException(error); throw error; }); let retries = 10; const isReactivation = () => { const subscriptionStatus = m.route.param('subscription_status'); return subscriptionStatus === 'inactive' || subscriptionStatus === 'canceled'; }; const resolvePayment = (gateway_payment_method, payment_confirmed, payment_id, isEdit) => m.route.set(`/projects/${projectVM.currentProject().project_id}/subscriptions/thank_you?project_id=${projectVM.currentProject().project_id}&payment_method=${gateway_payment_method}&payment_confirmed=${payment_confirmed}${payment_id ? `&payment_id=${payment_id}` : ''}${isEdit && !isReactivation() ? '&is_edit=1' : ''}`); const requestInfo = (promise, paymentId, defaultPaymentMethod, isEdit) => { if (retries <= 0) { return promise.resolve(resolvePayment(defaultPaymentMethod, false, paymentId, isEdit)); } paymentInfo(paymentId).then((infoR) => { if (_.isNull(infoR.gateway_payment_method) || _.isUndefined(infoR.gateway_payment_method)) { if (!_.isNull(infoR.gateway_errors)) { return promise.reject(_.first(infoR.gateway_errors)); } return h.sleep(4000).then(() => { retries -= 1; return requestInfo(promise, paymentId, defaultPaymentMethod); }); } return promise.resolve(resolvePayment(infoR.gateway_payment_method, true, paymentId, isEdit)); }).catch(error => promise.reject({})); }; const getPaymentInfoUntilNoError = (paymentMethod, isEdit) => ({ id, catalog_payment_id }) => { const p = new Promise((resolve, reject) => { const paymentId = isEdit ? catalog_payment_id : id; if (paymentId) { paymentInfoId(paymentId); requestInfo({resolve, reject}, paymentId, paymentMethod, isEdit); } else { resolvePayment(paymentMethod, false, null, isEdit); } }); return p; }; let creditCardRetries = 5; const waitForSavedCreditCard = promise => (creditCardId) => { if (creditCardRetries <= 0) { return promise.reject({ message: I18n.t('submission.card_processing_failure', I18nScope()) }); } creditCardInfo(creditCardId).then(([infoR]) => { if (_.isEmpty(infoR.gateway_data)) { if (!_.isEmpty(infoR.gateway_errors)) { return promise.reject(_.first(infoR.gateway_errors)); } return h.sleep(4000).then(() => { creditCardRetries -= 1; return waitForSavedCreditCard(promise)(creditCardId); }); } return promise.resolve({ creditCardId }); }).catch(error => promise.reject({ message: error.message })); return promise; }; const processCreditCard = (cardHash, fields) => { const p = new Promise((resolve, reject) => { saveCreditCard(cardHash) .then(waitForSavedCreditCard({resolve, reject})) .catch(reject); }); return p; }; const kondutoExecute = function () { const currentUser = getCurrentUserCached(); const customerID = currentUser.common_id; if (customerID) { var period = 300; var limit = 20 * 1e3; var nTry = 0; var intervalID = setInterval(function () { var clear = limit / period <= ++nTry; if ((typeof (Konduto) !== "undefined") && (typeof (Konduto.setCustomerID) !== "undefined")) { window.Konduto.setCustomerID(customerID); clear = true; } if (clear) { clearInterval(intervalID); } }, period); } }; const sendCreditCardPayment = (selectedCreditCard, fields, commonData, addVM) => { if (!fields) { return false; } fields.isLoading(true); m.redraw(); const meta = _.first(document.querySelectorAll('[name=pagarme-encryption-key]')); const encryptionKey = meta.getAttribute('content'); window.pagarme.encryption_key = encryptionKey; const card = h.buildCreditCard(fields.creditCardFields); const customer = fields.fields; const address = customer.address().getFields(); const phoneDdd = address.phone_number ? h.extractPhoneDDD(address.phone_number) : null; const phoneNumber = address.phone_number ? h.extractPhoneNumber(address.phone_number) : null; const addressState = address.state_id ? _.findWhere(addVM.states(), { id: address.state_id }) : address.address_state; const addressCountry = _.findWhere(addVM.countries(), { id: address.country_id }) || {}; window.pagarme.client.connect({ encryption_key: encryptionKey }) .then(client => client.security.encrypt(card)) .then((cardHash) => { const payload = { subscription: true, anonymous: customer.anonymous(), user_id: commonData.userCommonId, project_id: commonData.projectCommonId, amount: commonData.amount, payment_method: 'credit_card', credit_card_owner_document: fields.creditCardFields.cardOwnerDocument(), is_international: address.country_id !== addVM.defaultCountryID, customer: { name: customer.completeName(), document_number: customer.ownerDocument(), address: { neighborhood: address.address_neighbourhood, street: address.address_street, street_number: address.address_number, zipcode: address.address_zip_code, country: addressCountry.name, country_code: addressCountry.code, state: addressState.acronym ? addressState.acronym : addressState, city: address.address_city, complementary: address.address_complement }, phone: { ddi: '55', ddd: phoneDdd, number: phoneNumber } } }; if (commonData.rewardCommonId) { _.extend(payload, { reward_id: commonData.rewardCommonId }); } if (commonData.subscription_id) { _.extend(payload, { id: commonData.subscription_id }); } const pay = ({ creditCardId }) => { kondutoExecute() const p = new Promise((resolve, reject) => { if (creditCardId) { _.extend(payload, { card_id: creditCardId.id, credit_card_id: creditCardId.id }); } if (commonData.subscription_id) { sendSubscriptionUpgrade(payload).then(resolve).catch(reject); } else { sendPaymentRequest(payload).then(resolve).catch(reject); } }); return p; }; updateUser(userPayload(customer, address)) .then(() => processCreditCard(cardHash, fields)) .then(pay) .then(getPaymentInfoUntilNoError(payload.payment_method, Boolean(commonData.subscription_id))) .catch(displayError(fields)); }); }; const sendSlipPayment = (fields, commonData) => { fields.isLoading(true); m.redraw(); const customer = fields.fields; const address = customer.address().getFields(); const phoneDdd = address.phone_number ? h.extractPhoneDDD(address.phone_number) : null; const phoneNumber = address.phone_number ? h.extractPhoneNumber(address.phone_number) : null; const addressState = _.findWhere(addressVM.states(), { id: address.state_id }); const addressCountry = _.findWhere(addressVM.countries(), { id: address.country_id }); const payload = { subscription: true, anonymous: customer.anonymous(), user_id: commonData.userCommonId, project_id: commonData.projectCommonId, amount: commonData.amount, payment_method: 'boleto', customer: { name: customer.completeName(), document_number: customer.ownerDocument(), address: { neighborhood: address.address_neighbourhood, street: address.address_street, street_number: address.address_number, zipcode: address.address_zip_code, // TOdO: remove hard-coded country when international support is added on the back-end country: 'Brasil', country_code: 'BR', state: addressState.acronym, city: address.address_city, complementary: address.address_complement }, phone: { ddi: '55', ddd: phoneDdd, number: phoneNumber } } }; if (commonData.rewardCommonId) { _.extend(payload, { reward_id: commonData.rewardCommonId }); } if (commonData.subscription_id) { _.extend(payload, { id: commonData.subscription_id }); } const sendPayment = () => { const p = new Promise((resolve, reject) => { if (commonData.subscription_id) { sendSubscriptionUpgrade(payload).then(resolve).catch(reject); } else { sendPaymentRequest(payload).then(resolve).catch(reject); } }); return p; }; updateUser(userPayload(customer, address)) .then(sendPayment) .then(getPaymentInfoUntilNoError(payload.payment_method, Boolean(commonData.subscription_id))) .catch(displayError(fields)); }; // Makes a request count down of retries of getting payment info const trialsToGetPaymentInfo = (p, catalog_payment_id, retries) => { if (retries > 0) { paymentInfo(catalog_payment_id).then((infoR) => { if (_.isNull(infoR.gateway_payment_method) || _.isUndefined(infoR.gateway_payment_method)) { if (!_.isNull(infoR.gateway_errors)) { return p.reject(_.first(infoR.gateway_errors)); } return h.sleep(4000).then(() => trialsToGetPaymentInfo(p, catalog_payment_id, retries - 1)); } return p.resolve({ boleto_url: infoR.boleto_url, boleto_expiration_date: infoR.boleto_expiration_date, boleto_barcode: infoR.boleto_barcode, status: infoR.status }); }).catch(() => p.reject({})); } else { return p.reject({}); } return p.promise; }; // Try recharge a payment if it's slip is expired, pinging /rpc/payment_info endpoint // looking up for new payment_info const tryRechargeSubscription = (subscription_id) => { const p = new Promise((resolve, reject) => { rechargeSubscription .postWithToken({ subscription_id }) .then(payment_data => trialsToGetPaymentInfo({resolve, reject}, payment_data.catalog_payment_id, 5)) .catch((error) => { h.captureException(error); throw error; }) .catch(reject); }); return p; }; const commonPaymentVM = { sendCreditCardPayment, sendSlipPayment, paymentInfo, tryRechargeSubscription }; export default commonPaymentVM;
the_stack
module androidui.widget { import View = android.view.View; import Gravity = android.view.Gravity; import ViewGroup = android.view.ViewGroup; import MotionEvent = android.view.MotionEvent; import FrameLayout = android.widget.FrameLayout; import AbsListView = android.widget.AbsListView; import ScrollView = android.widget.ScrollView; import OverScroller = android.widget.OverScroller; import Integer = java.lang.Integer; export interface OverScrollLocker { lockOverScrollTop(lockTop:number):void; lockOverScrollBottom(lockBottom:number):void; getScrollContentBottom():number; } export module OverScrollLocker{ const InstanceMap = new WeakMap<View, OverScrollLocker>(); export function getFrom(view:View):OverScrollLocker { let scrollLocker = InstanceMap.get(view); if(!scrollLocker){ if(view instanceof AbsListView){ scrollLocker = new ListViewOverScrollLocker(view); }else if(view instanceof ScrollView){ scrollLocker = new ScrollViewScrollLocker(view); } if(scrollLocker) InstanceMap.set(view, scrollLocker); } return scrollLocker; } abstract class BaseOverScrollLocker implements OverScrollLocker{ lockTop:number; lockBottom:number; isInTouch:boolean; view:View; constructor(view:View){ this.view = view; const onTouchEventFunc = view.onTouchEvent; view.onTouchEvent = (event:MotionEvent):boolean =>{ let result = onTouchEventFunc.call(view, event); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: this.isInTouch = true; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: this.isInTouch = false; break; } return result; } } lockOverScrollTop(lockTop:number):void { this.lockTop = lockTop; if(!this.isInTouch && this.getOverScrollY() < -lockTop){ this.springBackToLockTop(); } } lockOverScrollBottom(lockBottom:number):void { this.lockBottom = lockBottom; if(!this.isInTouch && this.getOverScrollY() > lockBottom){ this.springBackToLockBottom(); } } abstract getOverScrollY():number; abstract getScrollContentBottom():number; abstract springBackToLockTop():void; abstract springBackToLockBottom():void; } class ListViewOverScrollLocker extends BaseOverScrollLocker{ listView:AbsListView; constructor(listView:AbsListView){ super(listView); this.listView = listView; this.configListView(); } private configListView(){ let listView = this.listView; if(!listView.mFlingRunnable) listView.mFlingRunnable = new AbsListView.FlingRunnable(listView); const scroller:OverScroller = listView.mFlingRunnable.mScroller; listView.mFlingRunnable.startOverfling = (initialVelocity:number)=>{ scroller.setInterpolator(null); let minY = Integer.MIN_VALUE, maxY = Integer.MAX_VALUE; if(listView.mScrollY < 0) minY = -this.lockTop; else if(listView.mScrollY > 0) maxY = this.lockBottom; scroller.fling(0, listView.mScrollY, 0, initialVelocity, 0, 0, minY, maxY, 0, listView._mOverflingDistance);//listView.getHeight() listView.mTouchMode = AbsListView.TOUCH_MODE_OVERFLING; listView.invalidate(); listView.postOnAnimation(listView.mFlingRunnable); }; const layoutChildrenFunc = listView.layoutChildren; listView.layoutChildren = () => { const overScrollY = this.getOverScrollY(); layoutChildrenFunc.call(listView); if(overScrollY!==0){ listView.overScrollBy(0, -overScrollY, 0, listView.mScrollY, 0, 0, 0, listView.mOverscrollDistance, false); const atEdge:boolean = listView.trackMotionScroll(-overScrollY, -overScrollY); if(atEdge){ listView.overScrollBy(0, overScrollY, 0, listView.mScrollY, 0, 0, 0, listView.mOverscrollDistance, false); }else{ //listView.mTouchMode = AbsListView.TOUCH_MODE_SCROLL; listView.mFlingRunnable.mScroller.abortAnimation(); } } }; listView.checkOverScrollStartScrollIfNeeded = ():boolean =>{ return listView.mScrollY > this.lockBottom || listView.mScrollY < this.lockTop; }; listView.mFlingRunnable.edgeReached = (delta:number)=>{ let initialVelocity = listView.mFlingRunnable.mScroller.getCurrVelocity(); if(delta>0) initialVelocity = -initialVelocity; listView.mFlingRunnable.startOverfling(initialVelocity); }; const oldSpringBack = scroller.springBack; scroller.springBack = (startX:number, startY:number, minX:number, maxX:number, minY:number, maxY:number):boolean=> { minY = -this.lockTop; maxY = this.lockBottom; return oldSpringBack.call(scroller, startX, startY, minX, maxX, minY, maxY); }; const oldFling = scroller.fling; scroller.fling = (startX:number, startY:number, velocityX:number, velocityY:number, minX:number, maxX:number, minY:number, maxY:number, overX=0, overY=0):void =>{ if(velocityY>0) overY += this.lockBottom; else overY += this.lockTop; oldFling.call(scroller, startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, overX, overY); }; } getScrollContentBottom():number { let childCount = this.listView.getChildCount(); let maxBottom = 0; let minTop = 0; for(let i=0; i<childCount; i++){ let child = this.listView.getChildAt(i); let childBottom = child.getBottom(); let childTop = child.getTop(); if(childBottom > maxBottom){ maxBottom = childBottom; } if(childTop < minTop){ minTop = childTop; } } if(minTop>0) minTop = 0; if(this.listView.getAdapter() && childCount>0){ return (maxBottom - minTop) * this.listView.getAdapter().getCount() / childCount; } return 0; } getOverScrollY():number { return this.listView.mScrollY; } private startSpringBack(){ this.listView.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_FLING); //springBack func has been override, the args will change later this.listView.mFlingRunnable.mScroller.springBack(0, this.listView.mScrollY, 0, 0, 0, 0); this.listView.mTouchMode = AbsListView.TOUCH_MODE_OVERFLING; this.listView.postOnAnimation(this.listView.mFlingRunnable); } springBackToLockTop():void { this.startSpringBack(); } springBackToLockBottom():void { this.startSpringBack(); } } class ScrollViewScrollLocker extends BaseOverScrollLocker{ scrollView:ScrollView; constructor(scrollView:ScrollView){ super(scrollView); this.scrollView = scrollView; const scroller = scrollView.mScroller; const oldSpringBack = scroller.springBack; scroller.springBack = (startX:number, startY:number, minX:number, maxX:number, minY:number, maxY:number):boolean=> { minY = -this.lockTop; maxY = this.scrollView.getScrollRange() + this.lockBottom; return oldSpringBack.call(scroller, startX, startY, minX, maxX, minY, maxY); }; const oldFling = scroller.fling; scroller.fling = (startX:number, startY:number, velocityX:number, velocityY:number, minX:number, maxX:number, minY:number, maxY:number, overX=0, overY=0):void =>{ if(velocityY>0) overY += this.lockBottom; else overY += this.lockTop; minY -= this.lockTop; maxY += this.lockBottom; oldFling.call(scroller, startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, overX, overY); }; this.listenScrollContentHeightChange(); } private listenScrollContentHeightChange(){ const listenHeightChange = (v:View)=>{ const onSizeChangedFunc = v.onSizeChanged; v.onSizeChanged = (w: number, h: number, oldw: number, oldh: number): void =>{ onSizeChangedFunc.call(v, w, h, oldw, oldh); //awake the scroll bar & check the footer header position this.scrollView.overScrollBy(0, 0, 0, this.scrollView.mScrollY, 0, this.scrollView.getScrollRange(), 0, this.scrollView.mOverscrollDistance, false); } }; if(this.scrollView.getChildCount()>0){ listenHeightChange(this.scrollView.getChildAt(0)); }else{ const onViewAddedFunc = this.scrollView.onViewAdded; this.scrollView.onViewAdded = (v:View):void =>{ onViewAddedFunc.call(this.scrollView, v); listenHeightChange(v); } } } getScrollContentBottom():number { if (this.scrollView.getChildCount() > 0) { return this.scrollView.getChildAt(0).getBottom(); } return this.scrollView.getPaddingTop(); } getOverScrollY():number { let scrollY = this.scrollView.getScrollY(); if(scrollY < 0) return scrollY; let scrollRange = this.scrollView.getScrollRange(); if(scrollY > scrollRange){ return scrollY - scrollRange; } return 0; } private startSpringBack(){ if (this.scrollView.mScroller.springBack(this.scrollView.mScrollX, this.scrollView.mScrollY, 0, 0, 0, this.scrollView.getScrollRange())) { this.scrollView.postInvalidateOnAnimation(); } } springBackToLockTop():void { this.startSpringBack(); } springBackToLockBottom():void { this.startSpringBack(); } } } }
the_stack
import type {Class, Initable} from "@swim/util"; import {Affinity, MemberFastenerClass, Animator} from "@swim/component"; import {AnyLength, Length, AnyAngle, Angle, AnyR2Point, R2Point, R2Box} from "@swim/math"; import {AnyFont, Font, AnyColor, Color} from "@swim/style"; import {Look, ThemeAnimator} from "@swim/theme"; import {ViewContextType, AnyView, View, ViewRef, ViewSet} from "@swim/view"; import {GraphicsViewInit, GraphicsView, TypesetView, TextRunView} from "@swim/graphics"; import {AnyDialView, DialView} from "../dial/DialView"; import type {GaugeViewObserver} from "./GaugeViewObserver"; /** @public */ export type AnyGaugeView = GaugeView | GaugeViewInit; /** @public */ export interface GaugeViewInit extends GraphicsViewInit { limit?: number; center?: AnyR2Point; innerRadius?: AnyLength; outerRadius?: AnyLength; startAngle?: AnyAngle; sweepAngle?: AnyAngle; cornerRadius?: AnyLength; dialSpacing?: AnyLength; dialColor?: AnyColor; meterColor?: AnyColor; labelPadding?: AnyLength; tickAlign?: number; tickRadius?: AnyLength; tickLength?: AnyLength; tickWidth?: AnyLength; tickPadding?: AnyLength; tickColor?: AnyColor; font?: AnyFont; textColor?: AnyColor; title?: GraphicsView | string; dials?: AnyDialView[]; } /** @public */ export interface GaugeViewDialExt { attachLabelView(labelView: GraphicsView): void; detachLabelView(labelView: GraphicsView): void; attachLegendView(legendView: GraphicsView): void; detachLegendView(legendView: GraphicsView): void; } /** @public */ export class GaugeView extends GraphicsView { override readonly observerType?: Class<GaugeViewObserver>; @Animator({type: Number, value: 0, updateFlags: View.NeedsLayout}) readonly limit!: Animator<this, number>; @Animator({type: R2Point, value: R2Point.origin(), updateFlags: View.NeedsLayout}) readonly center!: Animator<this, R2Point, AnyR2Point>; @ThemeAnimator({type: Length, value: Length.pct(30), updateFlags: View.NeedsLayout}) readonly innerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.pct(40), updateFlags: View.NeedsLayout}) readonly outerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Angle, value: Angle.rad(-Math.PI / 2), updateFlags: View.NeedsLayout}) readonly startAngle!: ThemeAnimator<this, Angle, AnyAngle>; @ThemeAnimator({type: Angle, value: Angle.rad(2 * Math.PI), updateFlags: View.NeedsLayout}) readonly sweepAngle!: ThemeAnimator<this, Angle, AnyAngle>; @ThemeAnimator({type: Length, value: Length.pct(50)}) readonly cornerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.px(1), updateFlags: View.NeedsLayout}) readonly dialSpacing!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Color, value: null, look: Look.subduedColor}) readonly dialColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Color, value: null, look: Look.accentColor}) readonly meterColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Length, value: Length.pct(25)}) readonly labelPadding!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Number, value: 1.0}) readonly tickAlign!: ThemeAnimator<this, number>; @ThemeAnimator({type: Length, value: Length.pct(45)}) readonly tickRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.pct(50)}) readonly tickLength!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.px(1)}) readonly tickWidth!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.px(2)}) readonly tickPadding!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Color, value: null, look: Look.neutralColor}) readonly tickColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Font, value: null, inherits: true}) readonly font!: ThemeAnimator<this, Font | null, AnyFont | null>; @ThemeAnimator({type: Color, value: null, look: Look.mutedColor}) readonly textColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ViewRef<GaugeView, GraphicsView & Initable<GraphicsViewInit | string>>({ key: true, type: TextRunView, binds: true, initView(titleView: GraphicsView): void { if (TypesetView.is(titleView)) { titleView.textAlign.setState("center", Affinity.Intrinsic); titleView.textBaseline.setState("middle", Affinity.Intrinsic); titleView.textOrigin.setState(this.owner.center.state, Affinity.Intrinsic); } }, willAttachView(titleView: GraphicsView): void { this.owner.callObservers("viewWillAttachGaugeTitle", titleView, this.owner); }, didDetachView(titleView: GraphicsView): void { this.owner.callObservers("viewDidDetachGaugeTitle", titleView, this.owner); }, fromAny(value: AnyView<GraphicsView> | string): GraphicsView { if (typeof value === "string") { if (this.view instanceof TextRunView) { this.view.text(value); return this.view; } else { return TextRunView.fromAny(value); } } else { return GraphicsView.fromAny(value); } }, }) readonly title!: ViewRef<this, GraphicsView & Initable<GraphicsViewInit | string>>; static readonly title: MemberFastenerClass<GaugeView, "title">; @ViewSet<GaugeView, DialView, GaugeViewDialExt>({ implements: true, type: DialView, binds: true, observes: true, willAttachView(dialView: DialView, targetView: View | null): void { this.owner.callObservers("viewWillAttachDial", dialView, targetView, this.owner); }, didAttachView(dialView: DialView): void { const labelView = dialView.label.view; if (labelView !== null) { this.attachLabelView(labelView); } const legendView = dialView.legend.view; if (legendView !== null) { this.attachLegendView(legendView); } }, willDetachView(dialView: DialView): void { const legendView = dialView.legend.view; if (legendView !== null) { this.detachLegendView(legendView); } const labelView = dialView.label.view; if (labelView !== null) { this.detachLabelView(labelView); } }, didDetachView(dialView: DialView): void { this.owner.callObservers("viewDidDetachDial", dialView, this.owner); }, viewDidSetDialValue(newValue: number, oldValue: number): void { this.owner.requireUpdate(View.NeedsLayout); }, viewWillAttachDialLabel(labelView: GraphicsView): void { this.attachLabelView(labelView); }, viewDidDetachDialLabel(labelView: GraphicsView): void { this.detachLabelView(labelView); }, attachLabelView(labelView: GraphicsView): void { // hook }, detachLabelView(labelView: GraphicsView): void { // hook }, viewWillAttachDialLegend(legendView: GraphicsView): void { this.attachLegendView(legendView); }, viewDidDetachDialLegend(legendView: GraphicsView): void { this.detachLegendView(legendView); }, attachLegendView(legendView: GraphicsView): void { // hook }, detachLegendView(legendView: GraphicsView): void { // hook }, }) readonly dials!: ViewSet<this, DialView> & GaugeViewDialExt; static readonly dials: MemberFastenerClass<GaugeView, "dials">; protected override onLayout(viewContext: ViewContextType<this>): void { super.onLayout(viewContext); this.layoutGauge(this.viewFrame); } protected layoutGauge(frame: R2Box): void { if (this.center.hasAffinity(Affinity.Intrinsic)) { const cx = (frame.xMin + frame.xMax) / 2; const cy = (frame.yMin + frame.yMax) / 2; this.center.setState(new R2Point(cx, cy), Affinity.Intrinsic); } const dialViews = this.dials.views; let autoCount = 0; for (const viewId in dialViews) { const dialView = dialViews[viewId]!; if (dialView.arrangement.value === "auto") { autoCount += 1; } } const size = Math.min(frame.width, frame.height); const gaugeLimit = this.limit.getValue(); const startAngle = this.startAngle.getValue(); const sweepAngle = this.sweepAngle.getValue(); let r0 = this.innerRadius.getValue().pxValue(size); const r1 = this.outerRadius.getValue().pxValue(size); const rs = this.dialSpacing.getValue().pxValue(size); const dr = autoCount > 1 ? (r1 - r0 - rs * (autoCount - 1)) / autoCount : r1 - r0; for (const viewId in dialViews) { const dialView = dialViews[viewId]!; if (dialView.arrangement.value === "auto") { if (isFinite(gaugeLimit)) { const dialLimit = dialView.limit.getValue(); dialView.limit.setState(Math.max(dialLimit, gaugeLimit), Affinity.Intrinsic); } dialView.startAngle.setState(startAngle, Affinity.Intrinsic); dialView.sweepAngle.setState(sweepAngle, Affinity.Intrinsic); dialView.innerRadius.setState(Length.px(r0), Affinity.Intrinsic); dialView.outerRadius.setState(Length.px(r0 + dr), Affinity.Intrinsic); r0 = r0 + dr + rs; } } const titleView = this.title.view; if (TypesetView.is(titleView)) { titleView.textOrigin.setState(this.center.state, Affinity.Intrinsic); } } override init(init: GaugeViewInit): void { super.init(init); if (init.limit !== void 0) { this.limit(init.limit); } if (init.innerRadius !== void 0) { this.innerRadius(init.innerRadius); } if (init.outerRadius !== void 0) { this.outerRadius(init.outerRadius); } if (init.startAngle !== void 0) { this.startAngle(init.startAngle); } if (init.sweepAngle !== void 0) { this.sweepAngle(init.sweepAngle); } if (init.cornerRadius !== void 0) { this.cornerRadius(init.cornerRadius); } if (init.dialSpacing !== void 0) { this.dialSpacing(init.dialSpacing); } if (init.dialColor !== void 0) { this.dialColor(init.dialColor); } if (init.meterColor !== void 0) { this.meterColor(init.meterColor); } if (init.labelPadding !== void 0) { this.labelPadding(init.labelPadding); } if (init.tickAlign !== void 0) { this.tickAlign(init.tickAlign); } if (init.tickRadius !== void 0) { this.tickRadius(init.tickRadius); } if (init.tickLength !== void 0) { this.tickLength(init.tickLength); } if (init.tickWidth !== void 0) { this.tickWidth(init.tickWidth); } if (init.tickPadding !== void 0) { this.tickPadding(init.tickPadding); } if (init.tickColor !== void 0) { this.tickColor(init.tickColor); } if (init.font !== void 0) { this.font(init.font); } if (init.textColor !== void 0) { this.textColor(init.textColor); } if (init.title !== void 0) { this.title(init.title); } const dials = init.dials; if (dials !== void 0) { for (let i = 0, n = dials.length; i < n; i += 1) { const dial = dials[i]!; this.appendChild(DialView.fromAny(dial), dial.key); } } } }
the_stack
'use strict'; import { join } from 'path'; import pfs = require('vs/base/node/pfs'); import { TPromise } from 'vs/base/common/winjs.base'; import { ICmakeService, LibOrExeObject } from 'vs/platform/ros/common/cmake'; import { DOMParser, XMLSerializer } from 'xmldom'; export class CmakeService implements ICmakeService { public _serviceBrand: any; public static MAKE_FILE_NAME = 'CMakeLists.txt'; public static PKG_FILE_NAME = 'package.xml'; // get find_package list public getFindPkg(path: string): TPromise<string[]> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { const srcStr = this.removeComment(contents.toString()); const subStr = srcStr.match(/(\n|^)\s*find_package\s*\(\s*catkin\s+REQUIRED\s+COMPONENTS\b[^\)]*\)/); if (subStr) { const pkgList = subStr[0].replace(/(\n|^)\s*find_package\s*\(\s*catkin\s+REQUIRED\s+COMPONENTS\s*/, '').replace(/\s*\)$/, '').split(/\s+/); return pkgList; } return []; }); } // set find_package list public setFindPkg(path: string, list: string[]): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { const newStr = contents.toString().replace(/(\n|^)\s*find_package\s*\(\s*catkin\s+REQUIRED\b[^\)]*\)/, `\nfind_package(catkin REQUIRED COMPONENTS ${list.join(' ')})`); return pfs.writeFile(filePath, newStr); }); } // set build dependency to package.xml public setBuildDepXml(path: string, list: string[], newList: string[]): TPromise<void> { for (let i = list.length - 1; i >= 0; i--) { if (newList.indexOf(list[i]) >= 0) { list.splice(i, 1); } } return this.delFromBuildDepXml(path, list).then(() => this.addToBuildDepXml(path, newList)); } // Get add_library or add_executable list public getLibOrExeList(path: string): TPromise<LibOrExeObject[]> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { let strArray = contents.toString().match(/(\n|^)\s*(add_library|add_executable)\s*\(\s*\w+/g); let objs: LibOrExeObject[] = []; if (strArray) { for (let i = 0; i < strArray.length; i++) { objs[i] = { name: strArray[i].match(/\w+$/)[0], isLib: /(\n|^)\s*add_library/.test(strArray[i]) }; } } return objs; }); } // Add file name to add_library or add_executable dependency list public addToLibOrExe(path: string, obj: LibOrExeObject, name: string): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { const regExp = new RegExp(`(\\n|^)\\s*${obj.isLib ? 'add_library' : 'add_executable'}\\s*\\(\\s*${obj.name}\\b`); const oldStr = contents.toString(); const subStr = oldStr.match(regExp); const newStr = oldStr.replace(regExp, `${subStr[0]}\n ${name}`); return pfs.writeFile(filePath, newStr); }); } // Add file name to new add_library or add_executable block public addToNewLibOrExe(path: string, obj: LibOrExeObject, name: string): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { const oldStr = contents.toString(); const newStr = `${oldStr}\n\n${obj.isLib ? 'add_library' : 'add_executable'}(${obj.name}\n ${name}\n)\nadd_dependencies(${obj.name} \${\${PROJECT_NAME}_EXPORTED_TARGETS} \${catkin_EXPORTED_TARGETS})\ntarget_link_libraries(${obj.name}\n \${catkin_LIBRARIES}\n)`; return pfs.writeFile(filePath, newStr); }); } // Clear the comment line from content private removeComment(content: string): string { return content.replace(/#.*/g, ''); } // add name to oldStr private addToListString(oldStr: string, name: string, subHeadReg: string, commentReg: string, subHead: string): string { const regExp = new RegExp(`(\\n|^)\\s*${subHeadReg}[^\\)]*\\)`); const srcStr = this.removeComment(oldStr); const subStr = srcStr.match(regExp); if (subStr) { // match ok const regExp2 = new RegExp(`(\\b|\\B)${name.replace('$', '\\$')}(\\b|\\B)`); if (regExp2.test(subStr[0])) { // The same name already exists return null; } const newReg = new RegExp(`(\\n|^)\\s*${subHeadReg}`); const newSub = oldStr.match(newReg); return oldStr.replace(newReg, `${newSub[0]}\n ${name}`); // add name } else { // match failed, find comment const cmtReg = new RegExp(`(\\n|^)\\s*#+\\s*${commentReg}[^\\)]*\\)`); const cmtStr = oldStr.match(cmtReg); if (cmtStr) { // Found in the comment return oldStr.replace(cmtStr[0], `\n${subHead}\n ${name}\n)`); // replace the comment } else { // create a new return `${oldStr}\n\n${subHead}\n ${name}\n)`; } } } // add dependency to find_package private addToFindPkgString(oldStr: string, name: string): string { return this.addToListString(oldStr, name, 'find_package\\s*\\(\\s*catkin\\s+REQUIRED\\s+COMPONENTS\\b', 'find_package\\s*\\(\\s*catkin\\s+REQUIRED\\s+COMPONENTS\\b', 'find_package(catkin REQUIRED COMPONENTS'); } // add dependency to generate_messages private addToGenerateMsgString(oldStr: string, name: string): string { return this.addToListString(oldStr, name, 'generate_messages\\s*\\(\\s*DEPENDENCIES\\b', 'generate_messages\\b', 'generate_messages(DEPENDENCIES'); } // add dependency to catkin_package private addToCatkinPkgString(oldStr: string, name: string): string { const regExp = /(\n|^)\s*catkin_package\s*\([^\)]*\)/; const srcStr = this.removeComment(oldStr); const subStr = srcStr.match(regExp); if (subStr) { // match ok const regExp2 = /\bCATKIN_DEPENDS\b[^\)A-Z]*/; const subStr2 = subStr[0].match(regExp2); if (subStr2) { // match ok const regExp3 = new RegExp(`\\b${name}\\b`); if (regExp3.test(subStr2[0])) { // The same name already exists return null; } const newReg = /\bCATKIN_DEPENDS/; const newSub = subStr[0].match(newReg); return oldStr.replace(subStr[0], subStr[0].replace(newReg, `${newSub[0]}\n ${name}`)); // add name } else { // create a new const newReg = /(\n|^)\s*catkin_package\s*\(/; const newSub = oldStr.match(newReg); return oldStr.replace(newReg, `${newSub[0]}\n CATKIN_DEPENDS\n ${name}`); // add CATKIN_DEPENDS } } else { // match failed, find comment const cmtReg = /(\n|^)\s*#+\s*catkin_package\b[^\)]*\)/; const cmtStr = oldStr.match(cmtReg); if (cmtStr) { // Found in the comment return oldStr.replace(cmtStr[0], `\ncatkin_package\n CATKIN_DEPENDS\n ${name}\n)`); // replace the comment } else { // create a new return `${oldStr}\n\ncatkin_package(\n CATKIN_DEPENDS\n ${name}\n)`; } } } // add name to the list and write to file private addToList(path: string, name: string, subHeadReg: string, commentReg: string, subHead: string): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { const newStr = this.addToListString(contents.toString(), name, subHeadReg, commentReg, subHead); if (newStr) { return pfs.writeFile(filePath, newStr); } return null; }); } // add folder to include_directories public addToIncludeDir(path: string, name: string): TPromise<void> { return this.addToList(path, name, 'include_directories\\s*\\(', 'include_directories\\b', 'include_directories('); } // add name to find_package public addToFindPkg(path: string, name: string): TPromise<void> { return this.addToList(path, name, 'find_package\\s*\\(\\s*catkin\\s+REQUIRED\\s+COMPONENTS\\b', 'find_package\\s*\\(\\s*catkin\\s+REQUIRED\\s+COMPONENTS\\b', 'find_package(catkin REQUIRED COMPONENTS'); } // add file name to the list of message files private addToMsgFilesBase(path: string, name: string, baseName: string): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { let oldStr = contents.toString(); let isChanged: boolean = false; let newStr = this.addToFindPkgString(oldStr, 'message_generation'); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToListString(oldStr, name, `${baseName}\\s*\\(\\s*FILES\\b`, `${baseName}\\b`, `${baseName}(FILES`); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToGenerateMsgString(oldStr, 'std_msgs'); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToCatkinPkgString(oldStr, 'message_runtime'); if (newStr) { oldStr = newStr; isChanged = true; } if (isChanged) { return pfs.writeFile(filePath, oldStr); } return null; }); } // add name to add_message_files public addToMsgFiles(path: string, name: string): TPromise<void> { return this.addToMsgFilesBase(path, name, 'add_message_files'); } // add name to add_service_files public addToSrvFiles(path: string, name: string): TPromise<void> { return this.addToMsgFilesBase(path, name, 'add_service_files'); } // add name to add_action_files public addToActionFiles(path: string, name: string): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { let oldStr = contents.toString(); let isChanged: boolean = false; let newStr = this.addToFindPkgString(oldStr, 'message_generation'); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToFindPkgString(oldStr, 'actionlib_msgs'); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToListString(oldStr, name, 'add_action_files\\s*\\(\\s*FILES\\b', 'add_action_files\\b', 'add_action_files(FILES'); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToGenerateMsgString(oldStr, 'std_msgs'); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToGenerateMsgString(oldStr, 'actionlib_msgs'); if (newStr) { oldStr = newStr; isChanged = true; } newStr = this.addToCatkinPkgString(oldStr, 'message_runtime'); if (newStr) { oldStr = newStr; isChanged = true; } if (isChanged) { return pfs.writeFile(filePath, oldStr); } return null; }); } // get a empty add_library or add_executable's name private getEmptyLibOrExe(oldStr: string): string { let strArray = oldStr.match(/(\n|^)\s*(add_library|add_executable)\s*\(\s*\w+\s*\)/); if (strArray) { return strArray[0].match(/\w+\s*\)/)[0].match(/\w+/)[0]; } return null; } // delete path name public delPathName(path: string, name: string): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { const regExp = new RegExp(`\\b${name}\\b\\s*`); const oldStr = contents.toString(); let newStr = oldStr.replace(regExp, ''); // delete name if (/\.cpp$/.test(name) || /\.h$/.test(name)) { // delete empty list const LibOrExe = this.getEmptyLibOrExe(newStr); if (LibOrExe) { const regExp2 = new RegExp(`(\\n|^)\\s*(add_library|add_executable)\\s*\\(\\s*${LibOrExe}\\s*\\)`); const regExp3 = new RegExp(`(\\n|^)\\s*add_dependencies\\s*\\(\\s*${LibOrExe}\\s+\\\${\\\${PROJECT_NAME}_EXPORTED_TARGETS}\\s+\\\${catkin_EXPORTED_TARGETS}\\s*\\)`); const regExp4 = new RegExp(`(\\n|^)\\s*target_link_libraries\\s*\\(\\s*${LibOrExe}\\s+\\\${catkin_LIBRARIES}\\s*\\)`); newStr = newStr.replace(regExp2, '').replace(regExp3, '').replace(regExp4, ''); } } else if (/\.msg$/.test(name)) { newStr = newStr.replace(/(\n|^)\s*add_message_files\s*\(\s*FILES\s*\)/, '\n# add_message_files(\n# FILES\n# )'); } else if (/\.srv$/.test(name)) { newStr = newStr.replace(/(\n|^)\s*add_service_files\s*\(\s*FILES\s*\)/, '\n# add_service_files(\n# FILES\n# )'); } else if (/\.action$/.test(name)) { newStr = newStr.replace(/(\n|^)\s*add_action_files\s*\(\s*FILES\s*\)/, '\n# add_action_files(\n# FILES\n# )'); } return pfs.writeFile(filePath, newStr); }); } // rename path name public renamePathName(path: string, name: string, newName: string): TPromise<void> { const filePath = join(path, CmakeService.MAKE_FILE_NAME); return pfs.readFile(filePath).then(contents => { const regExp = new RegExp(`\\b${name}\\b`); const oldStr = contents.toString(); const newStr = oldStr.replace(regExp, newName); // rename return pfs.writeFile(filePath, newStr); }); } // add multiple dependencies to package.xml private addToPackageXml(path: string, element: { key: string, text: string }[]): TPromise<void> { const filePath = join(path, CmakeService.PKG_FILE_NAME); return pfs.readFile(filePath).then(contents => { const doc = new DOMParser().parseFromString(contents.toString(), 'text/xml'); const pkg = doc.getElementsByTagName('package'); const format = pkg[0].getAttribute('format'); element.forEach((value) => { if (format === '2') { if (value.key === 'run_depend') { return; } } else { if (value.key === 'build_export_depend' || value.key === 'exec_depend') { return; } } const elems = doc.getElementsByTagName(value.key); for (let i = 0; i < elems.length; i++) { if (elems[i].firstChild.nodeValue === value.text) { return; } } const elem = doc.createElement(value.key); const txt = doc.createTextNode(value.text); elem.appendChild(txt); pkg[0].appendChild(elem); }); const newStr = new XMLSerializer().serializeToString(doc).replace(/></g, '>\n<'); return pfs.writeFile(filePath, newStr); }); } // delete multiple dependencies from package.xml private delFromPackageXml(path: string, element: { key: string, text: string }[]): TPromise<void> { const filePath = join(path, CmakeService.PKG_FILE_NAME); return pfs.readFile(filePath).then(contents => { const doc = new DOMParser().parseFromString(contents.toString(), 'text/xml'); const pkg = doc.getElementsByTagName('package'); element.forEach((value) => { const elems = doc.getElementsByTagName(value.key); for (let i = 0; i < elems.length; i++) { if (elems[i].firstChild.nodeValue === value.text) { pkg[0].removeChild(elems[i]); } } }); const newStr = new XMLSerializer().serializeToString(doc).replace(/\n\n\n/g, ''); return pfs.writeFile(filePath, newStr); }); } // add message dependencies to package.xml public addToMsgDepXml(path: string): TPromise<void> { return this.addToPackageXml(path, [{ key: 'build_depend', text: 'message_generation' }, { key: 'build_export_depend', text: 'message_generation' }, { key: 'run_depend', text: 'message_runtime' }, { key: 'exec_depend', text: 'message_runtime' }]); } // add build dependencies to package.xml private addToBuildDepXml(path: string, list: string[]): TPromise<void> { return this.addToPackageXml(path, list.map(val => ({ key: 'build_depend', text: val })).concat(list.map(val => ({ key: 'run_depend', text: val })), list.map(val => ({ key: 'build_export_depend', text: val })), list.map(val => ({ key: 'exec_depend', text: val })))); } // delete build dependencies from package.xml private delFromBuildDepXml(path: string, list: string[]): TPromise<void> { return this.delFromPackageXml(path, list.map(val => ({ key: 'build_depend', text: val })).concat(list.map(val => ({ key: 'run_depend', text: val })), list.map(val => ({ key: 'build_export_depend', text: val })), list.map(val => ({ key: 'exec_depend', text: val })))); } }
the_stack
interface Window { FileList: FileList|null; } type HTMLFormField = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | HTMLButtonElement; interface ISettings { [key: string]: boolean; } /** * Defaults */ let formRef: string | HTMLFormElement = null; // Experimental. Don't rely on them yet. let settings = { includeEmptyValuedElements: false, w3cSuccessfulControlsOnly: false }; // Currently matching only '[]'. const keyRegex = /[^\[\]]+|\[\]/g; let $form: HTMLFormElement = null; let $formElements: NodeListOf<HTMLFormField>; /** * Private methods */ /** * Check to see if the object is a HTML node. * * @param {HTMLFormElement} node * @returns {boolean} */ function isDomElementNode(node: HTMLFormElement): boolean { return !!(node && typeof node === 'object' && 'nodeType' in node && node.nodeType === 1); } /** * Check for last numeric key. */ function checkForLastNumericKey(o: {}): string | undefined { if (!o || typeof o !== 'object') { return; } return Object.keys(o).filter(function (elem) { return !isNaN(parseInt(elem, 10)); }).splice(-1)[0]; } /** * Get last numeric key from an object. * @param o object * @return int */ function getLastIntegerKey(o: {}) { var lastKeyIndex = checkForLastNumericKey(o); if (typeof lastKeyIndex === 'string') { return parseInt(lastKeyIndex, 10); } else { return 0; } } /** * Get the next numeric key (like the index from a PHP array) * @param o object * @return int */ function getNextIntegerKey(o: {}) { var lastKeyIndex = checkForLastNumericKey(o); if (typeof lastKeyIndex === 'string') { return parseInt(lastKeyIndex, 10) + 1; } else { return 0; } } /** * Get the real number of properties from an object. * * @param {object} o * @returns {number} */ function getObjLength(o: {}) { if (typeof o !== 'object' || o === null) { return 0; } var l = 0; var k; if (typeof Object.keys === 'function') { l = Object.keys(o).length; } else { for (k in o) { if (o.hasOwnProperty(k)) { l++; } } } return l; } /** * Simple extend of own properties. * Needed for our settings. * * @param {object} destination The object we want to extend. * @param {object} source The object with new properties that we want to add the the destination. * @return {object} */ function extend(settings: ISettings, source: ISettings) { let i: any; for (i in source) { if (source.hasOwnProperty(i)) { settings[i] = source[i]; } } return settings; } // Iteration through collections. // Compatible with IE. function forEach(arr: HTMLCollection, callback: (params: any) => void) { if ([].forEach) { return [].forEach.call(arr, callback); } let i; for (i = 0; i < arr.length; i++) { callback.call(arr, arr[i], i); } return; } // Constructor function init(options: string | [HTMLFormElement]) { // Assign the current form reference. if (!options || typeof options !== 'object' || !options[0]) { return false; } // The form reference is always the first parameter of the method. // Eg: formToObject('myForm') formRef = options[0]; // Override current settings. // Eg. formToObject('myForm', {mySetting: true}) if (typeof options[1] !== 'undefined' && getObjLength(options[1]) > 0) { extend(settings, options[1]); } if (!setForm()) { return false; } if (!setFormElements()) { return false; } return convertToObj(); } // Set the main form object we are working on. function setForm() { switch (typeof formRef) { case 'string': $form = document.getElementById(formRef as string) as HTMLFormElement; break; case 'object': if (isDomElementNode(formRef as HTMLFormElement)) { $form = formRef as HTMLFormElement; } break; } return $form; } function isUploadForm(): boolean { return $form.enctype && $form.enctype === 'multipart/form-data'; } // Set the elements we need to parse. function setFormElements() { $formElements = $form.querySelectorAll('input, textarea, select'); return $formElements.length; } function nodeHasSiblings($domNode: HTMLFormField) { let name = $domNode.name; return Array.prototype.filter.call($formElements, (input: HTMLFormField) => { return input.name === name; }).length > 1; } function isRadio($domNode: HTMLInputElement) { return $domNode.nodeName === 'INPUT' && $domNode.type === 'radio'; } function isCheckbox($domNode: HTMLInputElement) { return $domNode.nodeName === 'INPUT' && $domNode.type === 'checkbox'; } function isFileField($domNode: HTMLInputElement) { return $domNode.nodeName === 'INPUT' && $domNode.type === 'file'; } function isTextarea($domNode: HTMLTextAreaElement) { return $domNode.nodeName === 'TEXTAREA'; } function isSelectSimple($domNode: HTMLSelectElement) { return $domNode.nodeName === 'SELECT' && $domNode.type === 'select-one'; } function isSelectMultiple($domNode: HTMLSelectElement) { return $domNode.nodeName === 'SELECT' && $domNode.type === 'select-multiple'; } function isSubmitButton($domNode: HTMLButtonElement) { return $domNode.nodeName === 'BUTTON' && $domNode.type === 'submit'; } function isChecked($domNode: HTMLInputElement) { return $domNode.checked; } //function isMultiple($domNode){ // return ($domNode.multiple ? true : false); //} function isFileList($domNode: HTMLInputElement) { return (window.FileList && ($domNode.files instanceof <any>window.FileList)); } function getNodeValues($domNode: HTMLFormField) { // We're only interested in the radio that is checked. if (isRadio($domNode as HTMLInputElement)) { return isChecked($domNode as HTMLInputElement) ? ($domNode as HTMLInputElement).value : false; } // We're only interested in the checkbox that is checked. if (isCheckbox($domNode as HTMLInputElement)) { return isChecked($domNode as HTMLInputElement) ? ($domNode as HTMLInputElement).value : false; } // File inputs are a special case. // We have to grab the .files property of the input, which is a FileList. if (isFileField($domNode as HTMLInputElement)) { // Ignore input file fields if the form is not encoded properly. if (isUploadForm()) { // HTML5 compatible browser. if (isFileList($domNode as HTMLInputElement) && ($domNode as HTMLInputElement).files.length > 0) { return ($domNode as HTMLInputElement).files; } else { return ( ($domNode as HTMLInputElement).value && ($domNode as HTMLInputElement).value !== '' ? ($domNode as HTMLInputElement).value : false ); } } else { return false; } } // We're only interested in textarea fields that have values. if (isTextarea($domNode as HTMLTextAreaElement)) { return ( ($domNode as HTMLTextAreaElement).value && ($domNode as HTMLTextAreaElement).value !== '' ? ($domNode as HTMLTextAreaElement).value : false ); } if (isSelectSimple($domNode as HTMLSelectElement)) { if (($domNode as HTMLSelectElement).value && ($domNode as HTMLSelectElement).value !== '') { return ($domNode as HTMLSelectElement).value; } else if ( ($domNode as HTMLSelectElement).options && ($domNode as HTMLSelectElement).options.length && ($domNode as HTMLSelectElement).options[0].value !== '' ) { return ($domNode as HTMLSelectElement).options[0].value; } else { return false; } } // We're only interested in multiple selects that have at least one option selected. if (isSelectMultiple($domNode as HTMLSelectElement)) { if (($domNode as HTMLSelectElement).options && ($domNode as HTMLSelectElement).options.length > 0) { var values: any[] = []; forEach(($domNode as HTMLSelectElement).options, function ($option: HTMLOptionElement) { if ($option.selected) { values.push($option.value); } }); if (settings.includeEmptyValuedElements) { return values; } else { return (values.length ? values : false); } } else { return false; } } // We're only interested if the button is type="submit" if (isSubmitButton($domNode as HTMLButtonElement)) { if (($domNode as HTMLButtonElement).value && ($domNode as HTMLButtonElement).value !== '') { return ($domNode as HTMLButtonElement).value; } if (($domNode as HTMLButtonElement).innerText && ($domNode as HTMLButtonElement).innerText !== '') { return ($domNode as HTMLButtonElement).innerText; } return false; } // Fallback or other non special fields. if (typeof ($domNode as HTMLButtonElement).value !== 'undefined') { if (settings.includeEmptyValuedElements) { return ($domNode as HTMLButtonElement).value; } else { return (($domNode as HTMLButtonElement).value !== '' ? ($domNode as HTMLButtonElement).value : false); } } else { return false; } } function processSingleLevelNode($domNode: HTMLFormField, arr: any[], domNodeValue: any, result: any) { // Get the last remaining key. var key = arr[0]; // We're only interested in the radio that is checked. if (isRadio($domNode as HTMLInputElement)) { if (domNodeValue !== false) { result[key] = domNodeValue; return domNodeValue; } else { return; } } // Checkboxes are a special case. // We have to grab each checked values // and put them into an array. if (isCheckbox($domNode as HTMLInputElement)) { if (domNodeValue !== false) { if (nodeHasSiblings($domNode)) { if (!result[key]) { result[key] = []; } return result[key].push(domNodeValue); } else { result[key] = domNodeValue; } } else { return; } } // Multiple select is a special case. // We have to grab each selected option and put them into an array. if (isSelectMultiple($domNode as HTMLSelectElement)) { if (domNodeValue !== false) { result[key] = domNodeValue; } else { return; } } // Fallback or other cases that don't // need special treatment of the value. result[key] = domNodeValue; return domNodeValue; } function processMultiLevelNode($domNode: HTMLFormField, arr: any[], value: any, result: any): any { let keyName = arr[0]; if (arr.length > 1) { if (keyName === '[]') { //result.push({}); result[getNextIntegerKey(result) as number] = {}; return processMultiLevelNode( $domNode, arr.splice(1, arr.length), value, result[getLastIntegerKey(result)] ); } else { if (result[keyName] && getObjLength(result[keyName]) > 0) { //result[keyName].push(null); return processMultiLevelNode( $domNode, arr.splice(1, arr.length), value, result[keyName] ); } else { result[keyName] = {}; } return processMultiLevelNode($domNode, arr.splice(1, arr.length), value, result[keyName]); } } // Last key, attach the original value. if (arr.length === 1) { if (keyName === '[]') { //result.push(value); result[getNextIntegerKey(result)] = value; return result; } else { processSingleLevelNode($domNode, arr, value, result); // result[keyName] = value; return result; } } } function convertToObj() { var i = 0; var objKeyNames; var $domNode: HTMLFormField; var domNodeValue; var result = {}; var resultLength; for (i = 0; i < $formElements.length; i++) { $domNode = $formElements[i]; // Skip the element if the 'name' attribute is empty. // Skip the 'disabled' elements. // Skip the non selected radio elements. if ( !$domNode.name || $domNode.name === '' || $domNode.disabled || (isRadio($domNode as HTMLInputElement) && !isChecked($domNode as HTMLInputElement)) ) { continue; } // Get the final processed domNode value. domNodeValue = getNodeValues($domNode as HTMLInputElement); // Exclude empty valued nodes if the settings allow it. if (domNodeValue === false && !settings.includeEmptyValuedElements) { continue; } // Extract all possible keys // Eg. name="firstName", name="settings[a][b]", name="settings[0][a]" objKeyNames = $domNode.name.match(keyRegex); if (objKeyNames.length === 1) { processSingleLevelNode( $domNode, objKeyNames, (domNodeValue ? domNodeValue : ''), result ); } if (objKeyNames.length > 1) { processMultiLevelNode( $domNode, objKeyNames, (domNodeValue ? domNodeValue : ''), result ); } } // Check the length of the result. resultLength = getObjLength(result); return resultLength > 0 ? result : false; }
the_stack
// Key events export const CONSTANTS = { CURRENTLY_RUNNING: (file: string) => { return `Currently running: ${file}`; }, DEVICE_NAME: { CPX: "CPX", MICROBIT: "micro:bit", }, ID_NAME: { BUTTON_A: "BTN_A_OUTER", BUTTON_AB: "BTN_AB_OUTER", BUTTON_B: "BTN_B_OUTER", PIN_A1: "PIN_A1", PIN_A2: "PIN_A2", PIN_A3: "PIN_A3", PIN_A4: "PIN_A4", PIN_A5: "PIN_A5", PIN_A6: "PIN_A6", PIN_A7: "PIN_A7", PLAY_BUTTON: "play-button", REFRESH_BUTTON: "refresh-button", STOP_BUTTON: "stop-button", SWITCH: "SWITCH", }, KEYBOARD_KEYS: { A: "KeyA", B: "KeyB", C: "KeyC", CAPITAL_R: "R", CAPITAL_F: "F", ENTER: "Enter", S: "KeyS", NUMERIC_ONE: "Digit1", NUMERIC_TWO: "Digit2", NUMERIC_THREE: "Digit3", NUMERIC_FOUR: "Digit4", NUMERIC_FIVE: "Digit5", NUMERIC_SIX: "Digit6", NUMERIC_SEVEN: "Digit7", }, FILES_PLACEHOLDER: "The simulator will run the .py file you have focused on.", SIMULATOR_BUTTON_WIDTH: 60, TOOLBAR_INFO: `Explore what's on the board:`, LED_TINT_FACTOR: 0.5, }; export const AB_BUTTONS_KEYS = { BTN_A: "BTN_A", BTN_B: "BTN_B", BTN_AB: "BTN_AB", }; export const BUTTON_CLASSNAME = { ACTIVE: "sim-button-group", DEACTIVATED: "sim-button-group-deactivated", }; export const BUTTON_STYLING_CLASSES = { DEFAULT: "sim-button-outer", KEYPRESSED: "sim-button-key-press", }; export const CLUE_LEDS_COLORS = { WHITE_LEDS_OFF: "#ffde00", WHITE_LEDS_ON: "white", RED_LED_OFF: "#808080", RED_LED_ON: "red", }; export enum DEVICE_LIST_KEY { CPX = "CPX", MICROBIT = "micro:bit", CLUE = "CLUE", } // Pauses on Debug mode alter the state of the view export enum VIEW_STATE { PAUSE = "debug-pause", RUNNING = "running", } // export enum WEBVIEW_MESSAGES { SWITCH_DEVICE = "switch-device", REFRESH_SIMULATOR = "refresh-simulator", TOGGLE_PLAY_STOP = "toggle-play-stop", BUTTON_PRESS = "button-press", SENSOR_CHANGED = "sensor-changed", GESTURE = "gesture", SLIDER_TELEMETRY = "slider-telemetry", } export enum VSCODE_MESSAGES_TO_WEBVIEW { SET_DEVICE = "set-device", PAUSE_DEVICE = "pause-device", RUN_DEVICE = "run-device", RESET = "reset-state", CURRENT_FILE = "current-file", SET_STATE = "set-state", } export enum DEBUG_COMMANDS { STACK_TRACE = "stackTrace", CONTINUE = "continue", DISCONNECT = "disconnect", } export enum SENSOR_LIST { TEMPERATURE = "temperature", LIGHT = "light", ACCELEROMETER = "accelerometer", MOTION_X = "motion_x", MOTION_Y = "motion_y", MOTION_Z = "motion_z", LIGHT_R = "light_r", LIGHT_G = "light_g", LIGHT_B = "light_b", LIGHT_C = "light_c", HUMIDITY = "humidity", PRESSURE = "pressure", PROXIMITY = "proximity", MAGNET_X = "magnet_x", MAGNET_Y = "magnet_y", MAGNET_Z = "magnet_z", GYRO_X = "gyro_x", GYRO_Y = "gyro_y", GYRO_Z = "gyro_z", } export const GESTURES_MICROBIT = [ "shake", "up", "down", "left", "right", "face up", "face down", "freefall", "3g", "6g", "8g", ]; export const GESTURES_CLUE = ["up", "down", "left", "right", "shake"]; export enum WEBVIEW_ATTRIBUTES_KEY { INITIAL_DEVICE = "initial_device", TYPE = "webview_type", } export enum WEBVIEW_TYPES { SIMULATOR = "simulator", GETTING_STARTED = "getting_started", } export const DEFAULT_IMG_CLUE = `/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAEBAQEBAQEBA QEBAQEBAQICAQEBAQMCAgICAwMEBAMDAwMEBAYFBAQFBAMDBQcFBQYGBgYGBAUHBwcGBwYGBgb/2wBDAQEBAQEBAQMCAgMGBAMEB gYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgb/wAARCAJYAlgDASIAAhEBAxEB/8QAHwAAA QUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0Kxw RVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl 5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBA QAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRC hYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkp aanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD/AD/6KKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP//Z`; export default CONSTANTS;
the_stack
import * as tf from "@tensorflow/tfjs"; import { Rank, Tensor } from "@tensorflow/tfjs"; import { Cifar10 } from "tfjs-cifar10-web"; const NUM_DATASET_ELEMENTS = 65000; export const NUM_TRAIN_ELEMENTS = 55000; // const NUM_TEST_ELEMENTS = NUM_DATASET_ELEMENTS - NUM_TRAIN_ELEMENTS; const MNIST_IMAGES_SPRITE_PATH = "https://storage.googleapis.com/learnjs-data/model-builder/mnist_images.png"; const MNIST_LABELS_PATH = "https://storage.googleapis.com/learnjs-data/model-builder/mnist_labels_uint8"; /** * A class that serves as a schema for loading image data. */ export abstract class ImageData { public readonly IMAGE_HEIGHT: number; public readonly IMAGE_WIDTH: number; public readonly IMAGE_CHANNELS: number; public readonly IMAGE_SIZE: number = this.IMAGE_HEIGHT * this.IMAGE_WIDTH * this.IMAGE_CHANNELS; public readonly NUM_CLASSES: number; public pythonName: string; public dataLoaded: boolean = false; public readonly classStrings: string[] = null; protected trainImages: Tensor<Rank.R4>; protected testImages: Tensor<Rank>; protected trainLabels: Tensor<Rank>; protected testLabels: Tensor<Rank>; protected datasetName: string; public abstract async load(): Promise<void>; /** * Get all training data as a data tensor and a labels tensor. * * @returns * xs: The data tensor, of shape `[numTrainExamples, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS]`. * labels: The one-hot encoded labels tensor, of shape `[numTrainExamples, NUM_CLASSES]`. */ public getTrainData(numExamples: number = 15000): {xs: Tensor<tf.Rank.R4>, labels: Tensor<tf.Rank.R2>} { let xs = tf.reshape<tf.Rank.R4>(this.trainImages, [this.trainImages.size / this.IMAGE_SIZE, this.IMAGE_HEIGHT, this.IMAGE_WIDTH, this.IMAGE_CHANNELS]); let labels = tf.reshape<tf.Rank.R2>(this.trainLabels, [this.trainLabels.size / this.NUM_CLASSES, this.NUM_CLASSES]); if (numExamples != null) { xs = xs.slice([0, 0, 0, 0], [numExamples, this.IMAGE_HEIGHT, this.IMAGE_WIDTH, this.IMAGE_CHANNELS]); labels = labels.slice([0, 0], [numExamples, this.NUM_CLASSES]); } return {xs, labels}; } /** * Get all test data as a data tensor a a labels tensor. * * @param {number} numExamples Optional number of examples to get. If not provided, * all test examples will be returned. * @returns * xs: The data tensor, of shape `[numTrainExamples, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS]`. * labels: The one-hot encoded labels tensor, of shape `[numTestExamples, NUM_CLASSES]`. */ public getTestData(numExamples: number = 1500): {xs: Tensor<tf.Rank.R4>, labels: Tensor<tf.Rank.R2>} { let xs = tf.reshape<tf.Rank.R4>(this.testImages, [this.testImages.size / this.IMAGE_SIZE, this.IMAGE_HEIGHT, this.IMAGE_WIDTH, this.IMAGE_CHANNELS]); let labels = tf.reshape<tf.Rank.R2>(this.testLabels, [this.testLabels.size / this.NUM_CLASSES, this.NUM_CLASSES]); if (numExamples != null) { xs = xs.slice([0, 0, 0, 0], [numExamples, this.IMAGE_HEIGHT, this.IMAGE_WIDTH, this.IMAGE_CHANNELS]); labels = labels.slice([0, 0], [numExamples, this.NUM_CLASSES]); } return {xs, labels}; } /** * Returns test examples with the desired label. * * @param {number} numExamples number of examples to get. * @returns xs: The data tensor, of shape `[numTrainExamples, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS]`. * labels: The one-hot encoded labels tensor, of shape `[numTestExamples, NUM_CLASSES]`. */ public async getTestDataWithLabel(numExamples: number, label: string): Promise<{xs: Tensor<tf.Rank.R4>, labels: Tensor<tf.Rank.R2>}> { if (label === "all") { return this.getTestData(numExamples); } let {xs, labels} = this.getTestData(); // select only the numbers with the given label const classLabels = labels.argMax(1).arraySync() as number[]; const mask = tf.equal(classLabels, parseInt(label, 10)); xs = await tf.booleanMaskAsync(xs, mask) as Tensor<tf.Rank.R4>; labels = await tf.booleanMaskAsync(labels, mask) as Tensor<tf.Rank.R2>; xs = xs.slice([0, 0, 0, 0], [numExamples, xs.shape[1], xs.shape[2], xs.shape[3]]) as Tensor<tf.Rank.R4>; labels = labels.slice([0, 0], [numExamples, labels.shape[1]]) as Tensor<tf.Rank.R2>; return {xs, labels}; } protected toggleLoadingOverlay(): void { if (document.getElementById("loadingDataTab").style.display === "none") { document.getElementById("datasetLoadingName").innerText = this.datasetName; document.getElementById("loadingDataTab").style.display = "block"; } else { document.getElementById("loadingDataTab").style.display = "none"; } } } /** * A class that fetches the sprited CIFAR dataset and provide data as * Tensors. */ export class Cifar10Data extends ImageData { public static get Instance(): ImageData { return this.instance || (this.instance = new this()); } private static instance: Cifar10Data; public IMAGE_HEIGHT: number = 32; public IMAGE_WIDTH: number = 32; public IMAGE_CHANNELS: number = 3; public IMAGE_SIZE: number = this.IMAGE_HEIGHT * this.IMAGE_WIDTH * this.IMAGE_CHANNELS; public NUM_CLASSES: number = 10; public datasetName: string = "CIFAR-10"; public pythonName: string = "cifar10"; public readonly classStrings: string[] = ["Airplane", "Automobile", "Bird", "Cat", "Deer", "Dog", "Frog", "Horse", "Ship", "Truck"]; public async load(): Promise<void> { if (this.dataLoaded) { return; } this.toggleLoadingOverlay(); const data = new Cifar10(); await data.load(); const {xs: trainX, ys: trainY} = data.nextTrainBatch(15000); const {xs: testX, ys: testY} = data.nextTestBatch(1500); this.trainImages = trainX as unknown as Tensor<Rank.R4>; this.trainLabels = trainY as unknown as Tensor<Rank.R4>; this.testImages = testX as unknown as Tensor<Rank.R2>; this.testLabels = testY as unknown as Tensor<Rank.R2>; this.dataLoaded = true; document.getElementById("loadingDataTab").style.display = "none"; } } /** * A class that fetches the sprited MNIST dataset and provide data as * Tensors. */ export class MnistData extends ImageData { public static get Instance(): ImageData { return this.instance || (this.instance = new this()); } private static instance: MnistData; public IMAGE_HEIGHT: number = 28; public IMAGE_WIDTH: number = 28; public IMAGE_CHANNELS: number = 1; public IMAGE_SIZE: number = this.IMAGE_HEIGHT * this.IMAGE_WIDTH * this.IMAGE_CHANNELS; public NUM_CLASSES: number = 10; public datasetName: string = "MNIST"; public pythonName: string = "mnist"; public async load(): Promise<void> { // Make a request for the MNIST sprited image. if (this.dataLoaded) { return; } this.toggleLoadingOverlay(); const img = new Image(); const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const imgRequest = new Promise<Float32Array>((resolve, _) => { img.crossOrigin = ""; img.onload = () => { img.width = img.naturalWidth; img.height = img.naturalHeight; const datasetBytesBuffer = new ArrayBuffer(NUM_DATASET_ELEMENTS * this.IMAGE_SIZE * 4); const chunkSize = 5000; canvas.width = img.width; canvas.height = chunkSize; for (let i = 0; i < NUM_DATASET_ELEMENTS / chunkSize; i++) { const datasetBytesView = new Float32Array( datasetBytesBuffer, i * this.IMAGE_SIZE * chunkSize * 4, this.IMAGE_SIZE * chunkSize); ctx.drawImage( img, 0, i * chunkSize, img.width, chunkSize, 0, 0, img.width, chunkSize); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); for (let j = 0; j < imageData.data.length / 4; j++) { // All channels hold an equal value since the image is grayscale, so // just read the red channel. datasetBytesView[j] = imageData.data[j * 4] / 255; } } const dataImages = new Float32Array(datasetBytesBuffer); resolve(dataImages); }; img.src = MNIST_IMAGES_SPRITE_PATH; }); const labelsRequest = fetch(MNIST_LABELS_PATH); const [datasetImages, labelsResponse] = await Promise.all([imgRequest, labelsRequest]); const datasetLabels = new Uint8Array(await labelsResponse.arrayBuffer()); // Slice the the images and labels into train and test sets. const trainImages = datasetImages.slice(0, this.IMAGE_SIZE * NUM_TRAIN_ELEMENTS); this.trainImages = tf.tensor4d(trainImages, [trainImages.length / this.IMAGE_SIZE, this.IMAGE_HEIGHT, this.IMAGE_WIDTH, this.IMAGE_CHANNELS]); const testImages = datasetImages.slice(this.IMAGE_SIZE * NUM_TRAIN_ELEMENTS); this.testImages = tf.tensor4d(testImages, [testImages.length / this.IMAGE_SIZE, this.IMAGE_HEIGHT, this.IMAGE_WIDTH, this.IMAGE_CHANNELS]); const trainLabels = datasetLabels.slice(0, this.NUM_CLASSES * NUM_TRAIN_ELEMENTS); this.trainLabels = tf.tensor2d(trainLabels, [trainImages.length / this.IMAGE_SIZE, this.NUM_CLASSES]); const testLabels = datasetLabels.slice(this.NUM_CLASSES * NUM_TRAIN_ELEMENTS); this.testLabels = tf.tensor2d(testLabels, [testImages.length / this.IMAGE_SIZE, this.NUM_CLASSES]); this.dataLoaded = true; document.getElementById("loadingDataTab").style.display = "none"; } } export let dataset: ImageData = MnistData.Instance; export function changeDataset(newDataset: string): void { switch (newDataset) { case "mnist": dataset = MnistData.Instance; break; case "cifar": dataset = Cifar10Data.Instance; break; } // Set the image visualizations divs with class name identifiers Array.from(document.getElementById("classes").getElementsByClassName("option")).forEach((element, i) => { if (i !== 0) { // Skip the first since it represents 'Any' class element.innerHTML = (i - 1) + ( dataset.classStrings != null ? ` (${dataset.classStrings[i]})` : ""); } }); }
the_stack
import { Quaternion } from './quaternion' import { Plane } from './plane' import { Vector3 } from './vector3' export class Matrix { /** The internal elements for this type. */ public v: Float32Array /** Creates a new Matrix with the given array. */ constructor(array: ArrayLike<number>) { this.v = new Float32Array(16) this.v.set(array, 0) } public get m11(): number { return this.v[0] } public get m12(): number { return this.v[1] } public get m13(): number { return this.v[2] } public get m14(): number { return this.v[3] } public get m21(): number { return this.v[4] } public get m22(): number { return this.v[5] } public get m23(): number { return this.v[6] } public get m24(): number { return this.v[7] } public get m31(): number { return this.v[8] } public get m32(): number { return this.v[9] } public get m33(): number { return this.v[10] } public get m34(): number { return this.v[11] } public get m41(): number { return this.v[12] } public get m42(): number { return this.v[13] } public get m43(): number { return this.v[14] } public get m44(): number { return this.v[15] } /** Gets the up vector of this Matrix. */ public get up(): Vector3 { return new Vector3( this.v[4], this.v[5], this.v[6] ) } /** Gets the down vector of this Matrix. */ public get down(): Vector3 { return new Vector3( -this.v[4], -this.v[5], -this.v[6] ) } /** Gets the right vector of this Matrix. */ public get right(): Vector3 { return new Vector3( this.v[0], this.v[1], this.v[2] ) } /** Gets the left vector of this Matrix. */ public get left(): Vector3 { return new Vector3( -this.v[0], -this.v[1], -this.v[2] ) } /** Gets the forward vector of this Matrix. */ public get forward(): Vector3 { return new Vector3( -this.v[8], -this.v[9], -this.v[10] ) } /** Gets the back vector of this Matrix. */ public get back(): Vector3 { return new Vector3( this.v[8], this.v[9], this.v[10] ) } /** Gets the translation vector of this Matrix. */ public get translation(): Vector3 { return new Vector3( this.v[12], this.v[13], this.v[14] ) } public set m11(value: number) { this.v[0] = value } public set m12(value: number) { this.v[1] = value } public set m13(value: number) { this.v[2] = value } public set m14(value: number) { this.v[3] = value } public set m21(value: number) { this.v[4] = value } public set m22(value: number) { this.v[5] = value } public set m23(value: number) { this.v[6] = value } public set m24(value: number) { this.v[7] = value } public set m31(value: number) { this.v[8] = value } public set m32(value: number) { this.v[9] = value } public set m33(value: number) { this.v[10] = value } public set m34(value: number) { this.v[11] = value } public set m41(value: number) { this.v[12] = value } public set m42(value: number) { this.v[13] = value } public set m43(value: number) { this.v[14] = value } public set m44(value: number) { this.v[15] = value } /** Returns a Matrix translated by the given vector. */ public translate(v0: Vector3): Matrix { return Matrix.mul(this, Matrix.translation(v0)) } /** Returns a Matrix scaled by the given vector. */ public scale(v0: Vector3): Matrix { return Matrix.mul(this, Matrix.scale(v0)) } /** Returns a Matrix rotated about the X axis by the given radian. */ public rotateX(radian: number): Matrix { return Matrix.mul(this, Matrix.rotationX(radian)) } /** Returns a Matrix rotated about the Y axis by the given radian. */ public rotateY(radian: number): Matrix { return Matrix.mul(this, Matrix.rotationY(radian)) } /** Returns a Matrix rotated about the Z axis by the given radian. */ public rotateZ(radian: number): Matrix { return Matrix.mul(this, Matrix.rotationZ(radian)) } /** Returns the string representation of this object. */ public toString(): string { const buffer = [] as string[] buffer.push(`[${this.v[0]}, ${this.v[1]}, ${this.v[2]}, ${this.v[3]}`) buffer.push(` ${this.v[4]}, ${this.v[5]}, ${this.v[6]}, ${this.v[7]}`) buffer.push(` ${this.v[8]}, ${this.v[9]}, ${this.v[10]}, ${this.v[11]}`) buffer.push(` ${this.v[12]}, ${this.v[13]}, ${this.v[14]}, ${this.v[15]}]`) return buffer.join('\n') } /** Returns the type kind of this object. */ public kind(): string { return 'Matrix' } /** Returns a clone of this Matrix. */ public clone(): Matrix { return Matrix.clone(this) } /** Returns an identity Matrix. */ public static identity(): Matrix { return new Matrix([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]) } /** Returns a Matrix translation from the given position vector. */ public static translation(v0: Vector3): Matrix { return new Matrix([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, v0.v[0], v0.v[1], v0.v[2], 1 ]) } /** Creates a scaling Matrix from the given vector. */ public static scale(v0: Vector3): Matrix { return new Matrix([ v0.v[0], 0, 0, 0, 0, v0.v[1], 0, 0, 0, 0, v0.v[2], 0, 0, 0, 0, 1 ]) } /** Creates a X rotation Matrix from the given radian. */ public static rotationX(radians: number): Matrix { const cos = Math.cos(radians) const sin = Math.sin(radians) return new Matrix([ 1, 0, 0, 0, 0, cos, sin, 0, 0, -sin, cos, 0, 0, 0, 0, 1 ]) } /** Creates a Y rotation Matrix from the given radian. */ public static rotationY(radians: number): Matrix { const cos = Math.cos(radians) const sin = Math.sin(radians) return new Matrix([ cos, 0, -sin, 0, 0, 1, 0, 0, sin, 0, cos, 0, 0, 0, 0, 1 ]) } /** Creates a Z rotation Matrix from the given radian. */ public static rotationZ(radians: number): Matrix { const cos = Math.cos(radians) const sin = Math.sin(radians) return new Matrix([ cos, sin, 0, 0, -sin, cos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]) } /** Creates a Matrix from the given axis and radian. */ public static fromAxisAngle(axis: Vector3, radians: number): Matrix { const x = axis.v[0] const y = axis.v[1] const z = axis.v[2] const n0 = Math.sin(radians) const n1 = Math.cos(radians) const n2 = x * x const n3 = y * y const n4 = z * z const n5 = x * y const n6 = x * z const n7 = y * z return new Matrix([ n2 + (n1 * (1.0 - n2)), (n5 - (n1 * n5)) + (n0 * z), (n6 - (n1 * n6)) - (n0 * y), 0.0, (n5 - (n1 * n5)) - (n0 * z), n3 + (n1 * (1.0 - n3)), (n7 - (n1 * n7)) + (n0 * x), 0.0, (n6 - (n1 * n6)) + (n0 * y), (n7 - (n1 * n7)) - (n0 * x), n4 + (n1 * (1.0 - n4)), 0.0, 0.0, 0.0, 0.0, 1.0 ]) } /** Creates a perspective field of view Matrix. */ public static perspectiveFov(fov: number, aspect: number, near: number, far: number): Matrix { const n0 = 1.0 / Math.tan(fov * 0.5) const n1 = n0 / aspect const m0 = Matrix.identity() m0.v[0] = n1 m0.v[1] = 0 m0.v[2] = 0 m0.v[3] = 0 m0.v[5] = n0 m0.v[4] = 0 m0.v[6] = 0 m0.v[7] = 0 m0.v[8] = 0 m0.v[9] = 0 m0.v[10] = far / (near - far) m0.v[11] = -1 m0.v[12] = 0 m0.v[13] = 0 m0.v[15] = 0 m0.v[14] = (near * far) / (near - far) return m0 } /** Creates a perspective Matrix. */ public static perspective(width: number, height: number, near: number, far: number): Matrix { const m0 = Matrix.identity() m0.v[0] = (2.0 * near) / width; m0.v[1] = m0.v[2] = m0.v[3] = 0.0 m0.v[5] = (2.0 * near) / height m0.v[4] = m0.v[6] = m0.v[7] = 0.0 m0.v[10] = far / (near - far) m0.v[8] = m0.v[9] = 0.0 m0.v[11] = -1.0 m0.v[12] = m0.v[13] = m0.v[15] = 0.0 m0.v[14] = (near * far) / (near - far) return m0 } /** Returns a offset perspective Matrix. */ public static perspectiveOffset(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix { const m0 = Matrix.identity() m0.v[0] = (2.0 * near) / (right - left) m0.v[1] = m0.v[2] = m0.v[3] = 0.0 m0.v[5] = (2.0 * near) / (top - bottom) m0.v[4] = m0.v[6] = m0.v[7] = 0.0 m0.v[8] = (left + right) / (right - left) m0.v[9] = (top + bottom) / (top - bottom) m0.v[10] = far / (near - far) m0.v[11] = -1.0 m0.v[14] = (near * far) / (near - far) m0.v[12] = m0.v[13] = m0.v[15] = 0.0 return m0 } /** Returns an orthographic Matrix. */ public static orthographic(width: number, height: number, near: number, far: number): Matrix { const m0 = Matrix.identity() m0.v[0] = 2.0 / width m0.v[1] = m0.v[2] = m0.v[3] = 0.0 m0.v[5] = 2.0 / height m0.v[4] = m0.v[6] = m0.v[7] = 0.0 m0.v[10] = 1.0 / (near - far) m0.v[8] = m0.v[9] = m0.v[11] = 0.0 m0.v[12] = m0.v[13] = 0.0 m0.v[14] = near / (near - far) m0.v[15] = 1.0 return m0 } /** Returns an orthographic offset Matrix. */ public static orthographicOffset(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix { const m0 = Matrix.identity() m0.v[0] = 2.0 / (right - left) m0.v[1] = m0.v[2] = m0.v[3] = 0.0 m0.v[5] = 2.0 / (top - bottom) m0.v[4] = m0.v[6] = m0.v[7] = 0.0 m0.v[10] = 1.0 / (near - far) m0.v[8] = m0.v[9] = m0.v[11] = 0.0 m0.v[12] = (left + right) / (left - right) m0.v[13] = (top + bottom) / (bottom - top) m0.v[14] = near / (near - far) m0.v[15] = 1.0 return m0; } /** Returns a look at Matrix. */ public static lookAt(position: Vector3, target: Vector3, up: Vector3): Matrix { const m0 = Matrix.identity() const v0 = Vector3.normalize(Vector3.sub(position, target)) const v1 = Vector3.normalize(Vector3.cross(up, v0)) const v2 = Vector3.cross(v0, v1) m0.v[0] = v1.v[0] m0.v[1] = v2.v[0] m0.v[2] = v0.v[0] m0.v[3] = 0.0 m0.v[4] = v1.v[1] m0.v[5] = v2.v[1] m0.v[6] = v0.v[1] m0.v[7] = 0.0 m0.v[8] = v1.v[2] m0.v[9] = v2.v[2] m0.v[10] = v0.v[2] m0.v[11] = 0.0 m0.v[12] = -Vector3.dot(v1, position) m0.v[13] = -Vector3.dot(v2, position) m0.v[14] = -Vector3.dot(v0, position) m0.v[15] = 1.0 return m0 } /** Creates a world Matrix. */ public static world(position: Vector3, forward: Vector3, up: Vector3): Matrix { const m0 = Matrix.identity() const v0 = Vector3.normalize(Vector3.sub(position, forward)) const v1 = Vector3.normalize(Vector3.cross(up, v0)) const v2 = Vector3.cross(v0, v1) m0.v[0] = v1.v[0] m0.v[1] = v1.v[1] m0.v[2] = v1.v[2] m0.v[4] = v2.v[0] m0.v[5] = v2.v[1] m0.v[6] = v2.v[2] m0.v[8] = v0.v[0] m0.v[9] = v0.v[1] m0.v[10] = v0.v[2] m0.v[12] = 0.0 m0.v[13] = 0.0 m0.v[14] = 0.0 m0.v[15] = 1.0 m0.v[3] = -Vector3.dot(v1, position) m0.v[7] = -Vector3.dot(v2, position) m0.v[11] = -Vector3.dot(v0, position) return m0 } /** Creates a Matrix from the given quaternion. */ public static fromQuaternion(q0: Quaternion): Matrix { const m0 = Matrix.identity() const n0 = q0.v[0] * q0.v[0] const n1 = q0.v[1] * q0.v[1] const n2 = q0.v[2] * q0.v[2] const n3 = q0.v[0] * q0.v[1] const n4 = q0.v[2] * q0.v[3] const n5 = q0.v[2] * q0.v[0] const n6 = q0.v[1] * q0.v[3] const n7 = q0.v[1] * q0.v[2] const n8 = q0.v[0] * q0.v[3] m0.v[0] = 1.0 - (2.0 * (n1 + n2)) m0.v[1] = 2.0 * (n3 + n4) m0.v[2] = 2.0 * (n5 - n6) m0.v[3] = 0.0 m0.v[4] = 2.0 * (n3 - n4) m0.v[5] = 1.0 - (2.0 * (n2 + n0)) m0.v[6] = 2.0 * (n7 + n8) m0.v[7] = 0.0 m0.v[8] = 2.0 * (n5 + n6) m0.v[9] = 2.0 * (n7 - n8) m0.v[10] = 1.0 - (2.0 * (n1 + n0)) m0.v[11] = 0.0 m0.v[12] = 0.0 m0.v[13] = 0.0 m0.v[14] = 0.0 m0.v[15] = 1.0 return m0 } /** Creates a reflection Matrix about the given plane. */ public static reflection(p0: Plane): Matrix { const m0 = Matrix.identity() const p1 = Plane.normalize(p0) const x = p1.v[0] const y = p1.v[1] const z = p1.v[2] const n0 = -2.0 * x const n1 = -2.0 * y const n2 = -2.0 * z m0.v[0] = (n0 * x) + 1.0 m0.v[1] = n1 * x m0.v[2] = n2 * x m0.v[3] = 0.0 m0.v[4] = n0 * y m0.v[5] = (n1 * y) + 1.0 m0.v[6] = n2 * y m0.v[7] = 0.0 m0.v[8] = n0 * z m0.v[9] = n1 * z m0.v[10] = (n2 * z) + 1.0 m0.v[11] = 0.0 m0.v[12] = n0 * p1.v[3] m0.v[13] = n1 * p1.v[3] m0.v[14] = n2 * p1.v[3] m0.v[15] = 1.0 return m0 } /** Returns the invert of the given Matrix. */ public static invert(m0: Matrix): Matrix { const m1 = Matrix.identity() const n0 = m0.v[0] const n1 = m0.v[1] const n2 = m0.v[2] const n3 = m0.v[3] const n4 = m0.v[4] const n5 = m0.v[5] const n6 = m0.v[6] const n7 = m0.v[7] const n8 = m0.v[8] const n9 = m0.v[9] const n10 = m0.v[10] const n11 = m0.v[11] const n12 = m0.v[12] const n13 = m0.v[13] const n14 = m0.v[14] const n15 = m0.v[15] const n16 = (n10 * n15) - (n11 * n14); const n17 = (n9 * n15) - (n11 * n13); const n18 = (n9 * n14) - (n10 * n13); const n19 = (n8 * n15) - (n11 * n12); const n20 = (n8 * n14) - (n10 * n12); const n21 = (n8 * n13) - (n9 * n12); const n22 = ((n5 * n16) - (n6 * n17)) + (n7 * n18) const n23 = -(((n4 * n16) - (n6 * n19)) + (n7 * n20)) const n24 = ((n4 * n17) - (n5 * n19)) + (n7 * n21) const n25 = -(((n4 * n18) - (n5 * n20)) + (n6 * n21)) const n26 = 1.0 / ((((n0 * n22) + (n1 * n23)) + (n2 * n24)) + (n3 * n25)) m1.v[0] = n22 * n26 m1.v[4] = n23 * n26 m1.v[8] = n24 * n26 m1.v[12] = n25 * n26 m1.v[1] = -(((n1 * n16) - (n2 * n17)) + (n3 * n18)) * n26 m1.v[5] = (((n0 * n16) - (n2 * n19)) + (n3 * n20)) * n26 m1.v[9] = -(((n0 * n17) - (n1 * n19)) + (n3 * n21)) * n26 m1.v[13] = (((n0 * n18) - (n1 * n20)) + (n2 * n21)) * n26 const n27 = (n6 * n15) - (n7 * n14) const n28 = (n5 * n15) - (n7 * n13) const n29 = (n5 * n14) - (n6 * n13) const n30 = (n4 * n15) - (n7 * n12) const n32 = (n4 * n14) - (n6 * n12) const n33 = (n4 * n13) - (n5 * n12) m1.v[2] = (((n1 * n27) - (n2 * n28)) + (n3 * n29)) * n26 m1.v[6] = -(((n0 * n27) - (n2 * n30)) + (n3 * n32)) * n26 m1.v[10] = (((n0 * n28) - (n1 * n30)) + (n3 * n33)) * n26 m1.v[14] = -(((n0 * n29) - (n1 * n32)) + (n2 * n33)) * n26 const n34 = (n6 * n11) - (n7 * n10) const n35 = (n5 * n11) - (n7 * n9) const n36 = (n5 * n10) - (n6 * n9) const n37 = (n4 * n11) - (n7 * n8) const n38 = (n4 * n10) - (n6 * n8) const n39 = (n4 * n9) - (n5 * n8) m1.v[3] = -(((n1 * n34) - (n2 * n35)) + (n3 * n36)) * n26 m1.v[7] = (((n0 * n34) - (n2 * n37)) + (n3 * n38)) * n26 m1.v[11] = -(((n0 * n35) - (n1 * n37)) + (n3 * n39)) * n26 m1.v[15] = (((n0 * n36) - (n1 * n38)) + (n2 * n39)) * n26 return m1 } /** Returns the transpose of the given Matrix. */ public static transpose(m0: Matrix): Matrix { const m1 = Matrix.identity() m1.v[0] = m0.v[0] m1.v[1] = m0.v[4] m1.v[2] = m0.v[8] m1.v[3] = m0.v[12] m1.v[4] = m0.v[1] m1.v[5] = m0.v[5] m1.v[6] = m0.v[9] m1.v[7] = m0.v[13] m1.v[8] = m0.v[2] m1.v[9] = m0.v[6] m1.v[10] = m0.v[10] m1.v[11] = m0.v[14] m1.v[12] = m0.v[3] m1.v[13] = m0.v[7] m1.v[14] = m0.v[11] m1.v[15] = m0.v[15] return m1 } /** Returns the determinant of the given Matrix. */ public static determinant(m0: Matrix): number { const n0 = m0.v[0] const n1 = m0.v[1] const n2 = m0.v[2] const n3 = m0.v[3] const n4 = m0.v[4] const n5 = m0.v[5] const n6 = m0.v[6] const n7 = m0.v[7] const n8 = m0.v[8] const n9 = m0.v[9] const n10 = m0.v[10] const n11 = m0.v[11] const n12 = m0.v[12] const n13 = m0.v[13] const n14 = m0.v[14] const n15 = m0.v[15] const n16 = (n10 * n15) - (n11 * n14) const n17 = (n9 * n15) - (n11 * n13) const n18 = (n9 * n14) - (n10 * n13) const n19 = (n8 * n15) - (n11 * n12) const n20 = (n8 * n14) - (n10 * n12) const n21 = (n8 * n13) - (n9 * n12) return ((((n0 * (((n5 * n16) - (n6 * n17)) + (n7 * n18))) - (n1 * (((n4 * n16) - (n6 * n19)) + (n7 * n20)))) + (n2 * (((n4 * n17) - (n5 * n19)) + (n7 * n21)))) - (n3 * (((n4 * n18) - (n5 * n20)) + (n6 * n21)))) } /** Returns the linear interpolation between the given two matrices. */ public static lerp(m0: Matrix, m1: Matrix, amount: number): Matrix { const m2 = Matrix.identity() m2.v[0] = m0.v[0] + ((m1.v[0] - m0.v[0]) * amount) m2.v[1] = m0.v[1] + ((m1.v[1] - m0.v[1]) * amount) m2.v[2] = m0.v[2] + ((m1.v[2] - m0.v[2]) * amount) m2.v[3] = m0.v[3] + ((m1.v[3] - m0.v[3]) * amount) m2.v[4] = m0.v[4] + ((m1.v[4] - m0.v[4]) * amount) m2.v[5] = m0.v[5] + ((m1.v[5] - m0.v[5]) * amount) m2.v[6] = m0.v[6] + ((m1.v[6] - m0.v[6]) * amount) m2.v[7] = m0.v[7] + ((m1.v[7] - m0.v[7]) * amount) m2.v[8] = m0.v[8] + ((m1.v[8] - m0.v[8]) * amount) m2.v[9] = m0.v[9] + ((m1.v[9] - m0.v[9]) * amount) m2.v[10] = m0.v[10] + ((m1.v[10] - m0.v[10]) * amount) m2.v[11] = m0.v[11] + ((m1.v[11] - m0.v[11]) * amount) m2.v[12] = m0.v[12] + ((m1.v[12] - m0.v[12]) * amount) m2.v[13] = m0.v[13] + ((m1.v[13] - m0.v[13]) * amount) m2.v[14] = m0.v[14] + ((m1.v[14] - m0.v[14]) * amount) m2.v[15] = m0.v[15] + ((m1.v[15] - m0.v[15]) * amount) return m2 } /** Returns a Matrix with its values negated from the given Matrix. */ public static negate(m0: Matrix): Matrix { const m1 = Matrix.identity() m1.v[0] = -m0.v[0] m1.v[1] = -m0.v[1] m1.v[2] = -m0.v[2] m1.v[3] = -m0.v[3] m1.v[4] = -m0.v[4] m1.v[5] = -m0.v[5] m1.v[6] = -m0.v[6] m1.v[7] = -m0.v[7] m1.v[8] = -m0.v[8] m1.v[9] = -m0.v[9] m1.v[10] = -m0.v[10] m1.v[11] = -m0.v[11] m1.v[12] = -m0.v[12] m1.v[13] = -m0.v[13] m1.v[14] = -m0.v[14] m1.v[15] = -m0.v[15] return m1 } /** Outputs the addition of the given two matrices. */ public static fast_add(m0: Matrix, m1: Matrix, out: Matrix): void { out.v[0] = m0.v[0] + m1.v[0] out.v[1] = m0.v[1] + m1.v[1] out.v[2] = m0.v[2] + m1.v[2] out.v[3] = m0.v[3] + m1.v[3] out.v[4] = m0.v[4] + m1.v[4] out.v[5] = m0.v[5] + m1.v[5] out.v[6] = m0.v[6] + m1.v[6] out.v[7] = m0.v[7] + m1.v[7] out.v[8] = m0.v[8] + m1.v[8] out.v[9] = m0.v[9] + m1.v[9] out.v[10] = m0.v[10] + m1.v[10] out.v[11] = m0.v[11] + m1.v[11] out.v[12] = m0.v[12] + m1.v[12] out.v[13] = m0.v[13] + m1.v[13] out.v[14] = m0.v[14] + m1.v[14] out.v[15] = m0.v[15] + m1.v[15] } /** Returns the addition of the given two matrices. */ public static add(m0: Matrix, m1: Matrix): Matrix { const out = Matrix.identity() Matrix.fast_add(m0, m1, out) return out } /** Outputs the subtraction of the given two matrices. */ public static fast_sub(m0: Matrix, m1: Matrix, out: Matrix): void { out.v[0] = m0.v[0] - m1.v[0] out.v[1] = m0.v[1] - m1.v[1] out.v[2] = m0.v[2] - m1.v[2] out.v[3] = m0.v[3] - m1.v[3] out.v[4] = m0.v[4] - m1.v[4] out.v[5] = m0.v[5] - m1.v[5] out.v[6] = m0.v[6] - m1.v[6] out.v[7] = m0.v[7] - m1.v[7] out.v[8] = m0.v[8] - m1.v[8] out.v[9] = m0.v[9] - m1.v[9] out.v[10] = m0.v[10] - m1.v[10] out.v[11] = m0.v[11] - m1.v[11] out.v[12] = m0.v[12] - m1.v[12] out.v[13] = m0.v[13] - m1.v[13] out.v[14] = m0.v[14] - m1.v[14] out.v[15] = m0.v[15] - m1.v[15] } /** Returns the subtraction of the given two matrices. */ public static sub(m0: Matrix, m1: Matrix): Matrix { const out = Matrix.identity() Matrix.fast_sub(m0, m1, out) return out } /** Outputs the multiplication of the given two matrices. */ public static fast_mul(m0: Matrix, m1: Matrix, out: Matrix): void { out.v[0] = (((m0.v[0] * m1.v[0]) + (m0.v[1] * m1.v[4])) + (m0.v[2] * m1.v[8])) + (m0.v[3] * m1.v[12]) out.v[1] = (((m0.v[0] * m1.v[1]) + (m0.v[1] * m1.v[5])) + (m0.v[2] * m1.v[9])) + (m0.v[3] * m1.v[13]) out.v[2] = (((m0.v[0] * m1.v[2]) + (m0.v[1] * m1.v[6])) + (m0.v[2] * m1.v[10])) + (m0.v[3] * m1.v[14]) out.v[3] = (((m0.v[0] * m1.v[3]) + (m0.v[1] * m1.v[7])) + (m0.v[2] * m1.v[11])) + (m0.v[3] * m1.v[15]) out.v[4] = (((m0.v[4] * m1.v[0]) + (m0.v[5] * m1.v[4])) + (m0.v[6] * m1.v[8])) + (m0.v[7] * m1.v[12]) out.v[5] = (((m0.v[4] * m1.v[1]) + (m0.v[5] * m1.v[5])) + (m0.v[6] * m1.v[9])) + (m0.v[7] * m1.v[13]) out.v[6] = (((m0.v[4] * m1.v[2]) + (m0.v[5] * m1.v[6])) + (m0.v[6] * m1.v[10])) + (m0.v[7] * m1.v[14]) out.v[7] = (((m0.v[4] * m1.v[3]) + (m0.v[5] * m1.v[7])) + (m0.v[6] * m1.v[11])) + (m0.v[7] * m1.v[15]) out.v[8] = (((m0.v[8] * m1.v[0]) + (m0.v[9] * m1.v[4])) + (m0.v[10] * m1.v[8])) + (m0.v[11] * m1.v[12]) out.v[9] = (((m0.v[8] * m1.v[1]) + (m0.v[9] * m1.v[5])) + (m0.v[10] * m1.v[9])) + (m0.v[11] * m1.v[13]) out.v[10] = (((m0.v[8] * m1.v[2]) + (m0.v[9] * m1.v[6])) + (m0.v[10] * m1.v[10])) + (m0.v[11] * m1.v[14]) out.v[11] = (((m0.v[8] * m1.v[3]) + (m0.v[9] * m1.v[7])) + (m0.v[10] * m1.v[11])) + (m0.v[11] * m1.v[15]) out.v[12] = (((m0.v[12] * m1.v[0]) + (m0.v[13] * m1.v[4])) + (m0.v[14] * m1.v[8])) + (m0.v[15] * m1.v[12]) out.v[13] = (((m0.v[12] * m1.v[1]) + (m0.v[13] * m1.v[5])) + (m0.v[14] * m1.v[9])) + (m0.v[15] * m1.v[13]) out.v[14] = (((m0.v[12] * m1.v[2]) + (m0.v[13] * m1.v[6])) + (m0.v[14] * m1.v[10])) + (m0.v[15] * m1.v[14]) out.v[15] = (((m0.v[12] * m1.v[3]) + (m0.v[13] * m1.v[7])) + (m0.v[14] * m1.v[11])) + (m0.v[15] * m1.v[15]) } /** Returns the multiplication of the given two matrices. */ public static mul(m0: Matrix, m1: Matrix): Matrix { const out = Matrix.identity() Matrix.fast_mul(m0, m1, out) return out } /** Outputs the division of the given two matrices. */ public static fast_div(m0: Matrix, m1: Matrix, out: Matrix): void { out.v[0] = m0.v[0] / m1.v[0] out.v[1] = m0.v[1] / m1.v[1] out.v[2] = m0.v[2] / m1.v[2] out.v[3] = m0.v[3] / m1.v[3] out.v[4] = m0.v[4] / m1.v[4] out.v[5] = m0.v[5] / m1.v[5] out.v[6] = m0.v[6] / m1.v[6] out.v[7] = m0.v[7] / m1.v[7] out.v[8] = m0.v[8] / m1.v[8] out.v[9] = m0.v[9] / m1.v[9] out.v[10] = m0.v[10] / m1.v[10] out.v[11] = m0.v[11] / m1.v[11] out.v[12] = m0.v[12] / m1.v[12] out.v[13] = m0.v[13] / m1.v[13] out.v[14] = m0.v[14] / m1.v[14] out.v[15] = m0.v[15] / m1.v[15] } /** Returns the division of the given two matrices. */ public static div(m0: Matrix, m1: Matrix): Matrix { const out = Matrix.identity() Matrix.fast_div(m0, m1, out) return out } /** Outputs a clone of the given Matrix. */ public static fast_clone(m0: Matrix, out: Matrix) { for(let i = 0; i < 16; i+=1) { out.v[i] = m0.v[i] } } /** Returns a clone of the given Matrix. */ public static clone(m0: Matrix): Matrix { return new Matrix([ m0.v[0], m0.v[1], m0.v[2], m0.v[3], m0.v[4], m0.v[5], m0.v[6], m0.v[7], m0.v[8], m0.v[9], m0.v[10], m0.v[11], m0.v[12], m0.v[13], m0.v[14], m0.v[15] ]) } /** Creates a new Matrix with the given elements. */ public static create(array: ArrayLike<number>): Matrix { return new Matrix(array) } }
the_stack
import type { APIGatewayProxyEvent } from 'aws-lambda' import { signPayload, verifyEvent, verifySignature, WebhookVerificationError, DEFAULT_WEBHOOK_SIGNATURE_HEADER, } from './index' const payload = 'No more secrets, Marty.' const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const ONE_MINUTE = 60_000 const TEN_MINUTES = 10 * ONE_MINUTE const FIFTEEN_MINUTES = 15 * ONE_MINUTE // See: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/aws-lambda/trigger/api-gateway-proxy.d.ts const buildEvent = ({ payload, signature = '', signatureHeader = '', isBase64Encoded = false, }): APIGatewayProxyEvent => { const headers = {} headers[signatureHeader.toLocaleLowerCase()] = signature const body = isBase64Encoded ? Buffer.from(payload || '').toString('base64') : payload return { body, headers, multiValueHeaders: {}, isBase64Encoded, path: '', pathParameters: null, stageVariables: null, httpMethod: 'GET', queryStringParameters: null, requestContext: null, resource: null, multiValueQueryStringParameters: null, } } beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(jest.fn()) }) afterEach(() => { jest.spyOn(console, 'warn').mockRestore() }) describe('webhooks', () => { describe('using the timestampScheme verifier', () => { describe('signs a payload with default timestamp', () => { test('it has a time and scheme signature', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) expect(signature).toMatch(/t=(\d+),v1=([\da-f]+)/) }) test('it signs and verifies', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) expect( verifySignature('timestampSchemeVerifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the sha1 verifier', () => { describe('signs a payload', () => { test('it has a sha1 signature', () => { const signature = signPayload('sha1Verifier', { payload, secret, }) expect(signature).toMatch(/sha1=([\da-f]+)/) }) test('it signs and verifies', () => { const signature = signPayload('sha1Verifier', { payload, secret, }) expect( verifySignature('sha1Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the sha256 verifier', () => { describe('signs a payload', () => { test('it has a sha256 signature', () => { const signature = signPayload('sha256Verifier', { payload, secret, }) expect(signature).toMatch(/sha256=([\da-f]+)/) }) test('it signs and verifies', () => { const signature = signPayload('sha256Verifier', { payload, secret, }) expect( verifySignature('sha256Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the secret key verifier', () => { describe('signs a payload', () => { test('it has the key as a signature', () => { const signature = signPayload('secretKeyVerifier', { payload, secret, }) expect(signature).toEqual(secret) }) test('it signs and verifies', () => { const signature = signPayload('secretKeyVerifier', { payload, secret, }) expect( verifySignature('secretKeyVerifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the JWT verifier', () => { describe('signs a payload', () => { test('it has the JWT as a signature', () => { const signature = signPayload('jwtVerifier', { payload, secret, }) expect(signature).toEqual( 'eyJhbGciOiJIUzI1NiJ9.Tm8gbW9yZSBzZWNyZXRzLCBNYXJ0eS4.LBqlEwDa4bWxzrv_Y1_Y7S6_7czhzLZuF17d5c6YjXI' ) }) test('it signs and verifies', () => { const signature = signPayload('jwtVerifier', { payload, secret, }) expect( verifySignature('jwtVerifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the base64 sha1 verifier', () => { describe('signs a payload', () => { test('it signs and verifies', () => { const signature = signPayload('base64Sha1Verifier', { payload, secret, }) expect( verifySignature('base64Sha1Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the base64 sha256 verifier', () => { describe('signs a payload', () => { test('it has a base64 sha256 signature', () => { const body = '{"data": {"abandon_at": 1648585920141, ' + '"client_id": "client_25hz3vm5USqCG3a7jMXqdjzjJyK", ' + '"created_at": 1645993920141, "expire_at": 1646598720141, ' + '"id": "sess_25hz5CxFyrNJgDO1TY52LGPtM0e", ' + '"last_active_at": 1645993920141, "object": "session", ' + '"status": "active", "updated_at": 1645993920149, ' + '"user_id": "user_25h1zRMh7owJp6us0Sqs3UXwW0y"}, ' + '"object": "event", "type": "session.created"}' const payload = `msg_25hz5cPxRz5ilWSQSiYfgxpYHTH.1646004463.${body}` const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const signature = signPayload('base64Sha256Verifier', { payload, secret, }) expect(signature).toMatch( 'AaP4EgcpPC5oE3eppI/s6EMtQCZ4Ap34wNHPoxBoikI=' ) }) test('it signs and verifies', () => { const signature = signPayload('base64Sha256Verifier', { payload, secret, }) expect( verifySignature('base64Sha256Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('webhooks via event', () => { describe('when it receives an event it extracts the signature and payload from the event', () => { test('it can verify an event body payload with a signature it generates', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect( verifyEvent('timestampSchemeVerifier', { event, secret }) ).toBeTruthy() }) test('it can verify an event base64encoded body payload with a signature it generates', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, isBase64Encoded: true, }) expect( verifyEvent('timestampSchemeVerifier', { event, secret }) ).toBeTruthy() }) test('it can verify overriding the event body payload with a signature it generates', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) const event = buildEvent({ payload: { body: payload }, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect( verifyEvent('timestampSchemeVerifier', { event, payload, secret, }) ).toBeTruthy() }) test('it denies verification when signed with a different secret', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret: 'WERNER_BRANDES', }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('timestampSchemeVerifier', { event, secret }) }).toThrow(WebhookVerificationError) }) test('it verifies when within the timestamp tolerance', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, options: { currentTimestampOverride: Date.now() - TEN_MINUTES }, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('timestampSchemeVerifier', { event, secret, options: { tolerance: FIFTEEN_MINUTES }, }) }).toBeTruthy() }) test('it denies verification when verifying with a short tolerance', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, options: { currentTimestampOverride: Date.now() - TEN_MINUTES }, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('timestampSchemeVerifier', { event, secret, options: { tolerance: 5_000 }, }) }).toThrow(WebhookVerificationError) }) test('it denies verification when verifying with a short tolerance also for sha1 verifier', () => { const signature = signPayload('sha1Verifier', { payload, secret, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('sha1Verifier', { event, secret, options: { eventTimestamp: Date.now(), currentTimestampOverride: Date.now() - FIFTEEN_MINUTES, tolerance: ONE_MINUTE, }, }) }).toThrow(WebhookVerificationError) }) }) describe('provider specific tests', () => { test('clerk', () => { const body = '{"data": {"abandon_at": 1648585920141, ' + '"client_id": "client_25hz3vm5USqCG3a7jMXqdjzjJyK", ' + '"created_at": 1645993920141, "expire_at": 1646598720141, ' + '"id": "sess_25hz5CxFyrNJgDO1TY52LGPtM0e", ' + '"last_active_at": 1645993920141, "object": "session", ' + '"status": "active", "updated_at": 1645993920149, ' + '"user_id": "user_25h1zRMh7owJp6us0Sqs3UXwW0y"}, ' + '"object": "event", "type": "session.created"}' const event = buildEvent({ payload: body }) event.headers = { 'svix-signature': 'v1,AaP4EgcpPC5oE3eppI/s6EMtQCZ4Ap34wNHPoxBoikI=', 'svix-timestamp': '1646004463', 'svix-id': 'msg_25hz5cPxRz5ilWSQSiYfgxpYHTH', } const svix_id = event.headers['svix-id'] const svix_timestamp = event.headers['svix-timestamp'] const payload = `${svix_id}.${svix_timestamp}.${event.body}` const secret = 'whsec_MY_VOICE_IS_MY_PASSPORT_VERIFY_ME'.slice(6) expect( verifyEvent('base64Sha256Verifier', { event, secret, payload, options: { signatureHeader: 'svix-signature', signatureTransformer: (signature: string) => { // Clerk can pass a space separated list of signatures. // Let's just use the first one that's of version 1 const passedSignatures = signature.split(' ') for (const versionedSignature of passedSignatures) { const [version, signature] = versionedSignature.split(',') if (version === 'v1') { return signature } } }, eventTimestamp: parseInt(svix_timestamp, 10) * 1000, // One minute from the event's timestamp is within the default // tolerance of five minutes currentTimestampOverride: parseInt(svix_timestamp, 10) * 1000 - ONE_MINUTE, }, }) ).toBeTruthy() }) }) }) })
the_stack
import { ConfigService } from '@nestjs/config'; import { FeedFetcherService } from './feed-fetcher.service'; import nock from 'nock'; import path from 'path'; import { URL } from 'url'; import { readFileSync } from 'fs'; import { Repository } from 'typeorm'; import { Request, Response } from './entities'; import { RequestStatus } from './constants'; import { SQSClient } from '@aws-sdk/client-sqs'; import { mockClient } from 'aws-sdk-client-mock'; import dayjs from 'dayjs'; import { EventEmitter2 } from '@nestjs/event-emitter'; jest.mock('../utils/logger'); describe('FeedFetcherService', () => { let service: FeedFetcherService; let configService: ConfigService; const sqsClient = mockClient(SQSClient); const feedUrl = 'https://rss-feed.com/feed.xml'; const url = new URL(feedUrl); const feedFilePath = path.join(__dirname, '..', 'test', 'data', 'feed.xml'); const feedXml = readFileSync(feedFilePath, 'utf8'); const requestRepo: Repository<Request> = { insert: jest.fn(), findOne: jest.fn(), } as never; const responseRepo: Repository<Response> = { insert: jest.fn(), } as never; const eventEmitter: EventEmitter2 = { emit: jest.fn(), } as never; beforeEach(() => { configService = { get: jest.fn(), } as never; service = new FeedFetcherService( requestRepo, responseRepo, configService, eventEmitter, ); sqsClient.reset(); }); afterEach(() => { nock.cleanAll(); jest.resetAllMocks(); }); it('should be defined', () => { expect(service).toBeDefined(); }); describe('fetchFeedResponse', () => { it('does not throws when status code is non-200', async () => { nock(url.origin).get(url.pathname).replyWithFile(401, feedFilePath, { 'Content-Type': 'application/xml', }); await expect(service.fetchFeedResponse(feedUrl)).resolves.toBeDefined(); }); it('returns the feed xml', async () => { nock(url.origin).get(url.pathname).replyWithFile(200, feedFilePath, { 'Content-Type': 'application/xml', }); const res = await service.fetchFeedResponse(feedUrl); expect(await res.text()).toEqual(feedXml); }); }); describe('fetchAndSaveResponse', () => { const userAgent = 'user-agent'; beforeEach(() => { jest.spyOn(configService, 'get').mockImplementation((key) => { if (key === 'feedUserAgent') { return userAgent; } }); }); it('passes the correct fetch option to fetch feed', async () => { const userAgent = 'my-user-agent'; jest.spyOn(configService, 'get').mockImplementation((key) => { if (key === 'feedUserAgent') { return userAgent; } }); nock(url.origin) .get(url.pathname) .matchHeader('user-agent', userAgent) .replyWithFile(200, feedFilePath, { 'Content-Type': 'application/xml', }); await service.fetchAndSaveResponse(feedUrl); }); describe('if ok response', () => { it('saves request correctly', async () => { nock(url.origin).get(url.pathname).replyWithFile(200, feedFilePath, { 'Content-Type': 'application/xml', }); await service.fetchAndSaveResponse(feedUrl); expect(requestRepo.insert).toHaveBeenCalledWith({ url: feedUrl, status: RequestStatus.OK, fetchOptions: { userAgent, }, response: { statusCode: 200, isCloudflare: false, text: feedXml, }, // responseDetails: { // cloudflareServer: false, // statusCode: 200, // responseText: feedXml, // }, }); }); it('saves response with cloudflare flag correctly', async () => { nock(url.origin).get(url.pathname).replyWithFile(200, feedFilePath, { 'Content-Type': 'application/xml', Server: 'cloudflare', }); await service.fetchAndSaveResponse(feedUrl); expect(responseRepo.insert).toHaveBeenCalledWith({ isCloudflare: true, statusCode: 200, text: feedXml, }); }); }); describe('if not ok response', () => { const feedResponseBody = { message: 'failed', }; it('saves correctly', async () => { nock(url.origin).get(url.pathname).reply(404, feedResponseBody, { 'Content-Type': 'application/xml', }); await service.fetchAndSaveResponse(feedUrl); expect(requestRepo.insert).toHaveBeenCalledWith({ url: feedUrl, status: RequestStatus.FAILED, fetchOptions: { userAgent, }, response: { statusCode: 404, isCloudflare: false, text: JSON.stringify(feedResponseBody), }, }); }); it('saves response with cloudflare flag correctly', async () => { nock(url.origin).get(url.pathname).reply(404, feedResponseBody, { 'Content-Type': 'application/xml', Server: 'cloudflare', }); await service.fetchAndSaveResponse(feedUrl); expect(responseRepo.insert).toHaveBeenCalledWith({ isCloudflare: true, statusCode: 404, text: JSON.stringify(feedResponseBody), }); }); it('emits a url failed event', async () => { nock(url.origin).get(url.pathname).reply(404, feedResponseBody, { 'Content-Type': 'application/xml', }); await service.fetchAndSaveResponse(feedUrl); expect(eventEmitter.emit).toHaveBeenCalledWith('failed.url', { url: feedUrl, }); }); }); describe('if fetch failed', () => { it('saves request correctly', async () => { nock(url.origin).get(url.pathname).replyWithError('failed'); await service.fetchAndSaveResponse(feedUrl); expect(requestRepo.insert).toHaveBeenCalledWith({ url: feedUrl, status: RequestStatus.FETCH_ERROR, fetchOptions: { userAgent, }, errorMessage: expect.any(String), }); }); }); }); describe('onFailedUrl', () => { it('sends the url to sqs if past failure threshold', async () => { jest.spyOn(service, 'isPastFailureThreshold').mockResolvedValue(true); const sendFailedUrlToSqs = jest .spyOn(service, 'sendFailedUrlToSqs') .mockImplementation(); await service.onFailedUrl({ url: feedUrl }); expect(sendFailedUrlToSqs).toHaveBeenCalledWith(feedUrl); }); it('does not send the url to sqs if not past failure threshold', async () => { jest.spyOn(service, 'isPastFailureThreshold').mockResolvedValue(false); const sendFailedUrlToSqs = jest .spyOn(service, 'sendFailedUrlToSqs') .mockImplementation(); await service.onFailedUrl({ url: feedUrl }); expect(sendFailedUrlToSqs).not.toHaveBeenCalled(); }); it('does not reject if an unexpected error occurs', async () => { jest .spyOn(service, 'isPastFailureThreshold') .mockRejectedValue(new Error('fake-rejection')); await service.onFailedUrl({ url: feedUrl }); }); }); describe('isEarliestFailureDatePastThreshold', () => { it('returns true if date is past threshold', () => { service.failedDurationThresholdHours = 1; const failedDate = dayjs().subtract(2, 'hours').toDate(); expect(service.isEarliestFailureDatePastThreshold(failedDate)).toBe(true); }); it('returns false if date is not past threshold', () => { service.failedDurationThresholdHours = 1; const failedDate = dayjs().subtract(30, 'minutes').toDate(); expect(service.isEarliestFailureDatePastThreshold(failedDate)).toBe( false, ); }); }); describe('isPastFailureThreshold', () => { it('returns false if there is no latest request', async () => { jest.spyOn(requestRepo, 'findOne').mockResolvedValue(undefined); const result = await service.isPastFailureThreshold(feedUrl); expect(result).toBe(false); }); it('returns false if latest request is not failed', async () => { jest.spyOn(requestRepo, 'findOne').mockResolvedValue({ status: RequestStatus.OK, } as never); const result = await service.isPastFailureThreshold(feedUrl); expect(result).toBe(false); }); it('returns false if there is no earliest failed attempt', async () => { jest.spyOn(requestRepo, 'findOne').mockResolvedValue({ status: RequestStatus.FAILED, } as never); jest .spyOn(service, 'getEarliestFailedAttempt') .mockResolvedValue(undefined); const result = await service.isPastFailureThreshold(feedUrl); expect(result).toBe(false); }); it('returns false if earliest failure date is not past threshold', async () => { jest.spyOn(requestRepo, 'findOne').mockResolvedValue({ status: RequestStatus.FAILED, } as never); jest.spyOn(service, 'getEarliestFailedAttempt').mockResolvedValue({ createdAt: new Date(), } as never); jest .spyOn(service, 'isEarliestFailureDatePastThreshold') .mockReturnValue(false); const result = await service.isPastFailureThreshold(feedUrl); expect(result).toBe(false); }); it('returns true if earliest failure date is past threshold', async () => { jest.spyOn(requestRepo, 'findOne').mockResolvedValue({ status: RequestStatus.FAILED, } as never); jest.spyOn(service, 'getEarliestFailedAttempt').mockResolvedValue({ createdAt: new Date(), } as never); jest .spyOn(service, 'isEarliestFailureDatePastThreshold') .mockReturnValue(true); const result = await service.isPastFailureThreshold(feedUrl); expect(result).toBe(true); }); }); });
the_stack
import { Component } from './component'; import { Autowired, PostConstruct } from '../context/context'; import { RefSelector } from './componentAnnotations'; import { addCssClass, containsClass } from '../utils/dom'; import { getAriaPosInSet, setAriaSetSize, setAriaPosInSet, setAriaSelected, setAriaChecked, setAriaRole, setAriaLabel } from '../utils/aria'; import { KeyCode } from '../constants/keyCode'; import { ResizeObserverService } from "../misc/resizeObserverService"; import { waitUntil } from '../utils/function'; import { TabGuardComp } from './tabGuardComp'; import { FocusService } from '../focusService'; export interface VirtualListModel { getRowCount(): number; getRow(index: number): any; isRowSelected?(index: number): boolean | undefined; } export class VirtualList extends TabGuardComp { private model: VirtualListModel; private renderedRows = new Map<number, { rowComponent: Component, eDiv: HTMLDivElement; }>(); private componentCreator: (value: any, listItemElement: HTMLElement) => Component; private rowHeight = 20; private lastFocusedRowIndex: number | null; private isDestroyed = false; @Autowired('resizeObserverService') private readonly resizeObserverService: ResizeObserverService; @Autowired('focusService') private readonly focusService: FocusService; @RefSelector('eContainer') private readonly eContainer: HTMLElement; constructor( private readonly cssIdentifier = 'default', private readonly ariaRole = 'listbox', private listName?: string ) { super(VirtualList.getTemplate(cssIdentifier)); } @PostConstruct private postConstruct(): void { this.addScrollListener(); this.rowHeight = this.getItemHeight(); this.addResizeObserver(); this.initialiseTabGuard({ onFocusIn: (e: FocusEvent) => this.onFocusIn(e), onFocusOut: (e: FocusEvent) => this.onFocusOut(e), focusInnerElement: (fromBottom: boolean) => this.focusInnerElement(fromBottom), onTabKeyDown: e => this.onTabKeyDown(e), handleKeyDown: e => this.handleKeyDown(e) }); this.setAriaProperties(); } private setAriaProperties(): void { const translate = this.gridOptionsWrapper.getLocaleTextFunc(); const listName = translate('ariaDefaultListName', this.listName || 'List'); const ariaEl = this.eContainer; setAriaRole(ariaEl, this.ariaRole); setAriaLabel(ariaEl, listName); } private addResizeObserver(): void { const listener = this.drawVirtualRows.bind(this); const destroyObserver = this.resizeObserverService.observeResize(this.getGui(), listener); this.addDestroyFunc(destroyObserver); } protected focusInnerElement(fromBottom: boolean): void { this.focusRow(fromBottom ? this.model.getRowCount() - 1 : 0); } protected onFocusIn(e: FocusEvent): boolean { const target = e.target as HTMLElement; if (containsClass(target, 'ag-virtual-list-item')) { this.lastFocusedRowIndex = getAriaPosInSet(target) - 1; } return false; } protected onFocusOut(e: FocusEvent): boolean { if (!this.getFocusableElement().contains(e.relatedTarget as HTMLElement)) { this.lastFocusedRowIndex = null; } return false; } protected handleKeyDown(e: KeyboardEvent): void { switch (e.keyCode) { case KeyCode.UP: case KeyCode.DOWN: if (this.navigate(e.keyCode === KeyCode.UP)) { e.preventDefault(); } break; } } protected onTabKeyDown(e: KeyboardEvent): void { if (this.navigate(e.shiftKey)) { e.preventDefault(); } else { // focus on the first or last focusable element to ensure that any other handlers start from there this.focusService.focusInto(this.getGui(), !e.shiftKey); } } private navigate(up: boolean): boolean { if (this.lastFocusedRowIndex == null) { return false; } const nextRow = this.lastFocusedRowIndex + (up ? -1 : 1); if (nextRow < 0 || nextRow >= this.model.getRowCount()) { return false; } this.focusRow(nextRow); return true; } public getLastFocusedRow(): number | null { return this.lastFocusedRowIndex; } public focusRow(rowNumber: number): void { this.ensureIndexVisible(rowNumber); window.setTimeout(() => { const renderedRow = this.renderedRows.get(rowNumber); if (renderedRow) { renderedRow.eDiv.focus(); } }, 10); } public getComponentAt(rowIndex: number): Component | undefined { const comp = this.renderedRows.get(rowIndex); return comp && comp.rowComponent; } private static getTemplate(cssIdentifier: string) { return /* html */` <div class="ag-virtual-list-viewport ag-${cssIdentifier}-virtual-list-viewport" role="presentation"> <div class="ag-virtual-list-container ag-${cssIdentifier}-virtual-list-container" ref="eContainer"></div> </div>`; } private getItemHeight(): number { return this.gridOptionsWrapper.getListItemHeight(); } public ensureIndexVisible(index: number): void { const lastRow = this.model.getRowCount(); if (typeof index !== 'number' || index < 0 || index >= lastRow) { console.warn('invalid row index for ensureIndexVisible: ' + index); return; } const rowTopPixel = index * this.rowHeight; const rowBottomPixel = rowTopPixel + this.rowHeight; const eGui = this.getGui(); const viewportTopPixel = eGui.scrollTop; const viewportHeight = eGui.offsetHeight; const viewportBottomPixel = viewportTopPixel + viewportHeight; const viewportScrolledPastRow = viewportTopPixel > rowTopPixel; const viewportScrolledBeforeRow = viewportBottomPixel < rowBottomPixel; if (viewportScrolledPastRow) { // if row is before, scroll up with row at top eGui.scrollTop = rowTopPixel; } else if (viewportScrolledBeforeRow) { // if row is below, scroll down with row at bottom const newScrollPosition = rowBottomPixel - viewportHeight; eGui.scrollTop = newScrollPosition; } } public setComponentCreator(componentCreator: (value: any, listItemElement: HTMLElement) => Component): void { this.componentCreator = componentCreator; } public getRowHeight(): number { return this.rowHeight; } public getScrollTop(): number { return this.getGui().scrollTop; } public setRowHeight(rowHeight: number): void { this.rowHeight = rowHeight; this.refresh(); } public refresh(): void { if (this.model == null || this.isDestroyed) { return; } const rowCount = this.model.getRowCount(); this.eContainer.style.height = `${rowCount * this.rowHeight}px`; // ensure height is applied before attempting to redraw rows waitUntil(() => this.eContainer.clientHeight >= rowCount * this.rowHeight, () => { if (this.isDestroyed) { return; } this.clearVirtualRows(); this.drawVirtualRows(); } ); } private clearVirtualRows() { this.renderedRows.forEach((_, rowIndex) => this.removeRow(rowIndex)); } private drawVirtualRows() { const gui = this.getGui(); const topPixel = gui.scrollTop; const bottomPixel = topPixel + gui.offsetHeight; const firstRow = Math.floor(topPixel / this.rowHeight); const lastRow = Math.floor(bottomPixel / this.rowHeight); this.ensureRowsRendered(firstRow, lastRow); } private ensureRowsRendered(start: number, finish: number) { // remove any rows that are no longer required this.renderedRows.forEach((_, rowIndex) => { if ((rowIndex < start || rowIndex > finish) && rowIndex !== this.lastFocusedRowIndex) { this.removeRow(rowIndex); } }); // insert any required new rows for (let rowIndex = start; rowIndex <= finish; rowIndex++) { if (this.renderedRows.has(rowIndex)) { continue; } // check this row actually exists (in case overflow buffer window exceeds real data) if (rowIndex < this.model.getRowCount()) { this.insertRow(rowIndex); } } } private insertRow(rowIndex: number): void { const value = this.model.getRow(rowIndex); const eDiv = document.createElement('div'); addCssClass(eDiv, 'ag-virtual-list-item'); addCssClass(eDiv, `ag-${this.cssIdentifier}-virtual-list-item`); setAriaRole(eDiv, this.ariaRole === 'tree' ? 'treeitem' : 'option'); setAriaSetSize(eDiv, this.model.getRowCount()); setAriaPosInSet(eDiv, rowIndex + 1); eDiv.setAttribute('tabindex', '-1'); if (typeof this.model.isRowSelected === 'function') { const isSelected = this.model.isRowSelected(rowIndex); setAriaSelected(eDiv, !!isSelected); setAriaChecked(eDiv, isSelected); } eDiv.style.height = `${this.rowHeight}px`; eDiv.style.top = `${this.rowHeight * rowIndex}px`; const rowComponent = this.componentCreator(value, eDiv); rowComponent.addGuiEventListener('focusin', () => this.lastFocusedRowIndex = rowIndex); eDiv.appendChild(rowComponent.getGui()); // keep the DOM order consistent with the order of the rows if (this.renderedRows.has(rowIndex - 1)) { this.renderedRows.get(rowIndex - 1)!.eDiv.insertAdjacentElement('afterend', eDiv); } else if (this.renderedRows.has(rowIndex + 1)) { this.renderedRows.get(rowIndex + 1)!.eDiv.insertAdjacentElement('beforebegin', eDiv); } else { this.eContainer.appendChild(eDiv); } this.renderedRows.set(rowIndex, { rowComponent, eDiv }); } private removeRow(rowIndex: number) { const component = this.renderedRows.get(rowIndex)!; this.eContainer.removeChild(component.eDiv); this.destroyBean(component.rowComponent); this.renderedRows.delete(rowIndex); } private addScrollListener() { this.addGuiEventListener('scroll', () => this.drawVirtualRows()); } public setModel(model: VirtualListModel): void { this.model = model; } public destroy(): void { if (this.isDestroyed) { return; } this.clearVirtualRows(); this.isDestroyed = true; super.destroy(); } }
the_stack
import { createLogger } from '@surgio/logger'; import fs from 'fs-extra'; import _ from 'lodash'; import os from 'os'; import { join } from 'path'; import { ERR_INVALID_FILTER, OBFS_UA } from '../constant'; import { HttpNodeConfig, HttpsNodeConfig, NodeFilterType, NodeTypeEnum, PossibleNodeConfigType, ShadowsocksNodeConfig, ShadowsocksrNodeConfig, SnellNodeConfig, SortedNodeNameFilterType, VmessNodeConfig, } from '../types'; import { ensureConfigFolder, formatV2rayConfig, isIp, pickAndFormatStringList, } from './index'; import { applyFilter } from './filter'; const logger = createLogger({ service: 'surgio:utils:surge' }); export const getSurgeExtendHeaders = ( wsHeaders: Record<string, string>, ): string => { return Object.keys(wsHeaders) .map((headerKey) => `${headerKey}:${wsHeaders[headerKey]}`) .join('|'); }; /** * @see https://manual.nssurge.com/policy/proxy.html */ export const getSurgeNodes = function ( list: ReadonlyArray<PossibleNodeConfigType>, filter?: NodeFilterType | SortedNodeNameFilterType, ): string { // istanbul ignore next if (arguments.length === 2 && typeof filter === 'undefined') { throw new Error(ERR_INVALID_FILTER); } const result: string[] = applyFilter(list, filter) .map((nodeConfig): string | undefined => { switch (nodeConfig.type) { case NodeTypeEnum.Shadowsocks: { const config = nodeConfig as ShadowsocksNodeConfig; if (config.obfs && ['ws', 'wss'].includes(config.obfs)) { logger.warn( `不支持为 Surge 生成 v2ray-plugin 的 Shadowsocks 节点,节点 ${ nodeConfig!.nodeName } 会被省略`, ); return void 0; } // Native support for Shadowsocks if (nodeConfig?.surgeConfig?.shadowsocksFormat === 'ss') { return [ config.nodeName, [ 'ss', config.hostname, config.port, 'encrypt-method=' + config.method, ...pickAndFormatStringList(config, [ 'password', 'udp-relay', 'obfs', 'obfs-host', 'tfo', 'mptcp', ]), ...(typeof config.testUrl === 'string' ? [`test-url=${config.testUrl}`] : []), ...(typeof config.underlyingProxy === 'string' ? [`underlying-proxy=${config.underlyingProxy}`] : []), ].join(', '), ].join(' = '); } // Using custom format return [ config.nodeName, [ 'custom', config.hostname, config.port, config.method, config.password, 'https://raw.githubusercontent.com/ConnersHua/SSEncrypt/master/SSEncrypt.module', ...pickAndFormatStringList(config, [ 'udp-relay', 'obfs', 'obfs-host', 'tfo', 'mptcp', ]), ...(typeof config.testUrl === 'string' ? [`test-url=${config.testUrl}`] : []), ...(typeof config.underlyingProxy === 'string' ? [`underlying-proxy=${config.underlyingProxy}`] : []), ].join(', '), ].join(' = '); } case NodeTypeEnum.HTTPS: { const config = nodeConfig as HttpsNodeConfig; return [ config.nodeName, [ 'https', config.hostname, config.port, config.username, config.password, ...(typeof config.skipCertVerify === 'boolean' ? [`skip-cert-verify=${config.skipCertVerify}`] : []), ...(typeof config.underlyingProxy === 'string' ? [`underlying-proxy=${config.underlyingProxy}`] : []), ...(typeof config.testUrl === 'string' ? [`test-url=${config.testUrl}`] : []), ...pickAndFormatStringList(config, [ 'sni', 'tfo', 'mptcp', 'tls13', ]), ].join(', '), ].join(' = '); } case NodeTypeEnum.HTTP: { const config = nodeConfig as HttpNodeConfig; return [ config.nodeName, [ 'http', config.hostname, config.port, config.username, config.password, ...(typeof config.underlyingProxy === 'string' ? [`underlying-proxy=${config.underlyingProxy}`] : []), ...(typeof config.testUrl === 'string' ? [`test-url=${config.testUrl}`] : []), ...pickAndFormatStringList(config, ['tfo', 'mptcp']), ].join(', '), ].join(' = '); } case NodeTypeEnum.Snell: { const config = nodeConfig as SnellNodeConfig; return [ config.nodeName, [ 'snell', config.hostname, config.port, ...(typeof config.underlyingProxy === 'string' ? [`underlying-proxy=${config.underlyingProxy}`] : []), ...(typeof config.testUrl === 'string' ? [`test-url=${config.testUrl}`] : []), ...pickAndFormatStringList(config, [ 'psk', 'obfs', 'obfs-host', 'version', 'tfo', 'mptcp', ]), ].join(', '), ].join(' = '); } case NodeTypeEnum.Shadowsocksr: { const config = nodeConfig as ShadowsocksrNodeConfig; // istanbul ignore next if (!config.binPath) { throw new Error( '请按照文档 https://url.royli.dev/vdGh2 添加 Shadowsocksr 二进制文件路径', ); } const args = [ '-s', config.hostname, '-p', `${config.port}`, '-m', config.method, '-o', config.obfs, '-O', config.protocol, '-k', config.password, '-l', `${config.localPort}`, '-b', '127.0.0.1', ]; if (config.protoparam) { args.push('-G', config.protoparam); } if (config.obfsparam) { args.push('-g', config.obfsparam); } const configString = [ 'external', `exec = ${JSON.stringify(config.binPath)}`, ...args.map((arg) => `args = ${JSON.stringify(arg)}`), `local-port = ${config.localPort}`, ]; if (config.localPort === 0) { throw new Error( `为 Surge 生成 SSR 配置时必须为 Provider ${config.provider?.name} 设置 startPort,参考 https://url.royli.dev/bWcpe`, ); } if (config.hostnameIp && config.hostnameIp.length) { configString.push( ...config.hostnameIp.map((item) => `addresses = ${item}`), ); } if (isIp(config.hostname)) { configString.push(`addresses = ${config.hostname}`); } return [config.nodeName, configString.join(', ')].join(' = '); } case NodeTypeEnum.Vmess: { const config = nodeConfig as VmessNodeConfig; if (nodeConfig?.surgeConfig?.v2ray === 'native') { // Native support for vmess const configList = [ 'vmess', config.hostname, config.port, `username=${config.uuid}`, ]; if ( ['chacha20-ietf-poly1305', 'aes-128-gcm'].includes(config.method) ) { configList.push(`encrypt-method=${config.method}`); } if (config.network === 'ws') { configList.push('ws=true'); configList.push(`ws-path=${config.path}`); configList.push( 'ws-headers=' + JSON.stringify( getSurgeExtendHeaders({ host: config.host || config.hostname, 'user-agent': OBFS_UA, ..._.omit(config.wsHeaders, ['host']), // host 本质上是一个头信息,所以可能存在冲突的情况。以 host 属性为准。 }), ), ); } if (config.tls) { configList.push( 'tls=true', ...(typeof config.tls13 === 'boolean' ? [`tls13=${config.tls13}`] : []), ...(typeof config.skipCertVerify === 'boolean' ? [`skip-cert-verify=${config.skipCertVerify}`] : []), ...(config.host ? [`sni=${config.host}`] : []), ); } if (typeof config.tfo === 'boolean') { configList.push(`tfo=${config.tfo}`); } if (typeof config.mptcp === 'boolean') { configList.push(`mptcp=${config.mptcp}`); } if (config['underlyingProxy']) { configList.push(`underlying-proxy=${config['underlyingProxy']}`); } if (config['testUrl']) { configList.push(`test-url=${config['testUrl']}`); } if (nodeConfig?.surgeConfig?.vmessAEAD) { configList.push('vmess-aead=true'); } else { configList.push('vmess-aead=false'); } return [config.nodeName, configList.join(', ')].join(' = '); } else { // Using external provider // istanbul ignore next if (!config.binPath) { throw new Error( '请按照文档 https://url.royli.dev/vdGh2 添加 V2Ray 二进制文件路径', ); } if (config.localPort === 0) { throw new Error( `为 Surge 生成 Vmess 配置时必须为 Provider ${config.provider?.name} 设置 startPort,参考 https://url.royli.dev/bWcpe`, ); } const jsonFileName = `v2ray_${config.localPort}_${config.hostname}_${config.port}.json`; const jsonFilePath = join(ensureConfigFolder(), jsonFileName); const jsonFile = formatV2rayConfig( config.localPort as number, nodeConfig, ); const args = [ '--config', jsonFilePath.replace(os.homedir(), '$HOME'), ]; const configString = [ 'external', `exec = ${JSON.stringify(config.binPath)}`, ...args.map((arg) => `args = ${JSON.stringify(arg)}`), `local-port = ${config.localPort}`, ]; if (config.hostnameIp && config.hostnameIp.length) { configString.push( ...config.hostnameIp.map((item) => `addresses = ${item}`), ); } if (isIp(config.hostname)) { configString.push(`addresses = ${config.hostname}`); } // istanbul ignore next if (process.env.NODE_ENV !== 'test') { fs.writeJSONSync(jsonFilePath, jsonFile); } return [config.nodeName, configString.join(', ')].join(' = '); } } case NodeTypeEnum.Trojan: { const configList: string[] = [ 'trojan', nodeConfig.hostname, `${nodeConfig.port}`, `password=${nodeConfig.password}`, ...pickAndFormatStringList(nodeConfig, [ 'tfo', 'mptcp', 'sni', 'tls13', ]), ...(typeof nodeConfig.testUrl === 'string' ? [`test-url=${nodeConfig.testUrl}`] : []), ...(typeof nodeConfig.underlyingProxy === 'string' ? [`underlying-proxy=${nodeConfig.underlyingProxy}`] : []), ...(typeof nodeConfig.skipCertVerify === 'boolean' ? [`skip-cert-verify=${nodeConfig.skipCertVerify}`] : []), ]; if (nodeConfig.network === 'ws') { configList.push('ws=true'); configList.push(`ws-path=${nodeConfig.wsPath}`); if (nodeConfig.wsHeaders) { configList.push( 'ws-headers=' + JSON.stringify(getSurgeExtendHeaders(nodeConfig.wsHeaders)), ); } } return [nodeConfig.nodeName, configList.join(', ')].join(' = '); } case NodeTypeEnum.Socks5: { const config = [ nodeConfig.tls === true ? 'socks5-tls' : 'socks5', nodeConfig.hostname, nodeConfig.port, ...(typeof nodeConfig.underlyingProxy === 'string' ? [`underlying-proxy=${nodeConfig.underlyingProxy}`] : []), ...(typeof nodeConfig.testUrl === 'string' ? [`test-url=${nodeConfig.testUrl}`] : []), ...pickAndFormatStringList(nodeConfig, [ 'username', 'password', 'sni', 'tfo', 'mptcp', 'tls13', ]), ]; if (nodeConfig.tls === true) { config.push( ...(typeof nodeConfig.skipCertVerify === 'boolean' ? [`skip-cert-verify=${nodeConfig.skipCertVerify}`] : []), ...(typeof nodeConfig.clientCert === 'string' ? [`client-cert=${nodeConfig.clientCert}`] : []), ); } return [nodeConfig.nodeName, config.join(', ')].join(' = '); } // istanbul ignore next default: logger.warn( `不支持为 Surge 生成 ${(nodeConfig as any).type} 的节点,节点 ${ (nodeConfig as any).nodeName } 会被省略`, ); return void 0; } }) .filter((item): item is string => item !== undefined); return result.join('\n'); };
the_stack
/// <reference types="node" /> import Long = require('long'); declare namespace ByteBuffer {} export = ByteBuffer; export as namespace ByteBuffer; declare class ByteBuffer { /** * Constructs a new ByteBuffer. */ constructor(capacity?: number, littleEndian?: boolean, noAssert?: boolean); /** * Big endian constant that can be used instead of its boolean value. Evaluates to false. */ static BIG_ENDIAN: boolean; /** * Default initial capacity of 16. */ static DEFAULT_CAPACITY: number; /** * Default endianess of false for big endian. */ static DEFAULT_ENDIAN: boolean; /** * Default no assertions flag of false. */ static DEFAULT_NOASSERT: boolean; /** * Little endian constant that can be used instead of its boolean value. Evaluates to true. */ static LITTLE_ENDIAN: boolean; /** * Maximum number of bytes required to store a 32bit base 128 variable-length integer. */ static MAX_VARINT32_BYTES: number; /** * Maximum number of bytes required to store a 64bit base 128 variable-length integer. */ static MAX_VARINT64_BYTES: number; /** * Metrics representing number of bytes.Evaluates to 2. */ static METRICS_BYTES: number; /** * Metrics representing number of UTF8 characters.Evaluates to 1. */ static METRICS_CHARS: number; /** * ByteBuffer version. */ static VERSION: string; /** * Backing buffer. */ buffer: Buffer; /** * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation. */ limit: number; /** * Whether to use little endian byte order, defaults to false for big endian. */ littleEndian: boolean; /** * Marked offset. */ markedOffset: number; /** * Whether to skip assertions of offsets and values, defaults to false. */ noAssert: boolean; /** * Absolute read/write offset. */ offset: number; /** * Data view to manipulate the backing buffer. Becomes null if the backing buffer has a capacity of 0. */ view: DataView; /** * Allocates a new ByteBuffer backed by a buffer of the specified capacity. */ static allocate(capacity?: number, littleEndian?: boolean, noAssert?: boolean): ByteBuffer; /** * Decodes a base64 encoded string to binary like window.atob does. */ static atob(b64: string): string; /** * Encodes a binary string to base64 like window.btoa does. */ static btoa(str: string): string; /** * Calculates the number of UTF8 bytes of a string. */ static calculateUTF8Bytes(str: string): number; /** * Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. */ static calculateUTF8Chars(str: string): number; /** * Calculates the number of UTF8 bytes of a string. This is an alias of ByteBuffer#calculateUTF8Bytes. */ static calculateString(str: string): number; /** * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer. */ static calculateVarint32(value: number): number; /** * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer. */ static calculateVarint64(value: number | Long): number; /** * Concatenates multiple ByteBuffers into one. */ static concat( buffers: Array<ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string>, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean, ): ByteBuffer; /** * Decodes a base64 encoded string to a ByteBuffer. */ static fromBase64(str: string, littleEndian?: boolean, noAssert?: boolean): ByteBuffer; /** * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer. */ static fromBinary(str: string, littleEndian?: boolean, noAssert?: boolean): ByteBuffer; /** * Decodes a hex encoded string with marked offsets to a ByteBuffer. */ static fromDebug(str: string, littleEndian?: boolean, noAssert?: boolean): ByteBuffer; /** * Decodes a hex encoded string to a ByteBuffer. */ static fromHex(str: string, littleEndian?: boolean, noAssert?: boolean): ByteBuffer; /** * Decodes an UTF8 encoded string to a ByteBuffer. */ static fromUTF8(str: string, littleEndian?: boolean, noAssert?: boolean): ByteBuffer; /** * Gets the backing buffer type. */ static isByteBuffer(bb: any): boolean; /** * Wraps a buffer or a string. Sets the allocated ByteBuffer's ByteBuffer#offset to 0 and its ByteBuffer#limit to the length of the wrapped data. * @param buffer Anything that can be wrapped * @param encoding String encoding if buffer is a string ("base64", "hex", "binary", defaults to "utf8") * @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN. * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT. */ static wrap( buffer: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean, ): ByteBuffer; /** * Decodes a zigzag encoded signed 32bit integer. */ static zigZagDecode32(n: number): number; /** * Decodes a zigzag encoded signed 64bit integer. */ static zigZagDecode64(n: number | Long): Long; /** * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding. */ static zigZagEncode32(n: number): number; /** * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding. */ static zigZagEncode64(n: number | Long): Long; /** * Switches (to) big endian byte order. */ BE(bigEndian?: boolean): this; /** * Switches (to) little endian byte order. */ LE(bigEndian?: boolean): this; /** * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length. */ append( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number, ): this; /** * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data. */ appendTo(target: ByteBuffer, offset?: number): this; /** * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid. */ assert(assert: boolean): this; /** * Gets the capacity of this ByteBuffer's backing buffer. */ capacity(): number; /** * Clears this ByteBuffer's offsets by setting ByteBuffer#offset to 0 and * ByteBuffer#limit to the backing buffer's capacity. Discards ByteBuffer#markedOffset. */ clear(): this; /** * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for ByteBuffer#offset, ByteBuffer#markedOffset and ByteBuffer#limit. */ clone(copy?: boolean): ByteBuffer; /** * Compacts this ByteBuffer to be backed by a ByteBuffer#buffer of its contents' length. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will set offset = 0 and limit = capacity and adapt ByteBuffer#markedOffset to the same relative position if set. */ compact(begin?: number, end?: number): this; /** * Creates a copy of this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. */ copy(begin?: number, end?: number): ByteBuffer; /** * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. */ copyTo(target: ByteBuffer, targetOffset?: number, sourceOffset?: number, sourceLimit?: number): this; /** * Makes sure that this ByteBuffer is backed by a ByteBuffer#buffer of at least the specified capacity. If the current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity, the required capacity will be used instead. */ ensureCapacity(capacity: number): this; /** * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. */ fill(value: number | string, begin?: number, end?: number): this; /** * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets limit = offset and offset = 0. Make sure always to flip a ByteBuffer when all relative read or write operations are complete. */ flip(): this; /** * Marks an offset on this ByteBuffer to be used later. */ mark(offset?: number): this; /** * Sets the byte order. */ order(littleEndian: boolean): this; /** * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. */ prepend( source: ByteBuffer | string | ArrayBuffer | Buffer, encoding?: string | number, offset?: number, ): this; /** * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. */ prependTo(target: ByteBuffer, offset?: number): this; /** * Prints debug information about this ByteBuffer's contents. */ printDebug(out?: (text: string) => void): void; /** * Reads an 8bit signed integer. This is an alias of ByteBuffer#readInt8. */ readByte(offset?: number): number; /** * Reads the specified number of bytes */ readBytes(length: number, offset?: number): ByteBuffer; /** * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters itself. */ readCString(): string; readCString(offset: number): { string: string; length: number }; /** * Reads a 64bit float. This is an alias of ByteBuffer#readFloat64. */ readDouble(offset?: number): number; /** * Reads a 32bit float. This is an alias of ByteBuffer#readFloat32. */ readFloat(offset?: number): number; /** * Reads a 32bit float. */ readFloat32(offset?: number): number; /** * Reads a 64bit float. */ readFloat64(offset?: number): number; /** * Reads a length as uint32 prefixed UTF8 encoded string. */ readIString(): string; readIString(offset: number): { string: string; length: number }; /** * Reads a 32bit signed integer.This is an alias of ByteBuffer#readInt32. */ readInt(offset?: number): number; /** * Reads a 16bit signed integer. */ readInt16(offset?: number): number; /** * Reads a 32bit signed integer. */ readInt32(offset?: number): number; /** * Reads a 64bit signed integer. */ readInt64(offset?: number): Long; /** * Reads an 8bit signed integer. */ readInt8(offset?: number): number; /** * Reads a 64bit signed integer. This is an alias of ByteBuffer#readInt64. */ readLong(offset?: number): Long; /** * Reads a 16bit signed integer. This is an alias of ByteBuffer#readInt16. */ readShort(offset?: number): number; /** * Reads an UTF8 encoded string. This is an alias of ByteBuffer#readUTF8String. */ readString(length: number, metrics?: number): string; readString(length: number, metrics: number, offset: number): { string: string; length: number }; /** * Reads an UTF8 encoded string. */ readUTF8String(chars: number, metrics?: number): string; readUTF8String(chars: number, metrics: number, offset: number): { string: string; length: number }; /** * Reads a 16bit unsigned integer. */ readUint16(offset?: number): number; /** * Reads a 32bit unsigned integer. */ readUint32(offset?: number): number; /** * Reads a 64bit unsigned integer. */ readUint64(offset?: number): Long; /** * Reads an 8bit unsigned integer. */ readUint8(offset?: number): number; /** * Reads a length as varint32 prefixed UTF8 encoded string. */ readVString(): string; readVString(offset: number): { string: string; length: number }; /** * Reads a 32bit base 128 variable-length integer. */ readVarint32(): number; readVarint32(offset: number): { value: number; length: number }; /** * Reads a zig-zag encoded 32bit base 128 variable-length integer. */ readVarint32ZigZag(): number; readVarint32ZigZag(offset: number): { value: number; length: number }; /** * Reads a 64bit base 128 variable-length integer. Requires Long.js. */ readVarint64(): Long; readVarint64(offset: number): { value: Long; length: number }; /** * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js. */ readVarint64ZigZag(): Long; readVarint64ZigZag(offset: number): { value: Long; length: number }; /** * Gets the number of remaining readable bytes. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit, so this returns limit - offset. */ remaining(): number; /** * Resets this ByteBuffer's ByteBuffer#offset. If an offset has been marked through ByteBuffer#mark before, offset will be set to ByteBuffer#markedOffset, which will then be discarded. If no offset has been marked, sets offset = 0. */ reset(): this; /** * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that large or larger. */ resize(capacity: number): this; /** * Reverses this ByteBuffer's contents */ reverse(begin?: number, end?: number): this; /** * Skips the next length bytes. This will just advance */ skip(length: number): this; /** * Slices this ByteBuffer by creating a cloned instance with offset = begin and limit = end. */ slice(begin?: number, end?: number): ByteBuffer; /** * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. This is an alias of ByteBuffer#toBuffer. */ toArrayBuffer(forceCopy?: boolean): ArrayBuffer; /** * Encodes this ByteBuffer's contents to a base64 encoded string. */ toBase64(begin?: number, end?: number): string; /** * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes. */ toBinary(begin?: number, end?: number): string; /** * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. */ toBuffer(forceCopy?: boolean): Buffer; /** *Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are: * < : offset, * ' : markedOffset, * > : limit, * | : offset and limit, * [ : offset and markedOffset, * ] : markedOffset and limit, * ! : offset, markedOffset and limit */ toDebug(columns?: boolean): string | Array<string>; /** * Encodes this ByteBuffer's contents to a hex encoded string. */ toHex(begin?: number, end?: number): string; /** * Converts the ByteBuffer's contents to a string. */ toString(encoding?: string): string; /** * Encodes this ByteBuffer's contents between ByteBuffer#offset and ByteBuffer#limit to an UTF8 encoded string. */ toUTF8(): string; /** * Writes an 8bit signed integer. This is an alias of ByteBuffer#writeInt8. */ writeByte(value: number, offset?: number): this; /** * Writes an array of bytes. This is an alias for append */ writeBytes( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number, ): this; /** * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself. */ writeCString(str: string, offset?: number): this; /** * Writes a 64bit float. This is an alias of ByteBuffer#writeFloat64. */ writeDouble(value: number, offset?: number): this; /** * Writes a 32bit float. This is an alias of ByteBuffer#writeFloat32. */ writeFloat(value: number, offset?: number): this; /** * Writes a 32bit float. */ writeFloat32(value: number, offset?: number): this; /** * Writes a 64bit float. */ writeFloat64(value: number, offset?: number): this; /** * Writes a length as uint32 prefixed UTF8 encoded string. */ writeIString(str: string, offset?: number): this; /** * Writes a 32bit signed integer. This is an alias of ByteBuffer#writeInt32. */ writeInt(value: number, offset?: number): this; /** * Writes a 16bit signed integer. */ writeInt16(value: number, offset?: number): this; /** * Writes a 32bit signed integer. */ writeInt32(value: number, offset?: number): this; /** * Writes a 64bit signed integer. */ writeInt64(value: number | Long, offset?: number): this; /** * Writes an 8bit signed integer. */ writeInt8(value: number, offset?: number): this; /** * Write a 64bit signed integer. This is an alias of ByteBuffer#writeInt64. */ writeLong(value: number | Long, offset?: number): this; /** * Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16. */ writeShort(value: number, offset?: number): this; /** * Writes an UTF8 encoded string. This is an alias of ByteBuffer#writeUTF8String. */ writeString(str: string): this; writeString(str: string, offset: number): number; /** * Writes an UTF8 encoded string. */ writeUTF8String(str: string): this; writeUTF8String(str: string, offset?: number): number; /** * Writes a 16bit unsigned integer. */ writeUint16(value: number, offset?: number): this; /** * Writes a 32bit unsigned integer. */ writeUint32(value: number, offset?: number): this; /** * Writes a 64bit unsigned integer. */ writeUint64(value: number | Long, offset?: number): this; /** * Writes an 8bit unsigned integer. */ writeUint8(value: number, offset?: number): this; /** * Writes a length as varint32 prefixed UTF8 encoded string. */ writeVString(str: string): this; writeVString(str: string, offset: number): number; /** * Writes a 32bit base 128 variable-length integer. */ writeVarint32(value: number): this; writeVarint32(value: number, offset: number): number; /** * Writes a zig-zag encoded 32bit base 128 variable-length integer. */ writeVarint32ZigZag(value: number): this; writeVarint32ZigZag(value: number, offset: number): number; /** * Writes a 64bit base 128 variable-length integer. */ writeVarint64(value: number | Long): this; writeVarint64(value: number | Long, offset: number): number; /** * Writes a zig-zag encoded 64bit base 128 variable-length integer. */ writeVarint64ZigZag(value: number | Long): this; writeVarint64ZigZag(value: number | Long, offset: number): number; }
the_stack
import { auxiliaries, vec3 } from 'webgl-operate'; import { AccumulatePass, AntiAliasingKernel, BlitPass, Camera, Canvas, Context, DefaultFramebuffer, EventProvider, Framebuffer, Invalidate, Navigation, NdcFillingTriangle, Program, Renderbuffer, Renderer, Shader, Texture2D, Wizard, } from 'webgl-operate'; import { Demo } from '../demo'; import { colors, indices, vertices } from './cornellboxdata'; /* spellchecker: enable */ // tslint:disable:max-classes-per-file // camera constants const _gEye = vec3.fromValues( +0.000000, +0.005102, -3.861230); const _gCenter = vec3.fromValues( +0.000000, +0.000000, +0.000000); const _gUp = vec3.fromValues( +0.000000, +1.000000, +0.000000); // corners of axis aligned light cuboid const light0 = vec3.fromValues(-0.233813, +1 - 2e-2, -0.188126); const light1 = vec3.fromValues(+0.233813, +1 - 2e-1, +0.187411); export class CornellBoxRenderer extends Renderer { protected _extensions = false; // stuff protected _camera: Camera; protected _navigation: Navigation; protected _ndcTriangle: NdcFillingTriangle; // program and uniforms protected _program: Program; protected _uTransform: WebGLUniformLocation; protected _uFrame: WebGLUniformLocation; protected _uRand: WebGLUniformLocation; protected _uEye: WebGLUniformLocation; protected _uViewport: WebGLUniformLocation; protected _ndcOffsetKernel: AntiAliasingKernel; protected _uNdcOffset: WebGLUniformLocation; // Textures protected _hsphereImage: Texture2D; protected _lightsImage: Texture2D; // blit and accumulate protected _accumulate: AccumulatePass; protected _blit: BlitPass; protected _defaultFBO: DefaultFramebuffer; protected _colorRenderTexture: Texture2D; protected _depthRenderbuffer: Renderbuffer; protected _intermediateFBO: Framebuffer; // for webgl1 protected _verticesImage: Texture2D; protected _indicesImage: Texture2D; protected _colorsImage: Texture2D; protected onUpdate(): boolean { // Update camera navigation (process events) this._navigation.update(); return this._altered.any || this._camera.altered; } protected onPrepare(): void { const gl = this._context.gl; const gl2facade = this._context.gl2facade; if (!this._intermediateFBO.initialized) { this._colorRenderTexture.initialize(this._frameSize[0], this._frameSize[1], this._context.isWebGL2 ? gl.RGBA8 : gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE); this._depthRenderbuffer.initialize(this._frameSize[0], this._frameSize[1], gl.DEPTH_COMPONENT16); this._intermediateFBO.initialize([[gl2facade.COLOR_ATTACHMENT0, this._colorRenderTexture] , [gl.DEPTH_ATTACHMENT, this._depthRenderbuffer]]); } // resize if (this._altered.frameSize) { this._intermediateFBO.resize(this._frameSize[0], this._frameSize[1]); this._camera.viewport = [this._frameSize[0], this._frameSize[1]]; } if (this._altered.canvasSize) { this._camera.aspect = this._canvasSize[0] / this._canvasSize[1]; } if (this._altered.clearColor) { this._intermediateFBO.clearColor(this._clearColor); } if (this._altered.multiFrameNumber) { this._ndcOffsetKernel = new AntiAliasingKernel(this._multiFrameNumber); } this._accumulate.update(); if (this._camera.altered) { this._program.bind(); gl.uniformMatrix4fv(this._uTransform, false, this._camera.viewProjectionInverse); gl.uniform3fv(this._uEye, this._camera.eye); gl.uniform4f(this._uViewport, this._camera.viewport[0], this._camera.viewport[1], 1.0 / this._camera.viewport[0], 1.0 / this._camera.viewport[1]); } this._altered.reset(); this._camera.altered = false; } protected onFrame(frameNumber: number): void { const gl = this._context.gl; gl.viewport(0, 0, this._frameSize[0], this._frameSize[1]); this._intermediateFBO.bind(); this._intermediateFBO.clear(gl.COLOR_BUFFER_BIT, false, false); const ndcOffset = this._ndcOffsetKernel.get(frameNumber); ndcOffset[0] = 2.0 * ndcOffset[0] / this._frameSize[0]; ndcOffset[1] = 2.0 * ndcOffset[1] / this._frameSize[1]; // set uniforms this._program.bind(); gl.uniform1i(this._uFrame, frameNumber); gl.uniform1i(this._uRand, Math.floor(Math.random() * 1e6)); gl.uniform2fv(this._uNdcOffset, ndcOffset); this._hsphereImage.bind(gl.TEXTURE0); this._lightsImage.bind(gl.TEXTURE1); // webgl1 if (this._context.isWebGL1) { this._verticesImage.bind(gl.TEXTURE2); this._indicesImage.bind(gl.TEXTURE3); this._colorsImage.bind(gl.TEXTURE4); } // render geometry this._ndcTriangle.bind(); this._ndcTriangle.draw(); this._ndcTriangle.unbind(); this._intermediateFBO.unbind(); this._accumulate.frame(frameNumber); } protected onSwap(): void { if (this._accumulate.framebuffer) { this._blit.framebuffer = this._accumulate.framebuffer; } else { this._blit.framebuffer = this._intermediateFBO; } this._blit.frame(); } protected onInitialize(context: Context, callback: Invalidate, eventProvider: EventProvider): boolean { const gl = this._context.gl; const gl2facade = this._context.gl2facade; /* Enable required extensions. */ if (this._extensions === false && this._context.isWebGL1) { auxiliaries.assert(this._context.supportsStandardDerivatives, `expected OES_standard_derivatives support`); this._context.standardDerivatives; this._extensions = true; } if (this._camera === undefined) { this._camera = new Camera(); this._camera.eye = _gEye; this._camera.center = _gCenter; this._camera.up = _gUp; this._camera.near = 0.1; this._camera.far = 4.0; } // Initialize navigation this._navigation = new Navigation(callback, eventProvider); this._navigation.camera = this._camera; // program const vert = new Shader(this._context, gl.VERTEX_SHADER, 'cornell.vert'); vert.initialize(require('./cornell.vert')); const frag = new Shader(this._context, gl.FRAGMENT_SHADER, 'cornell.frag'); frag.initialize(require(this._context.isWebGL1 ? (this._context.supportsTextureFloat ? './cornell1.frag' : './cornell0.frag') : './cornell2.frag')); this._program = new Program(this._context); this._program.initialize([vert, frag], false); // attributes this._ndcTriangle = new NdcFillingTriangle(this._context); const aVertex = this._program.attribute('a_vertex', 0); this._program.link(); // uniforms this._uTransform = this._program.uniform('u_transform'); this._uFrame = this._program.uniform('u_frame'); this._uRand = this._program.uniform('u_rand'); this._uEye = this._program.uniform('u_eye'); this._uViewport = this._program.uniform('u_viewport'); this._program.bind(); gl.uniform1i(this._program.uniform('u_hsphere'), 0); gl.uniform1i(this._program.uniform('u_lights'), 1); this._program.unbind(); this._ndcTriangle.initialize(aVertex); // CREATE HEMISPHERE PATH SAMPLES and LIGHT AREA SAMPLES this._hsphereImage = new Texture2D(this._context, 'hsphereImage'); this._lightsImage = new Texture2D(this._context, 'lightsImage'); const points = this.pointsOnSphere(32 * 32); const samplerSize = Math.floor(Math.sqrt(points.length)); // shader expects 32 const spherePoints = new Float32Array(samplerSize * samplerSize * 3); for (let i = 0; i < samplerSize * samplerSize; ++i) { spherePoints[3 * i + 0] = points[i][0]; spherePoints[3 * i + 1] = points[i][1]; spherePoints[3 * i + 2] = points[i][2]; } // CREATE LIGHT AREA SAMPLES const lights = this.pointsInLight(light0, light1, 32 * 32); const lights2 = new Float32Array(lights.length * 3); let i2 = 0; for (const light of lights) { lights2[i2++] = light[0]; lights2[i2++] = light[1]; lights2[i2++] = light[2]; } // special case for webgl1 and no float support if (this._context.isWebGL1 && !this._context.supportsTextureFloat) { this._hsphereImage.initialize(32 * 3, 32, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._hsphereImage.data(this.encodeFloatArrayAndScale(spherePoints)); this._lightsImage.initialize(32 * 3, 32, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._lightsImage.data(this.encodeFloatArrayAndScale(lights2)); } else { const format = Wizard.queryInternalTextureFormat(this._context, gl.RGB, Wizard.Precision.float); this._hsphereImage.initialize(samplerSize, samplerSize, format[0], gl.RGB, format[1]); this._hsphereImage.data(spherePoints); this._lightsImage.initialize(32, 32, format[0], gl.RGB, format[1]); this._lightsImage.data(lights2); } this._hsphereImage.wrap(gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); this._hsphereImage.filter(gl.NEAREST, gl.NEAREST); this._lightsImage.wrap(gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); this._lightsImage.filter(gl.NEAREST, gl.NEAREST); // scene textures for webgl1 if (this._context.isWebGL1) { this._program.bind(); gl.uniform1i(this._program.uniform('u_vertices'), 2); gl.uniform1i(this._program.uniform('u_indices'), 3); gl.uniform1i(this._program.uniform('u_colors'), 4); this._program.unbind(); this._verticesImage = new Texture2D(this._context, 'verticesImage'); this._indicesImage = new Texture2D(this._context, 'indicesImage'); this._colorsImage = new Texture2D(this._context, 'colorsImage'); this._indicesImage.initialize(indices.length / 4, 1, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE); this._indicesImage.data(indices); if (context.supportsTextureFloat) { this._verticesImage.initialize(vertices.length / 3, 1, gl.RGB, gl.RGB, gl.FLOAT); this._verticesImage.data(vertices); this._colorsImage.initialize(colors.length / 3, 1, gl.RGB, gl.RGB, gl.FLOAT); this._colorsImage.data(colors); } else { // no floats => encode float in 3 bytes this._verticesImage.initialize(vertices.length / 3 * 3, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._verticesImage.data(this.encodeFloatArrayAndScale(vertices)); this._colorsImage.initialize(colors.length / 3 * 3, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._colorsImage.data(this.encodeFloatArray(colors)); } this._verticesImage.wrap(gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); this._verticesImage.filter(gl.NEAREST, gl.NEAREST); this._indicesImage.wrap(gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); this._indicesImage.filter(gl.NEAREST, gl.NEAREST); this._colorsImage.wrap(gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); this._colorsImage.filter(gl.NEAREST, gl.NEAREST); } this._uNdcOffset = this._program.uniform('u_ndcOffset'); this._defaultFBO = new DefaultFramebuffer(this._context, 'DefaultFBO'); this._defaultFBO.initialize(); this._colorRenderTexture = new Texture2D(this._context, 'ColorRenderTexture'); this._depthRenderbuffer = new Renderbuffer(this._context, 'DepthRenderbuffer'); this._intermediateFBO = new Framebuffer(this._context, 'IntermediateFBO'); this._accumulate = new AccumulatePass(this._context); this._accumulate.initialize(this._ndcTriangle); this._accumulate.precision = this._framePrecision; this._accumulate.texture = this._colorRenderTexture; this._blit = new BlitPass(this._context); this._blit.initialize(this._ndcTriangle); this._blit.readBuffer = gl2facade.COLOR_ATTACHMENT0; this._blit.drawBuffer = gl.BACK; this._blit.target = this._defaultFBO; return true; } protected onUninitialize(): void { this._program.uninitialize(); this._ndcTriangle.uninitialize(); this._hsphereImage.uninitialize(); this._lightsImage.uninitialize(); if (this._context.isWebGL1) { this._verticesImage.uninitialize(); this._indicesImage.uninitialize(); this._colorsImage.uninitialize(); } this._intermediateFBO.uninitialize(); this._defaultFBO.uninitialize(); this._colorRenderTexture.uninitialize(); this._depthRenderbuffer.uninitialize(); this._blit.uninitialize(); } protected onDiscarded(): void { this._altered.alter('canvasSize'); this._altered.alter('clearColor'); this._altered.alter('frameSize'); this._altered.alter('multiFrameNumber'); } // https://en.wikipedia.org/wiki/Fisher-Yates_shuffle shuffle(deck: Array<vec3>): Array<vec3> { const randomizedDeck = Array<vec3>(); const array = deck.slice(); while (array.length !== 0) { const rIndex = Math.floor(array.length * Math.random()); randomizedDeck.push(array[rIndex]); array.splice(rIndex, 1); } return randomizedDeck; } pointsInLight(llf: vec3, urb: vec3, minN: number): Array<vec3> { const lights = Array<vec3>(); const min = vec3.min(vec3.create(), llf, urb); const max = vec3.max(vec3.create(), llf, urb); const size = vec3.subtract(vec3.create(), max, min); const r = Math.ceil(Math.sqrt(1.0 * minN)); const step = vec3.scale(vec3.create(), size, (1.0 - 1e-4) / (r - 1.0)); // the "<=" and floating precision for (let x = min[0]; x <= max[0]; x += step[0]) { for (let z = min[2]; z <= max[2]; z += step[2]) { lights.push(vec3.fromValues(x, auxiliaries.rand(min[1], max[1]), z)); } } return this.shuffle(lights); } pointsOnSphere(numPoints: number): Array<vec3> { /* Random directions in tangent space. */ const donkey = new Array<vec3>(numPoints); for (let i = 0; i < donkey.length; ++i) { const bound = 1.0 - 1e-4; const x = auxiliaries.rand(-bound, bound); const z = auxiliaries.rand(-bound, bound); const y = Math.sqrt(Math.max(1.0 - x * x - z * z, 1e-4)); donkey[i] = vec3.normalize(vec3.create(), vec3.fromValues(x, y, z)); } return donkey; } fract(x: number): number { return x > 0 ? x - Math.floor(x) : x - Math.ceil(x); } encode_float24x1_to_uint8x3(out: vec3, x: number): vec3 { out[0] = Math.floor(x * 255.0); out[1] = Math.floor(this.fract(x * 255.0) * 255.0); out[2] = Math.floor(this.fract(x * 65536.0) * 255.0); return out; } encodeFloatArray(floats: Float32Array): Uint8Array { const byteEncodedArray = new Uint8Array(floats.length * 3); for (let i = 0; i < floats.length; i++) { const encodedVec3 = this.encode_float24x1_to_uint8x3(vec3.create(), floats[i]); byteEncodedArray[3 * i + 0] = encodedVec3[0]; byteEncodedArray[3 * i + 1] = encodedVec3[1]; byteEncodedArray[3 * i + 2] = encodedVec3[2]; } return byteEncodedArray; } // scale from [-1..+1] to [0..1] and encode encodeFloatArrayAndScale(floats: Float32Array): Uint8Array { const byteEncodedArray = new Uint8Array(floats.length * 3); for (let i = 0; i < floats.length; i++) { const encodedVec3 = this.encode_float24x1_to_uint8x3(vec3.create(), floats[i] * 0.5 + 0.5); byteEncodedArray[3 * i + 0] = encodedVec3[0]; byteEncodedArray[3 * i + 1] = encodedVec3[1]; byteEncodedArray[3 * i + 2] = encodedVec3[2]; } return byteEncodedArray; } } export class CornellBoxDemo extends Demo { private _canvas: Canvas; private _renderer: CornellBoxRenderer; onInitialize(element: HTMLCanvasElement | string): boolean { this._canvas = new Canvas(element); this._canvas.controller.multiFrameNumber = 1; this._canvas.framePrecision = Wizard.Precision.float; this._canvas.frameScale = [0.3333, 0.3333]; this._canvas.clearColor.fromHex('d6d8db'); this._canvas.controller.multiFrameNumber = 1024; this._canvas.element.addEventListener('click', () => { this._canvas.controller.update(); }); this._renderer = new CornellBoxRenderer(); this._canvas.renderer = this._renderer; return true; } onUninitialize(): void { this._canvas.dispose(); (this._renderer as Renderer).uninitialize(); } get canvas(): Canvas { return this._canvas; } get renderer(): CornellBoxRenderer { return this._renderer; } }
the_stack
import { dsvFormat, DSVParsedArray } from "d3-dsv" import fastCartesian from "fast-cartesian" import { findIndexFast, first, flatten, range, sampleFrom, slugifySameCase, toString, } from "../clientUtils/Util" import { CoreColumnStore, CoreRow, CoreMatrix, Time, CoreValueType, } from "./CoreTableConstants" import { ColumnTypeNames, CoreColumnDef } from "./CoreColumnDef" import { ErrorValue, ErrorValueTypes } from "./ErrorValues" import { OwidEntityCodeColumnDef, OwidEntityIdColumnDef, OwidEntityNameColumnDef, OwidTableSlugs, } from "./OwidTableConstants" import { ColumnSlug } from "../clientUtils/owidTypes" export const columnStoreToRows = ( columnStore: CoreColumnStore ): Record<string, CoreValueType>[] => { const firstCol = Object.values(columnStore)[0] if (!firstCol) return [] const slugs = Object.keys(columnStore) return firstCol.map((val, index) => { const newRow: Record<string, CoreValueType> = {} slugs.forEach((slug) => { newRow[slug] = columnStore[slug][index] }) return newRow }) } // If string exceeds maxLength, will replace the end char with a ... and drop the rest export const truncate = (str: string, maxLength: number): string => str.length > maxLength ? `${str.substr(0, maxLength - 3)}...` : str // Picks a type for each column from the first row then autotypes all rows after that so all values in // a column will have the same type. Only chooses between strings and numbers. const numberOnly = /^-?\d+\.?\d*$/ export const makeAutoTypeFn = ( numericSlugs?: ColumnSlug[] ): ((object: any) => any) => { const slugToType: any = {} numericSlugs?.forEach((slug) => { slugToType[slug] = "number" }) return (object: any): any => { for (const columnSlug in object) { const value = object[columnSlug] const type = slugToType[columnSlug] if (type === "string") { object[columnSlug] = value continue } const number = parseFloat(value) // The "+" type casting that d3 does for perf converts "" to 0, so use parseFloat. if (type === "number") { object[columnSlug] = isNaN(number) ? ErrorValueTypes.NaNButShouldBeNumber : number continue } if (isNaN(number) || !numberOnly.test(value)) { object[columnSlug] = value slugToType[columnSlug] = "string" continue } object[columnSlug] = number slugToType[columnSlug] = "number" } return object } } // Removes whitespace and non-word characters from column slugs if any exist. // The original names are moved to the name property on the column def. export const standardizeSlugs = ( rows: CoreRow[] ): { rows: CoreRow[]; defs: { name: string; slug: string }[] } | undefined => { const firstRow = rows[0] ?? {} const colsToRename = Object.keys(firstRow) .map((name) => { return { name, slug: slugifySameCase(name), } }) .filter((col) => col.name !== col.slug) if (!colsToRename.length) return undefined rows.forEach((row: CoreRow) => { colsToRename.forEach((col) => { row[col.slug] = row[col.name] delete row[col.name] }) }) return { rows, defs: colsToRename } } export const guessColumnDefFromSlugAndRow = ( slug: string, sampleValue: any ): CoreColumnDef => { const valueType = typeof sampleValue const name = slug if (slug === "Entity") return { slug, type: ColumnTypeNames.EntityName, name, } if (slug === "day") return { slug, type: ColumnTypeNames.Day, name: "Day", } if (slug === "year" || slug === "Year") return { slug, type: ColumnTypeNames.Year, name: "Year", } if (slug === OwidTableSlugs.entityName) return OwidEntityNameColumnDef if (slug === OwidTableSlugs.entityCode) return OwidEntityCodeColumnDef if (slug === OwidTableSlugs.entityId) return OwidEntityIdColumnDef if (slug === "date") return { slug, type: ColumnTypeNames.Date, name: "Date", } if (valueType === "number") return { slug, type: ColumnTypeNames.Numeric, name, } if (valueType === "string") { if (sampleValue.match(/^\d+$/)) return { slug, type: ColumnTypeNames.Numeric, name, } } return { slug, type: ColumnTypeNames.String, name } } export const makeRowFromColumnStore = ( rowIndex: number, columnStore: CoreColumnStore ): CoreRow => { const row: CoreRow = {} const columns = Object.values(columnStore) Object.keys(columnStore).forEach((slug, colIndex) => { row[slug] = columns[colIndex][rowIndex] }) return row } function isNotErrorValueOrEmptyCell<K>( value: K ): value is Exclude<K, ErrorValue | undefined> { return value !== undefined && !(value instanceof ErrorValue) } export interface InterpolationContext {} export interface LinearInterpolationContext extends InterpolationContext { // whether to extrapolate a variable at the start or end, where we cannot do linear interpolation // but need to just copy over the first/last value present over to empty fields. // e.g. [Error, Error, 2, 3, 4] would become [2, 2, 2, 3, 4] with extrapolateAtStart=true. extrapolateAtStart?: boolean extrapolateAtEnd?: boolean } export interface ToleranceInterpolationContext extends InterpolationContext { timeTolerance: number } export type InterpolationProvider<C extends InterpolationContext> = ( valuesSortedByTimeAsc: (number | ErrorValue)[], timesAsc: Time[], context: C, start: number, end: number ) => void export function linearInterpolation( valuesSortedByTimeAsc: (number | ErrorValue)[], timesAsc: Time[], context: LinearInterpolationContext, start: number = 0, end: number = valuesSortedByTimeAsc.length ): void { if (!valuesSortedByTimeAsc.length) return let prevNonBlankIndex = -1 let nextNonBlankIndex = -1 for (let index = start; index < end; index++) { const currentValue = valuesSortedByTimeAsc[index] if (isNotErrorValueOrEmptyCell(currentValue)) { prevNonBlankIndex = index continue } if (nextNonBlankIndex === -1 || nextNonBlankIndex <= index) { nextNonBlankIndex = findIndexFast( valuesSortedByTimeAsc, (val) => isNotErrorValueOrEmptyCell(val), index + 1, end ) } const prevValue = valuesSortedByTimeAsc[prevNonBlankIndex] const nextValue = valuesSortedByTimeAsc[nextNonBlankIndex] let value if ( isNotErrorValueOrEmptyCell(prevValue) && isNotErrorValueOrEmptyCell(nextValue) ) { const distLeft = index - prevNonBlankIndex const distRight = nextNonBlankIndex - index value = (prevValue * distRight + nextValue * distLeft) / (distLeft + distRight) } else if ( isNotErrorValueOrEmptyCell(prevValue) && context.extrapolateAtEnd ) value = prevValue else if ( isNotErrorValueOrEmptyCell(nextValue) && context.extrapolateAtStart ) value = nextValue else value = ErrorValueTypes.NoValueForInterpolation prevNonBlankIndex = index valuesSortedByTimeAsc[index] = value } } export function toleranceInterpolation( valuesSortedByTimeAsc: (number | ErrorValue)[], timesAsc: Time[], context: ToleranceInterpolationContext, start: number = 0, end: number = valuesSortedByTimeAsc.length ): void { if (!valuesSortedByTimeAsc.length) return let prevNonBlankIndex: number | undefined = undefined let nextNonBlankIndex: number | undefined = undefined for (let index = start; index < end; index++) { const currentValue = valuesSortedByTimeAsc[index] if (isNotErrorValueOrEmptyCell(currentValue)) { prevNonBlankIndex = index continue } if ( nextNonBlankIndex !== -1 && (nextNonBlankIndex === undefined || nextNonBlankIndex <= index) ) { nextNonBlankIndex = findIndexFast( valuesSortedByTimeAsc, isNotErrorValueOrEmptyCell, index + 1, end ) } const timeOfCurrent = timesAsc[index] const timeOfPrevIndex = prevNonBlankIndex !== undefined ? timesAsc[prevNonBlankIndex] : -Infinity const timeOfNextIndex = nextNonBlankIndex !== undefined && nextNonBlankIndex !== -1 ? timesAsc[nextNonBlankIndex] : Infinity const prevTimeDiff = Math.abs(timeOfPrevIndex - timeOfCurrent) const nextTimeDiff = Math.abs(timeOfNextIndex - timeOfCurrent) if ( nextNonBlankIndex !== -1 && nextTimeDiff <= prevTimeDiff && nextTimeDiff <= context.timeTolerance ) { valuesSortedByTimeAsc[index] = valuesSortedByTimeAsc[nextNonBlankIndex!] timesAsc[index] = timesAsc[nextNonBlankIndex!] } else if ( prevNonBlankIndex !== undefined && prevTimeDiff <= context.timeTolerance ) { valuesSortedByTimeAsc[index] = valuesSortedByTimeAsc[prevNonBlankIndex!] timesAsc[index] = timesAsc[prevNonBlankIndex!] } else valuesSortedByTimeAsc[index] = ErrorValueTypes.NoValueWithinTolerance } } export function interpolateRowValuesWithTolerance< ValueSlug extends ColumnSlug, TimeSlug extends ColumnSlug, Row extends { [key in TimeSlug]?: Time } & { [key in ValueSlug]?: any } >( rowsSortedByTimeAsc: Row[], valueSlug: ValueSlug, timeSlug: TimeSlug, timeTolerance: number ): Row[] { const values = rowsSortedByTimeAsc.map((row) => row[valueSlug]) const times = rowsSortedByTimeAsc.map((row) => row[timeSlug]) toleranceInterpolation(values, times, { timeTolerance }) return rowsSortedByTimeAsc.map((row, index) => { return { ...row, [valueSlug]: values[index], [timeSlug]: times[index], } }) } // A dumb function for making a function that makes a key for a row given certain columns. export const makeKeyFn = (columnStore: CoreColumnStore, columnSlugs: ColumnSlug[]) => (rowIndex: number): string => // toString() handles `undefined` and `null` values, which can be in the table. columnSlugs .map((slug) => toString(columnStore[slug][rowIndex])) .join(" ") // Memoization for immutable getters. Run the function once for this instance and cache the result. export const imemo = <Type>( target: unknown, propertyName: string, descriptor: TypedPropertyDescriptor<Type> ): void => { const originalFn = descriptor.get! descriptor.get = function (this: Record<string, Type>): Type { const propName = `${propertyName}_memoized` if (this[propName] === undefined) { // Define the prop the long way so we don't enumerate over it Object.defineProperty(this, propName, { configurable: false, enumerable: false, writable: false, value: originalFn.apply(this), }) } return this[propName] } } export const appendRowsToColumnStore = ( columnStore: CoreColumnStore, rows: CoreRow[] ): CoreColumnStore => { const slugs = Object.keys(columnStore) const newColumnStore = columnStore slugs.forEach((slug) => { newColumnStore[slug] = columnStore[slug].concat( rows.map((row) => row[slug]) ) }) return newColumnStore } const getColumnStoreLength = (store: CoreColumnStore): number => { for (const slug in store) { return store[slug].length } return 0 } export const concatColumnStores = ( stores: CoreColumnStore[], slugsToKeep?: ColumnSlug[] ): CoreColumnStore => { if (!stores.length) return {} const lengths = stores.map(getColumnStoreLength) const slugs = slugsToKeep ?? Object.keys(first(stores)!) const newColumnStore: CoreColumnStore = {} slugs.forEach((slug) => { newColumnStore[slug] = flatten( stores.map( (store, i) => store[slug] ?? new Array(lengths[i]).fill( ErrorValueTypes.MissingValuePlaceholder ) ) ) }) return newColumnStore } export const rowsToColumnStore = (rows: CoreRow[]): CoreColumnStore => { const columnsObject: CoreColumnStore = {} if (!rows.length) return columnsObject Object.keys(rows[0]).forEach((slug) => { columnsObject[slug] = rows.map((row) => row[slug]) }) return columnsObject } const guessColumnDefsFromRows = ( rows: CoreRow[], definedSlugs: Map<ColumnSlug, any> ): CoreColumnDef[] => { if (!rows[0]) return [] return Object.keys(rows[0]) .filter((slug) => !definedSlugs.has(slug)) .map((slug) => { const firstRowWithValue = rows.find( (row) => row[slug] !== undefined && row[slug] !== null && row[slug] !== "" ) const firstValue = firstRowWithValue ? firstRowWithValue[slug] : undefined return guessColumnDefFromSlugAndRow(slug, firstValue) }) } export const autodetectColumnDefs = ( rowsOrColumnStore: CoreColumnStore | CoreRow[], definedSlugs: Map<ColumnSlug, any> ): CoreColumnDef[] => { if (!Array.isArray(rowsOrColumnStore)) { const columnStore = rowsOrColumnStore as CoreColumnStore return Object.keys(columnStore) .filter((slug) => !definedSlugs.has(slug)) .map((slug) => { return guessColumnDefFromSlugAndRow( slug, columnStore[slug].find( (val) => val !== undefined && val !== null ) ) }) } return guessColumnDefsFromRows(rowsOrColumnStore, definedSlugs) } // Convenience method when you are replacing columns export const replaceDef = <ColumnDef extends CoreColumnDef>( defs: ColumnDef[], newDefs: ColumnDef[] ): ColumnDef[] => defs.map((def) => { const newDef = newDefs.find((newDef) => newDef.slug === def.slug) return newDef ?? def }) export const reverseColumnStore = ( columnStore: CoreColumnStore ): CoreColumnStore => { const newStore: CoreColumnStore = {} Object.keys(columnStore).forEach((slug) => { newStore[slug] = columnStore[slug].slice().reverse() }) return newStore } export const renameColumnStore = ( columnStore: CoreColumnStore, columnRenameMap: { [columnSlug: string]: ColumnSlug } ): CoreColumnStore => { const newStore: CoreColumnStore = {} Object.keys(columnStore).forEach((slug) => { if (columnRenameMap[slug]) newStore[columnRenameMap[slug]] = columnStore[slug] else newStore[slug] = columnStore[slug] }) return newStore } export const replaceCells = ( columnStore: CoreColumnStore, columnSlugs: ColumnSlug[], replaceFn: (val: CoreValueType) => CoreValueType ): CoreColumnStore => { const newStore: CoreColumnStore = { ...columnStore } columnSlugs.forEach((slug) => { newStore[slug] = newStore[slug].map(replaceFn) }) return newStore } // Returns a Set of random indexes to drop in an array, preserving the order of the array export const getDropIndexes = ( arrayLength: number, howMany: number, seed = Date.now() ): Set<number> => new Set(sampleFrom(range(0, arrayLength), howMany, seed)) export const replaceRandomCellsInColumnStore = ( columnStore: CoreColumnStore, howMany = 1, columnSlugs: ColumnSlug[] = [], seed = Date.now(), replacementGenerator: () => any = () => ErrorValueTypes.DroppedForTesting ): CoreColumnStore => { const newStore: CoreColumnStore = Object.assign({}, columnStore) columnSlugs.forEach((slug) => { const values = newStore[slug] const indexesToDrop = getDropIndexes(values.length, howMany, seed) newStore[slug] = values.map((value, index) => indexesToDrop.has(index) ? replacementGenerator() : value ) }) return newStore } export class Timer { constructor() { this._tickTime = Date.now() this._firstTickTime = this._tickTime } private _tickTime: number private _firstTickTime: number tick(msg?: string): number { const elapsed = Date.now() - this._tickTime // eslint-disable-next-line no-console if (msg) console.log(`${elapsed}ms ${msg}`) this._tickTime = Date.now() return elapsed } getTotalElapsedTime(): number { return Date.now() - this._firstTickTime } } export const rowsFromMatrix = (matrix: CoreMatrix): any[] => { const table = trimMatrix(matrix) const header = table[0] return table.slice(1).map((row) => { const newRow: any = {} header.forEach((col, index) => { newRow[col] = row[index] }) return newRow }) } const trimEmptyColumns = (matrix: CoreMatrix): CoreMatrix => matrix.map(trimArray) export const trimMatrix = (matrix: CoreMatrix): CoreMatrix => trimEmptyColumns(trimEmptyRows(matrix)) export const matrixToDelimited = ( table: CoreMatrix, delimiter = "\t" ): string => { return table .map((row: any) => row .map((cell: any) => cell === null || cell === undefined ? "" : cell ) .join(delimiter) ) .join("\n") } export const parseDelimited = ( str: string, delimiter?: string, parseFn?: any ): DSVParsedArray<Record<string, unknown>> => dsvFormat(delimiter ?? detectDelimiter(str)).parse(str, parseFn) export const detectDelimiter = (str: string): "\t" | "," | " " => str.includes("\t") ? "\t" : str.includes(",") ? "," : " " export const rowsToMatrix = (rows: any[]): CoreMatrix | undefined => rows.length ? [Object.keys(rows[0]), ...rows.map((row) => Object.values(row))] : undefined const isRowEmpty = (row: any[]): boolean => row.every(isCellEmpty) export const isCellEmpty = (cell: any): boolean => cell === null || cell === undefined || cell === "" export const trimEmptyRows = (matrix: CoreMatrix): CoreMatrix => { let trimAt = undefined for (let rowIndex = matrix.length - 1; rowIndex >= 0; rowIndex--) { if (!isRowEmpty(matrix[rowIndex])) break trimAt = rowIndex } return trimAt === undefined ? matrix : matrix.slice(0, trimAt) } export const trimArray = (arr: any[]): any[] => { let rightIndex: number for (rightIndex = arr.length - 1; rightIndex >= 0; rightIndex--) { if (!isCellEmpty(arr[rightIndex])) break } return arr.slice(0, rightIndex + 1) } export function cartesianProduct<T>(...allEntries: T[][]): T[][] { return fastCartesian(allEntries) } const applyNewSortOrder = (arr: any[], newOrder: number[]): any[] => newOrder.map((index) => arr[index]) export const sortColumnStore = ( columnStore: CoreColumnStore, slugs: ColumnSlug[] ): CoreColumnStore => { const firstCol = Object.values(columnStore)[0] if (!firstCol) return {} const len = firstCol.length const newOrder = range(0, len).sort(makeSortByFn(columnStore, slugs)) const newStore: CoreColumnStore = {} Object.keys(columnStore).forEach((slug) => { newStore[slug] = applyNewSortOrder(columnStore[slug], newOrder) }) return newStore } const makeSortByFn = ( columnStore: CoreColumnStore, columnSlugs: ColumnSlug[] ): ((indexA: number, indexB: number) => 1 | 0 | -1) => { const numSlugs = columnSlugs.length return (indexA: number, indexB: number): 1 | 0 | -1 => { const nodeAFirst = -1 const nodeBFirst = 1 for (let slugIndex = 0; slugIndex < numSlugs; slugIndex++) { const slug = columnSlugs[slugIndex] const col = columnStore[slug] const av = col[indexA] const bv = col[indexB] if (av < bv) return nodeAFirst if (av > bv) return nodeBFirst // todo: handle ErrorValues } return 0 } } export const emptyColumnsInFirstRowInDelimited = (str: string): string[] => { // todo: don't split a big string here, just do a faster first line scan const shortCsv = parseDelimited(str.split("\n").slice(0, 2).join("\n")) const firstRow: any = shortCsv[0] ?? {} const emptySlugs: string[] = [] Object.keys(firstRow).forEach((slug) => { if (firstRow[slug] === "") emptySlugs.push(slug) }) return emptySlugs }
the_stack
import { Buffer } from "buffer/" import BinTools from "../../utils/bintools" import BN from "bn.js" import { AmountOutput, SelectOutputClass, TransferableOutput, EVMOutput } from "./outputs" import { EVMConstants } from "./constants" import { EVMInput, SECPTransferInput, TransferableInput } from "./inputs" import { Output } from "../../common/output" import { UnixNow } from "../../utils/helperfunctions" import { StandardUTXO, StandardUTXOSet } from "../../common/utxos" import { PlatformChainID } from "../../utils/constants" import { StandardAssetAmountDestination, AssetAmount } from "../../common/assetamount" import { Serialization, SerializedEncoding } from "../../utils/serialization" import { UnsignedTx } from "./tx" import { ImportTx } from "./importtx" import { ExportTx } from "./exporttx" import { UTXOError, AddressError, InsufficientFundsError, FeeAssetError } from "../../utils/errors" /** * @ignore */ const bintools: BinTools = BinTools.getInstance() const serializer: Serialization = Serialization.getInstance() /** * Class for representing a single UTXO. */ export class UTXO extends StandardUTXO { protected _typeName = "UTXO" protected _typeID = undefined //serialize is inherited deserialize(fields: object, encoding: SerializedEncoding = "hex") { super.deserialize(fields, encoding) this.output = SelectOutputClass(fields["output"]["_typeID"]) this.output.deserialize(fields["output"], encoding) } fromBuffer(bytes: Buffer, offset: number = 0): number { this.codecID = bintools.copyFrom(bytes, offset, offset + 2) offset += 2 this.txid = bintools.copyFrom(bytes, offset, offset + 32) offset += 32 this.outputidx = bintools.copyFrom(bytes, offset, offset + 4) offset += 4 this.assetID = bintools.copyFrom(bytes, offset, offset + 32) offset += 32 const outputid: number = bintools .copyFrom(bytes, offset, offset + 4) .readUInt32BE(0) offset += 4 this.output = SelectOutputClass(outputid) return this.output.fromBuffer(bytes, offset) } /** * Takes a base-58 string containing a [[UTXO]], parses it, populates the class, and returns the length of the StandardUTXO in bytes. * * @param serialized A base-58 string containing a raw [[UTXO]] * * @returns The length of the raw [[UTXO]] * * @remarks * unlike most fromStrings, it expects the string to be serialized in cb58 format */ fromString(serialized: string): number { /* istanbul ignore next */ return this.fromBuffer(bintools.cb58Decode(serialized)) } /** * Returns a base-58 representation of the [[UTXO]]. * * @remarks * unlike most toStrings, this returns in cb58 serialization format */ toString(): string { /* istanbul ignore next */ return bintools.cb58Encode(this.toBuffer()) } clone(): this { const utxo: UTXO = new UTXO() utxo.fromBuffer(this.toBuffer()) return utxo as this } create( codecID: number = EVMConstants.LATESTCODEC, txID: Buffer = undefined, outputidx: Buffer | number = undefined, assetID: Buffer = undefined, output: Output = undefined ): this { return new UTXO(codecID, txID, outputidx, assetID, output) as this } } export class AssetAmountDestination extends StandardAssetAmountDestination< TransferableOutput, TransferableInput > {} /** * Class representing a set of [[UTXO]]s. */ export class UTXOSet extends StandardUTXOSet<UTXO> { protected _typeName = "UTXOSet" protected _typeID = undefined //serialize is inherited deserialize(fields: object, encoding: SerializedEncoding = "hex"): void { super.deserialize(fields, encoding) const utxos: {} = {} for (let utxoid in fields["utxos"]) { let utxoidCleaned: string = serializer.decoder( utxoid, encoding, "base58", "base58" ) utxos[`${utxoidCleaned}`] = new UTXO() utxos[`${utxoidCleaned}`].deserialize( fields["utxos"][`${utxoid}`], encoding ) } let addressUTXOs: {} = {} for (let address in fields["addressUTXOs"]) { let addressCleaned: string = serializer.decoder( address, encoding, "cb58", "hex" ) let utxobalance: {} = {} for (let utxoid in fields["addressUTXOs"][`${address}`]) { let utxoidCleaned: string = serializer.decoder( utxoid, encoding, "base58", "base58" ) utxobalance[`${utxoidCleaned}`] = serializer.decoder( fields["addressUTXOs"][`${address}`][`${utxoid}`], encoding, "decimalString", "BN" ) } addressUTXOs[`${addressCleaned}`] = utxobalance } this.utxos = utxos this.addressUTXOs = addressUTXOs } parseUTXO(utxo: UTXO | string): UTXO { const utxovar: UTXO = new UTXO() // force a copy if (typeof utxo === "string") { utxovar.fromBuffer(bintools.cb58Decode(utxo)) } else if (utxo instanceof UTXO) { utxovar.fromBuffer(utxo.toBuffer()) // forces a copy } else { /* istanbul ignore next */ throw new UTXOError( "Error - UTXO.parseUTXO: utxo parameter is not a UTXO or string" ) } return utxovar } create(): this { return new UTXOSet() as this } clone(): this { const newset: UTXOSet = this.create() const allUTXOs: UTXO[] = this.getAllUTXOs() newset.addArray(allUTXOs) return newset as this } _feeCheck(fee: BN, feeAssetID: Buffer): boolean { return ( typeof fee !== "undefined" && typeof feeAssetID !== "undefined" && fee.gt(new BN(0)) && feeAssetID instanceof Buffer ) } getMinimumSpendable = ( aad: AssetAmountDestination, asOf: BN = UnixNow(), locktime: BN = new BN(0), threshold: number = 1 ): Error => { const utxoArray: UTXO[] = this.getAllUTXOs() const outids: object = {} for (let i: number = 0; i < utxoArray.length && !aad.canComplete(); i++) { const u: UTXO = utxoArray[`${i}`] const assetKey: string = u.getAssetID().toString("hex") const fromAddresses: Buffer[] = aad.getSenders() if ( u.getOutput() instanceof AmountOutput && aad.assetExists(assetKey) && u.getOutput().meetsThreshold(fromAddresses, asOf) ) { const am: AssetAmount = aad.getAssetAmount(assetKey) if (!am.isFinished()) { const uout: AmountOutput = u.getOutput() as AmountOutput outids[`${assetKey}`] = uout.getOutputID() const amount = uout.getAmount() am.spendAmount(amount) const txid: Buffer = u.getTxID() const outputidx: Buffer = u.getOutputIdx() const input: SECPTransferInput = new SECPTransferInput(amount) const xferin: TransferableInput = new TransferableInput( txid, outputidx, u.getAssetID(), input ) const spenders: Buffer[] = uout.getSpenders(fromAddresses, asOf) spenders.forEach((spender: Buffer) => { const idx: number = uout.getAddressIdx(spender) if (idx === -1) { /* istanbul ignore next */ throw new AddressError( "Error - UTXOSet.getMinimumSpendable: no such address in output" ) } xferin.getInput().addSignatureIdx(idx, spender) }) aad.addInput(xferin) } else if ( aad.assetExists(assetKey) && !(u.getOutput() instanceof AmountOutput) ) { /** * Leaving the below lines, not simply for posterity, but for clarification. * AssetIDs may have mixed OutputTypes. * Some of those OutputTypes may implement AmountOutput. * Others may not. * Simply continue in this condition. */ /*return new Error('Error - UTXOSet.getMinimumSpendable: outputID does not ' + `implement AmountOutput: ${u.getOutput().getOutputID}`);*/ continue } } } if (!aad.canComplete()) { return new InsufficientFundsError( `Error - UTXOSet.getMinimumSpendable: insufficient funds to create the transaction` ) } const amounts: AssetAmount[] = aad.getAmounts() const zero: BN = new BN(0) for (let i: number = 0; i < amounts.length; i++) { const assetKey: string = amounts[`${i}`].getAssetIDString() const amount: BN = amounts[`${i}`].getAmount() if (amount.gt(zero)) { const spendout: AmountOutput = SelectOutputClass( outids[`${assetKey}`], amount, aad.getDestinations(), locktime, threshold ) as AmountOutput const xferout: TransferableOutput = new TransferableOutput( amounts[`${i}`].getAssetID(), spendout ) aad.addOutput(xferout) } const change: BN = amounts[`${i}`].getChange() if (change.gt(zero)) { const changeout: AmountOutput = SelectOutputClass( outids[`${assetKey}`], change, aad.getChangeAddresses() ) as AmountOutput const chgxferout: TransferableOutput = new TransferableOutput( amounts[`${i}`].getAssetID(), changeout ) aad.addChange(chgxferout) } } return undefined } /** * Creates an unsigned ImportTx transaction. * * @param networkID The number representing NetworkID of the node * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction * @param toAddress The address to send the funds * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} * @param importIns An array of [[TransferableInput]]s being imported * @param sourceChain A {@link https://github.com/feross/buffer|Buffer} for the chainid where the imports are coming from. * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. Fee will come from the inputs first, if they can. * @param feeAssetID Optional. The assetID of the fees being burned. * @param memo Optional contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * @param locktime Optional. The locktime field created in the resulting outputs * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO * @returns An unsigned transaction created from the passed in parameters. * */ buildImportTx = ( networkID: number, blockchainID: Buffer, toAddress: string, fromAddresses: Buffer[], atomics: UTXO[], sourceChain: Buffer = undefined, fee: BN = undefined, feeAssetID: Buffer = undefined ): UnsignedTx => { const zero: BN = new BN(0) let ins: TransferableInput[] = [] const outs: EVMOutput[] = [] if (typeof fee === "undefined") { fee = zero.clone() } let feepaid: BN = new BN(0) const map: Map<string, string> = new Map() atomics.forEach((atomic: UTXO): void => { const assetIDBuf: Buffer = atomic.getAssetID() const assetID: string = bintools.cb58Encode(atomic.getAssetID()) const output: AmountOutput = atomic.getOutput() as AmountOutput const amt: BN = output.getAmount().clone() let infeeamount: BN = amt.clone() if ( typeof feeAssetID !== "undefined" && fee.gt(zero) && feepaid.lt(fee) && Buffer.compare(feeAssetID, assetIDBuf) === 0 ) { feepaid = feepaid.add(infeeamount) if (feepaid.gt(fee)) { infeeamount = feepaid.sub(fee) feepaid = fee.clone() } else { infeeamount = zero.clone() } } const txid: Buffer = atomic.getTxID() const outputidx: Buffer = atomic.getOutputIdx() const input: SECPTransferInput = new SECPTransferInput(amt) const xferin: TransferableInput = new TransferableInput( txid, outputidx, assetIDBuf, input ) const from: Buffer[] = output.getAddresses() const spenders: Buffer[] = output.getSpenders(from) spenders.forEach((spender: Buffer): void => { const idx: number = output.getAddressIdx(spender) if (idx === -1) { /* istanbul ignore next */ throw new AddressError( "Error - UTXOSet.buildImportTx: no such address in output" ) } xferin.getInput().addSignatureIdx(idx, spender) }) ins.push(xferin) // lexicographically sort array ins = ins.sort(TransferableInput.comparator()) if (map.has(assetID)) { infeeamount = infeeamount.add(new BN(map.get(assetID))) } map.set(assetID, infeeamount.toString()) }) for (let [assetID, amount] of map) { // Create single EVMOutput for each assetID const evmOutput: EVMOutput = new EVMOutput( toAddress, new BN(amount), bintools.cb58Decode(assetID) ) outs.push(evmOutput) } const importTx: ImportTx = new ImportTx( networkID, blockchainID, sourceChain, ins, outs ) return new UnsignedTx(importTx) } /** * Creates an unsigned ExportTx transaction. * * @param networkID The number representing NetworkID of the node * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} * @param avaxAssetID {@link https://github.com/feross/buffer|Buffer} of the AssetID for AVAX * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who recieves the AVAX * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who owns the AVAX * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. * @param destinationChain Optional. A {@link https://github.com/feross/buffer|Buffer} for the chainid where to send the asset. * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} * @param feeAssetID Optional. The assetID of the fees being burned. * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * @param locktime Optional. The locktime field created in the resulting outputs * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO * @returns An unsigned transaction created from the passed in parameters. * */ buildExportTx = ( networkID: number, blockchainID: Buffer, amount: BN, avaxAssetID: Buffer, toAddresses: Buffer[], fromAddresses: Buffer[], changeAddresses: Buffer[] = undefined, destinationChain: Buffer = undefined, fee: BN = undefined, feeAssetID: Buffer = undefined, asOf: BN = UnixNow(), locktime: BN = new BN(0), threshold: number = 1 ): UnsignedTx => { let ins: EVMInput[] = [] let exportouts: TransferableOutput[] = [] if (typeof changeAddresses === "undefined") { changeAddresses = toAddresses } const zero: BN = new BN(0) if (amount.eq(zero)) { return undefined } if (typeof feeAssetID === "undefined") { feeAssetID = avaxAssetID } else if (feeAssetID.toString("hex") !== avaxAssetID.toString("hex")) { /* istanbul ignore next */ throw new FeeAssetError( "Error - UTXOSet.buildExportTx: feeAssetID must match avaxAssetID" ) } if (typeof destinationChain === "undefined") { destinationChain = bintools.cb58Decode(PlatformChainID) } const aad: AssetAmountDestination = new AssetAmountDestination( toAddresses, fromAddresses, changeAddresses ) if (avaxAssetID.toString("hex") === feeAssetID.toString("hex")) { aad.addAssetAmount(avaxAssetID, amount, fee) } else { aad.addAssetAmount(avaxAssetID, amount, zero) if (this._feeCheck(fee, feeAssetID)) { aad.addAssetAmount(feeAssetID, zero, fee) } } const success: Error = this.getMinimumSpendable( aad, asOf, locktime, threshold ) if (typeof success === "undefined") { exportouts = aad.getOutputs() } else { throw success } const exportTx: ExportTx = new ExportTx( networkID, blockchainID, destinationChain, ins, exportouts ) return new UnsignedTx(exportTx) } }
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://www.googleapis.com/discovery/v1/apis/plusDomains/v1/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google+ Domains API v1 */ function load(name: "plusdomains", version: "v1"): PromiseLike<void>; function load(name: "plusdomains", version: "v1", callback: () => any): void; const activities: plusdomains.ActivitiesResource; const audiences: plusdomains.AudiencesResource; const circles: plusdomains.CirclesResource; const comments: plusdomains.CommentsResource; const media: plusdomains.MediaResource; const people: plusdomains.PeopleResource; namespace plusdomains { interface Acl { /** Description of the access granted, suitable for display. */ description?: string; /** Whether access is restricted to the domain. */ domainRestricted?: boolean; /** The list of access entries. */ items?: PlusDomainsAclentryResource[]; /** Identifies this resource as a collection of access controls. Value: "plus#acl". */ kind?: string; } interface Activity { /** Identifies who has access to see this activity. */ access?: Acl; /** The person who performed this activity. */ actor?: { /** Actor info specific to particular clients. */ clientSpecificActorInfo?: { /** Actor info specific to YouTube clients. */ youtubeActorInfo?: { /** ID of the YouTube channel owned by the Actor. */ channelId?: string; }; }; /** The name of the actor, suitable for display. */ displayName?: string; /** The ID of the actor's Person resource. */ id?: string; /** The image representation of the actor. */ image?: { /** * The URL of the actor's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels of * each side. */ url?: string; }; /** An object representation of the individual components of name. */ name?: { /** The family name ("last name") of the actor. */ familyName?: string; /** The given name ("first name") of the actor. */ givenName?: string; }; /** The link to the actor's Google profile. */ url?: string; /** Verification status of actor. */ verification?: { /** Verification for one-time or manual processes. */ adHocVerified?: string; }; }; /** Street address where this activity occurred. */ address?: string; /** Additional content added by the person who shared this activity, applicable only when resharing an activity. */ annotation?: string; /** If this activity is a crosspost from another system, this property specifies the ID of the original activity. */ crosspostSource?: string; /** ETag of this response for caching purposes. */ etag?: string; /** Latitude and longitude where this activity occurred. Format is latitude followed by longitude, space separated. */ geocode?: string; /** The ID of this activity. */ id?: string; /** Identifies this resource as an activity. Value: "plus#activity". */ kind?: string; /** The location where this activity occurred. */ location?: Place; /** The object of this activity. */ object?: { /** * If this activity's object is itself another activity, such as when a person reshares an activity, this property specifies the original activity's * actor. */ actor?: { /** Actor info specific to particular clients. */ clientSpecificActorInfo?: { /** Actor info specific to YouTube clients. */ youtubeActorInfo?: { /** ID of the YouTube channel owned by the Actor. */ channelId?: string; }; }; /** The original actor's name, which is suitable for display. */ displayName?: string; /** ID of the original actor. */ id?: string; /** The image representation of the original actor. */ image?: { /** A URL that points to a thumbnail photo of the original actor. */ url?: string; }; /** A link to the original actor's Google profile. */ url?: string; /** Verification status of actor. */ verification?: { /** Verification for one-time or manual processes. */ adHocVerified?: string; }; }; /** The media objects attached to this activity. */ attachments?: Array<{ /** If the attachment is an article, this property contains a snippet of text from the article. It can also include descriptions for other types. */ content?: string; /** The title of the attachment, such as a photo caption or an article title. */ displayName?: string; /** If the attachment is a video, the embeddable link. */ embed?: { /** Media type of the link. */ type?: string; /** URL of the link. */ url?: string; }; /** The full image URL for photo attachments. */ fullImage?: { /** The height, in pixels, of the linked resource. */ height?: number; /** Media type of the link. */ type?: string; /** URL of the image. */ url?: string; /** The width, in pixels, of the linked resource. */ width?: number; }; /** The ID of the attachment. */ id?: string; /** The preview image for photos or videos. */ image?: { /** The height, in pixels, of the linked resource. */ height?: number; /** Media type of the link. */ type?: string; /** Image URL. */ url?: string; /** The width, in pixels, of the linked resource. */ width?: number; }; /** * The type of media object. Possible values include, but are not limited to, the following values: * - "photo" - A photo. * - "album" - A photo album. * - "video" - A video. * - "article" - An article, specified by a link. */ objectType?: string; /** * When previewing, these are the optional thumbnails for the post. When posting an article, choose one by setting the attachment.image.url property. If * you don't choose one, one will be chosen for you. */ previewThumbnails?: Array<{ /** URL of the thumbnail image. */ url?: string; }>; /** If the attachment is an album, this property is a list of potential additional thumbnails from the album. */ thumbnails?: Array<{ /** Potential name of the thumbnail. */ description?: string; /** Image resource. */ image?: { /** The height, in pixels, of the linked resource. */ height?: number; /** Media type of the link. */ type?: string; /** Image url. */ url?: string; /** The width, in pixels, of the linked resource. */ width?: number; }; /** URL of the webpage containing the image. */ url?: string; }>; /** The link to the attachment, which should be of type text/html. */ url?: string; }>; /** The HTML-formatted content, which is suitable for display. */ content?: string; /** The ID of the object. When resharing an activity, this is the ID of the activity that is being reshared. */ id?: string; /** * The type of the object. Possible values include, but are not limited to, the following values: * - "note" - Textual content. * - "activity" - A Google+ activity. */ objectType?: string; /** * The content (text) as provided by the author, which is stored without any HTML formatting. When creating or updating an activity, this value must be * supplied as plain text in the request. */ originalContent?: string; /** People who +1'd this activity. */ plusoners?: { /** The URL for the collection of people who +1'd this activity. */ selfLink?: string; /** Total number of people who +1'd this activity. */ totalItems?: number; }; /** Comments in reply to this activity. */ replies?: { /** The URL for the collection of comments in reply to this activity. */ selfLink?: string; /** Total number of comments on this activity. */ totalItems?: number; }; /** People who reshared this activity. */ resharers?: { /** The URL for the collection of resharers. */ selfLink?: string; /** Total number of people who reshared this activity. */ totalItems?: number; }; /** Status of the activity as seen by the viewer. */ statusForViewer?: { /** Whether the viewer can comment on the activity. */ canComment?: boolean; /** Whether the viewer can +1 the activity. */ canPlusone?: boolean; /** Whether the viewer can edit or delete the activity. */ canUpdate?: boolean; /** Whether the viewer has +1'd the activity. */ isPlusOned?: boolean; /** Whether reshares are disabled for the activity. */ resharingDisabled?: boolean; }; /** The URL that points to the linked resource. */ url?: string; }; /** ID of the place where this activity occurred. */ placeId?: string; /** Name of the place where this activity occurred. */ placeName?: string; /** The service provider that initially published this activity. */ provider?: { /** Name of the service provider. */ title?: string; }; /** The time at which this activity was initially published. Formatted as an RFC 3339 timestamp. */ published?: string; /** Radius, in meters, of the region where this activity occurred, centered at the latitude and longitude identified in geocode. */ radius?: string; /** Title of this activity. */ title?: string; /** The time at which this activity was last updated. Formatted as an RFC 3339 timestamp. */ updated?: string; /** The link to this activity. */ url?: string; /** * This activity's verb, which indicates the action that was performed. Possible values include, but are not limited to, the following values: * - "post" - Publish content to the stream. * - "share" - Reshare an activity. */ verb?: string; } interface ActivityFeed { /** ETag of this response for caching purposes. */ etag?: string; /** The ID of this collection of activities. Deprecated. */ id?: string; /** The activities in this page of results. */ items?: Activity[]; /** Identifies this resource as a collection of activities. Value: "plus#activityFeed". */ kind?: string; /** Link to the next page of activities. */ nextLink?: string; /** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */ nextPageToken?: string; /** Link to this activity resource. */ selfLink?: string; /** The title of this collection of activities, which is a truncated portion of the content. */ title?: string; /** The time at which this collection of activities was last updated. Formatted as an RFC 3339 timestamp. */ updated?: string; } interface Audience { /** ETag of this response for caching purposes. */ etag?: string; /** The access control list entry. */ item?: PlusDomainsAclentryResource; /** Identifies this resource as an audience. Value: "plus#audience". */ kind?: string; /** The number of people in this circle. This only applies if entity_type is CIRCLE. */ memberCount?: number; /** * The circle members' visibility as chosen by the owner of the circle. This only applies for items with "item.type" equals "circle". Possible values are: * * - "public" - Members are visible to the public. * - "limited" - Members are visible to a limited audience. * - "private" - Members are visible to the owner only. */ visibility?: string; } interface AudiencesFeed { /** ETag of this response for caching purposes. */ etag?: string; /** The audiences in this result. */ items?: Audience[]; /** Identifies this resource as a collection of audiences. Value: "plus#audienceFeed". */ kind?: string; /** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */ nextPageToken?: string; /** The total number of ACL entries. The number of entries in this response may be smaller due to paging. */ totalItems?: number; } interface Circle { /** The description of this circle. */ description?: string; /** The circle name. */ displayName?: string; /** ETag of this response for caching purposes. */ etag?: string; /** The ID of the circle. */ id?: string; /** Identifies this resource as a circle. Value: "plus#circle". */ kind?: string; /** The people in this circle. */ people?: { /** The total number of people in this circle. */ totalItems?: number; }; /** Link to this circle resource */ selfLink?: string; } interface CircleFeed { /** ETag of this response for caching purposes. */ etag?: string; /** The circles in this page of results. */ items?: Circle[]; /** Identifies this resource as a collection of circles. Value: "plus#circleFeed". */ kind?: string; /** Link to the next page of circles. */ nextLink?: string; /** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */ nextPageToken?: string; /** Link to this page of circles. */ selfLink?: string; /** The title of this list of resources. */ title?: string; /** The total number of circles. The number of circles in this response may be smaller due to paging. */ totalItems?: number; } interface Comment { /** The person who posted this comment. */ actor?: { /** Actor info specific to particular clients. */ clientSpecificActorInfo?: { /** Actor info specific to YouTube clients. */ youtubeActorInfo?: { /** ID of the YouTube channel owned by the Actor. */ channelId?: string; }; }; /** The name of this actor, suitable for display. */ displayName?: string; /** The ID of the actor. */ id?: string; /** The image representation of this actor. */ image?: { /** * The URL of the actor's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels of * each side. */ url?: string; }; /** A link to the Person resource for this actor. */ url?: string; /** Verification status of actor. */ verification?: { /** Verification for one-time or manual processes. */ adHocVerified?: string; }; }; /** ETag of this response for caching purposes. */ etag?: string; /** The ID of this comment. */ id?: string; /** The activity this comment replied to. */ inReplyTo?: Array<{ /** The ID of the activity. */ id?: string; /** The URL of the activity. */ url?: string; }>; /** Identifies this resource as a comment. Value: "plus#comment". */ kind?: string; /** The object of this comment. */ object?: { /** The HTML-formatted content, suitable for display. */ content?: string; /** * The object type of this comment. Possible values are: * - "comment" - A comment in reply to an activity. */ objectType?: string; /** * The content (text) as provided by the author, stored without any HTML formatting. When creating or updating a comment, this value must be supplied as * plain text in the request. */ originalContent?: string; }; /** People who +1'd this comment. */ plusoners?: { /** Total number of people who +1'd this comment. */ totalItems?: number; }; /** The time at which this comment was initially published. Formatted as an RFC 3339 timestamp. */ published?: string; /** Link to this comment resource. */ selfLink?: string; /** The time at which this comment was last updated. Formatted as an RFC 3339 timestamp. */ updated?: string; /** * This comment's verb, indicating what action was performed. Possible values are: * - "post" - Publish content to the stream. */ verb?: string; } interface CommentFeed { /** ETag of this response for caching purposes. */ etag?: string; /** The ID of this collection of comments. */ id?: string; /** The comments in this page of results. */ items?: Comment[]; /** Identifies this resource as a collection of comments. Value: "plus#commentFeed". */ kind?: string; /** Link to the next page of activities. */ nextLink?: string; /** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */ nextPageToken?: string; /** The title of this collection of comments. */ title?: string; /** The time at which this collection of comments was last updated. Formatted as an RFC 3339 timestamp. */ updated?: string; } interface Media { /** The person who uploaded this media. */ author?: { /** The author's name. */ displayName?: string; /** ID of the author. */ id?: string; /** The author's Google profile image. */ image?: { /** * The URL of the author's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels * of each side. */ url?: string; }; /** A link to the author's Google profile. */ url?: string; }; /** The display name for this media. */ displayName?: string; /** ETag of this response for caching purposes. */ etag?: string; /** Exif information of the media item. */ exif?: { /** The time the media was captured. Formatted as an RFC 3339 timestamp. */ time?: string; }; /** The height in pixels of the original image. */ height?: number; /** ID of this media, which is generated by the API. */ id?: string; /** The type of resource. */ kind?: string; /** The time at which this media was originally created in UTC. Formatted as an RFC 3339 timestamp that matches this example: 2010-11-25T14:30:27.655Z */ mediaCreatedTime?: string; /** The URL of this photo or video's still image. */ mediaUrl?: string; /** The time at which this media was uploaded. Formatted as an RFC 3339 timestamp. */ published?: string; /** The size in bytes of this video. */ sizeBytes?: string; /** The list of video streams for this video. There might be several different streams available for a single video, either Flash or MPEG, of various sizes */ streams?: Videostream[]; /** A description, or caption, for this media. */ summary?: string; /** The time at which this media was last updated. This includes changes to media metadata. Formatted as an RFC 3339 timestamp. */ updated?: string; /** The URL for the page that hosts this media. */ url?: string; /** The duration in milliseconds of this video. */ videoDuration?: string; /** * The encoding status of this video. Possible values are: * - "UPLOADING" - Not all the video bytes have been received. * - "PENDING" - Video not yet processed. * - "FAILED" - Video processing failed. * - "READY" - A single video stream is playable. * - "FINAL" - All video streams are playable. */ videoStatus?: string; /** The width in pixels of the original image. */ width?: number; } interface PeopleFeed { /** ETag of this response for caching purposes. */ etag?: string; /** * The people in this page of results. Each item includes the id, displayName, image, and url for the person. To retrieve additional profile data, see the * people.get method. */ items?: Person[]; /** Identifies this resource as a collection of people. Value: "plus#peopleFeed". */ kind?: string; /** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */ nextPageToken?: string; /** Link to this resource. */ selfLink?: string; /** The title of this collection of people. */ title?: string; /** * The total number of people available in this list. The number of people in a response might be smaller due to paging. This might not be set for all * collections. */ totalItems?: number; } interface Person { /** A short biography for this person. */ aboutMe?: string; /** The person's date of birth, represented as YYYY-MM-DD. */ birthday?: string; /** The "bragging rights" line of this person. */ braggingRights?: string; /** For followers who are visible, the number of people who have added this person or page to a circle. */ circledByCount?: number; /** The cover photo content. */ cover?: { /** Extra information about the cover photo. */ coverInfo?: { /** The difference between the left position of the cover image and the actual displayed cover image. Only valid for banner layout. */ leftImageOffset?: number; /** The difference between the top position of the cover image and the actual displayed cover image. Only valid for banner layout. */ topImageOffset?: number; }; /** The person's primary cover image. */ coverPhoto?: { /** The height of the image. */ height?: number; /** The URL of the image. */ url?: string; /** The width of the image. */ width?: number; }; /** * The layout of the cover art. Possible values include, but are not limited to, the following values: * - "banner" - One large image banner. */ layout?: string; }; /** (this field is not currently used) */ currentLocation?: string; /** The name of this person, which is suitable for display. */ displayName?: string; /** * The hosted domain name for the user's Google Apps account. For instance, example.com. The plus.profile.emails.read or email scope is needed to get this * domain name. */ domain?: string; /** * A list of email addresses that this person has, including their Google account email address, and the public verified email addresses on their Google+ * profile. The plus.profile.emails.read scope is needed to retrieve these email addresses, or the email scope can be used to retrieve just the Google * account email address. */ emails?: Array<{ /** * The type of address. Possible values include, but are not limited to, the following values: * - "account" - Google account email address. * - "home" - Home email address. * - "work" - Work email address. * - "other" - Other. */ type?: string; /** The email address. */ value?: string; }>; /** ETag of this response for caching purposes. */ etag?: string; /** * The person's gender. Possible values include, but are not limited to, the following values: * - "male" - Male gender. * - "female" - Female gender. * - "other" - Other. */ gender?: string; /** The ID of this person. */ id?: string; /** The representation of the person's profile photo. */ image?: { /** Whether the person's profile photo is the default one */ isDefault?: boolean; /** * The URL of the person's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels * of each side. */ url?: string; }; /** Whether this user has signed up for Google+. */ isPlusUser?: boolean; /** Identifies this resource as a person. Value: "plus#person". */ kind?: string; /** An object representation of the individual components of a person's name. */ name?: { /** The family name (last name) of this person. */ familyName?: string; /** The full name of this person, including middle names, suffixes, etc. */ formatted?: string; /** The given name (first name) of this person. */ givenName?: string; /** The honorific prefixes (such as "Dr." or "Mrs.") for this person. */ honorificPrefix?: string; /** The honorific suffixes (such as "Jr.") for this person. */ honorificSuffix?: string; /** The middle name of this person. */ middleName?: string; }; /** The nickname of this person. */ nickname?: string; /** * Type of person within Google+. Possible values include, but are not limited to, the following values: * - "person" - represents an actual person. * - "page" - represents a page. */ objectType?: string; /** The occupation of this person. */ occupation?: string; /** A list of current or past organizations with which this person is associated. */ organizations?: Array<{ /** The department within the organization. Deprecated. */ department?: string; /** A short description of the person's role in this organization. Deprecated. */ description?: string; /** The date that the person left this organization. */ endDate?: string; /** The location of this organization. Deprecated. */ location?: string; /** The name of the organization. */ name?: string; /** If "true", indicates this organization is the person's primary one, which is typically interpreted as the current one. */ primary?: boolean; /** The date that the person joined this organization. */ startDate?: string; /** The person's job title or role within the organization. */ title?: string; /** * The type of organization. Possible values include, but are not limited to, the following values: * - "work" - Work. * - "school" - School. */ type?: string; }>; /** A list of places where this person has lived. */ placesLived?: Array<{ /** If "true", this place of residence is this person's primary residence. */ primary?: boolean; /** A place where this person has lived. For example: "Seattle, WA", "Near Toronto". */ value?: string; }>; /** If a Google+ Page, the number of people who have +1'd this page. */ plusOneCount?: number; /** * The person's relationship status. Possible values include, but are not limited to, the following values: * - "single" - Person is single. * - "in_a_relationship" - Person is in a relationship. * - "engaged" - Person is engaged. * - "married" - Person is married. * - "its_complicated" - The relationship is complicated. * - "open_relationship" - Person is in an open relationship. * - "widowed" - Person is widowed. * - "in_domestic_partnership" - Person is in a domestic partnership. * - "in_civil_union" - Person is in a civil union. */ relationshipStatus?: string; /** The person's skills. */ skills?: string; /** The brief description (tagline) of this person. */ tagline?: string; /** The URL of this person's profile. */ url?: string; /** A list of URLs for this person. */ urls?: Array<{ /** The label of the URL. */ label?: string; /** * The type of URL. Possible values include, but are not limited to, the following values: * - "otherProfile" - URL for another profile. * - "contributor" - URL to a site for which this person is a contributor. * - "website" - URL for this Google+ Page's primary website. * - "other" - Other URL. */ type?: string; /** The URL value. */ value?: string; }>; /** Whether the person or Google+ Page has been verified. */ verified?: boolean; } interface Place { /** The physical address of the place. */ address?: { /** The formatted address for display. */ formatted?: string; }; /** The display name of the place. */ displayName?: string; /** The id of the place. */ id?: string; /** Identifies this resource as a place. Value: "plus#place". */ kind?: string; /** The position of the place. */ position?: { /** The latitude of this position. */ latitude?: number; /** The longitude of this position. */ longitude?: number; }; } interface PlusDomainsAclentryResource { /** A descriptive name for this entry. Suitable for display. */ displayName?: string; /** The ID of the entry. For entries of type "person" or "circle", this is the ID of the resource. For other types, this property is not set. */ id?: string; /** * The type of entry describing to whom access is granted. Possible values are: * - "person" - Access to an individual. * - "circle" - Access to members of a circle. * - "myCircles" - Access to members of all the person's circles. * - "extendedCircles" - Access to members of all the person's circles, plus all of the people in their circles. * - "domain" - Access to members of the person's Google Apps domain. * - "public" - Access to anyone on the web. */ type?: string; } interface Videostream { /** The height, in pixels, of the video resource. */ height?: number; /** MIME type of the video stream. */ type?: string; /** URL of the video stream. */ url?: string; /** The width, in pixels, of the video resource. */ width?: number; } interface ActivitiesResource { /** Get an activity. */ get(request: { /** The ID of the activity to get. */ activityId: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Activity>; /** Create a new activity for the authenticated user. */ insert(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * If "true", extract the potential media attachments for a URL. The response will include all possible attachments for a URL, including video, photos, * and articles based on the content of the page. */ preview?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the user to create the activity on behalf of. Its value should be "me", to indicate the authenticated user. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Activity>; /** List all of the activities in the specified collection for a particular user. */ list(request: { /** Data format for the response. */ alt?: string; /** The collection of activities to list. */ collection: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of activities to include in the response, which is used for paging. For any response, the actual number returned might be less than * the specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the user to get activities for. The special value "me" can be used to indicate the authenticated user. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<ActivityFeed>; } interface AudiencesResource { /** List all of the audiences to which a user can share. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of circles to include in the response, which is used for paging. For any response, the actual number returned might be less than the * specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the user to get audiences for. The special value "me" can be used to indicate the authenticated user. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AudiencesFeed>; } interface CirclesResource { /** Add a person to a circle. Google+ limits certain circle operations, including the number of circle adds. Learn More. */ addPeople(request: { /** Data format for the response. */ alt?: string; /** The ID of the circle to add the person to. */ circleId: string; /** Email of the people to add to the circle. Optional, can be repeated. */ email?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IDs of the people to add to the circle. Optional, can be repeated. */ userId?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Circle>; /** Get a circle. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the circle to get. */ circleId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Circle>; /** Create a new circle for the authenticated user. */ insert(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the user to create the circle on behalf of. The value "me" can be used to indicate the authenticated user. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Circle>; /** List all of the circles for a user. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of circles to include in the response, which is used for paging. For any response, the actual number returned might be less than the * specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the user to get circles for. The special value "me" can be used to indicate the authenticated user. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CircleFeed>; /** Update a circle's description. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** The ID of the circle to update. */ circleId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Circle>; /** Delete a circle. */ remove(request: { /** Data format for the response. */ alt?: string; /** The ID of the circle to delete. */ circleId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Remove a person from a circle. */ removePeople(request: { /** Data format for the response. */ alt?: string; /** The ID of the circle to remove the person from. */ circleId: string; /** Email of the people to add to the circle. Optional, can be repeated. */ email?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IDs of the people to remove from the circle. Optional, can be repeated. */ userId?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Update a circle's description. */ update(request: { /** Data format for the response. */ alt?: string; /** The ID of the circle to update. */ circleId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Circle>; } interface CommentsResource { /** Get a comment. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the comment to get. */ commentId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; /** Create a new comment in reply to an activity. */ insert(request: { /** The ID of the activity to reply to. */ activityId: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; /** List all of the comments for an activity. */ list(request: { /** The ID of the activity to get comments for. */ activityId: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of comments to include in the response, which is used for paging. For any response, the actual number returned might be less than * the specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The order in which to sort the list of comments. */ sortOrder?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CommentFeed>; } interface MediaResource { /** * Add a new media item to an album. The current upload size limitations are 36MB for a photo and 1GB for a video. Uploads do not count against quota if * photos are less than 2048 pixels on their longest side or videos are less than 15 minutes in length. */ insert(request: { /** Data format for the response. */ alt?: string; collection: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the user to create the activity on behalf of. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Media>; } interface PeopleResource { /** Get a person's profile. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the person to get the profile for. The special value "me" can be used to indicate the authenticated user. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Person>; /** List all of the people in the specified collection. */ list(request: { /** Data format for the response. */ alt?: string; /** The collection of people to list. */ collection: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the * specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The order to return people in. */ orderBy?: string; /** * The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Get the collection of people for the person identified. Use "me" to indicate the authenticated user. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PeopleFeed>; /** List all of the people in the specified collection for a particular activity. */ listByActivity(request: { /** The ID of the activity to get the list of people for. */ activityId: string; /** Data format for the response. */ alt?: string; /** The collection of people to list. */ collection: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the * specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PeopleFeed>; /** List all of the people who are members of a circle. */ listByCircle(request: { /** Data format for the response. */ alt?: string; /** The ID of the circle to get the members of. */ circleId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the * specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PeopleFeed>; } } }
the_stack
import { encoder, WorkspaceFile } from "../WorkspacesContext"; import JSZip from "jszip"; import { WorkspaceDescriptor } from "../model/WorkspaceDescriptor"; import { StorageFile, StorageService } from "./StorageService"; import { WorkspaceEvents } from "../hooks/WorkspaceHooks"; import { WorkspacesEvents } from "../hooks/WorkspacesHooks"; import { WorkspaceFileEvents } from "../hooks/WorkspaceFileHooks"; import { extname, join, relative } from "path"; import { Minimatch } from "minimatch"; import LightningFS from "@isomorphic-git/lightning-fs"; import { WorkspaceDescriptorService } from "./WorkspaceDescriptorService"; import { WorkspaceFsService } from "./WorkspaceFsService"; import { WorkspaceOrigin } from "../model/WorkspaceOrigin"; export class WorkspaceService { public constructor( public readonly storageService: StorageService, private readonly workspaceDescriptorService: WorkspaceDescriptorService, private readonly fsService: WorkspaceFsService ) {} public async create(args: { useInMemoryFs: boolean; storeFiles: (fs: LightningFS, workspace: WorkspaceDescriptor) => Promise<WorkspaceFile[]>; broadcastArgs: { broadcast: boolean }; origin: WorkspaceOrigin; preferredName?: string; }) { const workspace = await this.workspaceDescriptorService.create({ origin: args.origin, preferredName: args.preferredName, }); try { const files = await (args.useInMemoryFs ? this.fsService.withInMemoryFs(workspace.workspaceId, (fs) => args.storeFiles(fs, workspace)) : args.storeFiles(await this.fsService.getWorkspaceFs(workspace.workspaceId), workspace)); if (args.broadcastArgs.broadcast) { const broadcastChannel1 = new BroadcastChannel("workspaces"); const broadcastChannel2 = new BroadcastChannel(workspace.workspaceId); broadcastChannel1.postMessage({ type: "ADD_WORKSPACE", workspaceId: workspace.workspaceId, } as WorkspacesEvents); broadcastChannel2.postMessage({ type: "ADD", workspaceId: workspace.workspaceId } as WorkspaceEvents); } return { workspace, files }; } catch (e) { await this.workspaceDescriptorService.delete(workspace.workspaceId); throw e; } } public async getFilesWithLazyContent( fs: LightningFS, workspaceId: string, globPattern?: string ): Promise<WorkspaceFile[]> { const matcher = globPattern ? new Minimatch(globPattern, { dot: true }) : undefined; const gitDirPath = this.getAbsolutePath({ workspaceId, relativePath: ".git" }); return await this.storageService.walk({ fs, startFromDirPath: this.getAbsolutePath({ workspaceId }), shouldExcludeDir: (dirPath) => dirPath === gitDirPath, onVisit: async ({ absolutePath, relativePath }) => { const workspaceFile = new WorkspaceFile({ workspaceId, relativePath, getFileContents: () => this.storageService.getFile(fs, absolutePath).then((f) => f!.getFileContents()), }); if (matcher && !matcher.match(workspaceFile.name)) { return undefined; } return workspaceFile; }, }); } public async delete(workspaceId: string, broadcastArgs: { broadcast: boolean }): Promise<void> { await this.workspaceDescriptorService.delete(workspaceId); indexedDB.deleteDatabase(workspaceId); if (broadcastArgs.broadcast) { const broadcastChannel1 = new BroadcastChannel("workspaces"); const broadcastChannel2 = new BroadcastChannel(workspaceId); broadcastChannel1.postMessage({ type: "DELETE_WORKSPACE", workspaceId } as WorkspacesEvents); broadcastChannel2.postMessage({ type: "DELETE", workspaceId } as WorkspaceEvents); } } public async rename(workspaceId: string, newName: string, broadcastArgs: { broadcast: boolean }): Promise<void> { await this.workspaceDescriptorService.rename(workspaceId, newName); if (broadcastArgs.broadcast) { await this.workspaceDescriptorService.bumpLastUpdatedDate(workspaceId); const broadcastChannel1 = new BroadcastChannel("workspaces"); const broadcastChannel2 = new BroadcastChannel(workspaceId); broadcastChannel1.postMessage({ type: "RENAME_WORKSPACE", workspaceId } as WorkspacesEvents); broadcastChannel2.postMessage({ type: "RENAME", workspaceId } as WorkspaceEvents); } } public async prepareZip(fs: LightningFS, workspaceId: string, onlyExtensions?: string[]): Promise<Blob> { const workspaceRootDirPath = this.getAbsolutePath({ workspaceId }); const gitDirPath = this.getAbsolutePath({ workspaceId, relativePath: ".git" }); const paths = await this.storageService.walk({ fs, startFromDirPath: workspaceRootDirPath, shouldExcludeDir: (dirPath) => dirPath === gitDirPath, onVisit: async ({ absolutePath }) => absolutePath, }); const files = (await this.storageService.getFiles(fs, paths)).filter( (f) => !onlyExtensions || onlyExtensions.includes(extname(f.path).slice(1)) ); const zip = new JSZip(); for (const file of files) { zip.file(relative(workspaceRootDirPath, file.path), file.content); } return await zip.generateAsync({ type: "blob" }); } public async createOrOverwriteFile( fs: LightningFS, file: WorkspaceFile, broadcastArgs: { broadcast: boolean } ): Promise<void> { await this.storageService.createOrOverwriteFile(fs, this.toStorageFile(file)); if (broadcastArgs.broadcast) { await this.workspaceDescriptorService.bumpLastUpdatedDate(file.workspaceId); const broadcastChannel1 = new BroadcastChannel(this.getUniqueFileIdentifier(file)); const broadcastChannel2 = new BroadcastChannel(file.workspaceId); broadcastChannel1.postMessage({ type: "ADD", relativePath: file.relativePath, } as WorkspaceFileEvents); broadcastChannel2.postMessage({ type: "ADD_FILE", relativePath: file.relativePath, } as WorkspaceEvents); } } public async getFile(args: { fs: LightningFS; workspaceId: string; relativePath: string; }): Promise<WorkspaceFile | undefined> { const absolutePath = this.getAbsolutePath(args); const storageFile = await this.storageService.getFile(args.fs, absolutePath); if (!storageFile) { return; } return this.toWorkspaceFile(args.workspaceId, storageFile); } public async updateFile( fs: LightningFS, file: WorkspaceFile, getNewContents: () => Promise<string>, broadcastArgs: { broadcast: boolean } ): Promise<void> { await this.storageService.updateFile( fs, this.toStorageFile( new WorkspaceFile({ relativePath: file.relativePath, workspaceId: file.workspaceId, getFileContents: () => getNewContents().then((c) => encoder.encode(c)), }) ) ); if (broadcastArgs.broadcast) { await this.workspaceDescriptorService.bumpLastUpdatedDate(file.workspaceId); const broadcastChannel1 = new BroadcastChannel(this.getUniqueFileIdentifier(file)); const broadcastChannel2 = new BroadcastChannel(file.workspaceId); broadcastChannel1.postMessage({ type: "UPDATE", relativePath: file.relativePath, } as WorkspaceFileEvents); broadcastChannel2.postMessage({ type: "UPDATE_FILE", relativePath: file.relativePath, } as WorkspaceEvents); } } public async deleteFile(fs: LightningFS, file: WorkspaceFile, broadcastArgs: { broadcast: boolean }): Promise<void> { await this.storageService.deleteFile(fs, this.toStorageFile(file).path); if (broadcastArgs.broadcast) { await this.workspaceDescriptorService.bumpLastUpdatedDate(file.workspaceId); const broadcastChannel1 = new BroadcastChannel(this.getUniqueFileIdentifier(file)); const broadcastChannel2 = new BroadcastChannel(file.workspaceId); broadcastChannel1.postMessage({ type: "DELETE", relativePath: file.relativePath, } as WorkspaceFileEvents); broadcastChannel2.postMessage({ type: "DELETE_FILE", relativePath: file.relativePath, } as WorkspaceEvents); } } public async renameFile(args: { fs: LightningFS; file: WorkspaceFile; newFileNameWithoutExtension: string; broadcastArgs: { broadcast: boolean }; }): Promise<WorkspaceFile> { const renamedStorageFile = await this.storageService.renameFile( args.fs, this.toStorageFile(args.file), args.newFileNameWithoutExtension ); const renamedWorkspaceFile = this.toWorkspaceFile(args.file.workspaceId, renamedStorageFile); if (args.broadcastArgs.broadcast) { await this.workspaceDescriptorService.bumpLastUpdatedDate(args.file.workspaceId); const broadcastChannel1 = new BroadcastChannel(this.getUniqueFileIdentifier(args.file)); const broadcastChannel2 = new BroadcastChannel(this.getUniqueFileIdentifier(renamedWorkspaceFile)); const broadcastChannel3 = new BroadcastChannel(args.file.workspaceId); broadcastChannel1.postMessage({ type: "RENAME", oldRelativePath: args.file.relativePath, newRelativePath: renamedWorkspaceFile.relativePath, } as WorkspaceFileEvents); broadcastChannel2.postMessage({ type: "ADD", relativePath: renamedWorkspaceFile.relativePath, } as WorkspaceFileEvents); broadcastChannel3.postMessage({ type: "RENAME_FILE", oldRelativePath: args.file.relativePath, newRelativePath: renamedWorkspaceFile.relativePath, } as WorkspaceEvents); } return renamedWorkspaceFile; } public async existsFile(args: { fs: LightningFS; workspaceId: string; relativePath: string }): Promise<boolean> { return this.storageService.exists(args.fs, this.getAbsolutePath(args)); } public getAbsolutePath(args: { workspaceId: string; relativePath?: string }) { return join("/", args.relativePath ?? ""); } public async deleteFiles( fs: LightningFS, files: WorkspaceFile[], broadcastArgs: { broadcast: boolean } ): Promise<void> { if (files.length === 0) { return; } await Promise.all(files.map((f) => this.toStorageFile(f)).map((f) => this.storageService.deleteFile(fs, f.path))); if (broadcastArgs.broadcast) { await this.workspaceDescriptorService.bumpLastUpdatedDate(files[0].workspaceId); const relativePaths = files.map((file) => file.relativePath); const broadcastChannel = new BroadcastChannel(files[0].workspaceId); broadcastChannel.postMessage({ type: "DELETE_BATCH", workspaceId: files[0].workspaceId, relativePaths, } as WorkspaceEvents); } } public async moveFiles( fs: LightningFS, files: WorkspaceFile[], newDirPath: string, broadcastArgs: { broadcast: boolean } ): Promise<void> { if (files.length === 0) { return; } const relativePaths = await this.storageService.moveFiles( fs, files.map((f) => this.toStorageFile(f)), newDirPath ); if (broadcastArgs.broadcast) { await this.workspaceDescriptorService.bumpLastUpdatedDate(files[0].workspaceId); const broadcastChannel = new BroadcastChannel(files[0].workspaceId); broadcastChannel.postMessage({ type: "MOVE_BATCH", workspaceId: files[0].workspaceId, relativePaths, } as WorkspaceEvents); } } private toWorkspaceFile(workspaceId: string, storageFile: StorageFile): WorkspaceFile { return new WorkspaceFile({ workspaceId, getFileContents: storageFile.getFileContents, relativePath: relative(this.getAbsolutePath({ workspaceId }), storageFile.path), }); } private toStorageFile(workspaceFile: WorkspaceFile): StorageFile { return new StorageFile({ path: this.getAbsolutePath(workspaceFile), getFileContents: workspaceFile.getFileContents, }); } public getUniqueFileIdentifier(args: { workspaceId: string; relativePath: string }) { return args.workspaceId + "__" + this.getAbsolutePath(args); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PrivateLinkServices } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { NetworkManagementClient } from "../networkManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { PrivateLinkService, PrivateLinkServicesListNextOptionalParams, PrivateLinkServicesListOptionalParams, PrivateLinkServicesListBySubscriptionNextOptionalParams, PrivateLinkServicesListBySubscriptionOptionalParams, PrivateEndpointConnection, PrivateLinkServicesListPrivateEndpointConnectionsNextOptionalParams, PrivateLinkServicesListPrivateEndpointConnectionsOptionalParams, AutoApprovedPrivateLinkService, PrivateLinkServicesListAutoApprovedPrivateLinkServicesNextOptionalParams, PrivateLinkServicesListAutoApprovedPrivateLinkServicesOptionalParams, PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupNextOptionalParams, PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupOptionalParams, PrivateLinkServicesDeleteOptionalParams, PrivateLinkServicesGetOptionalParams, PrivateLinkServicesGetResponse, PrivateLinkServicesCreateOrUpdateOptionalParams, PrivateLinkServicesCreateOrUpdateResponse, PrivateLinkServicesListResponse, PrivateLinkServicesListBySubscriptionResponse, PrivateLinkServicesGetPrivateEndpointConnectionOptionalParams, PrivateLinkServicesGetPrivateEndpointConnectionResponse, PrivateLinkServicesUpdatePrivateEndpointConnectionOptionalParams, PrivateLinkServicesUpdatePrivateEndpointConnectionResponse, PrivateLinkServicesDeletePrivateEndpointConnectionOptionalParams, PrivateLinkServicesListPrivateEndpointConnectionsResponse, CheckPrivateLinkServiceVisibilityRequest, PrivateLinkServicesCheckPrivateLinkServiceVisibilityOptionalParams, PrivateLinkServicesCheckPrivateLinkServiceVisibilityResponse, PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupOptionalParams, PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupResponse, PrivateLinkServicesListAutoApprovedPrivateLinkServicesResponse, PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupResponse, PrivateLinkServicesListNextResponse, PrivateLinkServicesListBySubscriptionNextResponse, PrivateLinkServicesListPrivateEndpointConnectionsNextResponse, PrivateLinkServicesListAutoApprovedPrivateLinkServicesNextResponse, PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing PrivateLinkServices operations. */ export class PrivateLinkServicesImpl implements PrivateLinkServices { private readonly client: NetworkManagementClient; /** * Initialize a new instance of the class PrivateLinkServices class. * @param client Reference to the service client */ constructor(client: NetworkManagementClient) { this.client = client; } /** * Gets all private link services in a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ public list( resourceGroupName: string, options?: PrivateLinkServicesListOptionalParams ): PagedAsyncIterableIterator<PrivateLinkService> { const iter = this.listPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, options); } }; } private async *listPagingPage( resourceGroupName: string, options?: PrivateLinkServicesListOptionalParams ): AsyncIterableIterator<PrivateLinkService[]> { let result = await this._list(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, options?: PrivateLinkServicesListOptionalParams ): AsyncIterableIterator<PrivateLinkService> { for await (const page of this.listPagingPage(resourceGroupName, options)) { yield* page; } } /** * Gets all private link service in a subscription. * @param options The options parameters. */ public listBySubscription( options?: PrivateLinkServicesListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<PrivateLinkService> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: PrivateLinkServicesListBySubscriptionOptionalParams ): AsyncIterableIterator<PrivateLinkService[]> { let result = await this._listBySubscription(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listBySubscriptionNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listBySubscriptionPagingAll( options?: PrivateLinkServicesListBySubscriptionOptionalParams ): AsyncIterableIterator<PrivateLinkService> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * Gets all private end point connections for a specific private link service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ public listPrivateEndpointConnections( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesListPrivateEndpointConnectionsOptionalParams ): PagedAsyncIterableIterator<PrivateEndpointConnection> { const iter = this.listPrivateEndpointConnectionsPagingAll( resourceGroupName, serviceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPrivateEndpointConnectionsPagingPage( resourceGroupName, serviceName, options ); } }; } private async *listPrivateEndpointConnectionsPagingPage( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesListPrivateEndpointConnectionsOptionalParams ): AsyncIterableIterator<PrivateEndpointConnection[]> { let result = await this._listPrivateEndpointConnections( resourceGroupName, serviceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listPrivateEndpointConnectionsNext( resourceGroupName, serviceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPrivateEndpointConnectionsPagingAll( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesListPrivateEndpointConnectionsOptionalParams ): AsyncIterableIterator<PrivateEndpointConnection> { for await (const page of this.listPrivateEndpointConnectionsPagingPage( resourceGroupName, serviceName, options )) { yield* page; } } /** * Returns all of the private link service ids that can be linked to a Private Endpoint with auto * approved in this subscription in this region. * @param location The location of the domain name. * @param options The options parameters. */ public listAutoApprovedPrivateLinkServices( location: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesOptionalParams ): PagedAsyncIterableIterator<AutoApprovedPrivateLinkService> { const iter = this.listAutoApprovedPrivateLinkServicesPagingAll( location, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAutoApprovedPrivateLinkServicesPagingPage( location, options ); } }; } private async *listAutoApprovedPrivateLinkServicesPagingPage( location: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesOptionalParams ): AsyncIterableIterator<AutoApprovedPrivateLinkService[]> { let result = await this._listAutoApprovedPrivateLinkServices( location, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAutoApprovedPrivateLinkServicesNext( location, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAutoApprovedPrivateLinkServicesPagingAll( location: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesOptionalParams ): AsyncIterableIterator<AutoApprovedPrivateLinkService> { for await (const page of this.listAutoApprovedPrivateLinkServicesPagingPage( location, options )) { yield* page; } } /** * Returns all of the private link service ids that can be linked to a Private Endpoint with auto * approved in this subscription in this region. * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ public listAutoApprovedPrivateLinkServicesByResourceGroup( location: string, resourceGroupName: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupOptionalParams ): PagedAsyncIterableIterator<AutoApprovedPrivateLinkService> { const iter = this.listAutoApprovedPrivateLinkServicesByResourceGroupPagingAll( location, resourceGroupName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAutoApprovedPrivateLinkServicesByResourceGroupPagingPage( location, resourceGroupName, options ); } }; } private async *listAutoApprovedPrivateLinkServicesByResourceGroupPagingPage( location: string, resourceGroupName: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupOptionalParams ): AsyncIterableIterator<AutoApprovedPrivateLinkService[]> { let result = await this._listAutoApprovedPrivateLinkServicesByResourceGroup( location, resourceGroupName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAutoApprovedPrivateLinkServicesByResourceGroupNext( location, resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAutoApprovedPrivateLinkServicesByResourceGroupPagingAll( location: string, resourceGroupName: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupOptionalParams ): AsyncIterableIterator<AutoApprovedPrivateLinkService> { for await (const page of this.listAutoApprovedPrivateLinkServicesByResourceGroupPagingPage( location, resourceGroupName, options )) { yield* page; } } /** * Deletes the specified private link service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Deletes the specified private link service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, serviceName, options ); return poller.pollUntilDone(); } /** * Gets the specified private link service by resource group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesGetOptionalParams ): Promise<PrivateLinkServicesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, options }, getOperationSpec ); } /** * Creates or updates an private link service in the specified resource group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param parameters Parameters supplied to the create or update private link service operation. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, serviceName: string, parameters: PrivateLinkService, options?: PrivateLinkServicesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<PrivateLinkServicesCreateOrUpdateResponse>, PrivateLinkServicesCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<PrivateLinkServicesCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, parameters, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "azure-async-operation" }); } /** * Creates or updates an private link service in the specified resource group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param parameters Parameters supplied to the create or update private link service operation. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, serviceName: string, parameters: PrivateLinkService, options?: PrivateLinkServicesCreateOrUpdateOptionalParams ): Promise<PrivateLinkServicesCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, serviceName, parameters, options ); return poller.pollUntilDone(); } /** * Gets all private link services in a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ private _list( resourceGroupName: string, options?: PrivateLinkServicesListOptionalParams ): Promise<PrivateLinkServicesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listOperationSpec ); } /** * Gets all private link service in a subscription. * @param options The options parameters. */ private _listBySubscription( options?: PrivateLinkServicesListBySubscriptionOptionalParams ): Promise<PrivateLinkServicesListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } /** * Get the specific private end point connection by specific private link service in the resource * group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param options The options parameters. */ getPrivateEndpointConnection( resourceGroupName: string, serviceName: string, peConnectionName: string, options?: PrivateLinkServicesGetPrivateEndpointConnectionOptionalParams ): Promise<PrivateLinkServicesGetPrivateEndpointConnectionResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, peConnectionName, options }, getPrivateEndpointConnectionOperationSpec ); } /** * Approve or reject private end point connection for a private link service in a subscription. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param parameters Parameters supplied to approve or reject the private end point connection. * @param options The options parameters. */ updatePrivateEndpointConnection( resourceGroupName: string, serviceName: string, peConnectionName: string, parameters: PrivateEndpointConnection, options?: PrivateLinkServicesUpdatePrivateEndpointConnectionOptionalParams ): Promise<PrivateLinkServicesUpdatePrivateEndpointConnectionResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, peConnectionName, parameters, options }, updatePrivateEndpointConnectionOperationSpec ); } /** * Delete private end point connection for a private link service in a subscription. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param options The options parameters. */ async beginDeletePrivateEndpointConnection( resourceGroupName: string, serviceName: string, peConnectionName: string, options?: PrivateLinkServicesDeletePrivateEndpointConnectionOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, peConnectionName, options }, deletePrivateEndpointConnectionOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Delete private end point connection for a private link service in a subscription. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param options The options parameters. */ async beginDeletePrivateEndpointConnectionAndWait( resourceGroupName: string, serviceName: string, peConnectionName: string, options?: PrivateLinkServicesDeletePrivateEndpointConnectionOptionalParams ): Promise<void> { const poller = await this.beginDeletePrivateEndpointConnection( resourceGroupName, serviceName, peConnectionName, options ); return poller.pollUntilDone(); } /** * Gets all private end point connections for a specific private link service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ private _listPrivateEndpointConnections( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesListPrivateEndpointConnectionsOptionalParams ): Promise<PrivateLinkServicesListPrivateEndpointConnectionsResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, options }, listPrivateEndpointConnectionsOperationSpec ); } /** * Checks whether the subscription is visible to private link service. * @param location The location of the domain name. * @param parameters The request body of CheckPrivateLinkService API call. * @param options The options parameters. */ checkPrivateLinkServiceVisibility( location: string, parameters: CheckPrivateLinkServiceVisibilityRequest, options?: PrivateLinkServicesCheckPrivateLinkServiceVisibilityOptionalParams ): Promise<PrivateLinkServicesCheckPrivateLinkServiceVisibilityResponse> { return this.client.sendOperationRequest( { location, parameters, options }, checkPrivateLinkServiceVisibilityOperationSpec ); } /** * Checks whether the subscription is visible to private link service in the specified resource group. * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @param parameters The request body of CheckPrivateLinkService API call. * @param options The options parameters. */ checkPrivateLinkServiceVisibilityByResourceGroup( location: string, resourceGroupName: string, parameters: CheckPrivateLinkServiceVisibilityRequest, options?: PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupOptionalParams ): Promise< PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupResponse > { return this.client.sendOperationRequest( { location, resourceGroupName, parameters, options }, checkPrivateLinkServiceVisibilityByResourceGroupOperationSpec ); } /** * Returns all of the private link service ids that can be linked to a Private Endpoint with auto * approved in this subscription in this region. * @param location The location of the domain name. * @param options The options parameters. */ private _listAutoApprovedPrivateLinkServices( location: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesOptionalParams ): Promise<PrivateLinkServicesListAutoApprovedPrivateLinkServicesResponse> { return this.client.sendOperationRequest( { location, options }, listAutoApprovedPrivateLinkServicesOperationSpec ); } /** * Returns all of the private link service ids that can be linked to a Private Endpoint with auto * approved in this subscription in this region. * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ private _listAutoApprovedPrivateLinkServicesByResourceGroup( location: string, resourceGroupName: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupOptionalParams ): Promise< PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupResponse > { return this.client.sendOperationRequest( { location, resourceGroupName, options }, listAutoApprovedPrivateLinkServicesByResourceGroupOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, nextLink: string, options?: PrivateLinkServicesListNextOptionalParams ): Promise<PrivateLinkServicesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listNextOperationSpec ); } /** * ListBySubscriptionNext * @param nextLink The nextLink from the previous successful call to the ListBySubscription method. * @param options The options parameters. */ private _listBySubscriptionNext( nextLink: string, options?: PrivateLinkServicesListBySubscriptionNextOptionalParams ): Promise<PrivateLinkServicesListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listBySubscriptionNextOperationSpec ); } /** * ListPrivateEndpointConnectionsNext * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param nextLink The nextLink from the previous successful call to the ListPrivateEndpointConnections * method. * @param options The options parameters. */ private _listPrivateEndpointConnectionsNext( resourceGroupName: string, serviceName: string, nextLink: string, options?: PrivateLinkServicesListPrivateEndpointConnectionsNextOptionalParams ): Promise<PrivateLinkServicesListPrivateEndpointConnectionsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, nextLink, options }, listPrivateEndpointConnectionsNextOperationSpec ); } /** * ListAutoApprovedPrivateLinkServicesNext * @param location The location of the domain name. * @param nextLink The nextLink from the previous successful call to the * ListAutoApprovedPrivateLinkServices method. * @param options The options parameters. */ private _listAutoApprovedPrivateLinkServicesNext( location: string, nextLink: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesNextOptionalParams ): Promise< PrivateLinkServicesListAutoApprovedPrivateLinkServicesNextResponse > { return this.client.sendOperationRequest( { location, nextLink, options }, listAutoApprovedPrivateLinkServicesNextOperationSpec ); } /** * ListAutoApprovedPrivateLinkServicesByResourceGroupNext * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @param nextLink The nextLink from the previous successful call to the * ListAutoApprovedPrivateLinkServicesByResourceGroup method. * @param options The options parameters. */ private _listAutoApprovedPrivateLinkServicesByResourceGroupNext( location: string, resourceGroupName: string, nextLink: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupNextOptionalParams ): Promise< PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupNextResponse > { return this.client.sendOperationRequest( { location, resourceGroupName, nextLink, options }, listAutoApprovedPrivateLinkServicesByResourceGroupNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.serviceName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkService }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.serviceName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.PrivateLinkService }, 201: { bodyMapper: Mappers.PrivateLinkService }, 202: { bodyMapper: Mappers.PrivateLinkService }, 204: { bodyMapper: Mappers.PrivateLinkService }, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.parameters39, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.serviceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkServiceListResult }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Network/privateLinkServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkServiceListResult }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const getPrivateEndpointConnectionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateEndpointConnection }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.serviceName, Parameters.peConnectionName ], headerParameters: [Parameters.accept], serializer }; const updatePrivateEndpointConnectionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.PrivateEndpointConnection }, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.parameters40, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.serviceName, Parameters.peConnectionName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deletePrivateEndpointConnectionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.serviceName, Parameters.peConnectionName ], headerParameters: [Parameters.accept], serializer }; const listPrivateEndpointConnectionsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateEndpointConnectionListResult }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.serviceName ], headerParameters: [Parameters.accept], serializer }; const checkPrivateLinkServiceVisibilityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.PrivateLinkServiceVisibility }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters41, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.location ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const checkPrivateLinkServiceVisibilityByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.PrivateLinkServiceVisibility }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters41, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.location ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listAutoApprovedPrivateLinkServicesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/autoApprovedPrivateLinkServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutoApprovedPrivateLinkServicesResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.location ], headerParameters: [Parameters.accept], serializer }; const listAutoApprovedPrivateLinkServicesByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/autoApprovedPrivateLinkServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutoApprovedPrivateLinkServicesResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.location ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkServiceListResult }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkServiceListResult }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listPrivateEndpointConnectionsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateEndpointConnectionListResult }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink, Parameters.serviceName ], headerParameters: [Parameters.accept], serializer }; const listAutoApprovedPrivateLinkServicesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutoApprovedPrivateLinkServicesResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink, Parameters.location ], headerParameters: [Parameters.accept], serializer }; const listAutoApprovedPrivateLinkServicesByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutoApprovedPrivateLinkServicesResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink, Parameters.location ], headerParameters: [Parameters.accept], serializer };
the_stack
import { SurveyModel } from "../survey"; import { Base, EventBase } from "../base"; import { ISurvey } from "../base-interfaces"; import { property } from "../jsonobject"; import { findScrollableParent } from "../utils/utils"; export abstract class DragDropCore<T> extends Base { @property({ defaultValue: null, onSet: (val, target: DragDropCore<T>) => { target.ghostPositionChanged(); }, }) isBottom: boolean; //TODO rename isBottom to isShowGhostAtBottomOfDropTarget public onGhostPositionChanged: EventBase<Base> = new EventBase<Base>(); protected ghostPositionChanged(): void { this.onGhostPositionChanged.fire({}, {}); } public onBeforeDrop: EventBase<DragDropCore<T>> = new EventBase(); public onAfterDrop: EventBase<DragDropCore<T>> = new EventBase(); public draggedElement: any = null; protected abstract get draggedElementType(): string; protected parentElement: T; public dropTarget: any = null; protected get dropTargetDataAttributeName(): string { return `[data-sv-drop-target-${this.draggedElementType}]`; } protected get survey(): SurveyModel { return this.surveyValue || this.creator.survey; } public prevDropTarget: any = null; protected draggedElementShortcut: HTMLElement = null; private scrollIntervalId: number = null; private allowDropHere = false; constructor(private surveyValue?: ISurvey, private creator?: any) { super(); } public startDrag( event: PointerEvent, draggedElement: any, parentElement?: any, draggedElementNode?: HTMLElement ): void { if (event.which === 3) return; //right mouse btn this.draggedElement = draggedElement; this.parentElement = parentElement; this.doStartDrag(); const shortcutText = this.getShortcutText(this.draggedElement); this.draggedElementShortcut = this.createDraggedElementShortcut( shortcutText, draggedElementNode ); document.body.append(this.draggedElementShortcut); this.moveShortcutElement(event); document.addEventListener("pointermove", this.dragOver); document.addEventListener("pointercancel", this.handlePointerCancel); document.addEventListener("keydown", this.handleEscapeButton); document.addEventListener("pointerup", this.drop); this.draggedElementShortcut.addEventListener("pointerup", this.drop); } private dragOver = (event: PointerEvent) => { this.moveShortcutElement(event); this.draggedElementShortcut.style.cursor = "grabbing"; const dropTargetNode = this.findDropTargetNodeFromPoint( event.clientX, event.clientY ); if (!dropTargetNode) { this.banDropHere(); return; } this.dropTarget = this.getDropTargetByNode(dropTargetNode, event); let isBottom = this.calculateIsBottom(event.clientY, dropTargetNode); const isDropTargetValid = this.isDropTargetValid(this.dropTarget, isBottom, dropTargetNode); this.doDragOver(dropTargetNode); if (!isDropTargetValid) { this.banDropHere(); return; } this.allowDropHere = true; if (this.isDropTargetDoesntChanged(isBottom)) return; this.isBottom = null; //TODO need for property change trigger with guarantee but it would be better not to watch on isBottom property but have some event like onValidTargetDragOver this.isBottom = isBottom; this.afterDragOver(dropTargetNode); this.prevDropTarget = this.dropTarget; }; private drop = () => { if (this.allowDropHere) { this.onBeforeDrop.fire(this, null); const newElement = this.doDrop(); this.onAfterDrop.fire(this, { draggedElement: newElement }); } this.clear(); }; protected isDropTargetDoesntChanged(newIsBottom: boolean): boolean { return ( this.dropTarget === this.prevDropTarget && newIsBottom === this.isBottom ); } protected doStartDrag(): void { } protected abstract getShortcutText(draggedElement: any): string; protected createDraggedElementShortcut(text: string, draggedElementNode?: HTMLElement): HTMLElement { const draggedElementShortcut = document.createElement("div"); draggedElementShortcut.innerText = text; draggedElementShortcut.style.cssText = "height: 24px; min-width: 100px; border-radius: 36px; background-color: white; padding: 16px; cursor: grabbing; position: absolute; z-index: 1000; box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.1); font-family: 'Open Sans'; font-size: 16px; padding-left: 20px; line-height: 24px;"; return draggedElementShortcut; } protected doDragOver(dropTargetNode?: HTMLElement): void { } protected afterDragOver(dropTargetNode?: HTMLElement): void { } public getGhostPosition(item: any): string { if (this.dropTarget !== item) return null; if (this.isBottom) return "bottom"; return "top"; } protected abstract isDropTargetValid( dropTarget: any, isBottom: boolean, dropTargetNode?: HTMLElement ): boolean; private handlePointerCancel = (event: PointerEvent) => { this.clear(); }; protected handleEscapeButton = (event: KeyboardEvent) => { if (event.keyCode == 27) { this.clear(); } }; private moveShortcutElement(event: PointerEvent) { this.doScroll(event.clientY, event.clientX); const shortcutHeight = this.draggedElementShortcut.offsetHeight; const shortcutWidth = this.draggedElementShortcut.offsetWidth; let shortcutXOffset; let shortcutYOffset; const draggedIcon = this.draggedElementShortcut.querySelector(".svc-item-value-controls__drag .sv-svg-icon") || this.draggedElementShortcut.querySelector(".sv-ranking-item__icon"); if (draggedIcon) { const rectOuter = this.draggedElementShortcut.getBoundingClientRect(); const rectInner = draggedIcon.getBoundingClientRect(); shortcutXOffset = rectInner.x - rectOuter.x + rectInner.width / 2; shortcutYOffset = rectInner.y - rectOuter.y + rectInner.height / 2; } else { shortcutXOffset = shortcutWidth / 2; shortcutYOffset = shortcutHeight / 2; } const documentClientHeight = document.documentElement.clientHeight; const documentClientWidth = document.documentElement.clientWidth; if (event.clientX + shortcutXOffset >= documentClientWidth) { this.draggedElementShortcut.style.left = event.pageX - event.clientX + documentClientWidth - shortcutWidth + "px"; this.draggedElementShortcut.style.top = event.pageY - shortcutYOffset + "px"; return; } if (event.clientX - shortcutXOffset <= 0) { this.draggedElementShortcut.style.left = event.pageX - event.clientX + "px"; this.draggedElementShortcut.style.top = event.pageY - shortcutYOffset + "px"; return; } if (event.clientY + shortcutYOffset >= documentClientHeight) { this.draggedElementShortcut.style.left = event.pageX - shortcutXOffset + "px"; this.draggedElementShortcut.style.top = event.pageY - event.clientY + documentClientHeight - shortcutHeight + "px"; return; } if (event.clientY - shortcutYOffset <= 0) { this.draggedElementShortcut.style.left = event.pageX - shortcutXOffset + "px"; this.draggedElementShortcut.style.top = event.pageY - event.clientY + "px"; return; } this.draggedElementShortcut.style.left = event.pageX - shortcutXOffset + "px"; this.draggedElementShortcut.style.top = event.pageY - shortcutYOffset + "px"; } private doScroll(clientY: number, clientX: number) { cancelAnimationFrame(this.scrollIntervalId); const startScrollBoundary = 50; this.draggedElementShortcut.hidden = true; let dragOverNode = <HTMLElement>document.elementFromPoint(clientX, clientY); this.draggedElementShortcut.hidden = false; let scrollableParentNode = findScrollableParent(dragOverNode); let top = scrollableParentNode.getBoundingClientRect().top; let bottom = scrollableParentNode.getBoundingClientRect().bottom; let left = scrollableParentNode.getBoundingClientRect().left; let right = scrollableParentNode.getBoundingClientRect().right; const repeat = () => { if (clientY - top <= startScrollBoundary) { scrollableParentNode.scrollTop -= 15; } else if (bottom - clientY <= startScrollBoundary) { scrollableParentNode.scrollTop += 15; } else if (right - clientX <= startScrollBoundary) { scrollableParentNode.scrollLeft += 15; } else if (clientX - left <= startScrollBoundary) { scrollableParentNode.scrollLeft -= 15; } this.scrollIntervalId = requestAnimationFrame(repeat); }; this.scrollIntervalId = requestAnimationFrame(repeat); } protected banDropHere = (): void => { this.doBanDropHere(); this.allowDropHere = false; this.dropTarget = null; this.draggedElementShortcut.style.cursor = "not-allowed"; this.isBottom = null; }; protected doBanDropHere = (): void => { }; protected getDataAttributeValueByNode(node: HTMLElement) { let datasetName = "svDropTarget"; const words = this.draggedElementType.split("-"); words.forEach((word) => { datasetName += this.capitalizeFirstLetter(word); }); return node.dataset[datasetName]; } protected getDropTargetByNode( dropTargetNode: HTMLElement, event: PointerEvent ): any { let dataAttributeValue = this.getDataAttributeValueByNode(dropTargetNode); return this.getDropTargetByDataAttributeValue( dataAttributeValue, dropTargetNode, event ); } private capitalizeFirstLetter(string: string) { return string.charAt(0).toUpperCase() + string.slice(1); } //TODO adandone unrequired params (survey-elements) protected abstract getDropTargetByDataAttributeValue( dataAttributeValue: string, dropTargetNode?: HTMLElement, event?: PointerEvent ): any; protected calculateMiddleOfHTMLElement(HTMLElement: HTMLElement): number { const rect = HTMLElement.getBoundingClientRect(); return rect.y + rect.height / 2; } protected calculateIsBottom( clientY: number, dropTargetNode?: HTMLElement ): boolean { const middle = this.calculateMiddleOfHTMLElement(dropTargetNode); return clientY >= middle; } private findDropTargetNodeFromPoint( clientX: number, clientY: number ): HTMLElement { this.draggedElementShortcut.hidden = true; let dragOverNode = <HTMLElement>document.elementFromPoint(clientX, clientY); this.draggedElementShortcut.hidden = false; if (!dragOverNode) return null; return this.findDropTargetNodeByDragOverNode(dragOverNode); } protected findDropTargetNodeByDragOverNode(dragOverNode: HTMLElement): HTMLElement { const result: HTMLElement = dragOverNode.querySelector(this.dropTargetDataAttributeName) || dragOverNode.closest(this.dropTargetDataAttributeName); return result; } protected abstract doDrop(): any; protected clear = () => { cancelAnimationFrame(this.scrollIntervalId); document.removeEventListener("pointermove", this.dragOver); document.removeEventListener("pointercancel", this.handlePointerCancel); document.removeEventListener("keydown", this.handleEscapeButton); document.removeEventListener("pointerup", this.drop); this.draggedElementShortcut.removeEventListener("pointerup", this.drop); document.body.removeChild(this.draggedElementShortcut); this.doClear(); this.dropTarget = null; this.draggedElementShortcut = null; this.draggedElement = null; this.isBottom = null; this.parentElement = null; this.scrollIntervalId = null; }; protected doClear(): void { } }
the_stack
import path from 'path'; import { StrykerOptions, INSTRUMENTER_CONSTANTS, MutantCoverage, CoverageAnalysis } from '@stryker-mutator/api/core'; import { Logger } from '@stryker-mutator/api/logging'; import { commonTokens, Injector, PluginContext, tokens } from '@stryker-mutator/api/plugin'; import { TestRunner, MutantRunOptions, DryRunResult, MutantRunResult, toMutantRunResult, DryRunStatus, TestResult, TestStatus, DryRunOptions, BaseTestResult, } from '@stryker-mutator/api/test-runner'; import { escapeRegExp, notEmpty, requireResolve } from '@stryker-mutator/util'; import type * as jest from '@jest/types'; import type * as jestTestResult from '@jest/test-result'; import { SerializableError } from '@jest/types/build/TestResult'; import { JestOptions } from '../src-generated/jest-runner-options'; import { jestTestAdapterFactory } from './jest-test-adapters'; import { JestTestAdapter, RunSettings } from './jest-test-adapters/jest-test-adapter'; import { JestConfigLoader } from './config-loaders/jest-config-loader'; import { withCoverageAnalysis } from './jest-plugins'; import * as pluginTokens from './plugin-tokens'; import { configLoaderFactory } from './config-loaders'; import { JestRunnerOptionsWithStrykerOptions } from './jest-runner-options-with-stryker-options'; import { JEST_OVERRIDE_OPTIONS } from './jest-override-options'; import { jestWrapper, mergeMutantCoverage, verifyAllTestFilesHaveCoverage } from './utils'; import { state } from './messaging'; export function createJestTestRunnerFactory(namespace: typeof INSTRUMENTER_CONSTANTS.NAMESPACE | '__stryker2__' = INSTRUMENTER_CONSTANTS.NAMESPACE): { (injector: Injector<PluginContext>): JestTestRunner; inject: ['$injector']; } { jestTestRunnerFactory.inject = tokens(commonTokens.injector); function jestTestRunnerFactory(injector: Injector<PluginContext>) { return injector .provideValue(pluginTokens.processEnv, process.env) .provideValue(pluginTokens.jestVersion, jestWrapper.getVersion()) .provideFactory(pluginTokens.jestTestAdapter, jestTestAdapterFactory) .provideFactory(pluginTokens.configLoader, configLoaderFactory) .provideValue(pluginTokens.globalNamespace, namespace) .injectClass(JestTestRunner); } return jestTestRunnerFactory; } export const jestTestRunnerFactory = createJestTestRunnerFactory(); export class JestTestRunner implements TestRunner { private readonly jestConfig: jest.Config.InitialOptions; private readonly jestOptions: JestOptions; private readonly enableFindRelatedTests: boolean; public static inject = tokens( commonTokens.logger, commonTokens.options, pluginTokens.processEnv, pluginTokens.jestTestAdapter, pluginTokens.configLoader, pluginTokens.globalNamespace ); constructor( private readonly log: Logger, options: StrykerOptions, private readonly processEnvRef: NodeJS.ProcessEnv, private readonly jestTestAdapter: JestTestAdapter, configLoader: JestConfigLoader, private readonly globalNamespace: typeof INSTRUMENTER_CONSTANTS.NAMESPACE | '__stryker2__' ) { this.jestOptions = (options as JestRunnerOptionsWithStrykerOptions).jest; // Get jest configuration from stryker options and assign it to jestConfig const configFromFile = configLoader.loadConfig(); this.jestConfig = this.mergeConfigSettings(configFromFile, this.jestOptions || {}); // Get enableFindRelatedTests from stryker jest options or default to true this.enableFindRelatedTests = this.jestOptions.enableFindRelatedTests; if (this.enableFindRelatedTests) { this.log.debug('Running jest with --findRelatedTests flag. Set jest.enableFindRelatedTests to false to run all tests on every mutant.'); } else { this.log.debug( 'Running jest without --findRelatedTests flag. Set jest.enableFindRelatedTests to true to run only relevant tests on every mutant.' ); } } public async dryRun({ coverageAnalysis, disableBail, files, }: Pick<DryRunOptions, 'coverageAnalysis' | 'disableBail' | 'files'>): Promise<DryRunResult> { state.coverageAnalysis = coverageAnalysis; const mutantCoverage: MutantCoverage = { perTest: {}, static: {} }; const fileNamesWithMutantCoverage: string[] = []; if (coverageAnalysis !== 'off') { state.setMutantCoverageHandler((fileName, report) => { mergeMutantCoverage(mutantCoverage, report); fileNamesWithMutantCoverage.push(fileName); }); } const fileNamesUnderTest = this.enableFindRelatedTests ? files : undefined; try { const { dryRunResult, jestResult } = await this.run({ fileNamesUnderTest, jestConfig: this.configForDryRun(fileNamesUnderTest, coverageAnalysis), testLocationInResults: true, }); if (dryRunResult.status === DryRunStatus.Complete && coverageAnalysis !== 'off') { const errorMessage = verifyAllTestFilesHaveCoverage(jestResult, fileNamesWithMutantCoverage); if (errorMessage) { return { status: DryRunStatus.Error, errorMessage, }; } else { dryRunResult.mutantCoverage = mutantCoverage; } } return dryRunResult; } finally { state.resetMutantCoverageHandler(); } } public async mutantRun({ activeMutant, sandboxFileName, testFilter, disableBail }: MutantRunOptions): Promise<MutantRunResult> { const fileNameUnderTest = this.enableFindRelatedTests ? sandboxFileName : undefined; state.coverageAnalysis = 'off'; let testNamePattern: string | undefined; if (testFilter) { testNamePattern = testFilter.map((testId) => `(${escapeRegExp(testId)})`).join('|'); } process.env[INSTRUMENTER_CONSTANTS.ACTIVE_MUTANT_ENV_VARIABLE] = activeMutant.id.toString(); try { const { dryRunResult } = await this.run({ fileNamesUnderTest: fileNameUnderTest ? [fileNameUnderTest] : undefined, jestConfig: this.configForMutantRun(fileNameUnderTest), testNamePattern, }); return toMutantRunResult(dryRunResult, disableBail); } finally { delete process.env[INSTRUMENTER_CONSTANTS.ACTIVE_MUTANT_ENV_VARIABLE]; } } private configForDryRun(fileNamesUnderTest: string[] | undefined, coverageAnalysis: CoverageAnalysis): jest.Config.InitialOptions { return withCoverageAnalysis(this.configWithRoots(fileNamesUnderTest), coverageAnalysis); } private configForMutantRun(fileNameUnderTest: string | undefined): jest.Config.InitialOptions { return this.configWithRoots(fileNameUnderTest ? [fileNameUnderTest] : undefined); } private configWithRoots(fileNamesUnderTest: string[] | undefined): jest.Config.InitialOptions { let config: jest.Config.InitialOptions; if (fileNamesUnderTest && this.jestConfig.roots) { // Make sure the file under test lives inside one of the roots config = { ...this.jestConfig, roots: [...this.jestConfig.roots, ...new Set(fileNamesUnderTest.map((file) => path.dirname(file)))], }; } else { config = this.jestConfig; } return config; } private async run(settings: RunSettings): Promise<{ dryRunResult: DryRunResult; jestResult: jestTestResult.AggregatedResult }> { this.setEnv(); if (this.log.isTraceEnabled()) { this.log.trace('Invoking Jest with config %s', JSON.stringify(settings)); } const { results } = await this.jestTestAdapter.run(settings); return { dryRunResult: this.collectRunResult(results), jestResult: results }; } private collectRunResult(results: jestTestResult.AggregatedResult): DryRunResult { if (results.numRuntimeErrorTestSuites) { const errorMessage = results.testResults .map((testSuite) => this.collectSerializableErrorText(testSuite.testExecError)) .filter(notEmpty) .join(', '); return { status: DryRunStatus.Error, errorMessage, }; } else { return { status: DryRunStatus.Complete, tests: this.processTestResults(results.testResults), }; } } private collectSerializableErrorText(error: SerializableError | undefined): string | undefined { return error && `${error.code && `${error.code} `}${error.message} ${error.stack}`; } private setEnv() { // Jest CLI will set process.env.NODE_ENV to 'test' when it's null, do the same here // https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L12-L14 if (!this.processEnvRef.NODE_ENV) { this.processEnvRef.NODE_ENV = 'test'; } // Force colors off: https://github.com/chalk/supports-color#info process.env.FORCE_COLOR = '0'; if (this.jestOptions.projectType === 'create-react-app') { try { requireResolve('react-scripts/config/env.js'); } catch (err) { this.log.warn( 'Unable to load environment variables using "react-scripts/config/env.js". The environment variables might differ from expected. Please open an issue if you think this is a bug: https://github.com/stryker-mutator/stryker-js/issues/new/choose.' ); this.log.debug('Inner error', err); } } } private processTestResults(suiteResults: jestTestResult.TestResult[]): TestResult[] { const testResults: TestResult[] = []; for (const suiteResult of suiteResults) { for (const testResult of suiteResult.testResults) { const result: BaseTestResult = { id: testResult.fullName, name: testResult.fullName, timeSpentMs: testResult.duration ?? 0, fileName: suiteResult.testFilePath, startPosition: testResult.location ? { // Stryker works 0-based internally, jest works 1-based: https://jestjs.io/docs/cli#--testlocationinresults line: testResult.location.line - 1, column: testResult.location.column, } : undefined, }; switch (testResult.status) { case 'passed': testResults.push({ status: TestStatus.Success, ...result, }); break; case 'failed': testResults.push({ status: TestStatus.Failed, failureMessage: testResult.failureMessages.join(', '), ...result, }); break; default: testResults.push({ status: TestStatus.Skipped, ...result, }); break; } } } return testResults; } private mergeConfigSettings(configFromFile: jest.Config.InitialOptions, options: JestOptions): jest.Config.InitialOptions { const config = (options.config ?? {}) as jest.Config.InitialOptions; const stringify = (obj: unknown) => JSON.stringify(obj, null, 2); this.log.debug( `Merging file-based config ${stringify(configFromFile)} with custom config ${stringify(config)} and default (internal) stryker config ${stringify(JEST_OVERRIDE_OPTIONS)}` ); const mergedConfig: jest.Config.InitialOptions = { ...configFromFile, ...config, ...JEST_OVERRIDE_OPTIONS, }; mergedConfig.globals = { ...mergedConfig.globals, __strykerGlobalNamespace__: this.globalNamespace, }; return mergedConfig; } }
the_stack
import { Theme } from "../../core/Theme"; import { percent, p100, p50 } from "../../core/util/Percent"; import { ColorSet } from "../../core/util/ColorSet"; import { setColor } from "../../themes/DefaultTheme"; import * as $ease from "../../core/util/Ease"; /** * @ignore */ export class HierarchyDefaultTheme extends Theme { protected setupDefaultRules() { super.setupDefaultRules(); const ic = this._root.interfaceColors; const gridLayout = this._root.gridLayout; const r = this.rule.bind(this); /** * ======================================================================== * charts/hierarchy * ======================================================================== */ r("Hierarchy").setAll({ legendLabelText: "{category}", legendValueText: "{sum.formatNumber('#.#')}", width: p100, height: p100, colors: ColorSet.new(this._root, { step: 2 }), downDepth: 1, initialDepth: 5, singleBranchOnly: true, maskContent: true, animationEasing: $ease.out($ease.cubic) }); r("HierarchyNode").setAll({ toggleKey: "disabled", setStateOnChildren: true, position: "absolute", isMeasured: false, cursorOverStyle: "pointer", tooltipText: "{category}: {sum}" }); r("HierarchyNode", ["last"]).setAll({ cursorOverStyle: "default" }); { const rule = r("Label", ["hierarchy", "node"]); rule.setAll({ centerX: p50, centerY: p50, position: "absolute", paddingBottom: 1, paddingTop: 1, paddingRight: 4, paddingLeft: 4, text: "{category}", populateText: true, oversizedBehavior: "fit", minScale: 0.3 }); setColor(rule, "fill", ic, "alternativeText"); } { const rule = r("HierarchyLink"); rule.setAll({ isMeasured: false, position: "absolute", strokeWidth: 1, strokeOpacity: 1, strength: 0.9, distance: 1.1 }); setColor(rule, "stroke", ic, "grid"); } r("Circle", ["linkedhierarchy", "shape"]).setAll({ position: "absolute", fillOpacity: 1, strokeOpacity: 0, radius: 15, tooltipY: 0 }); r("Circle", ["linkedhierarchy", "shape", "outer"]).setAll({ position: "absolute", opacity: 1, fillOpacity: 0, strokeDasharray: 0, strokeOpacity: 1, radius: 15, scale: 1.1, interactive: false }) r("Circle", ["linkedhierarchy", "shape", "outer"]).states.create("disabled", { opacity: 1, scale: 1.1, strokeDasharray: 2 }); r("Circle", ["linkedhierarchy", "shape", "outer"]).states.create("hoverDisabled", { scale: 1.2, opacity: 1, strokeDasharray: 2 }); r("Circle", ["linkedhierarchy", "shape", "outer"]).states.create("hover", { scale: 1.05, strokeDasharray: 0 }); r("Circle", ["linkedhierarchy", "shape", "outer"]).states.create("hidden", { opacity: 0, strokeDasharray: 0 }); /** * ------------------------------------------------------------------------ * charts/hierarchy: BreadcrumbBar * ------------------------------------------------------------------------ */ r("BreadcrumbBar").setAll({ paddingLeft: 8, layout: gridLayout }); { const rule = r("Label", ["breadcrumb"]); rule.setAll({ paddingRight: 4, paddingLeft: 4, cursorOverStyle: "pointer", populateText: true, text: "{category}:", }); setColor(rule, "fill", ic, "primaryButton"); } { const rule = r("Label", ["breadcrumb"]).states.create("hover", {}); setColor(rule, "fill", ic, "primaryButtonHover"); } { const rule = r("Label", ["breadcrumb"]).states.create("down", { stateAnimationDuration: 0 }); setColor(rule, "fill", ic, "primaryButtonDown"); } { const rule = r("Label", ["breadcrumb", "last"]); rule.setAll({ populateText: true, text: "{category}", fontWeight: "bold", cursorOverStyle: "default" }); setColor(rule, "fill", ic, "primaryButton"); } { const rule = r("RoundedRectangle", ["breadcrumb", "label", "background"]); rule.setAll({ fillOpacity: 0, }); setColor(rule, "fill", ic, "background"); } /** * ------------------------------------------------------------------------ * charts/hierarchy: Partition * ------------------------------------------------------------------------ */ r("Partition").setAll({ downDepth: 1, upDepth: 0, initialDepth: 5 }); r("HierarchyNode", ["partition"]).setAll({ setStateOnChildren: false }); r("HierarchyNode", ["partition"]).states.create("hidden", { opacity: 1, visible: true }); { const rule = r("Label", ["partition", "node"]); rule.setAll({ x: p50, y: p50, centerY: p50, centerX: p50, paddingBottom: 1, paddingTop: 1, paddingLeft: 1, paddingRight: 1, rotation: 90, populateText: true, text: "{category}", oversizedBehavior: "fit", minScale: 0.4 }); setColor(rule, "fill", ic, "alternativeText"); } r("Label", ["horizontal", "partition", "node"]).setAll({ rotation: 0 }); { const rule = r("RoundedRectangle", ["partition", "node", "shape"]); rule.setAll({ strokeOpacity: 1, strokeWidth: 1, cornerRadiusBR: 0, cornerRadiusTR: 0, cornerRadiusBL: 0, cornerRadiusTL: 0 }); setColor(rule, "stroke", ic, "background"); } r("RoundedRectangle", ["partition", "node", "shape", "last"]).setAll({ fillOpacity: 0.75 }); /** * ------------------------------------------------------------------------ * charts/hierarchy: Sunburst * ------------------------------------------------------------------------ */ r("Sunburst").setAll({ singleBranchOnly: true }); r("HierarchyNode", ["sunburst"]).setAll({ setStateOnChildren: false }); r("HierarchyNode", ["sunburst"]).states.create("hidden", { opacity: 0, visible: false }); { const rule = r("Slice", ["sunburst", "node", "shape"]); rule.setAll({ strokeOpacity: 1, strokeWidth: 1, cornerRadius: 0 }); setColor(rule, "stroke", ic, "background"); } r("Slice", ["sunburst", "node", "shape", "last"]).setAll({ fillOpacity: 0.75 }); { const rule = r("RadialLabel", ["sunburst", "node"]); rule.setAll({ textType: "radial", paddingBottom: 1, paddingTop: 1, paddingLeft: 1, paddingRight: 1, centerX: p50, populateText: true, text: "{category}", oversizedBehavior: "fit", minScale: 0.4, baseRadius: p50, rotation: 0 }); setColor(rule, "fill", ic, "alternativeText"); } /** * ------------------------------------------------------------------------ * charts/hierarchy: ForceDirected * ------------------------------------------------------------------------ */ r("ForceDirected").setAll({ minRadius: percent(1), maxRadius: percent(8), initialFrames: 500, centerStrength: 0.8, manyBodyStrength: -14, velocityDecay: 0.5, linkWithStrength: 0.5, showOnFrame: 10, singleBranchOnly: false, upDepth: Infinity, downDepth: 1, initialDepth: 5, topDepth: 0 }); /** * ------------------------------------------------------------------------ * charts/hierarchy: Tree * ------------------------------------------------------------------------ */ r("Tree").setAll({ orientation: "vertical", paddingLeft: 20, paddingRight: 20, paddingTop: 20, paddingBottom: 20, singleBranchOnly: false, upDepth: Infinity, downDepth: 1, initialDepth: 5, topDepth: 0 }); /** * ------------------------------------------------------------------------ * charts/hierarchy: Pack * ------------------------------------------------------------------------ */ r("Pack").setAll({ paddingLeft: 20, paddingTop: 20, paddingBottom: 20, paddingRight: 20 }); { const rule = r("Label", ["pack", "node"]); rule.setAll({ centerY: p50, centerX: p50, paddingBottom: 1, paddingTop: 1, paddingLeft: 1, paddingRight: 1, populateText: true, text: "{category}", oversizedBehavior: "fit", minScale: 0.4 }); setColor(rule, "fill", ic, "alternativeText"); } { const rule = r("Circle", ["pack", "node", "shape"]); rule.setAll({ strokeOpacity: 0.5, fillOpacity: 0.8, strokeWidth: 1, }); setColor(rule, "stroke", ic, "background"); } r("LinkedHierarchyNode").setAll({ draggable: true }); r("LinkedHierarchyNode").states.create("hidden", { scale: 0, opacity: 0, visible: false }); /** * ------------------------------------------------------------------------ * charts/hierarchy: Treemap * ------------------------------------------------------------------------ */ r("Treemap").setAll({ upDepth: 0, layoutAlgorithm: "squarify" }); { const rule = r("Label", ["treemap", "node"]); rule.setAll({ x: p50, y: p50, centerY: p50, centerX: p50, paddingBottom: 1, paddingTop: 1, paddingLeft: 1, paddingRight: 1, populateText: true, text: "{category}", oversizedBehavior: "fit", minScale: 0.4 }); setColor(rule, "fill", ic, "alternativeText"); } r("HierarchyNode", ["treemap", "node"]).setAll({ tooltipY: percent(40), isMeasured: false, position: "absolute" }); { const rule = r("RoundedRectangle", ["treemap", "node", "shape"]); rule.setAll({ strokeOpacity: 1, strokeWidth: 1, cornerRadiusBR: 0, cornerRadiusTR: 0, cornerRadiusBL: 0, cornerRadiusTL: 0, fillOpacity: 1 }); setColor(rule, "stroke", ic, "background"); } } }
the_stack
import { createServer, IncomingMessage, Server, ServerResponse } from 'http' import fs from 'fs' import path from 'path' import { parse as parseCookies, CookieParseOptions as CookieOptions } from 'cookie' import { parse as parseQuery, IParseOptions } from 'qs' import CookiesClass from 'cookies' import statuses from 'statuses' import accepts from 'accepts' import encodeurl from 'encodeurl' import escapeHtml from 'escape-html' import vary from 'vary' import onfinish from 'on-finished' import destroy from 'destroy' import mime from 'mime-types' import { createContainer, runWithContainer, Container, ContextStorage, MaybeAsync } from 'farrow-pipeline' import { Response } from './response' import { BasenamesContext, handleBasenames } from './basenames' import { Router, RouterPipeline } from './router' import { createLogger, LoggerEvent, LoggerOptions } from './logger' import { access, getBody, getContentLength, isPromise } from './util' import { RequestContext, RequestInfoContext, ResponseContext } from './context' import type { Stream } from 'stream' import type { Options as BodyOptions } from 'co-body' import type { JsonType } from 'farrow-schema' import type { RequestCookies, RequestHeaders, RequestQuery, RequestInfo } from './requestInfo' import type { ResponseInfo, Status, Headers, Cookies, Body, RedirectBody, FileBodyOptions, CustomBodyHandler, } from './responseInfo' export type HttpLoggerOptions = LoggerOptions & { /** * it should ignore the introspection request log of farrow-api or not * default is true */ ignoreIntrospectionRequestOfFarrowApi?: boolean } export type HttpPipelineOptions = { basenames?: string[] body?: BodyOptions cookie?: CookieOptions query?: IParseOptions contexts?: (params: { req: IncomingMessage; requestInfo: RequestInfo; basename: string }) => ContextStorage logger?: boolean | HttpLoggerOptions errorStack?: boolean } export type HttpHandlerOptions = { onLast?: CustomBodyHandler } export type HttpPipeline = RouterPipeline & { handle: (req: IncomingMessage, res: ServerResponse, options?: HttpHandlerOptions) => MaybeAsync<void> listen: (...args: Parameters<Server['listen']>) => Server server: () => Server } export const NOT_FOUND_RESPONSE = Response.status(404).text('404 Not Found') export const createHttpPipeline = (options?: HttpPipelineOptions): HttpPipeline => { const isNotProduction = process.env.NODE_ENV !== 'production' const config: HttpPipelineOptions = { logger: isNotProduction, errorStack: isNotProduction, ...options, } const loggerOptions: HttpLoggerOptions = { ignoreIntrospectionRequestOfFarrowApi: true, ...(!config.logger || typeof config.logger === 'boolean' ? {} : config.logger), } const logger = config.logger ? createLogger(loggerOptions) : null const router = Router() const handleRequest: HttpPipeline['handle'] = (req, res, options) => { if (typeof req.url !== 'string') { throw new Error(`req.url is not existed`) } const { url } = req const [pathname = '/', search = ''] = url.split('?') const method = req.method ?? 'GET' const query = (req as any).query ?? (parseQuery(search, config.query) as RequestQuery) const headers = req.headers as RequestHeaders const cookies = parseCookies(req.headers['cookie'] ?? '', config.cookie) as RequestCookies const handleRequestLog = (body: any) => { const isIntrospectionRequest = method.toLowerCase() === 'post' && typeof body === 'object' && body && body.type === 'Introspection' const shouldLog = logger && !(loggerOptions.ignoreIntrospectionRequestOfFarrowApi && isIntrospectionRequest) if (shouldLog) { const startTime = Date.now() const url = req.url ?? '' let contentLength = 0 let hasLogOut = false const logOutput = (event: LoggerEvent) => { if (hasLogOut) return hasLogOut = true logger?.logOutput(method, url, res.statusCode, startTime, contentLength || getContentLength(res), event) } logger.logInput(method, url) // log close res.once('close', () => { logOutput('close') }) // log error res.once('error', () => { logOutput('error') }) // log finish res.once('finish', () => { logOutput('finish') }) // log stream pipe response res.once('pipe', (readable) => { readable.on('data', (chunk) => { contentLength += chunk.length }) }) } } const handleBody = (body: any) => { handleRequestLog(body) const { basename, requestInfo } = handleBasenames(config.basenames ?? [], { pathname, method, query, body, headers, cookies, }) const storages = config.contexts?.({ req, requestInfo, basename, }) const container = createContainer({ ...storages, request: RequestContext.create(req), response: ResponseContext.create(res), basenames: BasenamesContext.create([basename]), requestInfo: RequestInfoContext.create(requestInfo), }) const maybeAsyncResponse = router.run(requestInfo, { container, onLast: () => { if (options?.onLast) { return Response.custom(options.onLast) } return NOT_FOUND_RESPONSE }, }) if (isPromise(maybeAsyncResponse)) { return maybeAsyncResponse.then((response) => handleResponse({ req, res, requestInfo, responseInfo: response.info, container, }), ) } return handleResponse({ req, res, requestInfo, responseInfo: maybeAsyncResponse.info, container, }) } if ((req as any).body) { return handleBody((req as any).body) } const maybeAsyncBody = getBody(req, config.body) if (maybeAsyncBody) { return maybeAsyncBody .then((body) => handleBody(body)) .catch((err) => { throw err }) } return handleBody(maybeAsyncBody) } const handle: HttpPipeline['handle'] = (req, res, options) => { const handleError = (error: any) => { const message = (config.errorStack ? error?.stack || error?.message : error?.message) ?? '' if (!res.headersSent) { res.statusCode = error.statusCode ?? 500 res.setHeader('Content-Type', 'text/plain') res.setHeader('Content-Length', Buffer.byteLength(message)) } if (!res.writableEnded) { res.end(Buffer.from(message)) } } try { const result = handleRequest(req, res, options) if (isPromise(result)) { return result.catch(handleError) } } catch (error: any) { handleError(error) } } const server: HttpPipeline['server'] = () => { return createServer(handle) } const listen: HttpPipeline['listen'] = (...args) => { return server().listen(...args) } return { ...router, handle, listen, server, } } export const Http = createHttpPipeline export type ResponseParams = { requestInfo: RequestInfo responseInfo: ResponseInfo req: IncomingMessage res: ServerResponse container: Container } export const handleResponse = (params: ResponseParams) => { const { req, res, requestInfo, responseInfo, container } = params const basenames = container.read(BasenamesContext) const prefix = basenames.join('') const accept = accepts(req) // handle response status const handleStatus = (status: Status = { code: 200 }) => { const { code, message } = status res.statusCode = code res.statusMessage = message || (statuses.message[code] ?? '') } // handle response headers const handleHeaders = (headers: Headers) => { const names = Object.keys(headers) for (let i = 0; i < names.length; i++) { const name = names[i] const value = headers[name] if (value) { res.setHeader(name, value) } } } // handle response cookies const handleCookies = (cookies: Cookies) => { const cookiesInstance = new CookiesClass(req, res) const names = Object.keys(cookies) for (let i = 0; i < names.length; i++) { const name = names[i] const cookie = cookies[name] if (cookie.value !== null) { cookiesInstance.set(name, `${cookie.value}`, cookie.options) } else { cookiesInstance.set(name, '', cookie.options) } } } const handleEmpty = () => { const code = responseInfo.status?.code ?? 204 handleStatus({ code }) res.end() } const handleString = (content: string) => { const length = Buffer.byteLength(content) res.setHeader('Content-Length', length) res.end(content) } const handleJson = (json: JsonType) => { const content = JSON.stringify(json) const length = Buffer.byteLength(content) res.setHeader('Content-Length', length) res.end(content) } const handleRedirect = (body: RedirectBody) => { let url = body.value if (url === 'back') { const referrer = `${req.headers['referer']}` || '/' url = referrer } // handle route name and basename if (body.usePrefix && !url.startsWith('//') && url.startsWith('/')) { url = prefix + url } const code = responseInfo.status?.code ?? 302 handleStatus({ code: statuses.redirect[code] ? code : 302, }) handleHeaders({ Location: encodeurl(url), }) if (accept.types('html')) { handleHeaders({ 'Content-Type': 'text/html; charset=utf-8', }) handleString(`Redirecting to ${escapeHtml(url)}`) } else { handleString(`Redirecting to ${url}`) } } const handleBuffer = (buffer: Buffer) => { res.setHeader('Content-Length', buffer.length) res.end(buffer) } const handleFile = async (filename: string, options?: FileBodyOptions) => { try { await access(filename, fs.constants.F_OK | fs.constants.R_OK) } catch (error: any) { return handleResponse({ ...params, responseInfo: Response.status(404).text(error.message).info, }) } const stream = fs.createReadStream(filename, options) if (!res.getHeader('Content-Type')) { const ext = path.extname(filename) const contentType = mime.contentType(ext) if (contentType) { res.setHeader('Content-Type', contentType) } } return handleStream(res, stream) } const handleBody = (body: Body | undefined): MaybeAsync<void> => { if (!body || body.type === 'empty') { return handleEmpty() } if (body.type === 'string') { return handleString(body.value) } if (body.type === 'json') { return handleJson(body.value) } if (body.type === 'redirect') { return handleRedirect(body) } if (body.type === 'stream') { return handleStream(res, body.value) } if (body.type === 'buffer') { return handleBuffer(body.value) } if (body.type === 'file') { return handleFile(body.value) } if (body.type === 'custom') { const { handler } = body const handleResponse = () => { return handler({ req, res, requestInfo, responseInfo: omitBody(responseInfo), }) } return runWithContainer(handleResponse, container) } throw new Error(`Unsupported response body: ${JSON.stringify(body, null, 2)}`) } handleStatus(responseInfo.status) if (responseInfo.cookies) { handleCookies(responseInfo.cookies) } if (responseInfo.headers) { handleHeaders(responseInfo.headers) } if (responseInfo.vary) { vary(res, responseInfo.vary) } return handleBody(responseInfo.body) } const omitBody = <T extends { body?: any }>(obj: T): Omit<T, 'body'> => { const { body, ...rest } = obj return rest } const handleStream = (res: ServerResponse, stream: Stream) => { return new Promise<void>((resolve, reject) => { stream.once('error', reject) stream.pipe(res) onfinish(res, (error) => { if (error) { reject(error) } else { resolve() } destroy(stream) }) }) }
the_stack
import * as vscode from 'vscode'; import { Httpgd } from 'httpgd'; import { HttpgdPlot, IHttpgdViewer, HttpgdViewerOptions } from './httpgdTypes'; import * as path from 'path'; import * as fs from 'fs'; import * as ejs from 'ejs'; import { config, setContext, UriIcon } from '../util'; import { extensionContext } from '../extension'; import { FocusPlotMessage, InMessage, OutMessage, ToggleStyleMessage, UpdatePlotMessage, HidePlotMessage, AddPlotMessage, PreviewPlotLayout, PreviewPlotLayoutMessage, ToggleFullWindowMessage } from './webviewMessages'; import { HttpgdIdResponse, HttpgdPlotId, HttpgdRendererId } from 'httpgd/lib/types'; import { Response } from 'node-fetch'; const commands = [ 'showViewers', 'openUrl', 'openExternal', 'showIndex', 'toggleStyle', 'toggleFullWindow', 'togglePreviewPlots', 'exportPlot', 'nextPlot', 'prevPlot', 'lastPlot', 'firstPlot', 'hidePlot', 'closePlot', 'resetPlots', 'zoomIn', 'zoomOut' ] as const; type CommandName = typeof commands[number]; export function initializeHttpgd(): HttpgdManager { const httpgdManager = new HttpgdManager(); for (const cmd of commands) { const fullCommand = `r.plot.${cmd}`; const cb = httpgdManager.getCommandHandler(cmd); vscode.commands.registerCommand(fullCommand, cb); } return httpgdManager; } export class HttpgdManager { viewers: HttpgdViewer[] = []; viewerOptions: HttpgdViewerOptions; recentlyActiveViewers: HttpgdViewer[] = []; constructor() { const htmlRoot = extensionContext.asAbsolutePath('html/httpgd'); this.viewerOptions = { parent: this, htmlRoot: htmlRoot, preserveFocus: true }; } public showViewer(urlString: string): void { const url = new URL(urlString); const host = url.host; const token = url.searchParams.get('token') || undefined; const ind = this.viewers.findIndex( (viewer) => viewer.host === host ); if (ind >= 0) { const viewer = this.viewers.splice(ind, 1)[0]; this.viewers.unshift(viewer); viewer.show(); } else { const conf = config(); const colorTheme = conf.get('plot.defaults.colorTheme', 'vscode'); this.viewerOptions.stripStyles = (colorTheme === 'vscode'); this.viewerOptions.previewPlotLayout = conf.get<PreviewPlotLayout>('plot.defaults.plotPreviewLayout', 'multirow'); this.viewerOptions.refreshTimeoutLength = conf.get('plot.timing.refreshInterval', 10); this.viewerOptions.resizeTimeoutLength = conf.get('plot.timing.resizeInterval', 100); this.viewerOptions.fullWindow = conf.get('plot.defaults.fullWindowMode', false); this.viewerOptions.token = token; const viewer = new HttpgdViewer(host, this.viewerOptions); this.viewers.unshift(viewer); } } public registerActiveViewer(viewer: HttpgdViewer): void { const ind = this.recentlyActiveViewers.indexOf(viewer); if (ind) { this.recentlyActiveViewers.splice(ind, 1); } this.recentlyActiveViewers.unshift(viewer); } public getRecentViewer(): HttpgdViewer | undefined { return this.recentlyActiveViewers.find((viewer) => !!viewer.webviewPanel); } public getNewestViewer(): HttpgdViewer | undefined { return this.viewers[0]; } public getCommandHandler(command: CommandName): (...args: any[]) => void { return (...args: any[]) => { this.handleCommand(command, ...args); }; } public async openUrl(): Promise<void> { const clipText = await vscode.env.clipboard.readText(); const val0 = clipText.trim().split(/[\n ]/)[0]; const options: vscode.InputBoxOptions = { value: val0, prompt: 'Please enter the httpgd url' }; const urlString = await vscode.window.showInputBox(options); if (urlString) { this.showViewer(urlString); } } // generic command handler public handleCommand(command: CommandName, hostOrWebviewUri?: string | vscode.Uri, ...args: any[]): void { // the number and type of arguments given to a command can vary, depending on where it was called from: // - calling from the title bar menu provides two arguments, the first of which identifies the webview // - calling from the command palette provides no arguments // - calling from a command uri provides a flexible number/type of arguments // below is an attempt to handle these different combinations efficiently and (somewhat) robustly // if (command === 'showViewers') { this.viewers.forEach(viewer => { viewer.show(true); }); return; } else if (command === 'openUrl') { void this.openUrl(); return; } // Identify the correct viewer let viewer: HttpgdViewer | undefined; if (typeof hostOrWebviewUri === 'string') { const host = hostOrWebviewUri; viewer = this.viewers.find((viewer) => viewer.host === host); } else if (hostOrWebviewUri instanceof vscode.Uri) { const uri = hostOrWebviewUri; viewer = this.viewers.find((viewer) => viewer.getPanelPath() === uri.path); } // fall back to most recent viewer viewer ||= this.getRecentViewer(); // Abort if no viewer identified if (!viewer) { return; } // Get possible arguments for commands: const stringArg = findItemOfType(args, 'string'); const boolArg = findItemOfType(args, 'boolean'); // Call corresponding method, possibly with an argument: switch (command) { case 'showIndex': { void viewer.focusPlot(stringArg); break; } case 'nextPlot': { void viewer.nextPlot(boolArg); break; } case 'prevPlot': { void viewer.prevPlot(boolArg); break; } case 'lastPlot': { void viewer.nextPlot(true); break; } case 'firstPlot': { void viewer.prevPlot(true); break; } case 'resetPlots': { viewer.resetPlots(); break; } case 'toggleStyle': { void viewer.toggleStyle(boolArg); break; } case 'togglePreviewPlots': { void viewer.togglePreviewPlots(stringArg as PreviewPlotLayout); break; } case 'closePlot': { void viewer.closePlot(stringArg); break; } case 'hidePlot': { void viewer.hidePlot(stringArg); break; } case 'exportPlot': { void viewer.exportPlot(stringArg); break; } case 'zoomIn': { void viewer.zoomIn(); break; } case 'zoomOut': { void viewer.zoomOut(); break; } case 'openExternal': { void viewer.openExternal(); break; } case 'toggleFullWindow': { void viewer.toggleFullWindow(); break; } default: { break; } } } } interface EjsData { overwriteStyles: boolean; previewPlotLayout: PreviewPlotLayout; activePlot?: HttpgdPlotId; plots: HttpgdPlot<string>[]; largePlot: HttpgdPlot<string>; host: string; asLocalPath: (relPath: string) => string; asWebViewPath: (localPath: string) => string; makeCommandUri: (command: string, ...args: any[]) => string; overwriteCssPath: string; // only used to render an individual smallPlot div: plot?: HttpgdPlot<string>; } interface ShowOptions { viewColumn: vscode.ViewColumn, preserveFocus?: boolean } export class HttpgdViewer implements IHttpgdViewer { readonly parent: HttpgdManager; readonly host: string; readonly token?: string; // Actual webview where the plot viewer is shown // Will have to be created anew, if the user closes it and the plot changes webviewPanel?: vscode.WebviewPanel; // Api that provides plot contents etc. readonly api: Httpgd; // active plots plots: HttpgdPlot<string>[] = []; // Id of the currently viewed plot activePlot?: HttpgdPlotId; // Ids of plots that are not shown, but not closed inside httpgd hiddenPlots: HttpgdPlotId[] = []; readonly defaultStripStyles: boolean = true; stripStyles: boolean; readonly defaultPreviewPlotLayout: PreviewPlotLayout = 'multirow'; previewPlotLayout: PreviewPlotLayout; readonly defaultFullWindow: boolean = false; fullWindow: boolean; // Custom file to be used instead of `styleOverwrites.css` customOverwriteCssPath?: string; // Size of the view area: viewHeight: number; viewWidth: number; // Size of the shown plot (as computed): plotHeight: number; plotWidth: number; readonly zoom0: number = 1; zoom: number = this.zoom0; resizeTimeout?: NodeJS.Timeout; readonly resizeTimeoutLength: number = 1300; refreshTimeout?: NodeJS.Timeout; readonly refreshTimeoutLength: number = 10; private lastExportUri?: vscode.Uri; readonly htmlTemplate: string; readonly smallPlotTemplate: string; readonly htmlRoot: string; readonly showOptions: ShowOptions; readonly webviewOptions: vscode.WebviewPanelOptions & vscode.WebviewOptions; // Computed properties: // Get/set active plot by index instead of id: protected get activeIndex(): number { if(!this.activePlot){ return -1; } return this.getIndex(this.activePlot); } protected set activeIndex(ind: number) { if (this.plots.length === 0) { this.activePlot = undefined; } else { ind = Math.max(ind, 0); ind = Math.min(ind, this.plots.length - 1); this.activePlot = this.plots[ind].id; } } // constructor called by the session watcher if a corresponding function was called in R // creates a new api instance itself constructor(host: string, options: HttpgdViewerOptions) { this.host = host; this.token = options.token; this.parent = options.parent; this.api = new Httpgd(this.host, this.token, true); this.api.onPlotsChanged((newState) => { void this.refreshPlots(newState.plots); }); this.api.onConnectionChanged(() => { // todo }); this.api.onDeviceActiveChanged(() => { // todo }); const conf = config(); this.customOverwriteCssPath = conf.get('plot.customStyleOverwrites', ''); const localResourceRoots = ( this.customOverwriteCssPath ? [extensionContext.extensionUri, vscode.Uri.file(path.dirname(this.customOverwriteCssPath))] : undefined ); this.htmlRoot = options.htmlRoot; this.htmlTemplate = fs.readFileSync(path.join(this.htmlRoot, 'index.ejs'), 'utf-8'); this.smallPlotTemplate = fs.readFileSync(path.join(this.htmlRoot, 'smallPlot.ejs'), 'utf-8'); this.showOptions = { viewColumn: options.viewColumn ?? vscode.ViewColumn[conf.get<string>('session.viewers.viewColumn.plot') || 'Two'], preserveFocus: !!options.preserveFocus }; this.webviewOptions = { enableCommandUris: true, enableScripts: true, retainContextWhenHidden: true, localResourceRoots: localResourceRoots }; this.defaultStripStyles = options.stripStyles ?? this.defaultStripStyles; this.stripStyles = this.defaultStripStyles; this.defaultPreviewPlotLayout = options.previewPlotLayout ?? this.defaultPreviewPlotLayout; this.previewPlotLayout = this.defaultPreviewPlotLayout; this.defaultFullWindow = options.fullWindow ?? this.defaultFullWindow; this.fullWindow = this.defaultFullWindow; this.resizeTimeoutLength = options.refreshTimeoutLength ?? this.resizeTimeoutLength; this.refreshTimeoutLength = options.refreshTimeoutLength ?? this.refreshTimeoutLength; void this.api.connect(); //void this.checkState(); } // Methods to interact with the webview // Can e.g. be called by vscode commands + menu items: // Called to create a new webview if the user closed the old one: public show(preserveFocus?: boolean): void { preserveFocus ??= this.showOptions.preserveFocus; if (!this.webviewPanel) { const showOptions = { ...this.showOptions, preserveFocus: preserveFocus }; this.webviewPanel = this.makeNewWebview(showOptions); this.refreshHtml(); } else { this.webviewPanel.reveal(undefined, preserveFocus); } this.parent.registerActiveViewer(this); } public openExternal(): void { let urlString = `http://${this.host}/live`; if (this.token) { urlString += `?token=${this.token}`; } const uri = vscode.Uri.parse(urlString); void vscode.env.openExternal(uri); } // focus a specific plot id public async focusPlot(id?: HttpgdPlotId): Promise<void> { this.activePlot = id || this.activePlot; const plt = this.plots[this.activeIndex]; if (plt.height !== this.viewHeight || plt.width !== this.viewHeight || plt.zoom !== this.zoom) { await this.refreshPlots(this.api.getPlots()); } else { this._focusPlot(); } } protected _focusPlot(plotId?: HttpgdPlotId): void { plotId ??= this.activePlot; if(!plotId){ return; } const msg: FocusPlotMessage = { message: 'focusPlot', plotId: plotId }; this.postWebviewMessage(msg); void this.setContextValues(); } // navigate through plots (supply `true` to go to end/beginning of list) public async nextPlot(last?: boolean): Promise<void> { this.activeIndex = last ? this.plots.length - 1 : this.activeIndex + 1; await this.focusPlot(); } public async prevPlot(first?: boolean): Promise<void> { this.activeIndex = first ? 0 : this.activeIndex - 1; await this.focusPlot(); } // restore closed plots, reset zoom, redraw html public resetPlots(): void { this.hiddenPlots = []; this.zoom = this.zoom0; void this.refreshPlots(this.api.getPlots(), true, true); } public hidePlot(id?: HttpgdPlotId): void { id ??= this.activePlot; if (!id) { return; } const tmpIndex = this.activeIndex; this.hiddenPlots.push(id); this.plots = this.plots.filter((plt) => !this.hiddenPlots.includes(plt.id)); if (id === this.activePlot) { this.activeIndex = tmpIndex; this._focusPlot(); } this._hidePlot(id); } protected _hidePlot(id: HttpgdPlotId): void { const msg: HidePlotMessage = { message: 'hidePlot', plotId: id }; this.postWebviewMessage(msg); } public async closePlot(id?: HttpgdPlotId): Promise<void> { id ??= this.activePlot; if (id) { this.hidePlot(id); await this.api.removePlot({ id: id }); } } public toggleStyle(force?: boolean): void { this.stripStyles = force ?? !this.stripStyles; const msg: ToggleStyleMessage = { message: 'toggleStyle', useOverwrites: this.stripStyles }; this.postWebviewMessage(msg); } public toggleFullWindow(force?: boolean): void { this.fullWindow = force ?? !this.fullWindow; const msg: ToggleFullWindowMessage = { message: 'toggleFullWindow', useFullWindow: this.fullWindow }; this.postWebviewMessage(msg); } public togglePreviewPlots(force?: PreviewPlotLayout): void { if (force) { this.previewPlotLayout = force; } else if (this.previewPlotLayout === 'multirow') { this.previewPlotLayout = 'scroll'; } else if (this.previewPlotLayout === 'scroll') { this.previewPlotLayout = 'hidden'; } else if (this.previewPlotLayout === 'hidden') { this.previewPlotLayout = 'multirow'; } const msg: PreviewPlotLayoutMessage = { message: 'togglePreviewPlotLayout', style: this.previewPlotLayout }; this.postWebviewMessage(msg); } public zoomOut(): void { if (this.zoom > 0) { this.zoom -= 0.1; void this.resizePlot(); } } public zoomIn(): void { this.zoom += 0.1; void this.resizePlot(); } public async setContextValues(mightBeInBackground: boolean = false): Promise<void> { if (this.webviewPanel?.active) { this.parent.registerActiveViewer(this); await setContext('r.plot.active', true); await setContext('r.plot.canGoBack', this.activeIndex > 0); await setContext('r.plot.canGoForward', this.activeIndex < this.plots.length - 1); } else if (!mightBeInBackground) { await setContext('r.plot.active', false); } } public getPanelPath(): string | undefined { if (!this.webviewPanel) { return undefined; } const dummyUri = this.webviewPanel.webview.asWebviewUri(vscode.Uri.file('')); const m = /^[^.]*/.exec(dummyUri.authority); const webviewId = m?.[0] || ''; return `webview-panel/webview-${webviewId}`; } protected getIndex(id: HttpgdPlotId): number { return this.plots.findIndex((plt: HttpgdPlot<string>) => plt.id === id); } protected handleResize(height: number, width: number, userTriggered: boolean = false): void { this.viewHeight = height; this.viewWidth = width; if (userTriggered || this.resizeTimeoutLength === 0) { if(this.resizeTimeout){ clearTimeout(this.resizeTimeout); } this.resizeTimeout = undefined; void this.resizePlot(); } else if (!this.resizeTimeout) { this.resizeTimeout = setTimeout(() => { void this.resizePlot().then(() => this.resizeTimeout = undefined ); }, this.resizeTimeoutLength); } } protected async resizePlot(id?: HttpgdPlotId): Promise<void> { id ??= this.activePlot; if (!id) { return; } const plt = await this.getPlotContent(id, this.viewWidth, this.viewHeight, this.zoom); this.plotWidth = plt.width; this.plotHeight = plt.height; this.updatePlot(plt); } protected async refreshPlots(plotsIdResponse: HttpgdIdResponse[], redraw: boolean = false, force: boolean = false): Promise<void> { const nPlots = this.plots.length; let plotIds = plotsIdResponse.map((x) => x.id); plotIds = plotIds.filter((id) => !this.hiddenPlots.includes(id)); const newPlotPromises = plotIds.map(async (id) => { const plot = this.plots.find((plt) => plt.id === id); if (force || !plot || id === this.activePlot) { return await this.getPlotContent(id, this.viewWidth, this.viewHeight, this.zoom); } else { return plot; } }); const newPlots = await Promise.all(newPlotPromises); const oldPlotIds = this.plots.map(plt => plt.id); this.plots = newPlots; if (this.plots.length !== nPlots) { this.activePlot = this.plots[this.plots.length - 1]?.id; } if (redraw || !this.webviewPanel) { this.refreshHtml(); } else { for (const plt of this.plots) { if (oldPlotIds.includes(plt.id)) { this.updatePlot(plt); } else { this.addPlot(plt); } } this._focusPlot(); } } protected updatePlot(plt: HttpgdPlot<string>): void { const msg: UpdatePlotMessage = { message: 'updatePlot', plotId: plt.id, svg: plt.data }; this.postWebviewMessage(msg); } protected addPlot(plt: HttpgdPlot<string>): void { const ejsData = this.makeEjsData(); ejsData.plot = plt; const html = ejs.render(this.smallPlotTemplate, ejsData); const msg: AddPlotMessage = { message: 'addPlot', html: html }; this.postWebviewMessage(msg); void this.focusPlot(plt.id); void this.setContextValues(); } // get content of a single plot protected async getPlotContent(id: HttpgdPlotId, width: number, height: number, zoom: number): Promise<HttpgdPlot<string>> { const args = { id: id, height: height, width: width, zoom: zoom, renderer: 'svgp' }; const plotContent = await this.api.getPlot(args); const svg = await plotContent?.text() || ''; const plt: HttpgdPlot<string> = { id: id, data: svg, height: height, width: width, zoom: zoom, }; this.viewHeight ??= plt.height; this.viewWidth ??= plt.width; return plt; } // functions for initial or re-drawing of html: protected refreshHtml(): void { this.webviewPanel ??= this.makeNewWebview(); this.webviewPanel.webview.html = ''; this.webviewPanel.webview.html = this.makeHtml(); // make sure that fullWindow is set correctly: this.toggleFullWindow(this.fullWindow); void this.setContextValues(true); } protected makeHtml(): string { const ejsData = this.makeEjsData(); const html = ejs.render(this.htmlTemplate, ejsData); return html; } protected makeEjsData(): EjsData { const asLocalPath = (relPath: string) => { if (!this.webviewPanel) { return relPath; } const localUri = vscode.Uri.file(path.join(this.htmlRoot, relPath)); return localUri.fsPath; }; const asWebViewPath = (localPath: string) => { if (!this.webviewPanel) { return localPath; } const localUri = vscode.Uri.file(path.join(this.htmlRoot, localPath)); const webViewUri = this.webviewPanel.webview.asWebviewUri(localUri); return webViewUri.toString(); }; const makeCommandUri = (command: string, ...args: any[]) => { const argString = encodeURIComponent(JSON.stringify(args)); return `command:${command}?${argString}`; }; let overwriteCssPath = ''; if (this.customOverwriteCssPath) { const uri = vscode.Uri.file(this.customOverwriteCssPath); overwriteCssPath = this.webviewPanel?.webview.asWebviewUri(uri).toString() || ''; } else { overwriteCssPath = asWebViewPath('styleOverwrites.css'); } const ejsData: EjsData = { overwriteStyles: this.stripStyles, previewPlotLayout: this.previewPlotLayout, plots: this.plots, largePlot: this.plots[this.activeIndex], activePlot: this.activePlot, host: this.host, asLocalPath: asLocalPath, asWebViewPath: asWebViewPath, makeCommandUri: makeCommandUri, overwriteCssPath: overwriteCssPath }; return ejsData; } protected makeNewWebview(showOptions?: ShowOptions): vscode.WebviewPanel { const webviewPanel = vscode.window.createWebviewPanel( 'RPlot', 'R Plot', showOptions || this.showOptions, this.webviewOptions ); webviewPanel.iconPath = new UriIcon('graph'); webviewPanel.onDidDispose(() => this.webviewPanel = undefined); webviewPanel.onDidChangeViewState(() => { void this.setContextValues(); }); webviewPanel.webview.onDidReceiveMessage((e: OutMessage) => { this.handleWebviewMessage(e); }); return webviewPanel; } protected handleWebviewMessage(msg: OutMessage): void { if (msg.message === 'log') { console.log(msg.body); } else if (msg.message === 'resize') { const height = msg.height; const width = msg.width; const userTriggered = msg.userTriggered; void this.handleResize(height, width, userTriggered); } } protected postWebviewMessage(msg: InMessage): void { this.webviewPanel?.webview.postMessage(msg); } // export plot // if no format supplied, show a quickpick menu etc. // if no filename supplied, show selector window public async exportPlot(id?: HttpgdPlotId, rendererId?: HttpgdRendererId, outFile?: string): Promise<void> { // make sure id is valid or return: id ||= this.activePlot || this.plots[this.plots.length - 1]?.id; const plot = this.plots.find((plt) => plt.id === id); if (!plot) { void vscode.window.showWarningMessage('No plot available for export.'); return; } // make sure format is valid or return: if (!rendererId) { const renderers = this.api.getRenderers(); const qpItems = renderers.map(renderer => ({ label: renderer.name, detail: renderer.descr, id: renderer.id })); const options: vscode.QuickPickOptions = { placeHolder: 'Please choose a file format' }; // format = await vscode.window.showQuickPick(formats, options); const qpPick = await vscode.window.showQuickPick(qpItems, options); rendererId = qpPick?.id; if(!rendererId){ return; } } // make sure outFile is valid or return: if (!outFile) { const options: vscode.SaveDialogOptions = {}; // Suggest a file extension: const renderer = this.api.getRenderers().find(r => r.id === rendererId); const ext = renderer?.ext.replace(/^\./, ''); // try to set default URI: if(this.lastExportUri){ const noExtPath = this.lastExportUri.fsPath.replace(/\.[^.]*$/, ''); const defaultPath = noExtPath + (ext ? `.${ext}` : ''); options.defaultUri = vscode.Uri.file(defaultPath); } else { // construct default Uri const defaultFolder = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; if(defaultFolder){ const defaultName = 'plot' + (ext ? `.${ext}` : ''); options.defaultUri = vscode.Uri.file(path.join(defaultFolder, defaultName)); } } // set file extension filter if(ext && renderer?.name){ options.filters = { [renderer.name]: [ext], ['All']: ['*'], }; } const outUri = await vscode.window.showSaveDialog(options); if(outUri){ this.lastExportUri = outUri; outFile = outUri.fsPath; } else { return; } } // get plot: const plt = await this.api.getPlot({ id: this.activePlot, renderer: rendererId }) as unknown as Response; // I am not sure why eslint thinks this is the // browser Response object and not the node-fetch one. // cross-fetch problem or config problem in vscode-r? const dest = fs.createWriteStream(outFile); dest.on('error', (err) => void vscode.window.showErrorMessage( `Export failed: ${err.message}` )); dest.on('close', () => void vscode.window.showInformationMessage( `Export done: ${outFile}` )); void plt.body.pipe(dest); } // Dispose-function to clean up when vscode closes // E.g. to close connections etc., notify R, ... public dispose(): void { this.api.disconnect(); } } // helper function to handle argument lists that might contain (useless) extra arguments function findItemOfType(arr: any[], type: 'string'): string | undefined; function findItemOfType(arr: any[], type: 'boolean'): boolean | undefined; function findItemOfType(arr: any[], type: 'number'): number | undefined; function findItemOfType<T = unknown>(arr: any[], type: string): T { const item = arr.find((elm) => typeof elm === type) as T; return item; }
the_stack
import { ServerType, STATE_CLOSED, STATE_CLOSING } from './common'; import { now, makeStateMachine, calculateDurationInMs, makeInterruptibleAsyncInterval, ns, EventEmitterWithState } from '../utils'; import { connect } from '../cmap/connect'; import { Connection, ConnectionOptions } from '../cmap/connection'; import { MongoNetworkError, AnyError } from '../error'; import { Long, Document } from '../bson'; import { ServerHeartbeatStartedEvent, ServerHeartbeatSucceededEvent, ServerHeartbeatFailedEvent } from './events'; import { Server } from './server'; import type { InterruptibleAsyncInterval, Callback } from '../utils'; import type { TopologyVersion } from './server_description'; import { CancellationToken, TypedEventEmitter } from '../mongo_types'; /** @internal */ const kServer = Symbol('server'); /** @internal */ const kMonitorId = Symbol('monitorId'); /** @internal */ const kConnection = Symbol('connection'); /** @internal */ const kCancellationToken = Symbol('cancellationToken'); /** @internal */ const kRTTPinger = Symbol('rttPinger'); /** @internal */ const kRoundTripTime = Symbol('roundTripTime'); const STATE_IDLE = 'idle'; const STATE_MONITORING = 'monitoring'; const stateTransition = makeStateMachine({ [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED], [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] }); const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); function isInCloseState(monitor: Monitor) { return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING; } /** @internal */ export interface MonitorPrivate { state: string; } /** @public */ export interface MonitorOptions extends Omit<ConnectionOptions, 'id' | 'generation' | 'hostAddress'> { connectTimeoutMS: number; heartbeatFrequencyMS: number; minHeartbeatFrequencyMS: number; } /** @public */ export type MonitorEvents = { serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; resetServer(error?: Error): void; resetConnectionPool(): void; close(): void; } & EventEmitterWithState; /** @internal */ export class Monitor extends TypedEventEmitter<MonitorEvents> { /** @internal */ s: MonitorPrivate; address: string; options: Readonly< Pick<MonitorOptions, 'connectTimeoutMS' | 'heartbeatFrequencyMS' | 'minHeartbeatFrequencyMS'> >; connectOptions: ConnectionOptions; [kServer]: Server; [kConnection]?: Connection; [kCancellationToken]: CancellationToken; /** @internal */ [kMonitorId]?: InterruptibleAsyncInterval; [kRTTPinger]?: RTTPinger; constructor(server: Server, options: MonitorOptions) { super(); this[kServer] = server; this[kConnection] = undefined; this[kCancellationToken] = new CancellationToken(); this[kCancellationToken].setMaxListeners(Infinity); this[kMonitorId] = undefined; this.s = { state: STATE_CLOSED }; this.address = server.description.address; this.options = Object.freeze({ connectTimeoutMS: options.connectTimeoutMS ?? 10000, heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 10000, minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500 }); const cancellationToken = this[kCancellationToken]; // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration const connectOptions = Object.assign( { id: '<monitor>' as const, generation: server.s.pool.generation, connectionType: Connection, cancellationToken, hostAddress: server.description.hostAddress }, options, // force BSON serialization options { raw: false, promoteLongs: true, promoteValues: true, promoteBuffers: true } ); // ensure no authentication is used for monitoring delete connectOptions.credentials; if (connectOptions.autoEncrypter) { delete connectOptions.autoEncrypter; } this.connectOptions = Object.freeze(connectOptions); } connect(): void { if (this.s.state !== STATE_CLOSED) { return; } // start const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; this[kMonitorId] = makeInterruptibleAsyncInterval(monitorServer(this), { interval: heartbeatFrequencyMS, minInterval: minHeartbeatFrequencyMS, immediate: true }); } requestCheck(): void { if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { return; } this[kMonitorId]?.wake(); } reset(): void { const topologyVersion = this[kServer].description.topologyVersion; if (isInCloseState(this) || topologyVersion == null) { return; } stateTransition(this, STATE_CLOSING); resetMonitorState(this); // restart monitor stateTransition(this, STATE_IDLE); // restart monitoring const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; this[kMonitorId] = makeInterruptibleAsyncInterval(monitorServer(this), { interval: heartbeatFrequencyMS, minInterval: minHeartbeatFrequencyMS }); } close(): void { if (isInCloseState(this)) { return; } stateTransition(this, STATE_CLOSING); resetMonitorState(this); // close monitor this.emit('close'); stateTransition(this, STATE_CLOSED); } } function resetMonitorState(monitor: Monitor) { monitor[kMonitorId]?.stop(); monitor[kMonitorId] = undefined; monitor[kRTTPinger]?.close(); monitor[kRTTPinger] = undefined; monitor[kCancellationToken].emit('cancel'); monitor[kConnection]?.destroy({ force: true }); monitor[kConnection] = undefined; } function checkServer(monitor: Monitor, callback: Callback<Document>) { let start = now(); monitor.emit(Server.SERVER_HEARTBEAT_STARTED, new ServerHeartbeatStartedEvent(monitor.address)); function failureHandler(err: AnyError) { monitor[kConnection]?.destroy({ force: true }); monitor[kConnection] = undefined; monitor.emit( Server.SERVER_HEARTBEAT_FAILED, new ServerHeartbeatFailedEvent(monitor.address, calculateDurationInMs(start), err) ); monitor.emit('resetServer', err); monitor.emit('resetConnectionPool'); callback(err); } const connection = monitor[kConnection]; if (connection && !connection.closed) { const { serverApi, helloOk } = connection; const connectTimeoutMS = monitor.options.connectTimeoutMS; const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; const topologyVersion = monitor[kServer].description.topologyVersion; const isAwaitable = topologyVersion != null; const cmd = { [serverApi?.version || helloOk ? 'hello' : 'ismaster']: true, ...(isAwaitable && topologyVersion ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } : {}) }; const options = isAwaitable ? { socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, exhaustAllowed: true } : { socketTimeoutMS: connectTimeoutMS }; if (isAwaitable && monitor[kRTTPinger] == null) { monitor[kRTTPinger] = new RTTPinger( monitor[kCancellationToken], Object.assign( { heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions ) ); } connection.command(ns('admin.$cmd'), cmd, options, (err, isMaster) => { if (err) { failureHandler(err); return; } if ('isWritablePrimary' in isMaster) { // Provide pre-hello-style response document. isMaster.ismaster = isMaster.isWritablePrimary; } const rttPinger = monitor[kRTTPinger]; const duration = isAwaitable && rttPinger ? rttPinger.roundTripTime : calculateDurationInMs(start); monitor.emit( Server.SERVER_HEARTBEAT_SUCCEEDED, new ServerHeartbeatSucceededEvent(monitor.address, duration, isMaster) ); // if we are using the streaming protocol then we immediately issue another `started` // event, otherwise the "check" is complete and return to the main monitor loop if (isAwaitable && isMaster.topologyVersion) { monitor.emit( Server.SERVER_HEARTBEAT_STARTED, new ServerHeartbeatStartedEvent(monitor.address) ); start = now(); } else { monitor[kRTTPinger]?.close(); monitor[kRTTPinger] = undefined; callback(undefined, isMaster); } }); return; } // connecting does an implicit `ismaster` connect(monitor.connectOptions, (err, conn) => { if (err) { monitor[kConnection] = undefined; // we already reset the connection pool on network errors in all cases if (!(err instanceof MongoNetworkError)) { monitor.emit('resetConnectionPool'); } failureHandler(err); return; } if (conn) { if (isInCloseState(monitor)) { conn.destroy({ force: true }); return; } monitor[kConnection] = conn; monitor.emit( Server.SERVER_HEARTBEAT_SUCCEEDED, new ServerHeartbeatSucceededEvent( monitor.address, calculateDurationInMs(start), conn.ismaster ) ); callback(undefined, conn.ismaster); } }); } function monitorServer(monitor: Monitor) { return (callback: Callback) => { stateTransition(monitor, STATE_MONITORING); function done() { if (!isInCloseState(monitor)) { stateTransition(monitor, STATE_IDLE); } callback(); } checkServer(monitor, (err, isMaster) => { if (err) { // otherwise an error occurred on initial discovery, also bail if (monitor[kServer].description.type === ServerType.Unknown) { monitor.emit('resetServer', err); return done(); } } // if the check indicates streaming is supported, immediately reschedule monitoring if (isMaster && isMaster.topologyVersion) { setTimeout(() => { if (!isInCloseState(monitor)) { monitor[kMonitorId]?.wake(); } }, 0); } done(); }); }; } function makeTopologyVersion(tv: TopologyVersion) { return { processId: tv.processId, // tests mock counter as just number, but in a real situation counter should always be a Long counter: Long.isLong(tv.counter) ? tv.counter : Long.fromNumber(tv.counter) }; } /** @internal */ export interface RTTPingerOptions extends ConnectionOptions { heartbeatFrequencyMS: number; } /** @internal */ export class RTTPinger { /** @internal */ [kConnection]?: Connection; /** @internal */ [kCancellationToken]: CancellationToken; /** @internal */ [kRoundTripTime]: number; /** @internal */ [kMonitorId]: NodeJS.Timeout; closed: boolean; constructor(cancellationToken: CancellationToken, options: RTTPingerOptions) { this[kConnection] = undefined; this[kCancellationToken] = cancellationToken; this[kRoundTripTime] = 0; this.closed = false; const heartbeatFrequencyMS = options.heartbeatFrequencyMS; this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); } get roundTripTime(): number { return this[kRoundTripTime]; } close(): void { this.closed = true; clearTimeout(this[kMonitorId]); this[kConnection]?.destroy({ force: true }); this[kConnection] = undefined; } } function measureRoundTripTime(rttPinger: RTTPinger, options: RTTPingerOptions) { const start = now(); options.cancellationToken = rttPinger[kCancellationToken]; const heartbeatFrequencyMS = options.heartbeatFrequencyMS; if (rttPinger.closed) { return; } function measureAndReschedule(conn?: Connection) { if (rttPinger.closed) { conn?.destroy({ force: true }); return; } if (rttPinger[kConnection] == null) { rttPinger[kConnection] = conn; } rttPinger[kRoundTripTime] = calculateDurationInMs(start); rttPinger[kMonitorId] = setTimeout( () => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS ); } const connection = rttPinger[kConnection]; if (connection == null) { connect(options, (err, conn) => { if (err) { rttPinger[kConnection] = undefined; rttPinger[kRoundTripTime] = 0; return; } measureAndReschedule(conn); }); return; } connection.command(ns('admin.$cmd'), { ismaster: 1 }, undefined, err => { if (err) { rttPinger[kConnection] = undefined; rttPinger[kRoundTripTime] = 0; return; } measureAndReschedule(); }); }
the_stack
import {bodyCost} from '../creepSetups/CreepSetup'; import {isCreep} from '../declarations/typeGuards'; import {profile} from '../profiler/decorator'; import {ExpansionEvaluator} from '../strategy/ExpansionEvaluator'; import {getCacheExpiration, irregularExponentialMovingAverage} from '../utilities/utils'; import {Zerg} from '../zerg/Zerg'; import {MY_USERNAME} from '../~settings'; const RECACHE_TIME = 2500; const OWNED_RECACHE_TIME = 1000; const ROOM_CREEP_HISTORY_TICKS = 25; const SCORE_RECALC_PROB = 0.05; const FALSE_SCORE_RECALC_PROB = 0.01; const RoomIntelMemoryDefaults = {}; @profile export class RoomIntel { /** * Mark a room as being visible this tick */ private static markVisible(room: Room): void { room.memory[_MEM.TICK] = Game.time; } /** * Returns the last tick at which the room was visible, or -100 */ static lastVisible(roomName: string): number { if (Memory.rooms[roomName]) { return Memory.rooms[roomName][_MEM.TICK] || -100; } else { return -100; } } /** * Records all info for permanent room objects, e.g. sources, controllers, etc. */ private static recordPermanentObjects(room: Room): void { const savedSources: SavedSource[] = []; for (const source of room.sources) { const container = source.pos.findClosestByLimitedRange(room.containers, 2); savedSources.push({ c : source.pos.coordName, contnr: container ? container.pos.coordName : undefined }); } room.memory[_RM.SOURCES] = savedSources; room.memory[_RM.CONTROLLER] = room.controller ? { c : room.controller.pos.coordName, [_RM_CTRL.LEVEL] : room.controller.level, [_RM_CTRL.OWNER] : room.controller.owner ? room.controller.owner.username : undefined, [_RM_CTRL.RESERVATION] : room.controller.reservation ? { [_RM_CTRL.RES_USERNAME] : room.controller.reservation.username, [_RM_CTRL.RES_TICKSTOEND]: room.controller.reservation.ticksToEnd, } : undefined, [_RM_CTRL.SAFEMODE] : room.controller.safeMode, [_RM_CTRL.SAFEMODE_AVAILABLE]: room.controller.safeModeAvailable, [_RM_CTRL.SAFEMODE_COOLDOWN] : room.controller.safeModeCooldown, [_RM_CTRL.PROGRESS] : room.controller.progress, [_RM_CTRL.PROGRESS_TOTAL] : room.controller.progressTotal } : undefined; room.memory[_RM.MINERAL] = room.mineral ? { c : room.mineral.pos.coordName, [_RM_MNRL.DENSITY] : room.mineral.density, [_RM_MNRL.MINERALTYPE]: room.mineral.mineralType } : undefined; room.memory[_RM.SKLAIRS] = _.map(room.keeperLairs, lair => { return {c: lair.pos.coordName}; }); room.memory[_RM.PORTALS] = _.map(room.portals, portal => { const dest = portal.destination instanceof RoomPosition ? portal.destination.name : portal.destination; const expiration = portal.ticksToDecay != undefined ? Game.time + portal.ticksToDecay : Game.time + 1e6; return {c: portal.pos.coordName, dest: dest, [_MEM.EXPIRATION]: expiration}; }); if (room.controller && room.controller.owner) { room.memory[_RM.IMPORTANT_STRUCTURES] = { [_RM_IS.TOWERS] : _.map(room.towers, t => t.pos.coordName), [_RM_IS.SPAWNS] : _.map(room.spawns, s => s.pos.coordName), [_RM_IS.STORAGE] : room.storage ? room.storage.pos.coordName : undefined, [_RM_IS.TERMINAL]: room.terminal ? room.terminal.pos.coordName : undefined, [_RM_IS.WALLS] : _.map(room.walls, w => w.pos.coordName), [_RM_IS.RAMPARTS]: _.map(room.ramparts, r => r.pos.coordName), }; } else { room.memory[_RM.IMPORTANT_STRUCTURES] = undefined; } room.memory[_MEM.TICK] = Game.time; } /** * Update time-sensitive reservation and safemode info */ private static recordControllerInfo(controller: StructureController): void { const savedController = controller.room.memory[_RM.CONTROLLER]; if (savedController) { savedController[_RM_CTRL.RESERVATION] = controller.reservation ? { [_RM_CTRL.RES_USERNAME] : controller.reservation.username, [_RM_CTRL.RES_TICKSTOEND]: controller.reservation.ticksToEnd, } : undefined; savedController[_RM_CTRL.SAFEMODE] = controller.safeMode; savedController[_RM_CTRL.SAFEMODE_COOLDOWN] = controller.safeModeCooldown; } } static inSafeMode(roomName: string): boolean { if (!!Memory.rooms[roomName] && !!Memory.rooms[roomName][_RM.CONTROLLER]) { const safemode = Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.SAFEMODE]; const tick = Memory.rooms[roomName][_MEM.EXPIRATION]; if (safemode && tick) { return Game.time < tick + safemode; } } return false; } static safeModeCooldown(roomName: string): number | undefined { if (Memory.rooms[roomName] && Memory.rooms[roomName][_RM.CONTROLLER] && Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.SAFEMODE_COOLDOWN]) { const smcooldown = Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.SAFEMODE_COOLDOWN]; const tick = Memory.rooms[roomName][_MEM.EXPIRATION]; if (smcooldown && tick) { return smcooldown - (Game.time - tick); } } } private static recomputeScoreIfNecessary(room: Room): boolean { if (room.memory[_RM.EXPANSION_DATA] == false) { // room is uninhabitable or owned if (Math.random() < FALSE_SCORE_RECALC_PROB) { // false scores get evaluated very occasionally return ExpansionEvaluator.computeExpansionData(room); } } else { // if the room is not uninhabitable if (!room.memory[_RM.EXPANSION_DATA] || Math.random() < SCORE_RECALC_PROB) { // recompute some of the time return ExpansionEvaluator.computeExpansionData(room); } } return false; } private static updateInvasionData(room: Room): void { if (!room.memory[_RM.INVASION_DATA]) { room.memory[_RM.INVASION_DATA] = { harvested: 0, lastSeen : 0, }; } const sources = room.sources; const invasionData = room.memory[_RM.INVASION_DATA]!; for (const source of sources) { if (source.ticksToRegeneration == 1) { invasionData.harvested += source.energyCapacity - source.energy; } } if (room.invaders.length > 0) { invasionData.harvested = 0; invasionData.lastSeen = Game.time; } } private static updateHarvestData(room: Room): void { if (!room.memory[_RM.HARVEST]) { room.memory[_RM.HARVEST] = { [_ROLLING_STATS.AMOUNT] : 0, [_ROLLING_STATS.AVG10K] : _.sum(room.sources, s => s.energyCapacity / ENERGY_REGEN_TIME), [_ROLLING_STATS.AVG100K]: _.sum(room.sources, s => s.energyCapacity / ENERGY_REGEN_TIME), [_ROLLING_STATS.AVG1M] : _.sum(room.sources, s => s.energyCapacity / ENERGY_REGEN_TIME), [_MEM.TICK] : Game.time, }; } const harvest = room.memory[_RM.HARVEST] as RollingStats; for (const source of room.sources) { // TODO: this implicitly assumes all energy is harvested by me if (source.ticksToRegeneration == 1) { const dEnergy = source.energyCapacity - source.energy; const dTime = Game.time - harvest[_MEM.TICK] + 1; // +1 to avoid division by zero errors harvest[_ROLLING_STATS.AMOUNT] += dEnergy; harvest[_ROLLING_STATS.AVG10K] = +(irregularExponentialMovingAverage( dEnergy / dTime, harvest[_ROLLING_STATS.AVG10K], dTime, 10000)).toFixed(7); harvest[_ROLLING_STATS.AVG100K] = +(irregularExponentialMovingAverage( dEnergy / dTime, harvest[_ROLLING_STATS.AVG10K], dTime, 100000)).toFixed(7); harvest[_ROLLING_STATS.AVG1M] = +(irregularExponentialMovingAverage( dEnergy / dTime, harvest[_ROLLING_STATS.AVG10K], dTime, 1000000)).toFixed(7); harvest[_MEM.TICK] = Game.time; } } } private static updateCasualtyData(room: Room): void { if (!room.memory[_RM.CASUALTIES]) { room.memory[_RM.CASUALTIES] = { cost: { [_ROLLING_STATS.AMOUNT] : 0, [_ROLLING_STATS.AVG10K] : 0, [_ROLLING_STATS.AVG100K]: 0, [_ROLLING_STATS.AVG1M] : 0, [_MEM.TICK] : Game.time, } }; } const casualtiesCost = room.memory[_RM.CASUALTIES]!.cost as RollingStats; for (const tombstone of room.tombstones) { if (tombstone.ticksToDecay == 1) { // record any casualties, which are my creeps which died prematurely if ((tombstone.creep.ticksToLive || 0) > 1 && tombstone.creep.owner.username == MY_USERNAME && isCreep(tombstone.creep)) { const body = _.map(tombstone.creep.body, part => part.type); const lifetime = body.includes(CLAIM) ? CREEP_CLAIM_LIFE_TIME : CREEP_LIFE_TIME; const dCost = bodyCost(body) * (tombstone.creep.ticksToLive || 0) / lifetime; const dTime = Game.time - casualtiesCost[_MEM.TICK] + 1; casualtiesCost[_ROLLING_STATS.AMOUNT] += dCost; casualtiesCost[_ROLLING_STATS.AVG10K] = +(irregularExponentialMovingAverage( dCost / dTime, casualtiesCost[_ROLLING_STATS.AVG10K], dTime, 10000)).toFixed(7); casualtiesCost[_ROLLING_STATS.AVG100K] = +(irregularExponentialMovingAverage( dCost / dTime, casualtiesCost[_ROLLING_STATS.AVG100K], dTime, 100000)).toFixed(7); casualtiesCost[_ROLLING_STATS.AVG1M] = +(irregularExponentialMovingAverage( dCost / dTime, casualtiesCost[_ROLLING_STATS.AVG1M], dTime, 1000000)).toFixed(7); casualtiesCost[_MEM.TICK] = Game.time; } } } } /** * Get the pos a creep was in on the previous tick */ static getPreviousPos(creep: Creep | Zerg): RoomPosition { if (creep.room.memory[_RM.PREV_POSITIONS] && creep.room.memory[_RM.PREV_POSITIONS]![creep.id]) { return derefRoomPosition(creep.room.memory[_RM.PREV_POSITIONS]![creep.id]); } else { return creep.pos; // no data } } private static recordCreepPositions(room: Room): void { room.memory[_RM.PREV_POSITIONS] = {}; for (const creep of room.find(FIND_CREEPS)) { room.memory[_RM.PREV_POSITIONS]![creep.id] = creep.pos; } } private static recordCreepOccupancies(room: Room): void { if (!room.memory[_RM.CREEPS_IN_ROOM]) { room.memory[_RM.CREEPS_IN_ROOM] = {}; } const creepsInRoom = room.memory[_RM.CREEPS_IN_ROOM]!; for (const tick in creepsInRoom) { if (parseInt(tick, 10) < Game.time - ROOM_CREEP_HISTORY_TICKS) { delete creepsInRoom[tick]; } } creepsInRoom[Game.time] = _.map(room.hostiles, creep => creep.name); } private static recordSafety(room: Room): void { if (!room.memory[_RM.SAFETY]) { room.memory[_RM.SAFETY] = { safeFor : 0, unsafeFor: 0, safety1k : 1, safety10k: 1, tick : Game.time }; } let safety: number; const safetyData = room.memory[_RM.SAFETY] as SafetyData; if (room.dangerousHostiles.length > 0) { safetyData.safeFor = 0; safetyData.unsafeFor += 1; safety = 0; } else { safetyData.safeFor += 1; safetyData.unsafeFor = 0; safety = 1; } // Compute rolling averages const dTime = Game.time - safetyData.tick; safetyData.safety1k = +(irregularExponentialMovingAverage( safety, safetyData.safety1k, dTime, 1000)).toFixed(5); safetyData.safety10k = +(irregularExponentialMovingAverage( safety, safetyData.safety10k, dTime, 10000)).toFixed(5); safetyData.tick = Game.time; } static getSafetyData(roomName: string): SafetyData { if (!Memory.rooms[roomName]) { Memory.rooms[roomName] = {}; } if (!Memory.rooms[roomName][_RM.SAFETY]) { Memory.rooms[roomName][_RM.SAFETY] = { safeFor : 0, unsafeFor: 0, safety1k : 1, safety10k: 1, tick : Game.time }; } return Memory.rooms[roomName][_RM.SAFETY]!; } static isInvasionLikely(room: Room): boolean { const data = room.memory[_RM.INVASION_DATA]; if (!data) return false; if (data.lastSeen > 20000) { // maybe room is surrounded by owned/reserved rooms and invasions aren't possible return false; } switch (room.sources.length) { case 1: return data.harvested > 90000; case 2: return data.harvested > 75000; case 3: return data.harvested > 65000; default: // shouldn't ever get here return false; } } static roomOwnedBy(roomName: string): string | undefined { if (Memory.rooms[roomName] && Memory.rooms[roomName][_RM.CONTROLLER] && Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.OWNER]) { if (Game.time - (Memory.rooms[roomName][_MEM.TICK] || 0) < 25000) { // ownership expires after 25k ticks return Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.OWNER]; } } } static roomReservedBy(roomName: string): string | undefined { if (Memory.rooms[roomName] && Memory.rooms[roomName][_RM.CONTROLLER] && Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.RESERVATION]) { if (Game.time - (Memory.rooms[roomName][_MEM.TICK] || 0) < 10000) { // reservation expires after 10k ticks return Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.RESERVATION]![_RM_CTRL.RES_USERNAME]; } } } static roomReservationRemaining(roomName: string): number { if (Memory.rooms[roomName] && Memory.rooms[roomName][_RM.CONTROLLER] && Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.RESERVATION]) { const ticksToEnd = Memory.rooms[roomName][_RM.CONTROLLER]![_RM_CTRL.RESERVATION]![_RM_CTRL.RES_TICKSTOEND]; const timeSinceLastSeen = Game.time - (Memory.rooms[roomName][_MEM.TICK] || 0); return ticksToEnd - timeSinceLastSeen; } return 0; } static run(): void { let alreadyComputedScore = false; for (const name in Game.rooms) { const room: Room = Game.rooms[name]; this.markVisible(room); this.recordSafety(room); // Track invasion data, harvesting, and casualties for all colony rooms and outposts if (Overmind.colonyMap[room.name]) { // if it is an owned or outpost room this.updateInvasionData(room); this.updateHarvestData(room); this.updateCasualtyData(room); } // Record previous creep positions if needed (RoomIntel.run() is executed at end of each tick) if (room.hostiles.length > 0) { this.recordCreepPositions(room); if (room.my) { this.recordCreepOccupancies(room); } } // Record location of permanent objects in room and recompute score as needed if (Game.time >= (room.memory[_MEM.EXPIRATION] || 0)) { this.recordPermanentObjects(room); if (!alreadyComputedScore) { alreadyComputedScore = this.recomputeScoreIfNecessary(room); } // Refresh cache const recacheTime = room.owner ? OWNED_RECACHE_TIME : RECACHE_TIME; room.memory[_MEM.EXPIRATION] = getCacheExpiration(recacheTime, 250); } if (room.controller && Game.time % 5 == 0) { this.recordControllerInfo(room.controller); } } } } // For debugging purposes global.RoomIntel = RoomIntel;
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>Access is denied. Your account is not authorized to perform this operation.</p> */ export interface AccessDeniedException extends __SmithyException, $MetadataBearer { name: "AccessDeniedException"; $fault: "client"; Message?: string; } export namespace AccessDeniedException { /** * @internal */ export const filterSensitiveLog = (obj: AccessDeniedException): any => ({ ...obj, }); } export enum CmkType { AO_CMK = "AWS_OWNED_KMS_KEY", CM_CMK = "CUSTOMER_MANAGED_KMS_KEY", } /** * <p>The Data Store is in a transition state and the user requested action can not be performed.</p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; Message?: string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } export enum FHIRVersion { R4 = "R4", } export enum PreloadDataType { SYNTHEA = "SYNTHEA", } /** * <p> The input properties for the preloaded Data Store. Only data preloaded from Synthea is supported.</p> */ export interface PreloadDataConfig { /** * <p>The type of preloaded data. Only Synthea preloaded data is supported.</p> */ PreloadDataType: PreloadDataType | string | undefined; } export namespace PreloadDataConfig { /** * @internal */ export const filterSensitiveLog = (obj: PreloadDataConfig): any => ({ ...obj, }); } /** * <p> * The customer-managed-key(CMK) used when creating a Data Store. If a customer owned key is not specified, an AWS owned key will be used for encryption. * </p> */ export interface KmsEncryptionConfig { /** * <p> * The type of customer-managed-key(CMK) used for encyrption. The two types of supported CMKs are customer owned CMKs and AWS owned CMKs. * </p> */ CmkType: CmkType | string | undefined; /** * <p> * The KMS encryption key id/alias used to encrypt the Data Store contents at rest. * </p> */ KmsKeyId?: string; } export namespace KmsEncryptionConfig { /** * @internal */ export const filterSensitiveLog = (obj: KmsEncryptionConfig): any => ({ ...obj, }); } /** * <p> * The server-side encryption key configuration for a customer provided encryption key. * </p> */ export interface SseConfiguration { /** * <p> * The KMS encryption configuration used to provide details for data encryption. * </p> */ KmsEncryptionConfig: KmsEncryptionConfig | undefined; } export namespace SseConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: SseConfiguration): any => ({ ...obj, }); } /** * <p> * A tag is a label consisting of a user-defined key and value. The form for tags is {"Key", "Value"} * </p> */ export interface Tag { /** * <p> * The key portion of a tag. Tag keys are case sensitive. * </p> */ Key: string | undefined; /** * <p> * The value portion of tag. Tag values are case sensitive. * </p> */ Value: string | undefined; } export namespace Tag { /** * @internal */ export const filterSensitiveLog = (obj: Tag): any => ({ ...obj, }); } export interface CreateFHIRDatastoreRequest { /** * <p>The user generated name for the Data Store.</p> */ DatastoreName?: string; /** * <p>The FHIR version of the Data Store. The only supported version is R4.</p> */ DatastoreTypeVersion: FHIRVersion | string | undefined; /** * <p> * The server-side encryption key configuration for a customer provided encryption key specified for creating a Data Store. * </p> */ SseConfiguration?: SseConfiguration; /** * <p>Optional parameter to preload data upon creation of the Data Store. Currently, the only * supported preloaded data is synthetic data generated from Synthea.</p> */ PreloadDataConfig?: PreloadDataConfig; /** * <p>Optional user provided token used for ensuring idempotency.</p> */ ClientToken?: string; /** * <p> * Resource tags that are applied to a Data Store when it is created. * </p> */ Tags?: Tag[]; } export namespace CreateFHIRDatastoreRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateFHIRDatastoreRequest): any => ({ ...obj, }); } export enum DatastoreStatus { ACTIVE = "ACTIVE", CREATING = "CREATING", DELETED = "DELETED", DELETING = "DELETING", } export interface CreateFHIRDatastoreResponse { /** * <p>The AWS-generated Data Store id. This id is in the output from the initial Data Store * creation call.</p> */ DatastoreId: string | undefined; /** * <p>The datastore ARN is generated during the creation of the Data Store and can be found in * the output from the initial Data Store creation call.</p> */ DatastoreArn: string | undefined; /** * <p>The status of the FHIR Data Store. Possible statuses are ‘CREATING’, ‘ACTIVE’, ‘DELETING’, * ‘DELETED’.</p> */ DatastoreStatus: DatastoreStatus | string | undefined; /** * <p>The AWS endpoint for the created Data Store. For preview, only US-east-1 endpoints are * supported.</p> */ DatastoreEndpoint: string | undefined; } export namespace CreateFHIRDatastoreResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateFHIRDatastoreResponse): any => ({ ...obj, }); } /** * <p>Unknown error occurs in the service.</p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; Message?: string; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p>The user has exceeded their maximum number of allowed calls to the given API. </p> */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; Message?: string; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } /** * <p>The user input parameter was invalid.</p> */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; Message?: string; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } /** * <p>The filters applied to Data Store query.</p> */ export interface DatastoreFilter { /** * <p>Allows the user to filter Data Store results by name.</p> */ DatastoreName?: string; /** * <p>Allows the user to filter Data Store results by status.</p> */ DatastoreStatus?: DatastoreStatus | string; /** * <p>A filter that allows the user to set cutoff dates for records. All Data Stores created * before the specified date will be included in the results. </p> */ CreatedBefore?: Date; /** * <p>A filter that allows the user to set cutoff dates for records. All Data Stores created * after the specified date will be included in the results.</p> */ CreatedAfter?: Date; } export namespace DatastoreFilter { /** * @internal */ export const filterSensitiveLog = (obj: DatastoreFilter): any => ({ ...obj, }); } /** * <p>Displays the properties of the Data Store, including the ID, Arn, name, and the status of the Data Store.</p> */ export interface DatastoreProperties { /** * <p>The AWS-generated ID number for the Data Store.</p> */ DatastoreId: string | undefined; /** * <p>The Amazon Resource Name used in the creation of the Data Store.</p> */ DatastoreArn: string | undefined; /** * <p>The user-generated name for the Data Store.</p> */ DatastoreName?: string; /** * <p>The status of the Data Store. Possible statuses are 'CREATING', 'ACTIVE', 'DELETING', or 'DELETED'.</p> */ DatastoreStatus: DatastoreStatus | string | undefined; /** * <p>The time that a Data Store was created. </p> */ CreatedAt?: Date; /** * <p>The FHIR version. Only R4 version data is supported.</p> */ DatastoreTypeVersion: FHIRVersion | string | undefined; /** * <p>The AWS endpoint for the Data Store. Each Data Store will have it's own endpoint with Data Store ID in the endpoint URL.</p> */ DatastoreEndpoint: string | undefined; /** * <p> * The server-side encryption key configuration for a customer provided encryption key (CMK). * </p> */ SseConfiguration?: SseConfiguration; /** * <p>The preloaded data configuration for the Data Store. Only data preloaded from Synthea is supported.</p> */ PreloadDataConfig?: PreloadDataConfig; } export namespace DatastoreProperties { /** * @internal */ export const filterSensitiveLog = (obj: DatastoreProperties): any => ({ ...obj, }); } export interface DeleteFHIRDatastoreRequest { /** * <p> The AWS-generated ID for the Data Store to be deleted.</p> */ DatastoreId?: string; } export namespace DeleteFHIRDatastoreRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteFHIRDatastoreRequest): any => ({ ...obj, }); } export interface DeleteFHIRDatastoreResponse { /** * <p>The AWS-generated ID for the Data Store to be deleted.</p> */ DatastoreId: string | undefined; /** * <p>The Amazon Resource Name (ARN) that gives Amazon HealthLake access permission.</p> */ DatastoreArn: string | undefined; /** * <p>The status of the Data Store that the user has requested to be deleted. * </p> */ DatastoreStatus: DatastoreStatus | string | undefined; /** * <p>The AWS endpoint for the Data Store the user has requested to be deleted.</p> */ DatastoreEndpoint: string | undefined; } export namespace DeleteFHIRDatastoreResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteFHIRDatastoreResponse): any => ({ ...obj, }); } /** * <p> The requested Data Store was not found.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; Message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } export interface DescribeFHIRDatastoreRequest { /** * <p>The AWS-generated Data Store id. This is part of the ‘CreateFHIRDatastore’ output.</p> */ DatastoreId?: string; } export namespace DescribeFHIRDatastoreRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFHIRDatastoreRequest): any => ({ ...obj, }); } export interface DescribeFHIRDatastoreResponse { /** * <p>All properties associated with a Data Store, including the Data Store ID, Data Store ARN, * Data Store name, Data Store status, created at, Data Store type version, and Data Store * endpoint.</p> */ DatastoreProperties: DatastoreProperties | undefined; } export namespace DescribeFHIRDatastoreResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFHIRDatastoreResponse): any => ({ ...obj, }); } export interface DescribeFHIRExportJobRequest { /** * <p>The AWS generated ID for the Data Store from which files are being exported from for an export job.</p> */ DatastoreId: string | undefined; /** * <p>The AWS generated ID for an export job.</p> */ JobId: string | undefined; } export namespace DescribeFHIRExportJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFHIRExportJobRequest): any => ({ ...obj, }); } export enum JobStatus { COMPLETED = "COMPLETED", COMPLETED_WITH_ERRORS = "COMPLETED_WITH_ERRORS", FAILED = "FAILED", IN_PROGRESS = "IN_PROGRESS", SUBMITTED = "SUBMITTED", } /** * <p> * The configuration of the S3 bucket for either an import or export job. This includes assigning permissions for access. * </p> */ export interface S3Configuration { /** * <p> * The S3Uri is the user specified S3 location of the FHIR data to be imported into Amazon HealthLake. * </p> */ S3Uri: string | undefined; /** * <p> * The KMS key ID used to access the S3 bucket. * </p> */ KmsKeyId: string | undefined; } export namespace S3Configuration { /** * @internal */ export const filterSensitiveLog = (obj: S3Configuration): any => ({ ...obj, }); } /** * <p>The output data configuration that was supplied when the export job was created.</p> */ export type OutputDataConfig = OutputDataConfig.S3ConfigurationMember | OutputDataConfig.$UnknownMember; export namespace OutputDataConfig { /** * <p> * The output data configuration that was supplied when the export job was created. * </p> */ export interface S3ConfigurationMember { S3Configuration: S3Configuration; $unknown?: never; } export interface $UnknownMember { S3Configuration?: never; $unknown: [string, any]; } export interface Visitor<T> { S3Configuration: (value: S3Configuration) => T; _: (name: string, value: any) => T; } export const visit = <T>(value: OutputDataConfig, visitor: Visitor<T>): T => { if (value.S3Configuration !== undefined) return visitor.S3Configuration(value.S3Configuration); return visitor._(value.$unknown[0], value.$unknown[1]); }; /** * @internal */ export const filterSensitiveLog = (obj: OutputDataConfig): any => { if (obj.S3Configuration !== undefined) return { S3Configuration: S3Configuration.filterSensitiveLog(obj.S3Configuration) }; if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" }; }; } /** * <p>The properties of a FHIR export job, including the ID, ARN, name, and the status of the job.</p> */ export interface ExportJobProperties { /** * <p>The AWS generated ID for an export job.</p> */ JobId: string | undefined; /** * <p>The user generated name for an export job.</p> */ JobName?: string; /** * <p>The status of a FHIR export job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, or FAILED.</p> */ JobStatus: JobStatus | string | undefined; /** * <p>The time an export job was initiated.</p> */ SubmitTime: Date | undefined; /** * <p>The time an export job completed.</p> */ EndTime?: Date; /** * <p>The AWS generated ID for the Data Store from which files are being exported for an export job.</p> */ DatastoreId: string | undefined; /** * <p>The output data configuration that was supplied when the export job was created.</p> */ OutputDataConfig: OutputDataConfig | undefined; /** * <p>The Amazon Resource Name used during the initiation of the job.</p> */ DataAccessRoleArn?: string; /** * <p>An explanation of any errors that may have occurred during the export job.</p> */ Message?: string; } export namespace ExportJobProperties { /** * @internal */ export const filterSensitiveLog = (obj: ExportJobProperties): any => ({ ...obj, ...(obj.OutputDataConfig && { OutputDataConfig: OutputDataConfig.filterSensitiveLog(obj.OutputDataConfig) }), }); } export interface DescribeFHIRExportJobResponse { /** * <p>Displays the properties of the export job, including the ID, Arn, Name, and the status of the job. </p> */ ExportJobProperties: ExportJobProperties | undefined; } export namespace DescribeFHIRExportJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFHIRExportJobResponse): any => ({ ...obj, ...(obj.ExportJobProperties && { ExportJobProperties: ExportJobProperties.filterSensitiveLog(obj.ExportJobProperties), }), }); } export interface DescribeFHIRImportJobRequest { /** * <p>The AWS-generated ID of the Data Store.</p> */ DatastoreId: string | undefined; /** * <p>The AWS-generated job ID.</p> */ JobId: string | undefined; } export namespace DescribeFHIRImportJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFHIRImportJobRequest): any => ({ ...obj, }); } /** * <p> The input properties for an import job.</p> */ export type InputDataConfig = InputDataConfig.S3UriMember | InputDataConfig.$UnknownMember; export namespace InputDataConfig { /** * <p>The S3Uri is the user specified S3 location of the FHIR data to be imported into Amazon HealthLake. </p> */ export interface S3UriMember { S3Uri: string; $unknown?: never; } export interface $UnknownMember { S3Uri?: never; $unknown: [string, any]; } export interface Visitor<T> { S3Uri: (value: string) => T; _: (name: string, value: any) => T; } export const visit = <T>(value: InputDataConfig, visitor: Visitor<T>): T => { if (value.S3Uri !== undefined) return visitor.S3Uri(value.S3Uri); return visitor._(value.$unknown[0], value.$unknown[1]); }; /** * @internal */ export const filterSensitiveLog = (obj: InputDataConfig): any => { if (obj.S3Uri !== undefined) return { S3Uri: obj.S3Uri }; if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" }; }; } /** * <p>Displays the properties of the import job, including the ID, Arn, Name, and the status of the Data Store.</p> */ export interface ImportJobProperties { /** * <p>The AWS-generated id number for the Import job.</p> */ JobId: string | undefined; /** * <p>The user-generated name for an Import job.</p> */ JobName?: string; /** * <p>The job status for an Import job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, FAILED.</p> */ JobStatus: JobStatus | string | undefined; /** * <p>The time that the Import job was submitted for processing.</p> */ SubmitTime: Date | undefined; /** * <p>The time that the Import job was completed.</p> */ EndTime?: Date; /** * <p>The datastore id used when the Import job was created. </p> */ DatastoreId: string | undefined; /** * <p>The input data configuration that was supplied when the Import job was created.</p> */ InputDataConfig: InputDataConfig | undefined; /** * <p>The output data configuration that was supplied when the export job was created.</p> */ JobOutputDataConfig?: OutputDataConfig; /** * <p>The Amazon Resource Name (ARN) that gives Amazon HealthLake access to your input data.</p> */ DataAccessRoleArn?: string; /** * <p>An explanation of any errors that may have occurred during the FHIR import job. </p> */ Message?: string; } export namespace ImportJobProperties { /** * @internal */ export const filterSensitiveLog = (obj: ImportJobProperties): any => ({ ...obj, ...(obj.InputDataConfig && { InputDataConfig: InputDataConfig.filterSensitiveLog(obj.InputDataConfig) }), ...(obj.JobOutputDataConfig && { JobOutputDataConfig: OutputDataConfig.filterSensitiveLog(obj.JobOutputDataConfig), }), }); } export interface DescribeFHIRImportJobResponse { /** * <p>The properties of the Import job request, including the ID, ARN, name, and the status of the job.</p> */ ImportJobProperties: ImportJobProperties | undefined; } export namespace DescribeFHIRImportJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFHIRImportJobResponse): any => ({ ...obj, ...(obj.ImportJobProperties && { ImportJobProperties: ImportJobProperties.filterSensitiveLog(obj.ImportJobProperties), }), }); } export interface ListFHIRDatastoresRequest { /** * <p>Lists all filters associated with a FHIR Data Store request.</p> */ Filter?: DatastoreFilter; /** * <p>Fetches the next page of Data Stores when results are paginated.</p> */ NextToken?: string; /** * <p>The maximum number of Data Stores returned in a single page of a * ListFHIRDatastoresRequest call.</p> */ MaxResults?: number; } export namespace ListFHIRDatastoresRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListFHIRDatastoresRequest): any => ({ ...obj, }); } export interface ListFHIRDatastoresResponse { /** * <p>All properties associated with the listed Data Stores.</p> */ DatastorePropertiesList: DatastoreProperties[] | undefined; /** * <p>Pagination token that can be used to retrieve the next page of results.</p> */ NextToken?: string; } export namespace ListFHIRDatastoresResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListFHIRDatastoresResponse): any => ({ ...obj, }); } export interface ListFHIRExportJobsRequest { /** * <p> * This parameter limits the response to the export job with the specified Data Store ID. * </p> */ DatastoreId: string | undefined; /** * <p> * A pagination token used to identify the next page of results to return for a ListFHIRExportJobs query. * </p> */ NextToken?: string; /** * <p> * This parameter limits the number of results returned for a ListFHIRExportJobs to a maximum quantity specified by the user. * </p> */ MaxResults?: number; /** * <p> * This parameter limits the response to the export job with the specified job name. * </p> */ JobName?: string; /** * <p> * This parameter limits the response to the export jobs with the specified job status. * </p> */ JobStatus?: JobStatus | string; /** * <p> * This parameter limits the response to FHIR export jobs submitted before a user specified date. * </p> */ SubmittedBefore?: Date; /** * <p> * This parameter limits the response to FHIR export jobs submitted after a user specified date. * </p> */ SubmittedAfter?: Date; } export namespace ListFHIRExportJobsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListFHIRExportJobsRequest): any => ({ ...obj, }); } export interface ListFHIRExportJobsResponse { /** * <p> * The properties of listed FHIR export jobs, including the ID, ARN, name, and the status of the job. * </p> */ ExportJobPropertiesList: ExportJobProperties[] | undefined; /** * <p> * A pagination token used to identify the next page of results to return for a ListFHIRExportJobs query. * </p> */ NextToken?: string; } export namespace ListFHIRExportJobsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListFHIRExportJobsResponse): any => ({ ...obj, ...(obj.ExportJobPropertiesList && { ExportJobPropertiesList: obj.ExportJobPropertiesList.map((item) => ExportJobProperties.filterSensitiveLog(item)), }), }); } export interface ListFHIRImportJobsRequest { /** * <p> * This parameter limits the response to the import job with the specified Data Store ID. * </p> */ DatastoreId: string | undefined; /** * <p> * A pagination token used to identify the next page of results to return for a ListFHIRImportJobs query. * </p> */ NextToken?: string; /** * <p> * This parameter limits the number of results returned for a ListFHIRImportJobs to a maximum quantity specified by the user. * </p> */ MaxResults?: number; /** * <p> * This parameter limits the response to the import job with the specified job name. * </p> */ JobName?: string; /** * <p> * This parameter limits the response to the import job with the specified job status. * </p> */ JobStatus?: JobStatus | string; /** * <p> * This parameter limits the response to FHIR import jobs submitted before a user specified date. * </p> */ SubmittedBefore?: Date; /** * <p> * This parameter limits the response to FHIR import jobs submitted after a user specified date. * </p> */ SubmittedAfter?: Date; } export namespace ListFHIRImportJobsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListFHIRImportJobsRequest): any => ({ ...obj, }); } export interface ListFHIRImportJobsResponse { /** * <p> * The properties of a listed FHIR import jobs, including the ID, ARN, name, and the status of the job. * </p> */ ImportJobPropertiesList: ImportJobProperties[] | undefined; /** * <p> * A pagination token used to identify the next page of results to return for a ListFHIRImportJobs query. * </p> */ NextToken?: string; } export namespace ListFHIRImportJobsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListFHIRImportJobsResponse): any => ({ ...obj, ...(obj.ImportJobPropertiesList && { ImportJobPropertiesList: obj.ImportJobPropertiesList.map((item) => ImportJobProperties.filterSensitiveLog(item)), }), }); } export interface ListTagsForResourceRequest { /** * <p> * The Amazon Resource Name(ARN) of the Data Store for which tags are being added. * </p> */ ResourceARN: string | undefined; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResponse { /** * <p> * Returns a list of tags associated with a Data Store. * </p> */ Tags?: Tag[]; } export namespace ListTagsForResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({ ...obj, }); } export interface StartFHIRExportJobRequest { /** * <p>The user generated name for an export job.</p> */ JobName?: string; /** * <p>The output data configuration that was supplied when the export job was created.</p> */ OutputDataConfig: OutputDataConfig | undefined; /** * <p>The AWS generated ID for the Data Store from which files are being exported for an export job.</p> */ DatastoreId: string | undefined; /** * <p>The Amazon Resource Name used during the initiation of the job.</p> */ DataAccessRoleArn: string | undefined; /** * <p>An optional user provided token used for ensuring idempotency.</p> */ ClientToken?: string; } export namespace StartFHIRExportJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartFHIRExportJobRequest): any => ({ ...obj, ...(obj.OutputDataConfig && { OutputDataConfig: OutputDataConfig.filterSensitiveLog(obj.OutputDataConfig) }), }); } export interface StartFHIRExportJobResponse { /** * <p>The AWS generated ID for an export job.</p> */ JobId: string | undefined; /** * <p>The status of a FHIR export job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, or FAILED.</p> */ JobStatus: JobStatus | string | undefined; /** * <p>The AWS generated ID for the Data Store from which files are being exported for an export job.</p> */ DatastoreId?: string; } export namespace StartFHIRExportJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: StartFHIRExportJobResponse): any => ({ ...obj, }); } export interface StartFHIRImportJobRequest { /** * <p>The name of the FHIR Import job in the StartFHIRImport job request.</p> */ JobName?: string; /** * <p>The input properties of the FHIR Import job in the StartFHIRImport job request.</p> */ InputDataConfig: InputDataConfig | undefined; /** * <p>The output data configuration that was supplied when the export job was created.</p> */ JobOutputDataConfig: OutputDataConfig | undefined; /** * <p>The AWS-generated Data Store ID.</p> */ DatastoreId: string | undefined; /** * <p>The Amazon Resource Name (ARN) that gives Amazon HealthLake access permission.</p> */ DataAccessRoleArn: string | undefined; /** * <p>Optional user provided token used for ensuring idempotency.</p> */ ClientToken?: string; } export namespace StartFHIRImportJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartFHIRImportJobRequest): any => ({ ...obj, ...(obj.InputDataConfig && { InputDataConfig: InputDataConfig.filterSensitiveLog(obj.InputDataConfig) }), ...(obj.JobOutputDataConfig && { JobOutputDataConfig: OutputDataConfig.filterSensitiveLog(obj.JobOutputDataConfig), }), }); } export interface StartFHIRImportJobResponse { /** * <p>The AWS-generated job ID.</p> */ JobId: string | undefined; /** * <p>The status of an import job.</p> */ JobStatus: JobStatus | string | undefined; /** * <p>The AWS-generated Data Store ID.</p> */ DatastoreId?: string; } export namespace StartFHIRImportJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: StartFHIRImportJobResponse): any => ({ ...obj, }); } export interface TagResourceRequest { /** * <p> * The Amazon Resource Name(ARN)that gives Amazon HealthLake access to the Data Store which tags are being added to. * </p> */ ResourceARN: string | undefined; /** * <p> * The user specified key and value pair tags being added to a Data Store. * </p> */ Tags: Tag[] | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResponse {} export namespace TagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResponse): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * <p> * "The Amazon Resource Name(ARN) of the Data Store for which tags are being removed * </p> */ ResourceARN: string | undefined; /** * <p> * The keys for the tags to be removed from the Healthlake Data Store. * </p> */ TagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } export interface UntagResourceResponse {} export namespace UntagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({ ...obj, }); }
the_stack
export enum PostgresErrorCodes { // Class 00 — Successful Completion SUCCESSFUL_COMPLETION = '00000', // Class 01 — Warning WARNING = '01000', DYNAMIC_RESULT_SETS_RETURNED = '0100C', IMPLICIT_ZERO_BIT_PADDING = '01008', NULL_VALUE_ELIMINATED_IN_SET_FUNCTION = '01003', PRIVILEGE_NOT_GRANTED = '01007', PRIVILEGE_NOT_REVOKED = '01006', STRING_DATA_RIGHT_TRUNCATION = '01004', DEPRECATED_FEATURE = '01P01', // Class 02 — No Data (this is also a warning class per the SQL standard) NO_DATA = '02000', NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED = '02001', // Class 03 — SQL Statement Not Yet Complete SQL_STATEMENT_NOT_YET_COMPLETE = '03000', // Class 08 — Connection Exception CONNECTION_EXCEPTION = '08000', CONNECTION_DOES_NOT_EXIST = '08003', CONNECTION_FAILURE = '08006', SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION = '08001', SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION = '08004', TRANSACTION_RESOLUTION_UNKNOWN = '08007', PROTOCOL_VIOLATION = '08P01', // Class 09 — Triggered Action Exception TRIGGERED_ACTION_EXCEPTION = '09000', // Class 0A — Feature Not Supported FEATURE_NOT_SUPPORTED = '0A000', // Class 0B — Invalid Transaction Initiation INVALID_TRANSACTION_INITIATION = '0B000', // Class 0F — Locator Exception LOCATOR_EXCEPTION = '0F000', INVALID_LOCATOR_SPECIFICATION = '0F001', // Class 0L — Invalid Grantor INVALID_GRANTOR = '0L000', INVALID_GRANT_OPERATION = '0LP01', // Class 0P — Invalid Role Specification INVALID_ROLE_SPECIFICATION = '0P000', // Class 0Z — Diagnostics Exception DIAGNOSTICS_EXCEPTION = '0Z000', STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER = '0Z002', // Class 20 — Case Not Found CASE_NOT_FOUND = '20000', // Class 21 — Cardinality Violation CARDINALITY_VIOLATION = '21000', // Class 22 — Data Exception DATA_EXCEPTION = '22000', ARRAY_SUBSCRIPT_ERROR = '2202E', CHARACTER_NOT_IN_REPERTOIRE = '22021', DATETIME_FIELD_OVERFLOW = '22008', DIVISION_BY_ZERO = '22012', ERROR_IN_ASSIGNMENT = '22005', ESCAPE_CHARACTER_CONFLICT = '2200B', INDICATOR_OVERFLOW = '22022', INTERVAL_FIELD_OVERFLOW = '22015', INVALID_ARGUMENT_FOR_LOGARITHM = '2201E', INVALID_ARGUMENT_FOR_NTILE_FUNCTION = '22014', INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION = '22016', INVALID_ARGUMENT_FOR_POWER_FUNCTION = '2201F', INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION = '2201G', INVALID_CHARACTER_VALUE_FOR_CAST = '22018', INVALID_DATETIME_FORMAT = '22007', INVALID_ESCAPE_CHARACTER = '22019', INVALID_ESCAPE_OCTET = '2200D', INVALID_ESCAPE_SEQUENCE = '22025', NONSTANDARD_USE_OF_ESCAPE_CHARACTER = '22P06', INVALID_INDICATOR_PARAMETER_VALUE = '22010', INVALID_PARAMETER_VALUE = '22023', INVALID_REGULAR_EXPRESSION = '2201B', INVALID_ROW_COUNT_IN_LIMIT_CLAUSE = '2201W', INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE = '2201X', INVALID_TIME_ZONE_DISPLACEMENT_VALUE = '22009', INVALID_USE_OF_ESCAPE_CHARACTER = '2200C', MOST_SPECIFIC_TYPE_MISMATCH = '2200G', NULL_VALUE_NOT_ALLOWED = '22004', NULL_VALUE_NO_INDICATOR_PARAMETER = '22002', NUMERIC_VALUE_OUT_OF_RANGE = '22003', STRING_DATA_LENGTH_MISMATCH = '22026', SUBSTRING_ERROR = '22011', TRIM_ERROR = '22027', UNTERMINATED_C_STRING = '22024', ZERO_LENGTH_CHARACTER_STRING = '2200F', FLOATING_POINT_EXCEPTION = '22P01', INVALID_TEXT_REPRESENTATION = '22P02', INVALID_BINARY_REPRESENTATION = '22P03', BAD_COPY_FILE_FORMAT = '22P04', UNTRANSLATABLE_CHARACTER = '22P05', NOT_AN_XML_DOCUMENT = '2200L', INVALID_XML_DOCUMENT = '2200M', INVALID_XML_CONTENT = '2200N', INVALID_XML_COMMENT = '2200S', INVALID_XML_PROCESSING_INSTRUCTION = '2200T', // Class 23 — Integrity Constraint Violation, INTEGRITY_CONSTRAINT_VIOLATION = '23000', RESTRICT_VIOLATION = '23001', NOT_NULL_VIOLATION = '23502', FOREIGN_KEY_VIOLATION = '23503', UNIQUE_VIOLATION = '23505', CHECK_VIOLATION = '23514', EXCLUSION_VIOLATION = '23P01', // Class 24 — Invalid Cursor State, INVALID_CURSOR_STATE = '24000', // Class 25 — Invalid Transaction State, INVALID_TRANSACTION_STATE = '25000', ACTIVE_SQL_TRANSACTION = '25001', BRANCH_TRANSACTION_ALREADY_ACTIVE = '25002', HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL = '25008', INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION = '25003', INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION = '25004', NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION = '25005', READ_ONLY_SQL_TRANSACTION = '25006', SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED = '25007', NO_ACTIVE_SQL_TRANSACTION = '25P01', IN_FAILED_SQL_TRANSACTION = '25P02', // Class 26 — Invalid SQL Statement Name, INVALID_SQL_STATEMENT_NAME = '26000', // Class 27 — Triggered Data Change Violation, TRIGGERED_DATA_CHANGE_VIOLATION = '27000', // Class 28 — Invalid Authorization Specification, INVALID_AUTHORIZATION_SPECIFICATION = '28000', INVALID_PASSWORD = '28P01', // Class 2B — Dependent Privilege Descriptors Still Exist, DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST = '2B000', DEPENDENT_OBJECTS_STILL_EXIST = '2BP01', // Class 2D — Invalid Transaction Termination, INVALID_TRANSACTION_TERMINATION = '2D000', // Class 2F — SQL Routine Exception, SQL_ROUTINE_EXCEPTION = '2F000', FUNCTION_EXECUTED_NO_RETURN_STATEMENT = '2F005', MODIFYING_SQL_DATA_NOT_PERMITTED = '2F002', PROHIBITED_SQL_STATEMENT_ATTEMPTED = '2F003', READING_SQL_DATA_NOT_PERMITTED = '2F004', // Class 34 — Invalid Cursor Name, INVALID_CURSOR_NAME = '34000', // Class 38 — External Routine Exception, EXTERNAL_ROUTINE_EXCEPTION = '38000', CONTAINING_SQL_NOT_PERMITTED = '38001', // Class 39 — External Routine Invocation Exception, EXTERNAL_ROUTINE_INVOCATION_EXCEPTION = '39000', INVALID_SQLSTATE_RETURNED = '39001', TRIGGER_PROTOCOL_VIOLATED = '39P01', SRF_PROTOCOL_VIOLATED = '39P02', // Class 3B — Savepoint Exception, SAVEPOINT_EXCEPTION = '3B000', INVALID_SAVEPOINT_SPECIFICATION = '3B001', // Class 3D — Invalid Catalog Name, INVALID_CATALOG_NAME = '3D000', // Class 3F — Invalid Schema Name, INVALID_SCHEMA_NAME = '3F000', // Class 40 — Transaction Rollback, TRANSACTION_ROLLBACK = '40000', TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION = '40002', SERIALIZATION_FAILURE = '40001', STATEMENT_COMPLETION_UNKNOWN = '40003', DEADLOCK_DETECTED = '40P01', // Class 42 — Syntax Error or Access Rule Violation, SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION = '42000', SYNTAX_ERROR = '42601', INSUFFICIENT_PRIVILEGE = '42501', CANNOT_COERCE = '42846', GROUPING_ERROR = '42803', WINDOWING_ERROR = '42P20', INVALID_RECURSION = '42P19', INVALID_FOREIGN_KEY = '42830', INVALID_NAME = '42602', NAME_TOO_LONG = '42622', RESERVED_NAME = '42939', DATATYPE_MISMATCH = '42804', INDETERMINATE_DATATYPE = '42P18', COLLATION_MISMATCH = '42P21', INDETERMINATE_COLLATION = '42P22', WRONG_OBJECT_TYPE = '42809', UNDEFINED_COLUMN = '42703', UNDEFINED_FUNCTION = '42883', UNDEFINED_TABLE = '42P01', UNDEFINED_PARAMETER = '42P02', UNDEFINED_OBJECT = '42704', DUPLICATE_COLUMN = '42701', DUPLICATE_CURSOR = '42P03', DUPLICATE_DATABASE = '42P04', DUPLICATE_FUNCTION = '42723', DUPLICATE_PREPARED_STATEMENT = '42P05', DUPLICATE_SCHEMA = '42P06', DUPLICATE_TABLE = '42P07', DUPLICATE_ALIAS = '42712', DUPLICATE_OBJECT = '42710', AMBIGUOUS_COLUMN = '42702', AMBIGUOUS_FUNCTION = '42725', AMBIGUOUS_PARAMETER = '42P08', AMBIGUOUS_ALIAS = '42P09', INVALID_COLUMN_REFERENCE = '42P10', INVALID_COLUMN_DEFINITION = '42611', INVALID_CURSOR_DEFINITION = '42P11', INVALID_DATABASE_DEFINITION = '42P12', INVALID_FUNCTION_DEFINITION = '42P13', INVALID_PREPARED_STATEMENT_DEFINITION = '42P14', INVALID_SCHEMA_DEFINITION = '42P15', INVALID_TABLE_DEFINITION = '42P16', INVALID_OBJECT_DEFINITION = '42P17', // Class 44 — WITH CHECK OPTION Violation, WITH_CHECK_OPTION_VIOLATION = '44000', // Class 53 — Insufficient Resources, INSUFFICIENT_RESOURCES = '53000', DISK_FULL = '53100', OUT_OF_MEMORY = '53200', TOO_MANY_CONNECTIONS = '53300', CONFIGURATION_LIMIT_EXCEEDED = '53400', // Class 54 — Program Limit Exceeded, PROGRAM_LIMIT_EXCEEDED = '54000', STATEMENT_TOO_COMPLEX = '54001', TOO_MANY_COLUMNS = '54011', TOO_MANY_ARGUMENTS = '54023', // Class 55 — Object Not In Prerequisite State, OBJECT_NOT_IN_PREREQUISITE_STATE = '55000', OBJECT_IN_USE = '55006', CANT_CHANGE_RUNTIME_PARAM = '55P02', LOCK_NOT_AVAILABLE = '55P03', // Class 57 — Operator Intervention, OPERATOR_INTERVENTION = '57000', QUERY_CANCELED = '57014', ADMIN_SHUTDOWN = '57P01', CRASH_SHUTDOWN = '57P02', CANNOT_CONNECT_NOW = '57P03', DATABASE_DROPPED = '57P04', // Class 58 — System Error (errors external to PostgreSQL itself), SYSTEM_ERROR = '58000', IO_ERROR = '58030', UNDEFINED_FILE = '58P01', DUPLICATE_FILE = '58P02', // Class F0 — Configuration File Error, CONFIG_FILE_ERROR = 'F0000', LOCK_FILE_EXISTS = 'F0001', // Class HV — Foreign Data Wrapper Error (SQL/MED), FDW_ERROR = 'HV000', FDW_COLUMN_NAME_NOT_FOUND = 'HV005', FDW_DYNAMIC_PARAMETER_VALUE_NEEDED = 'HV002', FDW_FUNCTION_SEQUENCE_ERROR = 'HV010', FDW_INCONSISTENT_DESCRIPTOR_INFORMATION = 'HV021', FDW_INVALID_ATTRIBUTE_VALUE = 'HV024', FDW_INVALID_COLUMN_NAME = 'HV007', FDW_INVALID_COLUMN_NUMBER = 'HV008', FDW_INVALID_DATA_TYPE = 'HV004', FDW_INVALID_DATA_TYPE_DESCRIPTORS = 'HV006', FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER = 'HV091', FDW_INVALID_HANDLE = 'HV00B', FDW_INVALID_OPTION_INDEX = 'HV00C', FDW_INVALID_OPTION_NAME = 'HV00D', FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH = 'HV090', FDW_INVALID_STRING_FORMAT = 'HV00A', FDW_INVALID_USE_OF_NULL_POINTER = 'HV009', FDW_TOO_MANY_HANDLES = 'HV014', FDW_OUT_OF_MEMORY = 'HV001', FDW_NO_SCHEMAS = 'HV00P', FDW_OPTION_NAME_NOT_FOUND = 'HV00J', FDW_REPLY_HANDLE = 'HV00K', FDW_SCHEMA_NOT_FOUND = 'HV00Q', FDW_TABLE_NOT_FOUND = 'HV00R', FDW_UNABLE_TO_CREATE_EXECUTION = 'HV00L', FDW_UNABLE_TO_CREATE_REPLY = 'HV00M', FDW_UNABLE_TO_ESTABLISH_CONNECTION = 'HV00N', // Class P0 — PL/pgSQL Error, PLPGSQL_ERROR = 'P0000', RAISE_EXCEPTION = 'P0001', NO_DATA_FOUND = 'P0002', TOO_MANY_ROWS = 'P0003', // Class XX — Internal Error, INTERNAL_ERROR = 'XX000', DATA_CORRUPTED = 'XX001', INDEX_CORRUPTED = 'XX002', }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormQuote_Field_Service_Information { interface Header extends DevKit.Controls.IHeader { /** Enter the date when the quote pricing is effective or was first communicated to the customer. */ EffectiveFrom: DevKit.Controls.Date; /** Enter the expiration date or last day the quote pricing is effective for the customer. */ EffectiveTo: DevKit.Controls.Date; msdyn_TotalAmount: DevKit.Controls.Money; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab_Summary_tab_Sections { quote_information: DevKit.Controls.Section; shipping_information: DevKit.Controls.Section; Summary_tab_section_3: DevKit.Controls.Section; } interface tab_tab_3_Sections { products: DevKit.Controls.Section; ServiceLinesSection: DevKit.Controls.Section; suggestionsection: DevKit.Controls.Section; totals: DevKit.Controls.Section; } interface tab_Summary_tab extends DevKit.Controls.ITab { Section: tab_Summary_tab_Sections; } interface tab_tab_3 extends DevKit.Controls.ITab { Section: tab_tab_3_Sections; } interface Tabs { Summary_tab: tab_Summary_tab; tab_3: tab_tab_3; } interface Body { Tab: Tabs; /** Shows the complete Bill To address. */ BillTo_Composite: DevKit.Controls.String; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Type additional information to describe the quote, such as the products or services offered or details about the customer's product preferences. */ Description: DevKit.Controls.String; /** Type the discount amount for the quote if the customer is eligible for special savings. */ DiscountAmount: DevKit.Controls.Money; /** Type the discount rate that should be applied to the Detail Amount field to include additional savings for the customer in the quote. */ DiscountPercentage: DevKit.Controls.Decimal; /** Enter the date when the quote pricing is effective or was first communicated to the customer. */ EffectiveFrom: DevKit.Controls.Date; /** Enter the expiration date or last day the quote pricing is effective for the customer. */ EffectiveTo: DevKit.Controls.Date; /** Type the cost of freight or shipping for the products included in the quote for use in calculating the Total Amount field. */ FreightAmount: DevKit.Controls.Money; /** Select the freight terms to make sure shipping charges are processed correctly. */ FreightTermsCode: DevKit.Controls.OptionSet; /** Customer Account associated with this Quote */ msdyn_Account: DevKit.Controls.Lookup; /** The estimated cost of this quote */ msdyn_EstimatedCost: DevKit.Controls.Money; /** Estimated Margin of this quote */ msdyn_EstimatedQuoteMargin: DevKit.Controls.Decimal; /** The totals of all assigned Invoice Setups */ msdyn_InvoiceSetupTotals: DevKit.Controls.Money; /** Internal use only. */ msdyn_OrderType: DevKit.Controls.OptionSet; msdyn_TotalAmount: DevKit.Controls.Money; /** Type a descriptive name for the quote. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Choose the opportunity that the quote is related to for reporting and analytics. */ OpportunityId: DevKit.Controls.Lookup; /** Select the payment terms to indicate when the customer needs to pay the total amount. */ PaymentTermsCode: DevKit.Controls.OptionSet; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.Controls.Lookup; /** Shows the quote number for customer reference and searching capabilities. The number cannot be modified. */ QuoteNumber: DevKit.Controls.String; /** Shows the version number of the quote for revision history tracking. */ RevisionNumber: DevKit.Controls.Integer; /** Select a shipping method for deliveries sent to this address. */ ShippingMethodCode: DevKit.Controls.OptionSet; /** Shows the complete Ship To address. */ ShipTo_Composite: DevKit.Controls.String; /** Shows whether the quote is draft, active, won, or closed. Only draft quotes can be edited. */ StateCode: DevKit.Controls.OptionSet; /** Select the quote's status. */ StatusCode: DevKit.Controls.OptionSet; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the quote. */ TotalAmount: DevKit.Controls.Money; /** Shows the total product amount for the quote, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount due for the quote. */ TotalAmountLessFreight: DevKit.Controls.Money; /** Shows the sum of all existing and write-in products included on the quote, based on the specified price list and quantities. */ TotalLineItemAmount: DevKit.Controls.Money; /** Shows the total of the Tax amounts specified on all products included in the quote, included in the Total Amount due calculation for the quote. */ TotalTax: DevKit.Controls.Money; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Select whether the products included in the quote should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */ WillCall: DevKit.Controls.Boolean; } interface Navigation { nav_msdyn_quote_msdyn_quotebookingincident_Quote: DevKit.Controls.NavigationItem, nav_msdyn_quote_msdyn_quotebookingproduct_Quote: DevKit.Controls.NavigationItem, nav_msdyn_quote_msdyn_quotebookingservice_Quote: DevKit.Controls.NavigationItem, nav_msdyn_quote_msdyn_quotebookingservicetask_Quote: DevKit.Controls.NavigationItem, nav_msdyn_quote_msdyn_quotebookingsetup_Quote: DevKit.Controls.NavigationItem, nav_msdyn_quote_msdyn_quoteinvoicingsetup_Quote: DevKit.Controls.NavigationItem, navProducts: DevKit.Controls.NavigationItem } interface Grid { quotedetailsGrid: DevKit.Controls.Grid; servicesGrid: DevKit.Controls.Grid; } } class FormQuote_Field_Service_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Quote_Field_Service_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 Quote_Field_Service_Information */ Body: DevKit.FormQuote_Field_Service_Information.Body; /** The Header section of form Quote_Field_Service_Information */ Header: DevKit.FormQuote_Field_Service_Information.Header; /** The Navigation of form Quote_Field_Service_Information */ Navigation: DevKit.FormQuote_Field_Service_Information.Navigation; /** The Grid of form Quote_Field_Service_Information */ Grid: DevKit.FormQuote_Field_Service_Information.Grid; } namespace FormQuote_Project_Information { interface Header extends DevKit.Controls.IHeader { /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Shows whether the quote is draft, active, won, or closed. Only draft quotes can be edited. */ StateCode: DevKit.Controls.OptionSet; /** Select the quote's status. */ StatusCode: DevKit.Controls.OptionSet; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the quote. */ TotalAmount: DevKit.Controls.Money; } interface tab_competive_analysis_tab_Sections { analytics_tab_section_5: DevKit.Controls.Section; Summary_tab_section_10: DevKit.Controls.Section; } interface tab_profitability_analytics_tab_Sections { analyticResultSection: DevKit.Controls.Section; analyticsChartDetailsSection: DevKit.Controls.Section; } interface tab_ProjectPriceListsTab_Sections { ProjectPriceListsSection: DevKit.Controls.Section; } interface tab_quoteAnaylsis_tab_Sections { tab_6_section_1: DevKit.Controls.Section; tab_6_section_2: DevKit.Controls.Section; tab_6_section_3: DevKit.Controls.Section; } interface tab_QuoteLinesTab_Sections { DynamicProperties: DevKit.Controls.Section; ProductLinesSection: DevKit.Controls.Section; ProjectLinesSection: DevKit.Controls.Section; } interface tab_Summary_tab_Sections { addresses: DevKit.Controls.Section; description_section: DevKit.Controls.Section; quote_information: DevKit.Controls.Section; shipping_information: DevKit.Controls.Section; Summary_tab_section_8: DevKit.Controls.Section; Summary_tab_section_9: DevKit.Controls.Section; } interface tab_competive_analysis_tab extends DevKit.Controls.ITab { Section: tab_competive_analysis_tab_Sections; } interface tab_profitability_analytics_tab extends DevKit.Controls.ITab { Section: tab_profitability_analytics_tab_Sections; } interface tab_ProjectPriceListsTab extends DevKit.Controls.ITab { Section: tab_ProjectPriceListsTab_Sections; } interface tab_quoteAnaylsis_tab extends DevKit.Controls.ITab { Section: tab_quoteAnaylsis_tab_Sections; } interface tab_QuoteLinesTab extends DevKit.Controls.ITab { Section: tab_QuoteLinesTab_Sections; } interface tab_Summary_tab extends DevKit.Controls.ITab { Section: tab_Summary_tab_Sections; } interface Tabs { competive_analysis_tab: tab_competive_analysis_tab; profitability_analytics_tab: tab_profitability_analytics_tab; ProjectPriceListsTab: tab_ProjectPriceListsTab; quoteAnaylsis_tab: tab_quoteAnaylsis_tab; QuoteLinesTab: tab_QuoteLinesTab; Summary_tab: tab_Summary_tab; } interface Body { Tab: Tabs; /** Shows the complete Bill To address. */ BillTo_Composite: DevKit.Controls.String; /** Type the primary contact name at the customer's billing address. */ BillTo_ContactName: DevKit.Controls.String; /** Type a name for the customer's billing address, such as "Headquarters" or "Field office", to identify the address. */ BillTo_Name: DevKit.Controls.String; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Type additional information to describe the quote, such as the products or services offered or details about the customer's product preferences. */ Description: DevKit.Controls.String; /** Enter the date when the quote pricing is effective or was first communicated to the customer. */ EffectiveFrom: DevKit.Controls.Date; /** Enter the expiration date or last day the quote pricing is effective for the customer. */ EffectiveTo: DevKit.Controls.Date; /** Enter the date a decision or order is due from the customer to indicate the expiration date of the quote. */ ExpiresOn: DevKit.Controls.Date; /** Select the freight terms to make sure shipping charges are processed correctly. */ FreightTermsCode: DevKit.Controls.OptionSet; /** Account manager responsible for the quote. */ msdyn_AccountManagerId: DevKit.Controls.Lookup; /** Shows the estimated gross margin after accounting for non-chargeable components. */ msdyn_AdjustedGrossMargin: DevKit.Controls.Decimal; /** Shows the estimated gross margin after accounting for non-chargeable components. */ msdyn_AdjustedGrossMargin_1: DevKit.Controls.Decimal; /** Shows how the quote estimation of sales value and schedule compare to customer expectations on those parameters. Possible values are 1: Within Customer expectations, 2: Not Within Customer expectations, and 0: Customer expectations Not Available. */ msdyn_Competitive: DevKit.Controls.OptionSet; /** Shows how the quote estimation of sales value and schedule compare to customer expectations on those parameters. Possible values are 1: Within Customer expectations, 2: Not Within Customer expectations, and 0: Customer expectations Not Available. */ msdyn_Competitive_1: DevKit.Controls.OptionSet; /** The organizational unit in charge of the contract. */ msdyn_ContractOrganizationalUnitId: DevKit.Controls.Lookup; /** Shows the total customer budget for the quote, computed from all the quote lines. */ msdyn_CustomerBudgetRollUp: DevKit.Controls.Money; /** Shows how the estimated sales value on the quote compares to customer budgets. Possible values are 1: Within Customer Budget, 2: Exceeds Customer Budget, 0: Budget Estimate Not Available */ msdyn_EstimatedBudget: DevKit.Controls.OptionSet; /** Shows how the estimated sales value on the quote compares to customer budgets. Possible values are 1: Within Customer Budget, 2: Exceeds Customer Budget, 0: Budget Estimate Not Available */ msdyn_EstimatedBudget_1: DevKit.Controls.OptionSet; /** Estimated completion date, computed from the details of each quote line. */ msdyn_EstimatedCompletionRollUp: DevKit.Controls.Date; /** Shows how the estimated schedule on the quote compares to customer expectations. Possible values are 1: Estimated To Finish Early, 2: Estimated To Finish Late, 3: Estimated To Finish On Schedule, and 0: Schedule Not Available. */ msdyn_EstimatedSchedule: DevKit.Controls.OptionSet; /** Shows how the estimated schedule on the quote compares to customer expectations. Possible values are 1: Estimated To Finish Early, 2: Estimated To Finish Late, 3: Estimated To Finish On Schedule, and 0: Schedule Not Available. */ msdyn_EstimatedSchedule_1: DevKit.Controls.OptionSet; /** Shows the estimated gross margin without accounting for non-chargeable components. */ msdyn_GrossMargin: DevKit.Controls.Decimal; /** Shows the estimated gross margin without accounting for non-chargeable components. */ msdyn_GrossMargin_1: DevKit.Controls.Decimal; /** Internal use only. */ msdyn_OrderType: DevKit.Controls.OptionSet; /** Shows the estimated profitability of the quote. Possible values are Profitable, Not Profitable, and Profitability not available. */ msdyn_Profitability: DevKit.Controls.OptionSet; /** Shows the estimated profitability of the quote. Possible values are Profitable, Not Profitable, and Profitability not available. */ msdyn_Profitability_1: DevKit.Controls.OptionSet; msdyn_TotalChargeableCostRollup: DevKit.Controls.Money; msdyn_TotalNonchargeableCostRollup: DevKit.Controls.Money; /** Type a descriptive name for the quote. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Choose the opportunity that the quote is related to for reporting and analytics. */ OpportunityId: DevKit.Controls.Lookup; /** Select the payment terms to indicate when the customer needs to pay the total amount. */ PaymentTermsCode: DevKit.Controls.OptionSet; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.Controls.Lookup; /** Shows the quote number for customer reference and searching capabilities. The number cannot be modified. */ QuoteNumber: DevKit.Controls.String; /** Enter the delivery date requested by the customer for all products in the quote. */ RequestDeliveryBy: DevKit.Controls.Date; /** Enter the delivery date requested by the customer for all products in the quote. */ RequestDeliveryBy_1: DevKit.Controls.Date; /** Shows the version number of the quote for revision history tracking. */ RevisionNumber: DevKit.Controls.Integer; /** Select a shipping method for deliveries sent to this address. */ ShippingMethodCode: DevKit.Controls.OptionSet; /** Shows the complete Ship To address. */ ShipTo_Composite: DevKit.Controls.String; /** Select the quote's status. */ StatusCode: DevKit.Controls.OptionSet; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the quote. */ TotalAmount: DevKit.Controls.Money; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the quote. */ TotalAmount_1: DevKit.Controls.Money; /** Value of the Total Amount in base currency. */ TotalAmount_Base: DevKit.Controls.Money; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Select whether the products included in the quote should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */ WillCall: DevKit.Controls.Boolean; } interface Navigation { nav_msdyn_quote_msdyn_quotelineanalyticsbreakdown_Quote: DevKit.Controls.NavigationItem, nav_msdyn_quote_msdyn_quotelinetransaction: DevKit.Controls.NavigationItem, nav_msdyn_quote_msdyn_quotepricelist_Quote: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navOrders: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem, navProducts: DevKit.Controls.NavigationItem } interface Grid { ProjectQuoteLines: DevKit.Controls.Grid; quotedetailsGrid: DevKit.Controls.Grid; ProjectPriceListsSubGrid: DevKit.Controls.Grid; costRevenueDistribution: DevKit.Controls.Grid; quoteLineDetailAnalysis: DevKit.Controls.Grid; quoteLineComparisonGrid: DevKit.Controls.Grid; totalQuoteAmountComparisonGrid: DevKit.Controls.Grid; } } class FormQuote_Project_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Quote_Project_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 Quote_Project_Information */ Body: DevKit.FormQuote_Project_Information.Body; /** The Header section of form Quote_Project_Information */ Header: DevKit.FormQuote_Project_Information.Header; /** The Navigation of form Quote_Project_Information */ Navigation: DevKit.FormQuote_Project_Information.Navigation; /** The Grid of form Quote_Project_Information */ Grid: DevKit.FormQuote_Project_Information.Grid; } namespace FormQuote { interface tab_newQuote_Sections { quickQuote_salesinformation: DevKit.Controls.Section; quickQuote_summary: DevKit.Controls.Section; } interface tab_newQuote extends DevKit.Controls.ITab { Section: tab_newQuote_Sections; } interface Tabs { newQuote: tab_newQuote; } interface Body { Tab: Tabs; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Type additional information to describe the quote, such as the products or services offered or details about the customer's product preferences. */ Description: DevKit.Controls.String; /** Type a descriptive name for the quote. */ Name: DevKit.Controls.String; /** Choose the opportunity that the quote is related to for reporting and analytics. */ OpportunityId: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.Controls.Lookup; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; } } class FormQuote extends DevKit.IForm { /** * DynamicsCrm.DevKit form Quote * @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 Quote */ Body: DevKit.FormQuote.Body; } class QuoteApi { /** * DynamicsCrm.DevKit QuoteApi * @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 account with which the quote is associated. */ AccountId: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the billing address. */ BillTo_AddressId: DevKit.WebApi.GuidValue; /** Type the city for the customer's billing address. */ BillTo_City: DevKit.WebApi.StringValue; /** Shows the complete Bill To address. */ BillTo_Composite: DevKit.WebApi.StringValueReadonly; /** Type the primary contact name at the customer's billing address. */ BillTo_ContactName: DevKit.WebApi.StringValue; /** Type the country or region for the customer's billing address. */ BillTo_Country: DevKit.WebApi.StringValue; /** Type the fax number for the customer's billing address. */ BillTo_Fax: DevKit.WebApi.StringValue; /** Type the first line of the customer's billing address. */ BillTo_Line1: DevKit.WebApi.StringValue; /** Type the second line of the customer's billing address. */ BillTo_Line2: DevKit.WebApi.StringValue; /** Type the third line of the billing address. */ BillTo_Line3: DevKit.WebApi.StringValue; /** Type a name for the customer's billing address, such as "Headquarters" or "Field office", to identify the address. */ BillTo_Name: DevKit.WebApi.StringValue; /** Type the ZIP Code or postal code for the billing address. */ BillTo_PostalCode: DevKit.WebApi.StringValue; /** Type the state or province for the billing address. */ BillTo_StateOrProvince: DevKit.WebApi.StringValue; /** Type the phone number for the customer's billing address. */ BillTo_Telephone: DevKit.WebApi.StringValue; /** Shows the campaign that the order was created from. */ CampaignId: DevKit.WebApi.LookupValue; /** Enter the date when the quote was closed to indicate the expiration, revision, or cancellation date. */ ClosedOn_DateOnly: DevKit.WebApi.DateOnlyValue; /** Unique identifier of the contact associated with the quote. */ ContactId: DevKit.WebApi.LookupValueReadonly; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; customerid_account: DevKit.WebApi.LookupValue; customerid_contact: DevKit.WebApi.LookupValue; /** Type additional information to describe the quote, such as the products or services offered or details about the customer's product preferences. */ Description: DevKit.WebApi.StringValue; /** Type the discount amount for the quote if the customer is eligible for special savings. */ DiscountAmount: DevKit.WebApi.MoneyValue; /** Value of the Quote Discount Amount in base currency. */ DiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Type the discount rate that should be applied to the Detail Amount field to include additional savings for the customer in the quote. */ DiscountPercentage: DevKit.WebApi.DecimalValue; /** Enter the date when the quote pricing is effective or was first communicated to the customer. */ EffectiveFrom_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the expiration date or last day the quote pricing is effective for the customer. */ EffectiveTo_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** The primary email address for the entity. */ EmailAddress: DevKit.WebApi.StringValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Enter the date a decision or order is due from the customer to indicate the expiration date of the quote. */ ExpiresOn_DateOnly: DevKit.WebApi.DateOnlyValue; /** Type the cost of freight or shipping for the products included in the quote for use in calculating the Total Amount field. */ FreightAmount: DevKit.WebApi.MoneyValue; /** Value of the Freight Amount in base currency. */ FreightAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the freight terms to make sure shipping charges are processed correctly. */ FreightTermsCode: DevKit.WebApi.OptionSetValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Contains the date time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Customer Account associated with this Quote */ msdyn_Account: DevKit.WebApi.LookupValue; /** Account manager responsible for the quote. */ msdyn_AccountManagerId: DevKit.WebApi.LookupValue; /** Shows the estimated gross margin after accounting for non-chargeable components. */ msdyn_AdjustedGrossMargin: DevKit.WebApi.DecimalValueReadonly; /** Shows how the quote estimation of sales value and schedule compare to customer expectations on those parameters. Possible values are 1: Within Customer expectations, 2: Not Within Customer expectations, and 0: Customer expectations Not Available. */ msdyn_Competitive: DevKit.WebApi.OptionSetValueReadonly; /** The organizational unit in charge of the contract. */ msdyn_ContractOrganizationalUnitId: DevKit.WebApi.LookupValue; /** Shows the total customer budget for the quote, computed from all the quote lines. */ msdyn_CustomerBudgetRollUp: DevKit.WebApi.MoneyValueReadonly; /** Shows the value of the customer budget in the base currency. */ msdyn_customerbudgetrollup_Base: DevKit.WebApi.MoneyValueReadonly; /** Last Updated time of rollup field Customer Budget. */ msdyn_CustomerBudgetRollUp_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field Customer Budget. */ msdyn_CustomerBudgetRollUp_State: DevKit.WebApi.IntegerValueReadonly; /** Shows how the estimated sales value on the quote compares to customer budgets. Possible values are 1: Within Customer Budget, 2: Exceeds Customer Budget, 0: Budget Estimate Not Available */ msdyn_EstimatedBudget: DevKit.WebApi.OptionSetValueReadonly; /** Estimated completion date, computed from the details of each quote line. */ msdyn_EstimatedCompletionRollUp_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly; /** Last Updated time of rollup field Estimated Completion. */ msdyn_EstimatedCompletionRollUp_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field Estimated Completion. */ msdyn_EstimatedCompletionRollUp_State: DevKit.WebApi.IntegerValueReadonly; /** The estimated cost of this quote */ msdyn_EstimatedCost: DevKit.WebApi.MoneyValue; /** Value of the Estimated Cost in base currency. */ msdyn_estimatedcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Estimated Margin of this quote */ msdyn_EstimatedQuoteMargin: DevKit.WebApi.DecimalValueReadonly; /** Shows how the estimated schedule on the quote compares to customer expectations. Possible values are 1: Estimated To Finish Early, 2: Estimated To Finish Late, 3: Estimated To Finish On Schedule, and 0: Schedule Not Available. */ msdyn_EstimatedSchedule: DevKit.WebApi.OptionSetValueReadonly; /** Shows how the quote estimation compares to project estimation. Possible values are 0: Feasibility Not Available, 1: Feasible, and 2: Not Feasible. */ msdyn_feasible: DevKit.WebApi.OptionSetValue; /** Shows the estimated gross margin without accounting for non-chargeable components. */ msdyn_GrossMargin: DevKit.WebApi.DecimalValueReadonly; /** The totals of all assigned Invoice Setups */ msdyn_InvoiceSetupTotals: DevKit.WebApi.MoneyValue; /** Value of the Invoice Setup Totals in base currency. */ msdyn_invoicesetuptotals_Base: DevKit.WebApi.MoneyValueReadonly; /** Internal use only. */ msdyn_OrderType: DevKit.WebApi.OptionSetValue; /** Shows the estimated profitability of the quote. Possible values are Profitable, Not Profitable, and Profitability not available. */ msdyn_Profitability: DevKit.WebApi.OptionSetValueReadonly; /** The latest end date of all associated quote lines */ msdyn_QuoteLineEndDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** The earliest Start Date of all Quote Lines that are associated to this quote */ msdyn_QuoteLineStartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_TotalAmount: DevKit.WebApi.MoneyValueReadonly; /** Value of the TotalAmount in base currency. */ msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_TotalChargeableCostRollup: DevKit.WebApi.MoneyValueReadonly; /** Value of the Total Chargeable Cost in base currency. */ msdyn_totalchargeablecostrollup_Base: DevKit.WebApi.MoneyValueReadonly; /** Last Updated time of rollup field Total Chargeable Cost. */ msdyn_TotalChargeableCostRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field Total Chargeable Cost. */ msdyn_TotalChargeableCostRollup_State: DevKit.WebApi.IntegerValueReadonly; msdyn_TotalNonchargeableCostRollup: DevKit.WebApi.MoneyValueReadonly; /** Value of the Total Non-chargeable Cost in base currency. */ msdyn_totalnonchargeablecostrollup_Base: DevKit.WebApi.MoneyValueReadonly; /** Last Updated time of rollup field Total Non-chargeable Cost. */ msdyn_TotalNonchargeableCostRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field Total Non-chargeable Cost. */ msdyn_TotalNonchargeableCostRollup_State: DevKit.WebApi.IntegerValueReadonly; /** Type a descriptive name for the quote. */ Name: DevKit.WebApi.StringValue; /** Shows the duration in minutes for which the quote was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Choose the opportunity that the quote is related to for reporting and analytics. */ OpportunityId: DevKit.WebApi.LookupValue; /** 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; /** Select the payment terms to indicate when the customer needs to pay the total amount. */ PaymentTermsCode: DevKit.WebApi.OptionSetValue; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.WebApi.LookupValue; /** Pricing error for the quote. */ PricingErrorCode: DevKit.WebApi.OptionSetValue; /** Contains the id of the process associated with the entity. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the quote. */ QuoteId: DevKit.WebApi.GuidValue; /** Shows the quote number for customer reference and searching capabilities. The number cannot be modified. */ QuoteNumber: DevKit.WebApi.StringValue; /** Enter the delivery date requested by the customer for all products in the quote. */ RequestDeliveryBy_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the version number of the quote for revision history tracking. */ RevisionNumber: DevKit.WebApi.IntegerValueReadonly; /** Select a shipping method for deliveries sent to this address. */ ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the shipping address. */ ShipTo_AddressId: DevKit.WebApi.GuidValue; /** Type the city for the customer's shipping address. */ ShipTo_City: DevKit.WebApi.StringValue; /** Shows the complete Ship To address. */ ShipTo_Composite: DevKit.WebApi.StringValueReadonly; /** Type the primary contact name at the customer's shipping address. */ ShipTo_ContactName: DevKit.WebApi.StringValue; /** Type the country or region for the customer's shipping address. */ ShipTo_Country: DevKit.WebApi.StringValue; /** Type the fax number for the customer's shipping address. */ ShipTo_Fax: DevKit.WebApi.StringValue; /** Select the freight terms to make sure shipping orders are processed correctly. */ ShipTo_FreightTermsCode: DevKit.WebApi.OptionSetValue; /** Type the first line of the customer's shipping address. */ ShipTo_Line1: DevKit.WebApi.StringValue; /** Type the second line of the customer's shipping address. */ ShipTo_Line2: DevKit.WebApi.StringValue; /** Type the third line of the shipping address. */ ShipTo_Line3: DevKit.WebApi.StringValue; /** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */ ShipTo_Name: DevKit.WebApi.StringValue; /** Type the ZIP Code or postal code for the shipping address. */ ShipTo_PostalCode: DevKit.WebApi.StringValue; /** Type the state or province for the shipping address. */ ShipTo_StateOrProvince: DevKit.WebApi.StringValue; /** Type the phone number for the customer's shipping address. */ ShipTo_Telephone: DevKit.WebApi.StringValue; /** Skip Price Calculation (For Internal use) */ SkipPriceCalculation: DevKit.WebApi.OptionSetValue; /** Choose the service level agreement (SLA) that you want to apply to the quote record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this quote. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the quote is draft, active, won, or closed. Only draft quotes can be edited. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the quote's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the quote. */ TotalAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Amount in base currency. */ TotalAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total product amount for the quote, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount due for the quote. */ TotalAmountLessFreight: DevKit.WebApi.MoneyValue; /** Value of the Total Pre-Freight Amount in base currency. */ TotalAmountLessFreight_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total discount amount, based on the discount price and rate entered on the quote. */ TotalDiscountAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Discount Amount in base currency. */ TotalDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the sum of all existing and write-in products included on the quote, based on the specified price list and quantities. */ TotalLineItemAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Detail Amount in base currency. */ TotalLineItemAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total of the Manual Discount amounts specified on all products included in the quote. This value is reflected in the Detail Amount field on the quote and is added to any discount amount or rate specified on the quote */ TotalLineItemDiscountAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Line Item Discount Amount in base currency. */ TotalLineItemDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total of the Tax amounts specified on all products included in the quote, included in the Total Amount due calculation for the quote. */ TotalTax: DevKit.WebApi.MoneyValue; /** Value of the Total Tax in base currency. */ TotalTax_Base: DevKit.WebApi.MoneyValueReadonly; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ TraversedPath: DevKit.WebApi.StringValue; /** For internal use only. */ UniqueDscId: DevKit.WebApi.GuidValueReadonly; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Select whether the products included in the quote should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */ WillCall: DevKit.WebApi.BooleanValue; } } declare namespace OptionSet { namespace Quote { enum FreightTermsCode { /** 1 */ FOB, /** 2 */ No_Charge } enum msdyn_Competitive { /** 192350000 */ Customer_Budget_Not_Available, /** 192350002 */ Outside_Customer_Expectations, /** 192350001 */ Within_Customer_Expectations } enum msdyn_EstimatedBudget { /** 192350000 */ Budget_Estimate_Not_Available, /** 192350002 */ Exceeds_Customer_Budget, /** 192350001 */ Within_Customer_Budget } enum msdyn_EstimatedSchedule { /** 192350001 */ Estimated_To_Finish_Early, /** 192350002 */ Estimated_To_Finish_Late, /** 192350003 */ Estimated_To_Finish_On_Schedule, /** 192350000 */ Schedule_Not_Available } enum msdyn_feasible { /** 192350000 */ Feasibility_Not_Available, /** 192350001 */ Feasible, /** 192350002 */ Not_Feasible } enum msdyn_OrderType { /** 192350000 */ Item_based, /** 690970002 */ Service_Maintenance_Based, /** 192350001 */ Work_based } enum msdyn_Profitability { /** 192350002 */ Not_Profitable, /** 192350000 */ Profitability_Not_Available, /** 192350001 */ Profitable } enum PaymentTermsCode { /** 2 */ _2_10_Net_30, /** 1 */ Net_30, /** 3 */ Net_45, /** 4 */ Net_60 } enum PricingErrorCode { /** 36 */ Base_Currency_Attribute_Overflow, /** 37 */ Base_Currency_Attribute_Underflow, /** 1 */ Detail_Error, /** 27 */ Discount_Type_Invalid_State, /** 33 */ Inactive_Discount_Type, /** 3 */ Inactive_Price_Level, /** 20 */ Invalid_Current_Cost, /** 28 */ Invalid_Discount, /** 26 */ Invalid_Discount_Type, /** 19 */ Invalid_Price, /** 17 */ Invalid_Price_Level_Amount, /** 34 */ Invalid_Price_Level_Currency, /** 18 */ Invalid_Price_Level_Percentage, /** 9 */ Invalid_Pricing_Code, /** 30 */ Invalid_Pricing_Precision, /** 7 */ Invalid_Product, /** 29 */ Invalid_Quantity, /** 24 */ Invalid_Rounding_Amount, /** 23 */ Invalid_Rounding_Option, /** 22 */ Invalid_Rounding_Policy, /** 21 */ Invalid_Standard_Cost, /** 15 */ Missing_Current_Cost, /** 14 */ Missing_Price, /** 2 */ Missing_Price_Level, /** 12 */ Missing_Price_Level_Amount, /** 13 */ Missing_Price_Level_Percentage, /** 8 */ Missing_Pricing_Code, /** 6 */ Missing_Product, /** 31 */ Missing_Product_Default_UOM, /** 32 */ Missing_Product_UOM_Schedule_, /** 4 */ Missing_Quantity, /** 16 */ Missing_Standard_Cost, /** 5 */ Missing_Unit_Price, /** 10 */ Missing_UOM, /** 0 */ None, /** 35 */ Price_Attribute_Out_Of_Range, /** 25 */ Price_Calculation_Error, /** 11 */ Product_Not_In_Price_Level, /** 38 */ Transaction_currency_is_not_set_for_the_product_price_list_item } enum ShippingMethodCode { /** 1 */ Airborne, /** 2 */ DHL, /** 3 */ FedEx, /** 6 */ Full_Load, /** 5 */ Postal_Mail, /** 4 */ UPS, /** 7 */ Will_Call } enum ShipTo_FreightTermsCode { /** 1 */ Default_Value } enum SkipPriceCalculation { /** 0 */ DoPriceCalcAlways, /** 1 */ SkipPriceCalcOnRetrieve } enum StateCode { /** 1 */ Active, /** 3 */ Closed, /** 0 */ Draft, /** 2 */ Won } enum StatusCode { /** 6 */ Canceled, /** 1 */ In_Progress_1, /** 2 */ In_Progress_2, /** 5 */ Lost, /** 3 */ Open, /** 7 */ Revised, /** 4 */ Won } 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':['Field Service Information','Project Information','Quote'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { defineComponent, reactive, onMounted, computed, onUnmounted, nextTick, watch, ref, } from 'vue'; import classnames from '../../_util/classNames'; import getScrollBarSize from '../../_util/getScrollBarSize'; import KeyCode from '../../_util/KeyCode'; import omit from '../../_util/omit'; import supportsPassive from '../../_util/supportsPassive'; import { drawerChildProps } from './IDrawerPropTypes'; import { addEventListener, dataToArray, getTouchParentScroll, isNumeric, removeEventListener, transformArguments, transitionEndFun, windowIsUndefined, } from './utils'; const currentDrawer: Record<string, boolean> = {}; export interface scrollLockOptions { container: HTMLElement; } const DrawerChild = defineComponent({ inheritAttrs: false, props: drawerChildProps(), emits: ['close', 'handleClick', 'change'], setup(props, { emit, slots }) { const state = reactive({ startPos: { x: null, y: null, }, }); let timeout; const contentWrapper = ref<HTMLElement>(); const dom = ref<HTMLElement>(); const maskDom = ref<HTMLElement>(); const handlerDom = ref<HTMLElement>(); const contentDom = ref<HTMLElement>(); let levelDom = []; const drawerId = `drawer_id_${Number( (Date.now() + Math.random()) .toString() .replace('.', Math.round(Math.random() * 9).toString()), ).toString(16)}`; const passive = !windowIsUndefined && supportsPassive ? { passive: false } : false; onMounted(() => { nextTick(() => { const { open, getContainer, showMask, autofocus } = props; const container = getContainer?.(); getLevelDom(props); if (open) { if (container && container.parentNode === document.body) { currentDrawer[drawerId] = open; } // 默认打开状态时推出 level; openLevelTransition(); nextTick(() => { if (autofocus) { domFocus(); } }); if (showMask) { props.scrollLocker?.lock(); } } }); }); watch( () => props.level, () => { getLevelDom(props); }, { flush: 'post' }, ); watch( () => props.open, () => { const { open, getContainer, scrollLocker, showMask, autofocus } = props; const container = getContainer?.(); if (container && container.parentNode === document.body) { currentDrawer[drawerId] = !!open; } openLevelTransition(); if (open) { if (autofocus) { domFocus(); } if (showMask) { scrollLocker?.lock(); } } else { scrollLocker?.unLock(); } }, { flush: 'post' }, ); onUnmounted(() => { const { open } = props; delete currentDrawer[drawerId]; if (open) { setLevelTransform(false); document.body.style.touchAction = ''; } props.scrollLocker?.unLock(); }); watch( () => props.placement, val => { if (val) { // test 的 bug, 有动画过场,删除 dom contentDom.value = null; } }, ); const domFocus = () => { dom.value?.focus?.(); }; const removeStartHandler = (e: TouchEvent) => { if (e.touches.length > 1) { return; } state.startPos = { x: e.touches[0].clientX, y: e.touches[0].clientY, }; }; const removeMoveHandler = (e: TouchEvent) => { if (e.changedTouches.length > 1) { return; } const currentTarget = e.currentTarget as HTMLElement; const differX = e.changedTouches[0].clientX - state.startPos.x; const differY = e.changedTouches[0].clientY - state.startPos.y; if ( (currentTarget === maskDom.value || currentTarget === handlerDom.value || (currentTarget === contentDom.value && getTouchParentScroll(currentTarget, e.target as HTMLElement, differX, differY))) && e.cancelable ) { e.preventDefault(); } }; const transitionEnd = (e: TransitionEvent) => { const dom: HTMLElement = e.target as HTMLElement; removeEventListener(dom, transitionEndFun, transitionEnd); dom.style.transition = ''; }; const onClose = (e: Event) => { emit('close', e); }; const onKeyDown = (e: KeyboardEvent) => { if (e.keyCode === KeyCode.ESC) { e.stopPropagation(); onClose(e); } }; const onWrapperTransitionEnd = (e: TransitionEvent) => { const { open, afterVisibleChange } = props; if (e.target === contentWrapper.value && e.propertyName.match(/transform$/)) { dom.value.style.transition = ''; if (!open && getCurrentDrawerSome()) { document.body.style.overflowX = ''; if (maskDom.value) { maskDom.value.style.left = ''; maskDom.value.style.width = ''; } } if (afterVisibleChange) { afterVisibleChange(!!open); } } }; const horizontalBoolAndPlacementName = computed(() => { const { placement } = props; const isHorizontal = placement === 'left' || placement === 'right'; const placementName = `translate${isHorizontal ? 'X' : 'Y'}`; return { isHorizontal, placementName, }; }); const openLevelTransition = () => { const { open, width, height } = props; const { isHorizontal, placementName } = horizontalBoolAndPlacementName.value; const contentValue = contentDom.value ? contentDom.value.getBoundingClientRect()[isHorizontal ? 'width' : 'height'] : 0; const value = (isHorizontal ? width : height) || contentValue; setLevelAndScrolling(open, placementName, value); }; const setLevelTransform = ( open?: boolean, placementName?: string, value?: string | number, right?: number, ) => { const { placement, levelMove, duration, ease, showMask } = props; // router 切换时可能会导至页面失去滚动条,所以需要时时获取。 levelDom.forEach(dom => { dom.style.transition = `transform ${duration} ${ease}`; addEventListener(dom, transitionEndFun, transitionEnd); let levelValue = open ? value : 0; if (levelMove) { const $levelMove = transformArguments(levelMove, { target: dom, open }); levelValue = open ? $levelMove[0] : $levelMove[1] || 0; } const $value = typeof levelValue === 'number' ? `${levelValue}px` : levelValue; let placementPos = placement === 'left' || placement === 'top' ? $value : `-${$value}`; placementPos = showMask && placement === 'right' && right ? `calc(${placementPos} + ${right}px)` : placementPos; dom.style.transform = levelValue ? `${placementName}(${placementPos})` : ''; }); }; const setLevelAndScrolling = ( open?: boolean, placementName?: string, value?: string | number, ) => { if (!windowIsUndefined) { const right = document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight) && window.innerWidth > document.body.offsetWidth ? getScrollBarSize(true) : 0; setLevelTransform(open, placementName, value, right); toggleScrollingToDrawerAndBody(right); } emit('change', open); }; const toggleScrollingToDrawerAndBody = (right: number) => { const { getContainer, showMask, open } = props; const container = getContainer?.(); // 处理 body 滚动 if (container && container.parentNode === document.body && showMask) { const eventArray = ['touchstart']; const domArray = [document.body, maskDom.value, handlerDom.value, contentDom.value]; if (open && document.body.style.overflow !== 'hidden') { if (right) { addScrollingEffect(right); } document.body.style.touchAction = 'none'; // 手机禁滚 domArray.forEach((item, i) => { if (!item) { return; } addEventListener( item, eventArray[i] || 'touchmove', i ? removeMoveHandler : removeStartHandler, passive, ); }); } else if (getCurrentDrawerSome()) { document.body.style.touchAction = ''; if (right) { remScrollingEffect(right); } // 恢复事件 domArray.forEach((item, i) => { if (!item) { return; } removeEventListener( item, eventArray[i] || 'touchmove', i ? removeMoveHandler : removeStartHandler, passive, ); }); } } }; const addScrollingEffect = (right: number) => { const { placement, duration, ease } = props; const widthTransition = `width ${duration} ${ease}`; const transformTransition = `transform ${duration} ${ease}`; dom.value.style.transition = 'none'; switch (placement) { case 'right': dom.value.style.transform = `translateX(-${right}px)`; break; case 'top': case 'bottom': dom.value.style.width = `calc(100% - ${right}px)`; dom.value.style.transform = 'translateZ(0)'; break; default: break; } clearTimeout(timeout); timeout = setTimeout(() => { if (dom.value) { dom.value.style.transition = `${transformTransition},${widthTransition}`; dom.value.style.width = ''; dom.value.style.transform = ''; } }); }; const remScrollingEffect = (right: number) => { const { placement, duration, ease } = props; dom.value.style.transition = 'none'; let heightTransition: string; let widthTransition = `width ${duration} ${ease}`; const transformTransition = `transform ${duration} ${ease}`; switch (placement) { case 'left': { dom.value.style.width = '100%'; widthTransition = `width 0s ${ease} ${duration}`; break; } case 'right': { dom.value.style.transform = `translateX(${right}px)`; dom.value.style.width = '100%'; widthTransition = `width 0s ${ease} ${duration}`; if (maskDom.value) { maskDom.value.style.left = `-${right}px`; maskDom.value.style.width = `calc(100% + ${right}px)`; } break; } case 'top': case 'bottom': { dom.value.style.width = `calc(100% + ${right}px)`; dom.value.style.height = '100%'; dom.value.style.transform = 'translateZ(0)'; heightTransition = `height 0s ${ease} ${duration}`; break; } default: break; } clearTimeout(timeout); timeout = setTimeout(() => { if (dom.value) { dom.value.style.transition = `${transformTransition},${ heightTransition ? `${heightTransition},` : '' }${widthTransition}`; dom.value.style.transform = ''; dom.value.style.width = ''; dom.value.style.height = ''; } }); }; const getCurrentDrawerSome = () => !Object.keys(currentDrawer).some(key => currentDrawer[key]); const getLevelDom = ({ level, getContainer }) => { if (windowIsUndefined) { return; } const container = getContainer?.(); const parent = container ? (container.parentNode as HTMLElement) : null; levelDom = []; if (level === 'all') { const children: HTMLElement[] = parent ? Array.prototype.slice.call(parent.children) : []; children.forEach((child: HTMLElement) => { if ( child.nodeName !== 'SCRIPT' && child.nodeName !== 'STYLE' && child.nodeName !== 'LINK' && child !== container ) { levelDom.push(child); } }); } else if (level) { dataToArray(level).forEach(key => { document.querySelectorAll(key).forEach(item => { levelDom.push(item); }); }); } }; const onHandleClick = e => { emit('handleClick', e); }; const canOpen = ref(false); watch(dom, () => { nextTick(() => { canOpen.value = true; }); }); return () => { const { width, height, open: $open, prefixCls, placement, level, levelMove, ease, duration, getContainer, onChange, afterVisibleChange, showMask, maskClosable, maskStyle, keyboard, getOpenCount, scrollLocker, contentWrapperStyle, style, class: className, ...otherProps } = props; // 首次渲染都将是关闭状态。 const open = $open && canOpen.value; const wrapperClassName = classnames(prefixCls, { [`${prefixCls}-${placement}`]: true, [`${prefixCls}-open`]: open, [className]: !!className, 'no-mask': !showMask, }); const { placementName } = horizontalBoolAndPlacementName.value; // 百分比与像素动画不同步,第一次打用后全用像素动画。 // const defaultValue = !this.contentDom || !level ? '100%' : `${value}px`; const placementPos = placement === 'left' || placement === 'top' ? '-100%' : '100%'; const transform = open ? '' : `${placementName}(${placementPos})`; return ( <div {...omit(otherProps, ['switchScrollingEffect', 'autofocus'])} tabindex={-1} class={wrapperClassName} style={style} ref={dom} onKeydown={open && keyboard ? onKeyDown : undefined} onTransitionend={onWrapperTransitionEnd} > {showMask && ( <div class={`${prefixCls}-mask`} onClick={maskClosable ? onClose : undefined} style={maskStyle} ref={maskDom} /> )} <div class={`${prefixCls}-content-wrapper`} style={{ transform, msTransform: transform, width: isNumeric(width) ? `${width}px` : width, height: isNumeric(height) ? `${height}px` : height, ...contentWrapperStyle, }} ref={contentWrapper} > <div class={`${prefixCls}-content`} ref={contentDom}> {slots.default?.()} </div> {slots.handler ? ( <div onClick={onHandleClick} ref={handlerDom}> {slots.handler?.()} </div> ) : null} </div> </div> ); }; }, }); export default DrawerChild;
the_stack
import * as $ from 'jquery'; import {isNull, isNullOrUndefined} from 'util'; import {AbstractPopupComponent} from '@common/component/abstract-popup.component'; import { AfterViewInit, Component, ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import {Alert} from '@common/util/alert.util'; import {StringUtil} from '@common/util/string.util'; import {PopupService} from '@common/service/popup.service'; import {GridComponent} from '@common/component/grid/grid.component'; import {Header, SlickGridHeader} from '@common/component/grid/grid.header'; import {GridOption} from '@common/component/grid/grid.option'; import {DsType, Field, PrDataset} from '@domain/data-preparation/pr-dataset'; import {DatasetService} from '../../../../../dataset/service/dataset.service'; import {PreparationAlert} from '../../../../../util/preparation-alert.util'; import {DataflowService} from '../../../../service/dataflow.service'; class JoinInfo { public leftJoinKey: string; public rightJoinKey: string; } @Component({ selector: 'app-rule-join-popup', templateUrl: './rule-join-popup.component.html', }) export class RuleJoinPopupComponent extends AbstractPopupComponent implements OnInit, OnDestroy, AfterViewInit { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild('leftGrid') public leftGrid: GridComponent; // 조인 대상 원본 데이터 그리드 @ViewChild('rightGrid') public rightGrid: GridComponent; // 조인할 데이터 그리드 @ViewChild('previewGrid') public previewGrid: GridComponent; // 미리보기용 데이터 그리드 // selected column list public leftSelCols: string[] = []; public rightSelCols: string[] = []; // wrangled / imported dataset public dsType: string = ''; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Input() public dfId: string; @Input() public serverSyncIndex: string; @Output() // 조인 팝업을 닫을때 사용하는 eventemitter public joinComplete = new EventEmitter(); @Input('existingDataSet') // public leftDataset: Dataset; // 기존 데이터 public leftDataset: PrDataset; // 기존 데이터 @Input() // public rightDataset: Dataset; // 조인하게될 선택된 데이터 셋 public rightDataset: PrDataset; // 조인하게될 선택된 데이터 셋 @Input() public editRuleStr: string; // 표시 형식 플래그 public viewModeforLeft: string = 'grid'; // viewMode for existing data : grid / table public viewModeforRight: string = 'grid'; // view mode for Join : gird/ table public isDatasetListShow: boolean = false; // 조인할 데이터셋 리스트 show/hide public searchText: string = ''; // 데이터셋 검색 public leftJoinKeySearchText: string = ''; public rightJoinKeySearchText: string = ''; // 조인 정보 public leftJoinKey: string = ''; // 기준 테이블의 조인 컬럼이름 public rightJoinKey: string = ''; // 대상 테이블의 조인 컬럼이름 public joinList: JoinInfo[] = []; // 조인 정보 목록 public selectedJoinType: string = 'LEFT'; // 선택된 조인 형식 // 조인키 컬럼 리스트 public isLeftDatasetShow: boolean = false; // 왼쪽 데이터셋 컬럼리스트 public isRightDatasetShow: boolean = false; // 오른쪽 데이터셋 컬럼리스트 public isShowPreview: boolean = false; // 미리보기 결과 표시 여부 public isDatatypesShow: boolean = false; public numberOfColumns: number; public numberOfRows: number; public numberOfBytes: number = 0; public dataTypesList: any[] = []; // 편집인지 생성인지 public joinButtonText: string = 'Join'; // 전체 선택 기능 for grid & table public leftCheckAll: boolean = true; public rightCheckAll: boolean = false; // 데이터셋 리스트 - selectbox 에서 사용할 리스트 // public datasets: Dataset[] = []; public datasets: PrDataset[] = []; // Show/hide datasets only in this flow public isChecked: boolean = true; // Flag for mouse movement and keyboard navigation public flag: boolean = false; // 데이터셋츠 필터링 된 리스트 get filteredDatasetsForJoin() { // 리스트 let list = this.datasets; const nameDupMap: any = {}; list.forEach((dataaset) => { const nameCnt = (nameDupMap[dataaset.dsName]) ? nameDupMap[dataaset.dsName] : 0; dataaset.nameCnt = nameCnt + 1; nameDupMap[dataaset.dsName] = nameCnt + 1; }); // 선택된 RightDataset은 표시 안함 if (this.rightDataset) { list = list.filter(dataset => this.rightDataset.dsId !== dataset.dsId); } // 검색어가 있는지 체크 const isSearchTextEmpty = StringUtil.isNotEmpty(this.searchText); // 검색어가 있다면 if (isSearchTextEmpty) { list = list.filter((dataset) => { return dataset.dsName.toLowerCase().indexOf(this.searchText.toLowerCase()) > -1; }); } // OnlyShow if (this.isChecked) { list = list.filter((dataset) => { return dataset.isCurrentDataflow; }); } else { list = list.filter((dataset) => { return !dataset.isCurrentDataflow; }); } return list; } // get - filteredDatasets get filteredLeftKeyList() { let leftkeyList = this.leftSelCols; // 검색어가 있는지 체크 const isLeftKeySearchTextEmpty = StringUtil.isNotEmpty(this.leftJoinKeySearchText); // 검색어가 있다면 if (isLeftKeySearchTextEmpty) { leftkeyList = leftkeyList.filter((item) => { return item.toLowerCase().indexOf(this.leftJoinKeySearchText.toLowerCase()) > -1; }); } return leftkeyList; } get filteredRightKeyList() { let rightkeyList = this.rightSelCols; // 검색어가 있는지 체크 const isRightKeySearchTextEmpty = StringUtil.isNotEmpty(this.rightJoinKeySearchText); // 검색어가 있다면 if (isRightKeySearchTextEmpty) { rightkeyList = rightkeyList.filter((item) => { return item.toLowerCase().indexOf(this.rightJoinKeySearchText.toLowerCase()) > -1; }); } return rightkeyList; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(protected popupService: PopupService, protected dataflowService: DataflowService, protected datasetService: DatasetService, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { super.ngOnInit(); if (this.rightDataset.dsId !== '') { // 편집모드 this.joinButtonText = this.rightDataset.joinButtonText; this.editVersionRightDataset(this.rightDataset); } else { // 처음생성할때 // this.rightDataset = new Dataset(); this.rightDataset = new PrDataset(); } this.getDatasets(); } public ngAfterViewInit() { if (this.rightDataset.dsId === '') { // 처음생성할때 this.updateGrid(this.leftDataset.gridData, this.leftGrid).then(() => { this.setLeftCheckAll(true); // Default가 전체체크 }); } else { // 편집모드 this.leftSelCols = this.rightDataset.leftSelectCol; this.updateGrid(this.leftDataset.gridData, this.leftGrid).then(() => { if (this.leftDataset.gridData.fields.length === this.rightDataset.leftSelectCol.length) { this.setLeftCheckAll(true); // Default가 전체체크 } else { this.rightDataset.leftSelectCol.forEach(colName => this.leftGrid.columnSelection(colName)); } }); } } // function - ngAfterViewInit public ngOnDestroy() { super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Returns size * @return {string[]} */ public getSize() { let size = 0; if (true === Number.isInteger(this.numberOfBytes)) { size = this.numberOfBytes; } return this.formatBytes(size, 1).split(' '); } /** * Returns number of columns * @return {string} */ public getColumns() { let cols = '0'; if (true === Number.isInteger(this.numberOfColumns)) { cols = new Intl.NumberFormat().format(this.numberOfColumns); } return cols; } /** * Returns number of rows * @return {string} */ public getRows() { let rows = '0'; if (true === Number.isInteger(this.numberOfRows)) { rows = new Intl.NumberFormat().format(this.numberOfRows); } return rows; } /** * 왼쪽 그리드 헤더 클릭 이벤트 핸들러 * @param {object} event */ public leftGridHeaderClickHandler(event: { id: string, isSelect: boolean }) { this.leftCheckAll = this.gridHeaderClickHandler(event, this.leftSelCols, this.leftDataset, this.leftCheckAll); } // function - leftGridHeaderClickHandler /** * 왼쪽 테이블 클릭 이벤트 핸들러 * @param {string} columnId */ public leftTableClickHandler(columnId: string) { this.leftCheckAll = this.gridHeaderClickHandler( { id: columnId, isSelect: !(-1 < this.leftSelCols.indexOf(columnId)) }, this.leftSelCols, this.leftDataset, this.leftCheckAll ); } // function - leftTableClickHandler /** * 오른쪽 그리드 헤더 클릭 이벤트 핸들러 * @param {object} event */ public rightGridHeaderClickHandler(event: { id: string, isSelect: boolean }) { this.rightCheckAll = this.gridHeaderClickHandler(event, this.rightSelCols, this.rightDataset, this.rightCheckAll); } // function - rightGridHeaderClickHandler /** * 오른쪽 테이블 클릭 이벤트 핸들러 * @param {string} columnId */ public rightTableClickHandler(columnId: string) { this.rightCheckAll = this.gridHeaderClickHandler( { id: columnId, isSelect: !(-1 < this.rightSelCols.indexOf(columnId)) }, this.rightSelCols, this.rightDataset, this.rightCheckAll ); } // function - rightTableClickHandler /** * 왼쪽 select All 체크박스 선택시 * @param {boolean} force 강제 설정 값 */ public setLeftCheckAll(force?: boolean) { // 체크 상태 변경 if ('undefined' === typeof force) { this.leftCheckAll = !this.leftCheckAll; } else { this.leftCheckAll = force; } this.leftSelCols = this.leftCheckAll ? this.leftDataset.gridData.fields.map(field => field.name) : []; if ('grid' === this.viewModeforLeft) { if (this.leftCheckAll) { this.leftGrid.columnAllSelection(); } else { this.leftGrid.columnAllUnSelection(); } } } // function - setLeftCheckAll /** * 오른쪽 select All 체크박스 선택시 */ public setRightCheckAll(force?: boolean) { // 체크 상태 변경 if ('undefined' === typeof force) { this.rightCheckAll = !this.rightCheckAll; } else { this.rightCheckAll = force; } this.rightSelCols = this.rightCheckAll ? this.rightDataset.gridData.fields.map(field => field.name) : []; if ('grid' === this.viewModeforRight) { if (this.rightCheckAll) { this.rightGrid.columnAllSelection(); } else { this.rightGrid.columnAllUnSelection(); } } } // function - rightCheckAllEventHandler /** * 오른쪽 컬럼 select 자동 체크 */ public setRightCheckOnLoad() { this.rightSelCols = this.leftSelCols.filter(col => { let included = false; this.rightDataset.gridData.fields.forEach(field => { if (col === field.name) { included = true; } }); return included; }); if (0 < this.rightSelCols.length && this.rightSelCols.length === this.rightDataset.gridData.fields.length) { this.rightCheckAll = true; } this.rightSelCols.forEach(colName => this.rightGrid.columnSelection(colName)); } // function - setRightCheckOnLoad /** * join key 정보를 목록에 추가한다 */ public addJoinKeys() { if (this.selectedJoinType === '' || this.leftJoinKey === '' || this.rightJoinKey === '') { return; } // 정보 등록 const info = new JoinInfo(); info.leftJoinKey = this.leftJoinKey; info.rightJoinKey = this.rightJoinKey; const found = this.joinList.find(elem => (elem.leftJoinKey === info.leftJoinKey && elem.rightJoinKey === info.rightJoinKey)); if (undefined === found) { this.joinList.push(info); } else { Alert.warning(this.translateService.instant('msg.dp.ui.join.key.error')); } this.leftJoinKey = ''; this.rightJoinKey = ''; // this.previewJoinResult(); // 조인 결과 미리보기 } // function - addToJoinKeys /** * 특정 인덱스의 정보를 목록에 제거한다. * @param {number} index */ public removeJoinInfo(index: number) { if (index > -1) { this.joinList.splice(index, 1); if (0 === this.joinList.length) { this.selectedJoinType = ''; } } } // function - removeJoinInfo /** * 선택된 조인 형식을 저장한다. * @param {string} joinType */ public selectJoinType(joinType: string) { this.selectedJoinType = joinType; } // function - selectJoinType /** * 왼쪽 데이터 영역 표시 변경 * @param viewMode */ public toggleViewModeforLeft(viewMode) { this.viewModeforLeft = viewMode; if ('grid' === this.viewModeforLeft) { this.updateGrid(this.leftDataset.gridData, this.leftGrid).then(() => { this.leftSelCols.forEach(colName => this.leftGrid.columnSelection(colName)); }); } } // function - toggleViewModeforLeft /** * 오른쪽 그리드 표시 변경 * @param viewMode */ public toggleViewModeforRight(viewMode) { this.viewModeforRight = viewMode; if ('grid' === this.viewModeforRight) { this.updateGrid(this.rightDataset.gridData, this.rightGrid).then(() => { this.rightSelCols.forEach(colName => this.rightGrid.columnSelection(colName)); }); } } // function - toggleViewModeforRight /** * 오른쪽 데이터셋 셀렉트박스 show/hide * @param event */ public showDatasetList(event) { event.stopImmediatePropagation(); this.isDatasetListShow = true; setTimeout(() => $('.ddp-input-search').trigger('focus')); } // function - showDatasetList /** * Check if left has right as upstream * @param leftDsId * @param _rightDsId * @param upstreams * @return {boolean} */ public notUpstream(leftDsId, _rightDsId, upstreams) { const ret = true; const list = [leftDsId]; while (0 < list.length) { const pop = list.shift(); /* self item can be on list if( pop === rightDsId ) { ret = false; break; } */ for (const us of upstreams) { if (us.dsId === pop) { if (false === list.includes(us.dsId)) { list.push(us.upstreamDsId); } } } } return ret; } /** * Get dataset list for right */ public getDatasets() { this.loadingShow(); // 페이징처리 없음 this.page.size = 10000; const params = { dsName: '', sort: 'modifiedTime,desc', dsType: this.dsType, page: this.page.page, size: this.page.size, }; this.datasetService.getDatasets(params) .then((data) => { // data 에서 dsType 이 wrangled 안것만 가지고 온다 ( 자기 자신은 제외 - existing data ) this.datasets = this.datasets.concat(data['_embedded'].preparationdatasets).filter((item) => { return item.dsType === DsType.WRANGLED && item.dsId !== this.leftDataset.dsId; }); // 처음엔 selected = false this.datasets.map((item) => { item.selected = false; }); this.dataflowService.getUpstreams(this.dfId) .then((upstreams) => { const upstreamList = upstreams.filter((upstream) => { if (upstream.dfId === this.dfId) { return true; } }); // 현재 플로우에 들어있는 dataset 인지 확인 this.datasets = this.datasets.map((obj) => { obj.isCurrentDataflow = false; if (obj.dataflows.length !== 0) { for (const _df of obj.dataflows) { if (_df.dfId === this.dfId) { if (true === this.notUpstream(this.leftDataset.dsId, obj.dsId, upstreamList)) { obj.isCurrentDataflow = true; } } } } return obj; }); this.loadingHide(); }) .catch((error) => { this.loadingHide(); const prepError = this.dataprepExceptionHandler(error); PreparationAlert.output(prepError, this.translateService.instant(prepError.message)); }); }) .catch((error) => { this.loadingHide(); const prepError = this.dataprepExceptionHandler(error); PreparationAlert.output(prepError, this.translateService.instant(prepError.message)); }); } // function - getDatasets /** * right dataset List 선택 이벤트 핸들러 * @param event * @param dataset */ public selectDataset(event, dataset) { event.stopImmediatePropagation(); this.loadingShow(); // 초기화 check상태 & 선택 된 columns this.rightSelCols = []; this.joinList = []; // 조인리스트 초기화 if (this.selectedJoinType === '') { // 기본 유지. 없을 때만 초기값 LEFT this.selectedJoinType = 'LEFT'; } this.rightCheckAll = false; // 전체 체크 해제 this.rightDataset = dataset; // 클릭된 데이터셋을 this.rightDataset에 넣는다 setTimeout(() => this.isDatasetListShow = false); // 셀렉트 박스 닫힘); this.dataflowService.getDatasetWrangledData(this.rightDataset.dsId) .then((result) => { const gridData = this.getGridDataFromGridResponse(result.gridResponse); // 데이터 미리보기 const data = gridData.data.slice(0, 100); this.rightDataset.data = JSON.stringify(data); this.rightDataset.gridData = gridData; this.updateGrid(this.rightDataset.gridData, this.rightGrid).then(() => { // 컬럼 자동 선택 // this.setRightCheckOnLoad(); this.setRightCheckAll(true); }); // 조인키 넣기 this.setJoinKeys(); this.loadingHide(); }) .catch((error) => { this.loadingHide(); const prepError = this.dataprepExceptionHandler(error); PreparationAlert.output(prepError, this.translateService.instant(prepError.message)); }); this.initSelectedCommand(this.filteredDatasetsForJoin); } // function - selectDataset /** * 조인 편집하려고 들어오면 원래 있던 값들을 다시 넣어준다 * @param dataset */ public editVersionRightDataset(dataset) { this.loadingShow(); // dataset 이름이 없어서 넣어준다 this.dataflowService.getDataset(dataset.dsId).then((data) => { this.rightDataset.dsName = data.dsName; }); this.dataflowService.getDatasetWrangledData(dataset.dsId) .then((result) => { this.loadingHide(); console.log('result', result); const gridData = this.getGridDataFromGridResponse(result.gridResponse); // 데이터 그리드 미리보기 const data = gridData.data.slice(0, 100); this.rightDataset.data = JSON.stringify(data); this.rightDataset.gridData = gridData; // 조인키를 넣어 준다 this.rightJoinKey = ''; this.leftJoinKey = ''; // 선택됐었던 column list 초기화 this.rightSelCols = []; this.rightSelCols = this.rightDataset.rightSelectCol; this.updateGrid(this.rightDataset.gridData, this.rightGrid).then(() => { if (this.rightDataset.gridData.fields.length === this.rightDataset.rightSelectCol.length) { this.setRightCheckAll(true); // Default가 전체체크 } else { this.rightDataset.rightSelectCol.forEach(colName => this.rightGrid.columnSelection(colName)); } }); // 조인 타입 입력 this.selectedJoinType = this.rightDataset.selectedJoinType.toUpperCase(); // 조인키가 하나 이상이라면 if (this.rightDataset.joinRuleList) { this.joinList = this.rightDataset.joinRuleList; } }) .catch((error) => { this.loadingHide(); const prepError = this.dataprepExceptionHandler(error); PreparationAlert.output(prepError, this.translateService.instant(prepError.message)); }); } // function - selectDataset /** * 팝업 닫기 */ public closeJoin() { this.joinComplete.emit({event: 'ruleJoinComplete'}); } // function - closeJoin /** * 조인 룰 적용 */ public applyJoinRule() { const ruleStr = this.generateRuleString(); if (!ruleStr[0]) { Alert.error(ruleStr[1]); return; } // 이벤트 if (this.joinButtonText !== 'Join') { // 편집 const rule = { command: 'join', op: 'UPDATE', ruleString: ruleStr[1], ruleIdx: this.serverSyncIndex, uiRuleString: ruleStr[2] }; this.joinComplete.emit({event: 'ruleJoinComplete', ruleInfo: rule}); } else { // 생성 const rule = { command: 'join', op: 'APPEND', ruleString: ruleStr[1], uiRuleString: ruleStr[2] }; this.joinComplete.emit( { event: 'ruleJoinComplete', ruleInfo: rule, ruleIdx: this.serverSyncIndex }); } } // function - applyJoinRule /** * 조인키 왼쪽 selectbox show/hide */ public showLeftDataset(event) { event.stopImmediatePropagation(); this.isLeftDatasetShow = true; this.isRightDatasetShow = false; } // function - showLeftDataset /** * 조인키 오른쪽 selectbox show/hide */ public showRightDataset(event) { event.stopImmediatePropagation(); this.isRightDatasetShow = true; this.isLeftDatasetShow = false; } // function - showRightDataset /** * 조인키 왼쪽 selectbox 선택시 */ public onLeftJoinKeySelected(event, key) { event.stopImmediatePropagation(); if (key === 'Empty') { return; } this.leftJoinKey = key; for (const field of this.rightDataset.gridData.fields) { if (field.name && key === field.name) { this.rightJoinKey = key; break; } } setTimeout(() => this.isLeftDatasetShow = false); } // function - onLeftJoinKeySelected /** * 조인키 오른쪽 selectbox 선택시 */ public onRightJoinKeySelected(event, key) { event.stopImmediatePropagation(); if (key === 'Empty') { return; } this.rightJoinKey = key; if (this.leftJoinKey === '') { for (const field of this.leftDataset.gridData.fields) { if (field.name && key === field.name) { this.leftJoinKey = key; break; } } } setTimeout(() => this.isRightDatasetShow = false); } // function - onRightJoinKeySelected public showTypeList(event) { if (event.target.tagName !== 'A') { // Not sure if this is a good idea.. this.isDatatypesShow = !this.isDatatypesShow; } } /** * API의 gridResponse 를 통해서 UI 상의 그리드데이터를 얻는다 * @param gridResponse 매트릭스 정보 * @returns 그리드 데이터 */ private getGridDataFromGridResponse(gridResponse: any) { const colCnt = gridResponse.colCnt; const colNames = gridResponse.colNames; const colTypes = gridResponse.colDescs; const gridData = { data: [], fields: [] }; for (let idx = 0; idx < colCnt; idx++) { gridData.fields.push({ name: colNames[idx], type: colTypes[idx].type, seq: idx }); } gridResponse.rows.forEach((row) => { const obj = {}; for (let idx = 0; idx < colCnt; idx++) { obj[colNames[idx]] = row.objCols[idx]; } gridData.data.push(obj); }); return gridData; } // function - getGridDataFromGridResponse /** * 룰 문자열을 생성한다. */ public generateRuleString(): [boolean, string, object] { if (0 === this.leftSelCols.length) { return [false, this.translateService.instant('msg.dp.alert.sel.left.col'), null]; } if (0 === this.rightSelCols.length) { return [false, this.translateService.instant('msg.dp.alert.sel.right.col'), null]; } if ('' === this.selectedJoinType) { return [false, this.translateService.instant('msg.dp.alert.sel.join.type'), null]; } if (0 === this.joinList.length) { return [false, this.translateService.instant('msg.dp.alert.sel.join.key'), null]; } for (const joinKey of this.joinList) { if (false === this.leftSelCols.includes(joinKey.leftJoinKey)) { return [false, this.translateService.instant('msg.dp.alert.left.joinkey.error', {leftJoinKey: joinKey.leftJoinKey}), null]; } if (false === this.rightSelCols.includes(joinKey.rightJoinKey)) { return [false, this.translateService.instant('msg.dp.alert.right.joinkey.error', {rightJoinKey: joinKey.rightJoinKey}), null]; } } const conditions = this.joinList.map((joinInfo) => { return ('`' + joinInfo.leftJoinKey + '`') + '=' + ('`' + joinInfo.rightJoinKey + '`') }).join(' && '); let ruleStr: string = ''; ruleStr += `join leftSelectCol: ${this.getColumnNamesInArray(this.leftSelCols, '', '`').toString()}`; ruleStr += ` rightSelectCol: ${this.getColumnNamesInArray(this.rightSelCols, '', '`').toString()}`; ruleStr += ' condition: ' + conditions + ' joinType: \'' + this.selectedJoinType.toLowerCase() + '\' dataset2: \'' + this.rightDataset.dsId + '\''; const uiRuleString = { name: 'join', isBuilder: true, leftJoinKey: this.getColumnNamesInArray(this.joinList, 'leftJoinKey'), rightJoinKey: this.getColumnNamesInArray(this.joinList, 'rightJoinKey'), joinType: this.selectedJoinType, dataset2: this.rightDataset.dsId, rightCol: this.getColumnNamesInArray(this.rightSelCols, ''), leftCol: this.getColumnNamesInArray(this.leftSelCols, '') }; return [true, ruleStr, uiRuleString]; } // function - generateRuleString /** * 조인 결과를 미리 확인한다. */ public previewJoinResult() { if (this.joinList.length === 0) { return; } this.isShowPreview = true; // 기능이 동학하지 않아 임시 주석 처리함 -> 프리뷰 API 확인 후 주석 풀어서 기능 체크해야 함 this.loadingShow(); const ruleStr = this.generateRuleString(); if (!ruleStr[0]) { Alert.warning(ruleStr[1]); this.isShowPreview = false; this.loadingHide(); return; } // PREVIEW index = APPEND: next index || UPDATE: current index let syncIndex: number = Number(this.serverSyncIndex); if (syncIndex !== this.leftDataset.ruleCurIdx) { // when command is UPDATE, this.leftDataset.ruleCurIdx is syncIndex - 1; syncIndex = this.leftDataset.ruleCurIdx; } const rule = {command: 'join', op: 'PREVIEW', ruleString: ruleStr[1], ruleIdx: syncIndex}; this.dataflowService.applyRules(this.leftDataset.dsId, rule) .then((data) => { this.loadingHide(); if (data.errorMsg) { Alert.warning(this.translateService.instant('msg.dp.alert.apply.rule.fail')); } else { // 그리드 정보 (columns, rows, bytes etc) this.numberOfColumns = data['gridResponse'].colCnt; this.numberOfRows = data['gridResponse'].rows.length; this.numberOfBytes = 0; const gridData = this.getGridDataFromGridResponse(data.gridResponse); this._summaryGridInfo(gridData); this.updateGrid(gridData, this.previewGrid); } }) .catch((error) => { this.isShowPreview = false; this.loadingHide(); const prepError = this.dataprepExceptionHandler(error); PreparationAlert.output(prepError, this.translateService.instant(prepError.message)); }); } // function - previewJoinResult /** * 그리드 요약 정보 설정 * @param {GridData} gridData * @private */ private _summaryGridInfo(gridData: any) { // init type list this.dataTypesList = []; if (!isNullOrUndefined(gridData.fields)) { const tempMap: Map<string, number> = new Map(); gridData.fields.forEach((item) => { if (tempMap.get(item.type) > -1) { const temp = tempMap.get(item.type) + 1; tempMap.set(item.type, temp); } else { tempMap.set(item.type, 1); } }); tempMap.forEach((value: number, key: string) => { this.dataTypesList.push({label: key, value: value < 2 ? `${value} column` : `${value} columns`}); }); } } // function - _summaryGridInfo /** * 그리드 갱신 * @param {any} data 데이터셋 * @param {GridComponent} targetGrid 변경 대상 그리드 */ public updateGrid(data: any, targetGrid: GridComponent) { return new Promise((resolve) => { // 헤더정보 생성 const headers: Header[] = data.fields.map( (field: Field) => { return new SlickGridHeader() .Id(field.name) .Name('<span style="padding-left:20px;"><em class="' + this.getFieldTypeIconClass(field.type) + '"></em>' + field.name + '</span>') .Field(field.name) .Behavior('select') .Selectable(false) .CssClass('cell-selection') .Width(10 * (field.name.length) + 20) .MinWidth(100) .CannotTriggerInsert(true) .Resizable(true) .Unselectable(false) .Sortable(false) .Formatter(( (_scope) => { return (_row, _cell, value, columnDef, _dataContext) => { if (isNull(value) && columnDef.select) { return '<div style=\'background-color:#d6d9f1; position:absolute; top:0; left:0; right:0; bottom:0; line-height:30px; padding:0 10px; font-style: italic ; color:#b8bac2;\'>' + '(null)' + '</div>'; } else if (isNull(value) && !columnDef.select) { return '<div style=\'color:#b8bac2; font-style: italic ;line-height:30px;\'>' + '(null)' + '</div>'; } else if (!isNull(value) && columnDef.select) { return '<div style=\'background-color:#d6d9f1; position:absolute; top:0; left:0; right:0; bottom:0; line-height:30px; padding:0 10px;\'>' + value + '</div>'; } else if (columnDef.id === '_idProperty_') { return '<div style=\'line-height:30px;\'>' + '&middot;' + '</div>'; } else { return value; } }; })(this)) .build(); } ); let rows: any[] = data.data; const list = []; data.fields.filter((item) => { // 타입이 array or map인 경우에 리스트에 이름을 뺸다. if (item.type === 'MAP' || item.type === 'ARRAY') { list.push(item.name); } }); if (data.data.length > 0 && !data.data[0].hasOwnProperty('id')) { list.filter((item) => { rows = rows.map((row: any, idx: number) => { row.id = idx; isNull(row[item]) ? null : row[item] = JSON.stringify(row[item]); return row; }); }) } if (this.isShowPreview) { setTimeout(() => { targetGrid.create(headers, rows, new GridOption() .SyncColumnCellResize(true) .RowHeight(32) .NullCellStyleActivate(true) .EnableColumnReorder(false) .build() ); resolve(null); }, 100); } else { setTimeout(() => { targetGrid.create(headers, rows, new GridOption() .EnableHeaderClick(true) .SyncColumnCellResize(true) .EnableColumnReorder(false) .NullCellStyleActivate(true) .RowHeight(32) .build() ); resolve(null); }, 100); } }); } // function - updateGrid /** * Select box for commands - navigate with keyboard * @param event 이벤트 * @param currentList 현재 사용하는 리스트 * @param method */ public navigateWithKeyboardShortList(event, currentList, method) { // set scroll height const height = 25; // open select box when arrow up/ arrow down is pressed if (event.keyCode === 38 || event.keyCode === 40) { switch (method) { case 'right' : !this.isDatasetListShow ? this.isDatasetListShow = true : null; break; case 'joinLeft' : !this.isLeftDatasetShow ? this.isLeftDatasetShow = true : null; break; case 'joinRight' : !this.isRightDatasetShow ? this.isRightDatasetShow = true : null; break; } } // when there is no element in the list if (currentList.length === 0) { return; } // this.commandList 에 마지막 인덱스 const lastIndex = currentList.length - 1; // command List 에서 selected 된 index 를 찾는다 const idx = currentList.findIndex((command) => { if (command.selected) { return command; } }); // when Arrow up is pressed if (event.keyCode === 38) { // 선택된게 없다 if (idx === -1) { // 리스트에 마지막 인덱스를 selected 로 바꾼다 currentList[lastIndex].selected = true; // 스크롤을 마지막으로 보낸다 $('.ddp-list-selectbox2').scrollTop(lastIndex * height); // 리스트에서 가장 첫번쨰가 선택되어 있는데 arrow up 을 누르면 리스트에 마지막으로 보낸다 } else if (idx === 0) { currentList[0].selected = false; currentList[lastIndex].selected = true; // 스크롤을 마지막으로 보낸다 $('.ddp-list-selectbox2').scrollTop(lastIndex * height); } else { currentList[idx].selected = false; currentList[idx - 1].selected = true; $('.ddp-list-selectbox2').scrollTop((idx - 1) * height); } // when Arrow down is pressed } else if (event.keyCode === 40) { // 리스트에 첫번째 인텍스를 selected 로 바꾼다 if (idx === -1) { currentList[0].selected = true; // 리스트에서 가장 마지막이 선택되어 있는데 arrow down 을 누르면 다시 리스트 0번째로 이동한다 } else if (idx === lastIndex) { currentList[0].selected = true; currentList[lastIndex].selected = false; $('.ddp-list-selectbox2').scrollTop(0); } else { currentList[idx].selected = false; currentList[idx + 1].selected = true; $('.ddp-list-selectbox2').scrollTop((idx + 1) * height); } } // enter if (event.keyCode === 13) { // selected 된 index 를 찾는다 const selectedIdx = currentList.findIndex((command) => { if (command.selected) { return command; } }); // 선택된게 없는데 엔터를 눌렀을때 if (selectedIdx === -1) { return; } else { switch (method) { case 'right' : this.selectDataset(event, currentList[selectedIdx]); break; case 'joinLeft' : break; case 'joinRight' : break; } } // 스크롤, command select 초기화 this.initSelectedCommand(currentList); } } /** * change commandList selected -> false (초기화) */ public initSelectedCommand(list) { list.forEach((item) => { return item.selected = false; }); } // function - initSelectedCommand /** * nestlist, typelist, patternlist,movelist, quotelist 에서 mouseover 일때 Selected = true * @param event * @param list * @param index */ public listMouseOverAndOut(event, list, index) { if (!this.flag) { if (event.type === 'mouseover') { list[index].selected = true; } else if (event.type === 'mouseout') { this.initSelectedCommand(list); } } } // function - listMouseOver /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ private formatBytes(a, b) { // a=크기 , b=소숫점자릿 if (0 === a) return '0 Bytes'; const c = 1024; const d = b || 2; const e = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const f = Math.floor(Math.log(a) / Math.log(c)); return parseFloat((a / Math.pow(c, f)).toFixed(d)) + ' ' + e[f]; } /** * 왼쪽 그리드 헤더 클릭 이벤트 핸들러 * @param {object} event * @param {string[]} selectCols * @param {PrDataset} dataset * @param {boolean} checkAll */ // private gridHeaderClickHandler(event: { id: string, isSelect: boolean }, selectCols: string[], dataset: Dataset, checkAll: boolean) { private gridHeaderClickHandler(event: { id: string, isSelect: boolean }, selectCols: string[], dataset: PrDataset, checkAll: boolean) { // 선택 결과에 따라 선택 항목을 재조정한다 const colIdx = selectCols.indexOf(event.id); if (event.isSelect) { (-1 === colIdx) && (selectCols.push(event.id)); } else { (-1 < colIdx) && (selectCols.splice(colIdx, 1)); } // Check All 여부 checkAll = (dataset.gridData.fields.length === selectCols.length); return checkAll; } // function - gridHeaderClickHandler /** * 조인 키 설정 */ private setJoinKeys() { // 오른쪽 데이터셋을 바꿨을 때 left 의 첫번째 field를 넣고, right는 왼쪽과 동일한 field를 넣는데, 같은게 없으면 Empty 로 넣는다 this.leftJoinKey = this.leftSelCols[0]; const tempField = this.rightSelCols.filter(field => (this.leftJoinKey === field)); if (tempField.length !== 0) { this.rightJoinKey = tempField[0]; } else { this.leftJoinKey = ''; this.rightJoinKey = ''; } } // function - setJoinKeys /** * * @param fields * @param label * @param wrapChar */ protected getColumnNamesInArray(fields: any, label: string, wrapChar?: string): string[] { return fields.map((item) => { if (label !== '' && wrapChar) { return wrapChar + item[label] + wrapChar } if (label !== '' && !wrapChar) { return item[label] } if (label === '' && wrapChar) { return wrapChar + item + wrapChar } if (label === '' && !wrapChar) { return item } }); } }
the_stack
import { dirname, basename, resolve } from 'path'; import * as semver from 'semver'; import { ensureDir, emptyDir, readFile, readJson, writeFile, copy, remove, rename, chmod, createReadStream, createWriteStream, readdir } from 'fs-extra'; import * as Bluebird from 'bluebird'; const debug = require('debug')('build:builder'); const globby = require('globby'); const rcedit = require('rcedit'); const plist = require('plist'); import { Downloader } from './Downloader'; import { FFmpegDownloader } from './FFmpegDownloader'; import { BuildConfig } from './config'; import { NsisVersionInfo, DownloaderBase } from './common'; import { NsisComposer, NsisDiffer, Nsis7Zipper, nsisBuild } from './nsis-gen'; import { mergeOptions, findExecutable, findFFmpeg, findRuntimeRoot, findExcludableDependencies, tmpName, tmpFile, tmpDir, fixWindowsVersion, copyFileAsync, extractGeneric, compress } from './util'; export interface IParseOutputPatternOptions { name: string; version: string; platform: string; arch: string; } export interface IBuilderOptions { win?: boolean; mac?: boolean; linux?: boolean; x86?: boolean; x64?: boolean; tasks?: string[]; chromeApp?: boolean; mirror?: string; concurrent?: boolean; mute?: boolean; forceCaches?: boolean; destination?: string; } export class Builder { public static DEFAULT_OPTIONS: IBuilderOptions = { win: false, mac: false, linux: false, x86: false, x64: false, tasks: [], chromeApp: false, mirror: Downloader.DEFAULT_OPTIONS.mirror, concurrent: false, mute: true, forceCaches: Downloader.DEFAULT_OPTIONS.forceCaches, destination: DownloaderBase.DEFAULT_DESTINATION, }; public options: IBuilderOptions; constructor(options: IBuilderOptions = {}, public dir: string) { this.options = mergeOptions(Builder.DEFAULT_OPTIONS, options); debug('in constructor', 'dir', dir); debug('in constructor', 'options', this.options); } public async build() { const tasks: string[][] = []; [ 'win', 'mac', 'linux' ].map((platform) => { [ 'x86', 'x64' ].map((arch) => { if((<any>this.options)[platform] && (<any>this.options)[arch]) { tasks.push([ platform, arch ]); } }); }); for(const task of this.options.tasks) { const [ platform, arch ] = task.split('-'); if([ 'win', 'mac', 'linux' ].indexOf(platform) >= 0) { if([ 'x86', 'x64' ].indexOf(arch) >= 0) { tasks.push([ platform, arch ]); } } } if(!this.options.mute) { console.info('Starting building tasks...', { tasks, concurrent: this.options.concurrent, }); } if(tasks.length == 0) { throw new Error('ERROR_NO_TASK'); } if(this.options.concurrent) { await Bluebird.map(tasks, async ([ platform, arch ]) => { const options: any = {}; options[platform] = true; options[arch] = true; options.mirror = this.options.mirror; options.concurrent = false; options.mute = true; const builder = new Builder(options, this.dir); const started = Date.now(); if(!this.options.mute) { console.info(`Building for ${ platform }, ${ arch } starts...`); } await builder.build(); if(!this.options.mute) { console.info(`Building for ${ platform }, ${ arch } ends within ${ this.getTimeDiff(started) }s.`); } }); } else { const pkg: any = await readJson(resolve(this.dir, this.options.chromeApp ? 'manifest.json' : 'package.json')); const config = new BuildConfig(pkg); debug('in build', 'config', config); for(const [ platform, arch ] of tasks) { const started = Date.now(); if(!this.options.mute) { console.info(`Building for ${ platform }, ${ arch } starts...`); } try { await this.buildTask(platform, arch, pkg, config); } catch(err) { console.warn(err); } if(!this.options.mute) { console.info(`Building for ${ platform }, ${ arch } ends within ${ this.getTimeDiff(started) }s.`); } } } } protected getTimeDiff(started: number) { return ((Date.now() - started) / 1000).toFixed(2); } protected async writeStrippedManifest(path: string, pkg: any, config: BuildConfig) { const json: any = {}; for(const key in pkg) { if(pkg.hasOwnProperty(key) && config.strippedProperties.indexOf(key) === -1) { if (config.overriddenProperties && config.overriddenProperties.hasOwnProperty(key) ) { json[key] = config.overriddenProperties[key]; } else { json[key] = pkg[key]; } } } await writeFile(path, JSON.stringify(json)); } protected parseOutputPattern(pattern: string, options: IParseOutputPatternOptions, pkg: any, config: BuildConfig) { return pattern.replace(/\$\{\s*(\w+)\s*\}/g, (match: string, key: string) => { switch(key.toLowerCase()) { case 'name': return options.name; case 'version': return options.version; case 'platform': return options.platform; case 'arch': return options.arch; default: throw new Error('ERROR_KEY_UNKNOWN'); } }); } protected combineExecutable(executable: string, nwFile: string) { return new Promise((resolve, reject) => { const nwStream = createReadStream(nwFile); const stream = createWriteStream(executable, { flags: 'a', }); nwStream.on('error', reject); stream.on('error', reject); stream.on('finish', resolve); nwStream.pipe(stream); }); } protected readPlist(path: string): Promise<any> { return readFile(path, { encoding: 'utf-8', }) .then(data => plist.parse(data)); } protected writePlist(path: string, p: any) { return writeFile(path, plist.build(p)); } protected updateWinResources(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const pathResolve = resolve; return new Promise((resolve, reject) => { const path = pathResolve(targetDir, 'nw.exe'); const rc = { 'product-version': fixWindowsVersion(config.win.productVersion), 'file-version': fixWindowsVersion(config.win.fileVersion), 'version-string': { ProductName: config.win.productName, CompanyName: config.win.companyName, FileDescription: config.win.fileDescription, LegalCopyright: config.win.copyright, ...config.win.versionStrings, }, 'icon': config.win.icon ? pathResolve(this.dir, config.win.icon) : undefined, }; rcedit(path, rc, (err: Error) => err ? reject(err) : resolve()); }); } protected renameWinApp(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const src = resolve(targetDir, 'nw.exe'); const dest = resolve(targetDir, `${ config.win.productName }.exe`); return rename(src, dest); } protected async updatePlist(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const path = resolve(targetDir, './nwjs.app/Contents/Info.plist'); const plist = await this.readPlist(path); plist.CFBundleIdentifier = config.appId; plist.CFBundleName = config.mac.name; plist.CFBundleExecutable = config.mac.displayName; plist.CFBundleDisplayName = config.mac.displayName; plist.CFBundleVersion = config.mac.version; plist.CFBundleShortVersionString = config.mac.version; for(const key in config.mac.plistStrings) { if(config.mac.plistStrings.hasOwnProperty(key)) { plist[key] = config.mac.plistStrings[key]; } } await this.writePlist(path, plist); } protected async updateHelperPlist(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { if (!this.canRenameMacHelperApp(pkg, config)) { return; } const helperPath = await this.findMacHelperApp(targetDir); const path = resolve(helperPath, 'Contents/Info.plist'); const plist = await this.readPlist(path); const bin = pkg.product_string + ' Helper'; plist.CFBundleIdentifier = config.appId + '.helper'; plist.CFBundleDisplayName = bin; plist.CFBundleExecutable = bin; plist.CFBundleName = bin; await this.writePlist(path, plist); } protected async updateMacIcons(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const copyIcon = async (iconPath: string, dest: string) => { if(!iconPath) { // use the default return; } await copy(resolve(this.dir, iconPath), dest); }; await copyIcon(config.mac.icon, resolve(targetDir, './nwjs.app/Contents/Resources/app.icns')); await copyIcon(config.mac.documentIcon, resolve(targetDir, './nwjs.app/Contents/Resources/document.icns')); } protected async fixMacMeta(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const files = await globby([ '**/InfoPlist.strings' ], { cwd: targetDir, }); for(const file of files) { const path = resolve(targetDir, file); // Different versions has different encodings for `InforPlist.strings`. // We determine encoding by evaluating bytes of `CF` here. const data = await readFile(path); const encoding = data.indexOf(Buffer.from('43004600', 'hex')) >= 0 ? 'ucs2' : 'utf-8'; const strings = data.toString(encoding); const newStrings = strings.replace(/([A-Za-z]+)\s+=\s+"(.+?)";/g, (match: string, key: string, value: string) => { switch(key) { case 'CFBundleName': return `${ key } = "${ config.mac.name }";`; case 'CFBundleDisplayName': return `${ key } = "${ config.mac.displayName }";`; case 'CFBundleGetInfoString': return `${ key } = "${ config.mac.version }";`; case 'NSContactsUsageDescription': return `${ key } = "${ config.mac.description }";`; case 'NSHumanReadableCopyright': return `${ key } = "${ config.mac.copyright }";`; default: return `${ key } = "${ value }";`; } }); await writeFile(path, Buffer.from(newStrings, encoding)); } } protected async renameMacApp(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const app = resolve(targetDir, 'nwjs.app'); const bin = resolve(app, './Contents/MacOS/nwjs'); let dest = bin.replace(/nwjs$/, config.mac.displayName); await rename(bin, dest); dest = app.replace(/nwjs\.app$/, `${config.mac.displayName}.app`); return rename(app, dest); } protected async renameMacHelperApp(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { if (!this.canRenameMacHelperApp(pkg, config)) { return; } const app = await this.findMacHelperApp(targetDir); const bin = resolve(app, './Contents/MacOS/nwjs Helper'); let dest = bin.replace(/nwjs Helper$/, `${pkg.product_string} Helper`); await rename(bin, dest); dest = app.replace(/nwjs Helper\.app$/, `${pkg.product_string} Helper.app`); return rename(app, dest); } protected canRenameMacHelperApp(pkg: any, config: BuildConfig): boolean { if (semver.lt(config.nwVersion, '0.24.4')) { // this version doesn't support Helper app renaming. return false; } if (!pkg.product_string) { // we can't rename the Helper app as we don't have a new name. return false; } return true; } protected async findMacHelperApp(targetDir: string): Promise<string> { const path = resolve(targetDir, './nwjs.app/Contents/Versions'); // what version are we actually dealing with? const versions = await readdir(path); if (!versions || versions.length !== 1) { throw new Error("Can't rename the Helper as we can't find it"); } return resolve(path, versions[0], 'nwjs Helper.app'); } protected async fixLinuxMode(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const path = resolve(targetDir, 'nw'); await chmod(path, 0o744); } protected renameLinuxApp(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const src = resolve(targetDir, 'nw'); const dest = resolve(targetDir, `${ pkg.name }`); return rename(src, dest); } protected async prepareWinBuild(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { await this.updateWinResources(targetDir, appRoot, pkg, config); } protected async prepareMacBuild(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { await this.updateHelperPlist(targetDir, appRoot, pkg, config); await this.updatePlist(targetDir, appRoot, pkg, config); await this.updateMacIcons(targetDir, appRoot, pkg, config); await this.fixMacMeta(targetDir, appRoot, pkg, config); } protected async prepareLinuxBuild(targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { await this.fixLinuxMode(targetDir, appRoot, pkg, config); } protected async copyFiles(platform: string, targetDir: string, appRoot: string, pkg: any, config: BuildConfig) { const generalExcludes = [ '**/node_modules/.bin', '**/node_modules/*/{ example, examples, test, tests }', '**/{ .DS_Store, .git, .hg, .svn, *.log }', ]; const dependenciesExcludes = await findExcludableDependencies(this.dir, pkg) .then((excludable) => { return excludable.map(excludable => [ excludable, `${ excludable }/**/*` ]); }) .then((excludes) => { return Array.prototype.concat.apply([], excludes); }); debug('in copyFiles', 'dependenciesExcludes', dependenciesExcludes); const ignore = [ ...config.excludes, ...generalExcludes, ...dependenciesExcludes, ...[ config.output, `${ config.output }/**/*` ] ]; debug('in copyFiles', 'ignore', ignore); const files: string[] = await globby(config.files, { cwd: this.dir, // TODO: https://github.com/isaacs/node-glob#options, warn for cyclic links. follow: true, mark: true, ignore, }); debug('in copyFiles', 'config.files', config.files); debug('in copyFiles', 'files', files); if(config.packed) { switch(platform) { case 'win32': case 'win': case 'linux': const nwFile = await tmpName({ postfix: '.zip', }); await compress(this.dir, files.filter((file) => !file.endsWith('/')), 'zip', nwFile); const { path: tempDir } = await tmpDir(); await this.writeStrippedManifest(resolve(tempDir, 'package.json'), pkg, config); await compress(tempDir, [ './package.json' ], 'zip', nwFile); await remove(tempDir); const executable = await findExecutable(platform, targetDir); await this.combineExecutable(executable, nwFile); await remove(nwFile); break; case 'darwin': case 'osx': case 'mac': for(const file of files) { await copyFileAsync(resolve(this.dir, file), resolve(appRoot, file)); } await this.writeStrippedManifest(resolve(appRoot, 'package.json'), pkg, config); break; default: throw new Error('ERROR_UNKNOWN_PLATFORM'); } } else { for(const file of files) { await copyFileAsync(resolve(this.dir, file), resolve(appRoot, file)); } await this.writeStrippedManifest(resolve(appRoot, 'package.json'), pkg, config); } } protected async integrateFFmpeg(platform: string, arch: string, targetDir: string, pkg: any, config: BuildConfig) { const downloader = new FFmpegDownloader({ platform, arch, version: config.nwVersion, useCaches: true, showProgress: this.options.mute ? false : true, destination: this.options.destination, }); if(!this.options.mute) { console.info('Fetching FFmpeg prebuilt...', { platform: downloader.options.platform, arch: downloader.options.arch, version: downloader.options.version, }); } const ffmpegDir = await downloader.fetchAndExtract(); const src = await findFFmpeg(platform, ffmpegDir); const dest = await findFFmpeg(platform, targetDir); await copy(src, dest); } protected async buildNsisDiffUpdater(platform: string, arch: string, versionInfo: NsisVersionInfo, fromVersion: string, toVersion: string, pkg: any, config: BuildConfig) { const diffNsis = resolve(this.dir, config.output, `${ pkg.name }-${ toVersion }-from-${ fromVersion }-${ platform }-${ arch }-Update.exe`); const fromDir = resolve(this.dir, config.output, (await versionInfo.getVersion(fromVersion)).source); const toDir = resolve(this.dir, config.output, (await versionInfo.getVersion(toVersion)).source); const data = await (new NsisDiffer(fromDir, toDir, { // Basic. appName: config.win.productName, companyName: config.win.companyName, description: config.win.fileDescription, version: fixWindowsVersion(config.win.productVersion), copyright: config.win.copyright, icon: config.nsis.icon ? resolve(this.dir, config.nsis.icon) : undefined, unIcon: config.nsis.unIcon ? resolve(this.dir, config.nsis.unIcon) : undefined, // Compression. compression: 'lzma', solid: true, languages: config.nsis.languages, installDirectory: config.nsis.installDirectory, // Output. output: diffNsis, })).make(); const script = await tmpName(); await writeFile(script, data); await nsisBuild(toDir, script, { mute: this.options.mute, }); await remove(script); await versionInfo.addUpdater(toVersion, fromVersion, arch, diffNsis); } protected async buildDirTarget(platform: string, arch: string, runtimeDir: string, pkg: any, config: BuildConfig): Promise<string> { const targetDir = resolve(this.dir, config.output, this.parseOutputPattern(config.outputPattern, { name: pkg.name, version: pkg.version, platform, arch, }, pkg, config)); const runtimeRoot = await findRuntimeRoot(platform, runtimeDir); const appRoot = resolve(targetDir, (() => { switch(platform) { case 'win32': case 'win': case 'linux': return './'; case 'darwin': case 'osx': case 'mac': return './nwjs.app/Contents/Resources/app.nw/'; default: throw new Error('ERROR_UNKNOWN_PLATFORM'); } })()); await emptyDir(targetDir); await copy(runtimeRoot, targetDir, { //dereference: true, }); if(config.ffmpegIntegration) { await this.integrateFFmpeg(platform, arch, targetDir, pkg, config); } await ensureDir(appRoot); // Copy before refining might void the effort. switch(platform) { case 'win32': case 'win': await this.prepareWinBuild(targetDir, appRoot, pkg, config); await this.copyFiles(platform, targetDir, appRoot, pkg, config); await this.renameWinApp(targetDir, appRoot, pkg, config); break; case 'darwin': case 'osx': case 'mac': await this.prepareMacBuild(targetDir, appRoot, pkg, config); await this.copyFiles(platform, targetDir, appRoot, pkg, config); // rename Helper before main app rename. await this.renameMacHelperApp(targetDir, appRoot, pkg, config); await this.renameMacApp(targetDir, appRoot, pkg, config); break; case 'linux': await this.prepareLinuxBuild(targetDir, appRoot, pkg, config); await this.copyFiles(platform, targetDir, appRoot, pkg, config); await this.renameLinuxApp(targetDir, appRoot, pkg, config); break; default: throw new Error('ERROR_UNKNOWN_PLATFORM'); } return targetDir; } protected async buildArchiveTarget(type: string, sourceDir: string) { const targetArchive = resolve(dirname(sourceDir), `${ basename(sourceDir) }.${ type }`); await remove(targetArchive); const files = await globby([ '**/*' ], { cwd: sourceDir, }); await compress(sourceDir, files, type, targetArchive); return targetArchive; } protected async buildNsisTarget(platform: string, arch: string, sourceDir: string, pkg: any, config: BuildConfig) { if(platform != 'win') { if(!this.options.mute) { console.info(`Skip building nsis target for ${ platform }.`); } return; } const versionInfo = new NsisVersionInfo(resolve(this.dir, config.output, 'versions.nsis.json')); const targetNsis = resolve(dirname(sourceDir), `${ basename(sourceDir) }-Setup.exe`); const data = await (new NsisComposer({ // Basic. appName: config.win.productName, companyName: config.win.companyName, description: config.win.fileDescription, version: fixWindowsVersion(config.win.productVersion), copyright: config.win.copyright, icon: config.nsis.icon ? resolve(this.dir, config.nsis.icon) : undefined, unIcon: config.nsis.unIcon ? resolve(this.dir, config.nsis.unIcon) : undefined, // Compression. compression: 'lzma', solid: true, languages: config.nsis.languages, installDirectory: config.nsis.installDirectory, // Output. output: targetNsis, })).make(); const script = await tmpName(); await writeFile(script, data); await nsisBuild(sourceDir, script, { mute: this.options.mute, }); await remove(script); await versionInfo.addVersion(pkg.version, '', sourceDir); await versionInfo.addInstaller(pkg.version, arch, targetNsis); if(config.nsis.diffUpdaters) { for(const version of await versionInfo.getVersions()) { if(semver.gt(pkg.version, version)) { await this.buildNsisDiffUpdater(platform, arch, versionInfo, version, pkg.version, pkg, config); } } } await versionInfo.save(); } protected async buildNsis7zTarget(platform: string, arch: string, sourceDir: string, pkg: any, config: BuildConfig) { if(platform != 'win') { if(!this.options.mute) { console.info(`Skip building nsis7z target for ${ platform }.`); } return; } const sourceArchive = await this.buildArchiveTarget('7z', sourceDir); const versionInfo = new NsisVersionInfo(resolve(this.dir, config.output, 'versions.nsis.json')); const targetNsis = resolve(dirname(sourceDir), `${ basename(sourceDir) }-Setup.exe`); const data = await (new Nsis7Zipper(sourceArchive, { // Basic. appName: config.win.productName, companyName: config.win.companyName, description: config.win.fileDescription, version: fixWindowsVersion(config.win.productVersion), copyright: config.win.copyright, icon: config.nsis.icon ? resolve(this.dir, config.nsis.icon) : undefined, unIcon: config.nsis.unIcon ? resolve(this.dir, config.nsis.unIcon) : undefined, // Compression. compression: 'lzma', solid: true, languages: config.nsis.languages, installDirectory: config.nsis.installDirectory, // Output. output: targetNsis, })).make(); const script = await tmpName(); await writeFile(script, data); await nsisBuild(sourceDir, script, { mute: this.options.mute, }); await remove(script); await versionInfo.addVersion(pkg.version, '', sourceDir); await versionInfo.addInstaller(pkg.version, arch, targetNsis); if(config.nsis.diffUpdaters) { for(const version of await versionInfo.getVersions()) { if(semver.gt(pkg.version, version)) { await this.buildNsisDiffUpdater(platform, arch, versionInfo, version, pkg.version, pkg, config); } } } await versionInfo.save(); } protected async buildTask(platform: string, arch: string, pkg: any, config: BuildConfig) { if(platform === 'mac' && arch === 'x86' && !config.nwVersion.includes('0.12.3')) { if(!this.options.mute) { console.info(`The NW.js binary for ${ platform }, ${ arch } isn't available for ${ config.nwVersion }, skipped.`); } throw new Error('ERROR_TASK_MAC_X86_SKIPPED'); } const downloader = new Downloader({ platform, arch, version: config.nwVersion, flavor: config.nwFlavor, mirror: this.options.mirror, useCaches: true, showProgress: this.options.mute ? false : true, forceCaches: this.options.forceCaches, destination: this.options.destination, }); if(!this.options.mute) { console.info('Fetching NW.js binary...', { platform: downloader.options.platform, arch: downloader.options.arch, version: downloader.options.version, flavor: downloader.options.flavor, }); } const runtimeDir = await downloader.fetchAndExtract(); if(!this.options.mute) { console.info('Building targets...'); } const started = Date.now(); if(!this.options.mute) { console.info(`Building directory target starts...`); } const targetDir = await this.buildDirTarget(platform, arch, runtimeDir, pkg, config); if(!this.options.mute) { console.info(`Building directory target ends within ${ this.getTimeDiff(started) }s.`); } // TODO: Consider using `Bluebird.map` to enable concurrent target building. for(const target of config.targets) { const started = Date.now(); switch(target) { case 'zip': case '7z': if(!this.options.mute) { console.info(`Building ${ target } archive target starts...`); } await this.buildArchiveTarget(target, targetDir); if(!this.options.mute) { console.info(`Building ${ target } archive target ends within ${ this.getTimeDiff(started) }s.`); } break; case 'nsis': if(!this.options.mute) { console.info(`Building nsis target starts...`); } await this.buildNsisTarget(platform, arch, targetDir, pkg, config); if(!this.options.mute) { console.info(`Building nsis target ends within ${ this.getTimeDiff(started) }s.`); } break; case 'nsis7z': if(!this.options.mute) { console.info(`Building nsis7z target starts...`); } await this.buildNsis7zTarget(platform, arch, targetDir, pkg, config); if(!this.options.mute) { console.info(`Building nsis7z target ends within ${ this.getTimeDiff(started) }s.`); } break; default: throw new Error('ERROR_UNKNOWN_TARGET'); } } } }
the_stack
interface FontType { text: string; top?: string | number; fontColor?: string; fontSize?: string; fontStyle?: string; fontWeight?: string; lineHeight?: string; } interface ImgType { src: string; top?: string | number; width?: string; height?: string; $resolve?: Function; $reject?: Function; } declare type BorderRadiusType = string | number; declare type BackgroundType = string; declare type ShadowType = string; interface ConfigType { nodeType?: number; flag: 'WEB' | 'MP-WX' | 'UNI-H5' | 'UNI-MP' | 'TARO-H5' | 'TARO-MP'; el?: string; divElement?: HTMLDivElement; canvasElement?: HTMLCanvasElement; ctx: CanvasRenderingContext2D; dpr: number; width: string; height: string; unitFunc?: (num: number, unit: string) => number; rAF?: Function; setTimeout: Function; setInterval: Function; clearTimeout: Function; clearInterval: Function; beforeCreate?: Function; beforeInit?: Function; afterInit?: Function; beforeDraw?: Function; afterDraw?: Function; } declare type RequireKey = 'width' | 'height'; declare type UserConfigType = Partial<Omit<ConfigType, RequireKey>> & Required<Pick<ConfigType, RequireKey>>; interface WatchOptType { handler?: () => Function; immediate?: boolean; deep?: boolean; } declare class Lucky { protected readonly version: string; protected readonly config: ConfigType; protected readonly ctx: CanvasRenderingContext2D; protected htmlFontSize: number; protected rAF: Function; protected boxWidth: number; protected boxHeight: number; /** * 公共构造器 * @param config */ constructor(config: string | HTMLDivElement | UserConfigType); init(): void; /** * 初始化方法 */ protected initLucky(): void; /** * 鼠标点击事件 * @param e 事件参数 */ protected handleClick(e: MouseEvent): void; /** * 根标签的字体大小 */ protected setHTMLFontSize(): void; /** * 设备像素比 * window 环境下自动获取, 其余环境手动传入 */ protected setDpr(): void; /** * 重置盒子和canvas的宽高 */ private resetWidthAndHeight; /** * 根据 dpr 缩放 canvas 并处理位移 */ protected zoomCanvas(): void; /** * 从 window 对象上获取一些方法 */ private initWindowFunction; /** * 异步加载图片并返回图片的几何信息 * @param src 图片路径 * @param info 图片信息 */ protected loadImg(src: string, info: ImgType, resolveName?: string): Promise<HTMLImageElement>; /** * 公共绘制图片的方法 * @param imgObj 图片对象 * @param rectInfo: [x轴位置, y轴位置, 渲染宽度, 渲染高度] */ protected drawImage(imgObj: HTMLImageElement, ...rectInfo: [number, number, number, number]): void; /** * 获取长度 * @param length 将要转换的长度 * @return 返回长度 */ protected getLength(length: string | number | undefined): number; /** * 转换单位 * @param { string } value 将要转换的值 * @param { number } denominator 分子 * @return { number } 返回新的字符串 */ protected changeUnits(value: string, denominator?: number): number; /** * 添加一个新的响应式数据 (临时) * @param data 数据 * @param key 属性 * @param value 新值 */ $set(data: object, key: string | number, value: any): void; /** * 添加一个属性计算 (临时) * @param data 源数据 * @param key 属性名 * @param callback 回调函数 */ protected $computed(data: object, key: string, callback: Function): void; /** * 添加一个观察者 create user watcher * @param expr 表达式 * @param handler 回调函数 * @param watchOpt 配置参数 * @return 卸载当前观察者的函数 (暂未返回) */ protected $watch(expr: string | Function, handler: Function | WatchOptType, watchOpt?: WatchOptType): Function; } interface PrizeFontType$1 extends FontType { wordWrap?: boolean; lengthLimit?: string | number; } interface ButtonFontType$1 extends FontType { } interface BlockImgType$1 extends ImgType { rotate?: boolean; } interface PrizeImgType$1 extends ImgType { } interface ButtonImgType$1 extends ImgType { } interface BlockType$1 { padding?: string; background?: BackgroundType; imgs?: Array<BlockImgType$1>; } interface PrizeType$1 { range?: number; background?: BackgroundType; fonts?: Array<PrizeFontType$1>; imgs?: Array<PrizeImgType$1>; } interface ButtonType$1 { radius?: string; pointer?: boolean; background?: BackgroundType; fonts?: Array<ButtonFontType$1>; imgs?: Array<ButtonImgType$1>; } interface DefaultConfigType$1 { gutter?: string | number; offsetDegree?: number; speed?: number; speedFunction?: string; accelerationTime?: number; decelerationTime?: number; stopRange?: number; } interface DefaultStyleType$1 { background?: BackgroundType; fontColor?: PrizeFontType$1['fontColor']; fontSize?: PrizeFontType$1['fontSize']; fontStyle?: PrizeFontType$1['fontStyle']; fontWeight?: PrizeFontType$1['fontWeight']; lineHeight?: PrizeFontType$1['lineHeight']; wordWrap?: PrizeFontType$1['wordWrap']; lengthLimit?: PrizeFontType$1['lengthLimit']; } declare type StartCallbackType$1 = (e: MouseEvent) => void; declare type EndCallbackType$1 = (prize: object) => void; interface LuckyWheelConfig { blocks?: Array<BlockType$1>; prizes?: Array<PrizeType$1>; buttons?: Array<ButtonType$1>; defaultConfig?: DefaultConfigType$1; defaultStyle?: DefaultStyleType$1; start?: StartCallbackType$1; end?: EndCallbackType$1; } declare class LuckyWheel extends Lucky { private blocks; private prizes; private buttons; private defaultConfig; private defaultStyle; private _defaultConfig; private _defaultStyle; private startCallback?; private endCallback?; private Radius; private prizeRadius; private prizeDeg; private prizeRadian; private rotateDeg; private maxBtnRadius; private startTime; private endTime; private stopDeg; private endDeg; private FPS; /** * 中奖索引 * prizeFlag = undefined 时, 处于开始抽奖阶段, 正常旋转 * prizeFlag >= 0 时, 说明stop方法被调用, 并且传入了中奖索引 * prizeFlag === -1 时, 说明stop方法被调用, 并且传入了负值, 本次抽奖无效 */ private prizeFlag; private blockImgs; private prizeImgs; private btnImgs; /** * 大转盘构造器 * @param config 元素标识 * @param data 抽奖配置项 */ constructor(config: UserConfigType, data?: LuckyWheelConfig); protected initLucky(): void; /** * 初始化数据 * @param data */ private initData; /** * 初始化属性计算 */ private initComputed; /** * 初始化观察者 */ private initWatch; /** * 初始化 canvas 抽奖 * @param { willUpdateImgs } willUpdateImgs 需要更新的图片 */ init(willUpdateImgs?: { blockImgs?: Array<BlockImgType$1[] | undefined>; prizeImgs?: Array<PrizeImgType$1[] | undefined>; btnImgs?: Array<ButtonImgType$1[] | undefined>; }): void; /** * canvas点击事件 * @param e 事件参数 */ protected handleClick(e: MouseEvent): void; /** * 根据索引单独加载指定图片并缓存 * @param cellName 模块名称 * @param cellIndex 模块索引 * @param imgName 模块对应的图片缓存 * @param imgIndex 图片索引 */ private loadAndCacheImg; /** * 计算图片的渲染宽高 * @param imgObj 图片标签元素 * @param imgInfo 图片信息 * @param maxWidth 最大宽度 * @param maxHeight 最大高度 * @return [渲染宽度, 渲染高度] */ private computedWidthAndHeight; /** * 开始绘制 */ protected draw(): void; /** * 对外暴露: 开始抽奖方法 */ play(): void; /** * 对外暴露: 缓慢停止方法 * @param index 中奖索引 */ stop(index?: number): void; /** * 实际开始执行方法 * @param num 记录帧动画执行多少次 */ private run; /** * 缓慢停止的方法 */ private slowDown; /** * 获取相对宽度 * @param length 将要转换的宽度 * @param width 宽度计算百分比 * @return 返回相对宽度 */ private getWidth; /** * 获取相对高度 * @param length 将要转换的高度 * @param height 高度计算百分比 * @return 返回相对高度 */ private getHeight; /** * 获取相对(居中)X坐标 * @param width * @return 返回x坐标 */ private getOffsetX; /** * 换算渲染坐标 * @param x * @param y */ protected conversionAxis(x: number, y: number): [number, number]; } interface PrizeFontType extends FontType { wordWrap?: boolean; lengthLimit?: string | number; } interface ButtonFontType extends FontType { wordWrap?: boolean; lengthLimit?: string | number; } interface BlockImgType extends ImgType { } interface PrizeImgType extends ImgType { activeSrc?: string; } interface ButtonImgType extends ImgType { } interface BlockType { borderRadius?: BorderRadiusType; background?: BackgroundType; padding?: string; paddingTop?: string | number; paddingRight?: string | number; paddingBottom?: string | number; paddingLeft?: string | number; imgs?: Array<BlockImgType>; } interface CellType<T, U> { x: number; y: number; col?: number; row?: number; borderRadius?: BorderRadiusType; background?: BackgroundType; shadow?: ShadowType; fonts?: Array<T>; imgs?: Array<U>; } declare type PrizeType = CellType<PrizeFontType, PrizeImgType> & { range?: number; }; declare type ButtonType = CellType<ButtonFontType, ButtonImgType> & { callback?: Function; }; interface DefaultConfigType { gutter?: number; speed?: number; accelerationTime?: number; decelerationTime?: number; } interface DefaultStyleType { borderRadius?: BorderRadiusType; background?: BackgroundType; shadow?: ShadowType; fontColor?: PrizeFontType['fontColor']; fontSize?: PrizeFontType['fontSize']; fontStyle?: PrizeFontType['fontStyle']; fontWeight?: PrizeFontType['fontWeight']; lineHeight?: PrizeFontType['lineHeight']; wordWrap?: PrizeFontType['wordWrap']; lengthLimit?: PrizeFontType['lengthLimit']; } interface ActiveStyleType { background?: BackgroundType; shadow?: ShadowType; fontColor?: PrizeFontType['fontColor']; fontSize?: PrizeFontType['fontSize']; fontStyle?: PrizeFontType['fontStyle']; fontWeight?: PrizeFontType['fontWeight']; lineHeight?: PrizeFontType['lineHeight']; } declare type RowsType = number; declare type ColsType = number; declare type StartCallbackType = (e: MouseEvent, button?: ButtonType) => void; declare type EndCallbackType = (prize: object) => void; interface LuckyGridConfig { rows?: RowsType; cols?: ColsType; blocks?: Array<BlockType>; prizes?: Array<PrizeType>; buttons?: Array<ButtonType>; button?: ButtonType; defaultConfig?: DefaultConfigType; defaultStyle?: DefaultStyleType; activeStyle?: ActiveStyleType; start?: StartCallbackType; end?: EndCallbackType; } declare class LuckyGrid extends Lucky { private rows; private cols; private blocks; private prizes; private buttons; private button?; private defaultConfig; private defaultStyle; private activeStyle; private _defaultConfig; private _defaultStyle; private _activeStyle; private startCallback?; private endCallback?; private cellWidth; private cellHeight; private startTime; private endTime; private currIndex; private stopIndex; private endIndex; private demo; private timer; private FPS; /** * 中奖索引 * prizeFlag = undefined 时, 处于开始抽奖阶段, 正常旋转 * prizeFlag >= 0 时, 说明stop方法被调用, 并且传入了中奖索引 * prizeFlag === -1 时, 说明stop方法被调用, 并且传入了负值, 本次抽奖无效 */ private prizeFlag; private cells; private prizeArea; private blockImgs; private btnImgs; private prizeImgs; /** * 九宫格构造器 * @param config 元素标识 * @param data 抽奖配置项 */ constructor(config: UserConfigType, data?: LuckyGridConfig); protected initLucky(): void; /** * 初始化数据 * @param data */ private initData; /** * 初始化属性计算 */ private initComputed; /** * 初始化观察者 */ private initWatch; /** * 初始化 canvas 抽奖 * @param willUpdateImgs 需要更新的图片 */ init(willUpdateImgs?: { blockImgs?: Array<BlockImgType[] | undefined>; prizeImgs?: Array<PrizeImgType[] | undefined>; btnImgs?: Array<ButtonImgType[] | undefined>; }): void; /** * canvas点击事件 * @param e 事件参数 */ protected handleClick(e: MouseEvent): void; /** * 根据索引单独加载指定图片并缓存 * @param cellName 模块名称 * @param cellIndex 模块索引 * @param imgName 模块对应的图片缓存 * @param imgIndex 图片索引 */ private loadAndCacheImg; /** * 计算图片的渲染宽高 * @param imgObj 图片标签元素 * @param imgInfo 图片信息 * @param cell 格子信息 * @return [渲染宽度, 渲染高度] */ private computedWidthAndHeight; /** * 绘制九宫格抽奖 */ protected draw(): void; /** * 处理背景色 * @param x * @param y * @param width * @param height * @param background * @param isActive */ private handleBackground; /** * 对外暴露: 开始抽奖方法 */ play(): void; /** * 对外暴露: 缓慢停止方法 * @param index 中奖索引 */ stop(index?: number): void; /** * 实际开始执行方法 * @param num 记录帧动画执行多少次 */ private run; /** * 缓慢停止的方法 */ private slowDown; /** * 开启中奖标识自动游走 */ walk(): void; /** * 计算奖品格子的几何属性 * @param { array } [...矩阵坐标, col, row] * @return { array } [...真实坐标, width, height] */ private getGeometricProperty; /** * 转换并获取宽度 * @param width 将要转换的宽度 * @param col 横向合并的格子 * @return 返回相对宽度 */ private getWidth; /** * 转换并获取高度 * @param height 将要转换的高度 * @param row 纵向合并的格子 * @return 返回相对高度 */ private getHeight; /** * 获取相对(居中)X坐标 * @param width * @param col */ private getOffsetX; /** * 换算渲染坐标 * @param x * @param y */ protected conversionAxis(x: number, y: number): [number, number]; } export { LuckyGrid, LuckyWheel };
the_stack
import { addGraphQLResolvers, addGraphQLQuery, addGraphQLSchema } from '../../lib/vulcan-lib/graphql'; import { Comments } from '../../lib/collections/comments/collection'; import { Revisions } from '../../lib/collections/revisions/collection'; import { Tags } from '../../lib/collections/tags/collection'; import { Votes } from '../../lib/collections/votes/collection'; import { Users } from '../../lib/collections/users/collection'; import { augmentFieldsDict, accessFilterMultiple } from '../../lib/utils/schemaUtils'; import { compareVersionNumbers } from '../../lib/editor/utils'; import { annotateAuthors } from '../attributeEdits'; import { toDictionary } from '../../lib/utils/toDictionary'; import moment from 'moment'; import sumBy from 'lodash/sumBy'; import groupBy from 'lodash/groupBy'; import keyBy from 'lodash/keyBy'; import orderBy from 'lodash/orderBy'; import mapValues from 'lodash/mapValues'; import take from 'lodash/take'; import filter from 'lodash/filter'; import * as _ from 'underscore'; addGraphQLSchema(` type TagUpdates { tag: Tag! revisionIds: [String!] commentCount: Int commentIds: [String!] lastRevisedAt: Date lastCommentedAt: Date added: Int removed: Int users: [User!] } `); addGraphQLResolvers({ Query: { async TagUpdatesInTimeBlock(root: void, {before,after}: {before: Date, after: Date}, context: ResolverContext) { if (!before) throw new Error("Missing graphql parameter: before"); if (!after) throw new Error("Missing graphql parameter: after"); if(moment.duration(moment(before).diff(after)).as('hours') > 30) throw new Error("TagUpdatesInTimeBlock limited to a one-day interval"); // Get revisions to tags in the given time interval const tagRevisions = await Revisions.find({ collectionName: "Tags", fieldName: "description", editedAt: {$lt: before, $gt: after}, $or: [ {"changeMetrics.added": {$gt: 0}}, {"changeMetrics.removed": {$gt: 0}} ], }).fetch(); // Get root comments on tags in the given time interval const rootComments = await Comments.find({ deleted: false, postedAt: {$lt: before, $gt: after}, topLevelCommentId: null, tagId: {$exists: true, $ne: null}, }).fetch(); const userIds = _.uniq([...tagRevisions.map(tr => tr.userId), ...rootComments.map(rc => rc.userId)]) const usersAll = await context.loaders.Users.loadMany(userIds) const users = await accessFilterMultiple(context.currentUser, Users, usersAll, context) const usersById = keyBy(users, u => u._id); // Get the tags themselves const tagIds = _.uniq([...tagRevisions.map(r=>r.documentId), ...rootComments.map(c=>c.tagId)]); const tagsUnfiltered = await context.loaders.Tags.loadMany(tagIds); const tags = await accessFilterMultiple(context.currentUser, Tags, tagsUnfiltered, context); return tags.map(tag => { const relevantRevisions = _.filter(tagRevisions, rev=>rev.documentId===tag._id); const relevantRootComments = _.filter(rootComments, c=>c.tagId===tag._id); const relevantUsersIds = _.uniq([...relevantRevisions.map(tr => tr.userId), ...relevantRootComments.map(rc => rc.userId)]); const relevantUsers = _.map(relevantUsersIds, userId=>usersById[userId]); return { tag, revisionIds: _.map(relevantRevisions, r=>r._id), commentCount: relevantRootComments.length + sumBy(relevantRootComments, c=>c.descendentCount), commentIds: _.map(relevantRootComments, c=>c._id), lastRevisedAt: relevantRevisions.length>0 ? _.max(relevantRevisions, r=>r.editedAt).editedAt : null, lastCommentedAt: relevantRootComments.length>0 ? _.max(relevantRootComments, c=>c.lastSubthreadActivity).lastSubthreadActivity : null, added: sumBy(relevantRevisions, r=>r.changeMetrics.added), removed: sumBy(relevantRevisions, r=>r.changeMetrics.removed), users: relevantUsers, }; }); }, async RandomTag(root: void, args: void, context: ResolverContext): Promise<DbTag> { const sample = await Tags.aggregate([ {$match: {deleted: false, adminOnly: false}}, {$sample: {size: 1}} ]).toArray(); if (!sample || !sample.length) throw new Error("No tags found"); return sample[0]; }, async TagUpdatesByUser(root: void, {userId,limit,skip}: {userId: string, limit: number, skip: number}, context: ResolverContext) { // Get revisions to tags const tagRevisions = await Revisions.find({ collectionName: "Tags", fieldName: "description", userId, documentId: { $exists: true}, $or: [ {"changeMetrics.added": {$gt: 0}}, {"changeMetrics.removed": {$gt: 0}} ], }, { limit, skip, sort: { editedAt: -1} }).fetch(); // Get the tags themselves, keyed by the id const tagIds = _.uniq(tagRevisions.map(r=>r.documentId)); const tagsUnfiltered = (await context.loaders.Tags.loadMany(tagIds)); const tags = (await accessFilterMultiple(context.currentUser, Tags, tagsUnfiltered, context)).reduce( (acc, tag) => { acc[tag._id] = tag; return acc; }, {}); // unlike TagUpdatesInTimeBlock we only return info on one revision per tag. i.e. we do not collect them by tag. return tagRevisions.map(rev => { const tag = tags[rev.documentId]; return { tag, revisionIds: [rev._id], lastRevisedAt: rev.editedAt, added: rev.changeMetrics.added, removed: rev.changeMetrics.removed, }; }); } } }); addGraphQLQuery('TagUpdatesInTimeBlock(before: Date!, after: Date!): [TagUpdates!]'); addGraphQLQuery('TagUpdatesByUser(userId: String!, limit: Int!, skip: Int!): [TagUpdates!]'); addGraphQLQuery('RandomTag: Tag!'); type ContributorWithStats = { user: DbUser, contributionScore: number, numCommits: number, voteCount: number, }; type ContributorStats = { contributionScore: number, numCommits: number, voteCount: number, }; type ContributorStatsList = Partial<Record<string,ContributorStats>>; augmentFieldsDict(Tags, { contributors: { resolveAs: { arguments: 'limit: Int, version: String', type: "TagContributorsList", resolver: async (tag: DbTag, {limit, version}: {limit?: number, version?: string}, context: ResolverContext): Promise<{ contributors: ContributorWithStats[], totalCount: number, }> => { const contributionStatsByUserId = await getContributorsList(tag, version||null); const contributorUserIds = Object.keys(contributionStatsByUserId); const contributorUsersUnfiltered = await context.loaders.Users.loadMany(contributorUserIds); const contributorUsers = await accessFilterMultiple(context.currentUser, Users, contributorUsersUnfiltered, context); const usersById = keyBy(contributorUsers, u => u._id); const sortedContributors = orderBy(contributorUserIds, userId => -contributionStatsByUserId[userId]!.contributionScore); const topContributors: ContributorWithStats[] = sortedContributors.map(userId => ({ user: usersById[userId], ...contributionStatsByUserId[userId]!, })); if (limit) { return { contributors: take(topContributors, limit), totalCount: topContributors.length, } } else { return { contributors: topContributors, totalCount: topContributors.length, } } } } }, }); async function getContributorsList(tag: DbTag, version: string|null): Promise<ContributorStatsList> { if (version) return await buildContributorsList(tag, version); else if (tag.contributionStats) return tag.contributionStats; else return await updateDenormalizedContributorsList(tag); } async function buildContributorsList(tag: DbTag, version: string|null): Promise<ContributorStatsList> { if (!(tag?._id)) throw new Error("Invalid tag"); const tagRevisions: DbRevision[] = await Revisions.find({ collectionName: "Tags", fieldName: "description", documentId: tag._id, $or: [ {"changeMetrics.added": {$gt: 0}}, {"changeMetrics.removed": {$gt: 0}} ], }).fetch(); const selfVotes = await Votes.aggregate([ // All votes on relevant revisions { $match: { documentId: {$in: tagRevisions.map(r=>r._id)}, collectionName: "Revisions", cancelled: false, isUnvote: false, }}, // Filtered by: is a self-vote { $match: { $expr: { $eq: ["$userId", "$authorId"] } }} ]).toArray(); const selfVotesByUser = groupBy(selfVotes, v=>v.userId); const selfVoteScoreAdjustmentByUser = mapValues(selfVotesByUser, selfVotes => { const totalSelfVotePower = sumBy(selfVotes, v=>v.power) const strongestSelfVote = _.max(selfVotes, v=>v.power)?.power const numSelfVotes = selfVotes.length; return { excludedPower: totalSelfVotePower - strongestSelfVote, excludedVoteCount: numSelfVotes>0 ? (numSelfVotes-1) : 0, }; } ); const filteredTagRevisions = version ? _.filter(tagRevisions, r=>compareVersionNumbers(version, r.version)>=0) : tagRevisions; const revisionsByUserId: Record<string,DbRevision[]> = groupBy(filteredTagRevisions, r=>r.userId); const contributorUserIds: string[] = Object.keys(revisionsByUserId); const contributionStatsByUserId: Partial<Record<string,ContributorStats>> = toDictionary(contributorUserIds, userId => userId, userId => { const revisionsByThisUser = filter(tagRevisions, r=>r.userId===userId); const totalRevisionScore = sumBy(revisionsByUserId[userId], r=>r.baseScore)||0 const selfVoteAdjustment = selfVoteScoreAdjustmentByUser[userId] const excludedPower = selfVoteAdjustment?.excludedPower || 0; const excludedVoteCount = selfVoteAdjustment?.excludedVoteCount || 0; return { contributionScore: totalRevisionScore - excludedPower, numCommits: revisionsByThisUser.length, voteCount: sumBy(revisionsByThisUser, r=>r.voteCount) - excludedVoteCount, }; } ); return contributionStatsByUserId; } export async function updateDenormalizedContributorsList(tag: DbTag): Promise<ContributorStatsList> { const contributionStats = await buildContributorsList(tag, null); if (JSON.stringify(tag.contributionStats) !== JSON.stringify(contributionStats)) { await Tags.rawUpdateOne({_id: tag._id}, {$set: { contributionStats: contributionStats, }}); } return contributionStats; } export async function updateDenormalizedHtmlAttributions(tag: DbTag) { const html = await annotateAuthors(tag._id, "Tags", "description"); await Tags.rawUpdateOne({_id: tag._id}, {$set: { htmlWithContributorAnnotations: html, }}); return html; }
the_stack
import {Map} from 'immutable'; import {ActionType, getType} from 'typesafe-actions'; import * as helperActions from '../actions/bindChannel/helperActions'; import * as guideActions from '../actions/guideActions'; import * as markActions from '../actions/markActions'; import * as sceneActions from '../actions/sceneActions'; import * as interactionActions from '../actions/interactionActions'; import * as widgetActions from '../actions/widgetActions'; import {MarkRecord, MarkState} from '../store/factory/Mark'; import {SceneRecord} from '../store/factory/marks/Scene'; import {convertValuesToSignals, propSg} from '../util/prop-signal'; const ensureValuePresent = function(state: MarkState, path: string[], valToAdd): MarkState { return state.updateIn(path, marks => { if (marks.indexOf(valToAdd) === -1) { marks.push(valToAdd); // TODO(jzong) so, this creates a side effect which we rely on for scales but which breaks interactions } return marks; }); }; const ensureValuePresentImmutable = function(state: MarkState, path: string[], valToAdd): MarkState { return state.updateIn(path, marks => { if (marks.indexOf(valToAdd) === -1) { return [...marks, valToAdd]; // TODO(jzong) this one does what i think it does but would break stuff if i replaced the above with it } return marks; }); }; const ensureValueAbsent = function(state: MarkState, path: string[], valToRemove): MarkState { return state.updateIn(path, children => children.filter(c => c !== valToRemove)); }; // Helper reducer to add a mark to the store. Runs the mark through a method to // convert property values into signal references before setting the mark // within the store. // "state" is the marks store state; "action" is an object with a numeric // `._id`, string `.name`, and object `.props` defining the mark to be created. function makeMark(action: ActionType<typeof markActions.baseAddMark | typeof sceneActions.baseCreateScene>): MarkRecord { const def: MarkRecord | SceneRecord = action.payload.props; const props = def.encode && def.encode.update; return def.encode ? (def as any).merge({ encode: { update: convertValuesToSignals(props, (def as MarkRecord).type, action.meta) } }) : def; } // Helper reducer to configure a parent-child relationship between two marks. // "state" is the marks store state; "action" is an object with a numeric // `.childId` and either a numeric `.parentId` (for setting a parent) or `null` // (for clearing a parent, e.g. when removing a mark). function setParentMark(state: MarkState, params: {parentId: number; childId: number}): MarkState { const {parentId, childId} = params; // Nothing to do if no child is provided if (typeof childId === 'undefined') { return state; } const child = state.get(String(childId)); if (!child) { return state; } const existingParentId = child._parent; // If we're deleting a parent but there isn't one to begin with, do nothing // (`== null` is used to catch both `undefined` and explicitly `null`) if (existingParentId == null && !parentId) { return state; } const existingParent = state.get(String(existingParentId)); const newParent = parentId ? state.get(String(parentId)) : parentId; // Clearing a mark's parent reference if (newParent === null) { // Second, ensure the child ID has been removed from the parent's marks return ensureValueAbsent( // First, null out the child's parent reference state.setIn([String(childId), '_parent'], null), [String(existingParentId), 'marks'], childId ); } // Moving a mark from one parent to another if (existingParent && newParent) { // Finally, make sure the child ID is present in the new parent's marks array return ensureValuePresent( // Next, remove the child ID from the old parent's marks ensureValueAbsent( // First, update the child's _parent pointer to target the new parent state.setIn([String(childId), '_parent'], parentId), [String(existingParentId), 'marks'], childId ), [String(parentId), 'marks'], childId ); } // Setting a parent of a previously-parentless mark return ensureValuePresent( // First, update the child's _parent pointer to target the new parent state.setIn([String(childId), '_parent'], parentId), // .updateIn([String(parentId), 'marks'], marks => marks.push(childId)), [String(parentId), 'marks'], childId ); } /** * Move an Axis or Legend from one group to another * * @param {Object} state - An Immutable state object * @param {Object} action - An action object * @param {number} action.id - The ID of the Axis or Legend to move * @param {number} [action.oldGroupId] - The ID of the group to move it from * @param {number} action.groupId - The ID of the group to move it to * @param {string} collection - The collection to which this mark belongs, * either "legends" or "axes" * @returns {Object} A new Immutable state with the requested changes */ // function moveChildToGroup(state, action, collection) { // const oldGroupCollectionPath = action.oldGroupId + '.' + collection; // const newGroupCollectionPath = action.groupId + '.' + collection; // // Simple case: add to the new // if (!action.oldGroupId) { // return ensureValuePresent(state, newGroupCollectionPath, action.id); // } // // Remove from the old and add to the new // return ensureValuePresent( // ensureValueAbsent(state, oldGroupCollectionPath, action.id), // newGroupCollectionPath, // action.id // ); // } /** * Main marks reducer function, which generates a new state for the marks * property store based on the changes specified by the dispatched action object. * * @param {Object} state - An Immutable.Map state object * @param {Object} action - A redux action object * @returns {Object} A new Immutable.Map with the changes specified by the action */ export function marksReducer( state: MarkState, action: | ActionType<typeof markActions> | ActionType<typeof helperActions> | ActionType<typeof sceneActions.baseCreateScene> | ActionType<typeof guideActions.deleteGuide> | ActionType<typeof interactionActions.deleteInteraction> | ActionType<typeof widgetActions.deleteWidget> ): MarkState { if (typeof state === 'undefined') { return Map(); } const markId = action.meta; if (action.type === getType(sceneActions.baseCreateScene)) { return state.set(String(markId), makeMark(action)); } if (action.type === getType(markActions.baseAddMark)) { // Make the mark and .set it at the provided ID, then pass it through a // method that will check to see whether the mark needs to be added as // a child of another mark return setParentMark(state.set(String(markId), makeMark(action)), { parentId: action.payload.props ? action.payload.props._parent : null, childId: markId }); } if (action.type === getType(markActions.baseDeleteMark)) { return setParentMark(state, { childId: markId, parentId: null }).remove(String(markId)); } if (action.type === getType(markActions.setParent)) { return setParentMark(state, { parentId: action.payload, childId: markId }); } if (action.type === getType(markActions.updateMarkProperty)) { return state.setIn([String(markId), action.payload.property], action.payload.value); } if (action.type === getType(markActions.setMarkVisual)) { return state.setIn([String(markId), 'encode', 'update', action.payload.property], action.payload.def); } if (action.type === getType(markActions.disableMarkVisual)) { return state.setIn([String(markId), 'encode', 'update', action.payload, '_disabled'], true); } if (action.type === getType(markActions.resetMarkVisual)) { const markType = state.getIn([String(markId), 'type']); const property = action.payload; return state.setIn([String(markId), 'encode', 'update', property], { signal: propSg(markId, markType, property) }); } if (action.type === getType(markActions.setMarkExtent)) { return state .setIn([String(markId), 'encode', 'update', action.payload.oldExtent, '_disabled'], true) .setIn([String(markId), 'encode', 'update', action.payload.newExtent, '_disabled'], false); } if (action.type === getType(markActions.setVlUnit)) { return state.setIn([String(markId), '_vlUnit'], action.payload); } if (action.type === getType(markActions.bindScale)) { return state.setIn( [String(markId), 'encode', 'update', action.payload.property, 'scale'], action.payload.scaleId ); } const groupId = action.meta; if (action.type === getType(helperActions.addScaleToGroup)) { return ensureValuePresent(state, [String(groupId), 'scales'], action.payload); } if (action.type === getType(helperActions.addAxisToGroup)) { return ensureValuePresentImmutable(state, [String(groupId), 'axes'], action.payload); } if (action.type === getType(helperActions.addLegendToGroup)) { return ensureValuePresentImmutable(state, [String(groupId), 'legends'], action.payload); } if (action.type === getType(helperActions.addInteractionToGroup)) { return ensureValuePresentImmutable(state, [String(groupId), '_interactions'], action.payload); } if (action.type === getType(helperActions.addWidgetToGroup)) { return ensureValuePresentImmutable(state, [String(groupId), '_widgets'], action.payload); } const id = action.meta; if (action.type === getType(guideActions.deleteGuide)) { state = ensureValueAbsent(state, [String(action.payload.groupId), 'axes'], id); return ensureValueAbsent(state, [String(action.payload.groupId), 'legends'], id); } if (action.type === getType(interactionActions.deleteInteraction)) { return ensureValueAbsent(state, [String(action.payload.groupId), '_interactions'], id); } if (action.type === getType(widgetActions.deleteWidget)) { return ensureValueAbsent(state, [String(action.payload.groupId), '_widgets'], id); } return state; }
the_stack
const collectionToArray = <T>(col: { Item(key: any): T }): T[] => { const results: T[] = []; const enumerator = new Enumerator<T>(col); enumerator.moveFirst(); while (!enumerator.atEnd()) { results.push(enumerator.item()); enumerator.moveNext(); } return results; }; const toConnectionString = (o: { [index: string]: any }) => { o.Provider = o.Provider || 'sqloledb'; o['Data Source'] = o['Data Source'] || 'Server'; o['Integrated Security'] = o['Integrated Security'] || 'SSPI'; const parts: string[] = []; for (const key in o) { let val = o[key]; if (typeof val === 'string') { val = `'${val}'`; } parts.push(`${key}=${val}`); } return parts.join(';'); }; const connectionString = toConnectionString({ Provider: 'Microsoft.Jet.OLEDB.4.0', 'Data Source': 'c:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb' }); const connectionStringWithSys = toConnectionString({ Provider: 'Microsoft.Jet.OLEDB.4.0', 'Data Source': 'c:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb', 'jet oledb:system database': 'c:\\Program Files\\Microsoft Office\\Office\\system.mdw' }); const adPermObjTable = ADOX.ObjectTypeEnum.adPermObjTable; const adRightFull = ADOX.RightsEnum.adRightFull; const adInteger = ADODB.DataTypeEnum.adInteger; const adVarWChar = ADODB.DataTypeEnum.adVarWChar; const adVarChar = ADODB.DataTypeEnum.adVarChar; const adOpenKeyset = ADODB.CursorTypeEnum.adOpenKeyset; const adLockOptimistic = ADODB.LockTypeEnum.adLockOptimistic; const tryClose = (obj: { State: ADODB.ObjectStateEnum, Close(): void } | null) => { // TODO State could also be a combination of multiple values in this enum if (obj && obj.State === ADODB.ObjectStateEnum.adStateOpen) { obj.Close(); } return null; }; // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/columns-and-tables-append-methods-name-property-example-vb { let cat: ADOX.Catalog | null = null; let tbl: ADOX.Table | null = null; try { cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; tbl = new ActiveXObject('ADOX.Table'); tbl.Name = 'MyTable'; tbl.Columns.Append('Column1', adInteger); tbl.Columns.Append('Column2', adInteger); tbl.Columns.Append('Column3', adVarChar, 50); cat.Tables.Append(tbl); WScript.Echo('Table "MyTables" is added.'); cat.Tables.Delete(tbl.Name); WScript.Echo('Table "MyTable" is deleted'); cat.ActiveConnection = null; } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; tbl = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/connection-close-method-table-type-property-example-vb { let conn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; try { conn = new ActiveXObject('ADODB.Connection'); conn.Open(connectionString); cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = conn; const tbl = cat.Tables(0); WScript.Echo(tbl.Type); // Cache tbl.Type info cat.ActiveConnection = null; // tbl is orphaned // The following two lines will succeed only if the information was cached WScript.Echo(tbl.Type); WScript.Echo(tbl.Columns(0).DefinedSize); } catch (error) { WScript.Echo(error); } finally { // Clean up if (cat) { cat.ActiveConnection = null; } cat = null; conn = tryClose(conn); } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/create-method-example-vb { let cat: ADOX.Catalog | null = null; try { cat = new ActiveXObject('ADOX.Catalog'); cat.Create("Provider='Microsoft.Jet.OLEDB.4.0';Data Source='new.mdb'"); } catch (error) { WScript.Echo(error); } finally { cat = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/getobjectowner-and-setobjectowner-methods-example-vb { const cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionStringWithSys; // Print the original owner of Categories const strOwner = cat.GetObjectOwner('Categories', adPermObjTable); WScript.Echo(`Ower of Categories: ${strOwner}`); // Set the owner of Categories to Accounting cat.SetObjectOwner('Categories', adPermObjTable, 'Accounting'); for (const tblLoop of collectionToArray(cat.Tables)) { WScript.Echo(` Table: ${tblLoop.Name} Owner: ${cat.GetObjectOwner(tblLoop.Name, adPermObjTable)} `.trim()); } // Restore the original owner of Categories cat.SetObjectOwner('Categories', adPermObjTable, strOwner); } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/getpermissions-and-setpermissions-methods-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; try { cnn = new ActiveXObject('ADODB.Connection'); cnn.Provider = 'Microsoft.Jet.OLEDB.4.0'; cnn.Open("Data Source='Northwind.mdb';jet oledb:system database='system.mdw'"); cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; const displayPermissions = (title: string) => WScript.Echo(`${title}: ${cat!.Users('admin').GetPermissions('Orders', adPermObjTable)}`); // Retrieve original permissions const perm = cat.Users('admin').GetPermissions('Orders', adPermObjTable); WScript.Echo(`Permissions: ${perm}`); // Revoke all permissions cat.Users('admin').SetPermissions('Orders', adPermObjTable, ADOX.ActionEnum.adAccessRevoke, adRightFull); displayPermissions('Revoked permissions'); // Give the Admin user full rights on the orders object cat.Users('admin').SetPermissions('Orders', adPermObjTable, ADOX.ActionEnum.adAccessSet, adRightFull); displayPermissions('Full permissions'); // Restore original permissions cat.Users('admin').SetPermissions('Orders', adPermObjTable, ADOX.ActionEnum.adAccessSet, perm); displayPermissions('Final permissions'); } catch (error) { WScript.Echo(error); } finally { cat = null; cnn = tryClose(cnn); } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/groups-and-users-append-changepassword-methods-example-vb { let cat: ADOX.Catalog | null = null; let usrNew: ADOX.User | null = null; let usrLoop: ADOX.User | null; let grpLoop: ADOX.Group | null; let user: ADOX.User | null; let group: ADOX.Group | null; try { cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionStringWithSys; // Create and append a new group with a string cat.Groups.Append('Accounting'); // Create and append a new user with an object usrNew = new ActiveXObject('ADOX.User'); usrNew.Name = 'Pat Smith'; usrNew.ChangePassword('', 'Password1'); cat.Users.Append(usrNew); // Make the user Pat Smith a member of the // Accounting group by creating and adding the // appropriate Group object to the user's Groups // collection. The same is accomplished if a User // object representing Pat Smith is created and // appended to the Accounting group Users collection usrNew.Groups.Append('Accounting'); // Enumerate all User objects in the catalog's Users collection. for (usrLoop of collectionToArray(cat.Users)) { WScript.Echo(`${usrLoop.Name} belongs to the following groups:`); // Enumerate all Group objects in each User object's Groups collection const groups = collectionToArray(usrLoop.Groups); if (groups.length !== 0) { for (group of groups) { WScript.Echo(`\t\t${group.Name}`); } } else { WScript.Echo('\t[None]'); } } // Enumerate all Group objects in the default workspace's Groups collection for (grpLoop of collectionToArray(cat.Groups)) { WScript.Echo(`${grpLoop.Name} has as its members:`); // Enumerate all User objects in each Group object's User collection const users = collectionToArray(grpLoop.Users); if (users.length !== 0) { for (user of users) { WScript.Echo(`\t\t${user.Name}`); } } else { WScript.Echo('\t[None]'); } } // Delete new User and Group objects because this is only a demonstration cat.Users.Delete('Pat Smith'); cat.Groups.Delete('Accounting'); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; usrNew = null; usrLoop = null; grpLoop = null; user = null; group = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/indexes-append-method-example-vb { let cat: ADOX.Catalog | null = null; let tbl: ADOX.Table | null = null; let idx: ADOX.Index | null = null; try { // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Define the table and append it to the catalog tbl = new ActiveXObject('ADOX.Table'); tbl.Name = 'MyTable'; tbl.Columns.Append('Column1', adInteger); tbl.Columns.Append('Column2', adInteger); tbl.Columns.Append('Column3', adVarChar, 50); cat.Tables.Append(tbl); WScript.Echo('Table "MyTables" is added.'); // Define a multi-column index idx = new ActiveXObject('ADOX.Index'); idx.Name = 'multicolidx'; idx.Columns.Append('Column1'); idx.Columns.Append('Column2'); // Append the index to the table tbl.Indexes.Append(idx); WScript.Echo('The index is appended to table "MyTable".'); // Delete the table as this is a demonstration cat.Tables.Delete(tbl.Name); WScript.Echo('Table "MyTable" is deleeted.'); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; tbl = null; idx = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/keys-append-method-key-type-relatedcolumn-relatedtable-example-vb { let cat: ADOX.Catalog | null = null; let kyForeign: ADOX.Key | null = null; try { // Connect to the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Define the foreign key kyForeign = new ActiveXObject('ADOX.Key'); kyForeign.Name = 'CustOrder'; kyForeign.Type = ADOX.KeyTypeEnum.adKeyForeign; kyForeign.RelatedTable = 'Customers'; kyForeign.Columns.Append('CustomerId'); kyForeign.Columns('CustomerId').RelatedColumn = 'CustomerID'; kyForeign.UpdateRule = ADOX.RuleEnum.adRICascade; // Append the foreign key to the keys collection cat.Tables('Orders').Keys.Append(kyForeign); // Delete the key to demonstrate the Detele method cat.Tables('Orders').Keys.Delete(kyForeign.Name); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; kyForeign = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/procedures-append-method-example-vb { let cnn: ADODB.Connection | null = null; let cmd: ADODB.Command | null = null; let cat: ADOX.Catalog | null = null; try { // Open the Connection cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); // Create the parameterized command (Microsoft Jet specific) cmd = new ActiveXObject('ADODB.Command'); cmd.ActiveConnection = cnn; cmd.CommandText = ` PARAMETERS [CustId] TEXT; SELECT * FROM Customers WHERE CustomerId = [CustId] `; // Open the Catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; // Create the new Procedure cat.Procedures.Append('CustomerById', cmd); } catch (error) { WScript.Echo(error); } finally { cat = null; cmd = null; cnn = tryClose(cnn); } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/procedures-delete-method-example-vb { let cat: ADOX.Catalog | null = null; try { // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Delete the procedure cat.Procedures.Delete('CustomerById'); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/procedures-refresh-method-example-vb { let cat: ADOX.Catalog | null = null; try { // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Refresh the Procedures collection cat.Procedures.Refresh(); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/views-append-method-example-vb { let cat: ADOX.Catalog | null = null; let cmd: ADODB.Command | null = null; try { // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Create the command representing the view. cmd = new ActiveXObject('ADODB.Command'); cmd.CommandText = 'SELECT * FROM Customers'; // Create the new View cat.Views.Append('All Customers', cmd); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; cmd = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/views-delete-method-example-vb { let cat: ADOX.Catalog | null = null; try { // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Delete the View cat.Views.Delete('All Customers'); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/views-refresh-method-example-vb { let cat: ADOX.Catalog | null = null; try { // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Refresh the Views collection cat.Views.Refresh(); } catch (error) { WScript.Echo(error); } finally { cat = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/attributes-property-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; let tblEmp: ADOX.Table | null = null; let colTemp: ADOX.Column | null = null; let rstEmployees: ADODB.Recordset | null = null; try { // Connect the catalog cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; tblEmp = cat.Tables('Employees'); // Create a new Field object and append it to the Field collection of the Employees table colTemp = new ActiveXObject('ADOX.Column'); colTemp.Name = 'FaxPhone'; colTemp.Type = adVarWChar; colTemp.DefinedSize = 24; colTemp.Attributes = ADOX.ColumnAttributesEnum.adColNullable; tblEmp.Columns.Append(colTemp.Name, ADODB.DataTypeEnum.adWChar, 24); // Open the Employees table for updating as a Recordset rstEmployees = new ActiveXObject('ADODB.Recordset'); rstEmployees.Open('Employees', cnn, adOpenKeyset, adLockOptimistic, ADODB.CommandTypeEnum.adCmdTable); // Get user input WScript.Echo(` Enter fax number for ${rstEmployees('FirstName')} ${rstEmployees('LastName')}. [? - unknown, X - has no fax] `.trim()); const strInput = WScript.StdIn.ReadLine().toUpperCase().trim(); if (strInput) { let newValue: string | null; if (strInput === '?') { newValue = null; } else if (strInput === 'X') { newValue = ''; } else { newValue = strInput; } rstEmployees('FaxPhone').Value = newValue; rstEmployees.Update(); // Print report const faxValue = rstEmployees('FaxPhone').Value; let faxDisplayString: string; if (faxValue === null) { faxDisplayString = '[Unkown]'; } else if (faxValue === '') { faxDisplayString = '[Has no fax]'; } else { faxDisplayString = faxValue; } WScript.Echo(` Name\t\tFax number ${rstEmployees('FirstName')} ${rstEmployees('LastName')}\t\t${faxDisplayString} `.trim()); } } catch (error) { WScript.Echo(error); } finally { rstEmployees = tryClose(rstEmployees); if (tblEmp) { tblEmp.Columns.Delete(colTemp!.Name); } cnn = tryClose(cnn); cat = null; colTemp = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/catalog-activeconnection-property-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; try { cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; WScript.Echo(cat.Tables(0).Type); } catch (error) { WScript.Echo(error); } finally { cat = null; cnn = tryClose(cnn); } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/clustered-property-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; let tblLoop: ADOX.Table | null; let idxLoop: ADOX.Index | null; try { // Connect to the catalog cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; // Enumerate the tables for (tblLoop of collectionToArray(cat.Tables)) { // Enumerate the indexes for (idxLoop of collectionToArray(tblLoop.Indexes)) { WScript.Echo(`${tblLoop.Name} ${idxLoop.Name} ${idxLoop.Clustered}`); } } } catch (error) { WScript.Echo(error); } finally { cat = null; cnn = tryClose(cnn); tblLoop = null; idxLoop = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/command-and-commandtext-properties-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; let cmd: ADODB.Command | null = null; try { // Open the connection cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; // Get the command cmd = new ActiveXObject('ADODB.Command'); cmd = cat.Procedures('CustomerById').Command; // Update the CommandText cmd.CommandText = ` SELECT CustomerID, CompanyName ContactName FROM Customers WHERE CustomerId = [CustId] `.trim(); // Update the procedure cat.Procedures('CustomerById').Command = cmd; } catch (error) { WScript.Echo(error); } finally { cnn = tryClose(cnn); cat = null; cmd = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/parameters-collection-command-property-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; let cmd: ADODB.Command | null = null; let prm: ADODB.Parameter | null; try { // Open the connection cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; // Get the command cmd = cat.Procedures('CustomerById').Command; // Retreive Parameter information cmd.Parameters.Refresh(); for (prm of collectionToArray(cmd.Parameters)) { WScript.Echo(`${prm.Name}: ${prm.Type}`); } } catch (error) { WScript.Echo(error); } finally { cat = null; cmd = null; cnn = tryClose(cnn); prm = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/views-collection-commandtext-property-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null = null; let cmd: ADODB.Command | null = null; try { // Open the connection cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; // Get the command cmd = cat.Views('AllCustomers').Command; // Update the CommandText of the command cmd.CommandText = 'SELECT CustomerId, CompanyName, ContactName FROM Customers'; // Update the view cat.Views('AllCustomers').Command = cmd; } catch (error) { WScript.Echo(error); } finally { cat = null; cmd = null; cnn = tryClose(cnn); } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/datecreated-and-datemodified-properties-example-vb { const dateOutput = (caption: string, tbl: ADOX.Table) => { // Print DateCreated and DateModified information about specified Table object WScript.Echo(caption); WScript.Echo(`\tTable: ${tbl.Name}`); WScript.Echo(`\t\t${new Date(tbl.DateCreated).toString()}`); WScript.Echo(`\t\t${new Date(tbl.DateModified).toString()}`); WScript.Echo(''); }; let cat: ADOX.Catalog | null = null; try { // Connect to the catalog. cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; const tblEmployees = cat.Tables('Employees'); // Print current information about the Employees table dateOutput('Current properties', tblEmployees); // Create and append column to the Employees table. tblEmployees.Columns.Append('NewColumn', adInteger); cat.Tables.Refresh(); // Print new information about the Employees table. dateOutput('After creating a new column', tblEmployees); // Delete new column because this is a demonstration tblEmployees.Columns.Delete('NewColumn'); // Create and append new Table object to the Northwind database const tblNewTable = new ActiveXObject('ADOX.Table'); tblNewTable.Name = 'NewTable'; tblNewTable.Columns.Append('NewColumn', adInteger); cat.Tables.Append(tblNewTable); cat.Tables.Refresh(); // Print information about the new Table object dateOutput('After creating a new table', cat.Tables('NewTable')); // Delete new Table object because this is a demonstration cat.Tables.Delete(tblNewTable.Name); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/definedsize-property-example-vb { let rstEmployees: ADODB.Recordset | null = null; let catNorthwind: ADOX.Catalog | null; let colFirstname: ADOX.Column | null; let colNewFirstName: ADOX.Column | null; try { // Open a Recordset for the Employees table. rstEmployees = new ActiveXObject('ADODB.Recordset'); rstEmployees.Open('Employees', connectionString, adOpenKeyset, undefined, ADODB.CommandTypeEnum.adCmdTable); // Open a Catalog for the Northwind database, using same connection as rstEmployees catNorthwind = new ActiveXObject('ADOX.Catalog'); catNorthwind.ActiveConnection = rstEmployees.ActiveConnection; // Loop through the recordset displaying the contents of the FirstName field, the field's defined size, // and its actual size. Also store FirstName values in aryFirstName array. rstEmployees.MoveFirst(); WScript.Echo(''); WScript.Echo('Original Defined Size and Actual Size'); const firstnames: string[] = []; for (let i = 0; !rstEmployees.EOF; i++) { const firstField = rstEmployees('FirstName'); const [firstname, lastname] = [firstField.Value as string, rstEmployees('LastName').Value as string]; WScript.Echo(`Employee name: ${firstname} ${lastname}`); WScript.Echo(`\tFirstName Defined size: ${firstField.DefinedSize}`); WScript.Echo(`\tFirstName Actual size: ${firstField.ActualSize}`); firstnames[i] = firstname; // we don't check for null, because null is better than undefined when putting the first names back rstEmployees.MoveNext(); } rstEmployees.Close(); // Redefine the DefinedSize of FirstName in the catalog colFirstname = catNorthwind.Tables('Employees').Columns('FirstName'); colNewFirstName = new ActiveXObject('ADOX.Column'); colNewFirstName.Name = colFirstname.Name; colNewFirstName.Type = colFirstname.Type; colNewFirstName.DefinedSize = colFirstname.DefinedSize + 1; // Append new FirstName column to catalog catNorthwind.Tables('Employees').Columns.Delete(colFirstname.Name); catNorthwind.Tables('Employees').Columns.Append(colNewFirstName); // Open Employee table in Recordset for updating rstEmployees.Open('Employees', catNorthwind.ActiveConnection!, adOpenKeyset, adLockOptimistic, ADODB.CommandTypeEnum.adCmdTable); // Loop through the recordset displaying the contents of the FirstName field, the field's defined size, // and its actual size. Also restore FirstName values from aryFirstName. rstEmployees.MoveFirst(); WScript.Echo(''); WScript.Echo('Original Defined Size and Actual Size'); for (let i = 0; !rstEmployees.EOF; i++) { const firstField = rstEmployees('FirstName'); firstField.Value = firstnames[i]; WScript.Echo(`Employee name: ${firstField.Value} ${rstEmployees('LastName').Value}`); WScript.Echo(`\tFirstName Defined size: ${firstField.DefinedSize}`); WScript.Echo(`\tFirstName Actual size: ${firstField.ActualSize}`); rstEmployees.MoveNext(); } rstEmployees.Close(); // Restore original FirstName column to catalog catNorthwind.Tables('Employees').Columns.Delete(colNewFirstName.Name); catNorthwind.Tables('Employees').Columns.Append(colFirstname); // Restore original FirstName values to Employees table rstEmployees.Open('Employees', catNorthwind.ActiveConnection!, adOpenKeyset, adLockOptimistic, ADODB.CommandTypeEnum.adCmdTable); rstEmployees.MoveFirst(); for (let i = 0; !rstEmployees.EOF; i++) { rstEmployees('FirstName').Value = firstnames[i]; rstEmployees.MoveNext(); } rstEmployees.Close(); } catch (error) { WScript.Echo(error); } finally { catNorthwind = null; colNewFirstName = null; colFirstname = null; rstEmployees = tryClose(rstEmployees); } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/deleterule-property-example-vb { let cat: ADOX.Catalog | null = null; let tblNew: ADOX.Table | null; let kyPrimary: ADOX.Key | null; try { // Connect the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; // Name new table tblNew = new ActiveXObject('ADOX.Table'); tblNew.Name = 'NewTable'; // Append a numeric and a text field to new table. tblNew.Columns.Append('NumField', adInteger, 20); tblNew.Columns.Append('TextField', adVarChar, 20); // Append the new table cat.Tables.Append(tblNew); // Define the Primary key kyPrimary = new ActiveXObject('ADOX.Key'); kyPrimary.Name = 'NumField'; kyPrimary.Type = ADOX.KeyTypeEnum.adKeyPrimary; kyPrimary.RelatedTable = 'Customers'; kyPrimary.Columns.Append('NumField'); kyPrimary.Columns('NumField').RelatedColumn = 'CustomerId'; kyPrimary.DeleteRule = ADOX.RuleEnum.adRICascade; // Append the primary key cat.Tables('NewTable').Keys.Append(kyPrimary); WScript.Echo('The primary key is appended.'); // Delete the table as this is a demonstration. cat.Tables.Delete(tblNew.Name); WScript.Echo('The primary key is deleted.'); } catch (error) { WScript.Echo(error); } finally { if (cat) { cat.ActiveConnection = null; } cat = null; kyPrimary = null; tblNew = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/indexnulls-property-example-vb { // Connect the catalog. const cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); let catNorthwind: ADOX.Catalog | null = new ActiveXObject('ADOX.Catalog'); catNorthwind.ActiveConnection = cnn; // Append Country column to new index const idxNew = new ActiveXObject('ADOX.Index'); idxNew.Columns.Append('Country'); idxNew.Name = 'NewIndex'; // Set IndexNulls based on user selection WScript.Echo('Allow nulls Y/N (Y to allow, N to ignore)?'); const input = WScript.StdIn.ReadLine().toUpperCase(); switch (input) { case 'Y': idxNew.IndexNulls = ADOX.AllowNullsEnum.adIndexNullsAllow; break; case 'N': idxNew.IndexNulls = ADOX.AllowNullsEnum.adIndexNullsIgnore; break; } // Append new index to Employees table catNorthwind.Tables('Employees').Indexes.Append(idxNew); const rstEmployees = new ActiveXObject('ADODB.Recordset'); rstEmployees.Index = idxNew.Name; rstEmployees.Open('Employees', cnn, adOpenKeyset, adLockOptimistic, ADODB.CommandTypeEnum.adCmdTableDirect); // Add a new record to the Employees table. rstEmployees.AddNew(); rstEmployees('FirstName').Value = 'Gary'; rstEmployees('LastName').Value = 'Haarsager'; rstEmployees.Update(); // Bookmark the newly added record const bookmark = rstEmployees.Bookmark; // Use the new index to set the order of the records. rstEmployees.MoveFirst(); WScript.Echo(`Index = ${rstEmployees.Index}, IndexNulls = ${idxNew.IndexNulls}`); WScript.Echo('\tCountry - Name'); // Enumerate the Recordset. The value of the IndexNulls property will determine if the newly added record appears in the output. while (!rstEmployees.EOF) { const country = rstEmployees('Country').Value as string | null || '[NULL]'; WScript.Echo(`\t${country} - ${rstEmployees('FirstName').Value} ${rstEmployees('LastName').Value}`); rstEmployees.MoveNext(); } // Delete new record because this is a demonstration. rstEmployees.Bookmark = bookmark; rstEmployees.Delete(); rstEmployees.Close(); catNorthwind.Tables('Employees').Indexes.Delete(idxNew.Name); catNorthwind = null; } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/adox-code-example-numericscale-and-precision-properties-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null; let colLoop: ADOX.Column | null; try { // Connect the catalog. cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; // Retrieve the Order Details table const tblOD = cat.Tables('Order Details'); // Display numeric scale and precision of small integer fields. for (colLoop of collectionToArray(tblOD.Columns)) { if (colLoop.Type === ADODB.DataTypeEnum.adSmallInt) { WScript.Echo(` Column: ${colLoop.Name} Numeric scale: ${colLoop.NumericScale} Precision: ${colLoop.Precision} `.trim()); } } } catch (error) { WScript.Echo(error); } finally { cat = null; cnn = tryClose(cnn); colLoop = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/parentcatalog-property-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null; let tbl: ADOX.Table | null; try { cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; tbl = new ActiveXObject('ADOX.Table'); tbl.Name = 'MyContacts'; tbl.ParentCatalog = cat; // Create fields and append them to the new Table object. tbl.Columns.Append('ContactId', adInteger); tbl.Columns.Append('CustomerID', adVarWChar); tbl.Columns.Append('FirstName', adVarWChar); tbl.Columns.Append('LastName', adVarWChar); tbl.Columns.Append('Phone', adVarWChar, 20); tbl.Columns.Append('Notes', ADODB.DataTypeEnum.adLongVarWChar); // Make the ContactId column an auto incrementing column tbl.Columns('ContactId').Properties('AutoIncrement').Value = true; cat.Tables.Append(tbl); WScript.Echo(`Table 'MyContacts' is added.`); // Delete the table as this is a demonstration. cat.Tables.Delete(tbl.Name); WScript.Echo(`Table 'MyContacts' is deleted.`); } catch (error) { WScript.Echo(error); } finally { cnn = tryClose(cnn); cat = null; tbl = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/primarykey-and-unique-properties-example-vb { let catNorthwind: ADOX.Catalog | null = null; let tblNew: ADOX.Table | null; let idxNew: ADOX.Index | null; let idxLoop: ADOX.Index | null; try { // Connect the catalog catNorthwind = new ActiveXObject('ADOX.Catalog'); catNorthwind.ActiveConnection = connectionString; // Name new table tblNew = new ActiveXObject('ADOX.Table'); tblNew.Name = 'NewTable'; // Append a numeric and a text field to new table. tblNew.Columns.Append('NumField', adInteger, 20); tblNew.Columns.Append('TextField', adVarWChar, 20); // Append new Primary Key index on NumField column to new table idxNew = new ActiveXObject('ADOX.Index'); idxNew.Name = 'NumIndex'; idxNew.Columns.Append('NumField'); idxNew.PrimaryKey = true; idxNew.Unique = true; tblNew.Indexes.Append(idxNew); // Append an index on Textfield to new table.. // Note the different technique: Specifying index and column name as parameters of the Append method tblNew.Indexes.Append('TextIndex', 'TextField'); // Append the new table catNorthwind.Tables.Append(tblNew); WScript.Echo(`${tblNew.Indexes.Count} indexes in '${tblNew.Name}' table`); // Enumerate Indexes collection. for (idxLoop of collectionToArray(tblNew.Indexes)) { WScript.Echo(` Index ${idxLoop.Name} Primary key = ${idxLoop.PrimaryKey} Unique = ${idxLoop.Unique} Columns = ${collectionToArray(idxLoop.Columns).map(colLoop => colLoop.Name).join(', ')} `.trim()); } // Delete new table as this is a demonstration. catNorthwind.Tables.Delete(tblNew.Name); } catch (error) { WScript.Echo(error); } finally { if (catNorthwind) { catNorthwind.ActiveConnection = null; } catNorthwind = null; tblNew = null; idxNew = null; idxLoop = null; } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/sortorder-property-example-vb { let cnn: ADODB.Connection | null = null; let catNorthwind: ADOX.Catalog | null; let idxAscending: ADOX.Index | null; let rstEmployees: ADODB.Recordset | null = null; let idxDescending: ADOX.Index | null; try { // Connect to the catalog. cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); catNorthwind = new ActiveXObject('ADOX.Catalog'); catNorthwind.ActiveConnection = cnn; const enumerateRecordset = (indexName: string) => { rstEmployees = new ActiveXObject('ADODB.Recordset'); rstEmployees.Index = indexName; rstEmployees.Open('Employees', cnn!, adOpenKeyset, adLockOptimistic, ADODB.CommandTypeEnum.adCmdTableDirect); rstEmployees.MoveFirst(); WScript.Echo(`Index = ${rstEmployees.Index}`); WScript.Echo('\tCountry - Name'); // Enumerate the Recordset. The value of the IndexNulls property will determine if the newly added record appears in the output. while (!rstEmployees.EOF) { WScript.Echo(`\t${rstEmployees('Country').Value} - ${rstEmployees('FirstName').Value} ${rstEmployees('LastName').Value}`); rstEmployees.MoveNext(); } rstEmployees.Close(); }; // Append Country column to new index. idxAscending = new ActiveXObject('ADOX.Index'); idxAscending.Columns.Append('Country'); idxAscending.Columns('Country').SortOrder = ADOX.SortOrderEnum.adSortAscending; idxAscending.Name = 'Ascending'; idxAscending.IndexNulls = ADOX.AllowNullsEnum.adIndexNullsAllow; // Append new index to Employees table. catNorthwind.Tables('Employees').Indexes.Append(idxAscending); enumerateRecordset(idxAscending.Name); // Append Country column to new index. idxDescending = new ActiveXObject('ADOX.Index'); idxDescending.Columns.Append('Country'); idxDescending.Columns('Country').SortOrder = ADOX.SortOrderEnum.adSortDescending; idxDescending.Name = 'Descending'; idxDescending.IndexNulls = ADOX.AllowNullsEnum.adIndexNullsAllow; // Append descending index to Employees table. catNorthwind.Tables('Employees').Indexes.Append(idxDescending); enumerateRecordset(idxDescending.Name); // Delete new indexes because this is a demonstration. catNorthwind.Tables('Employees').Indexes.Delete(idxAscending.Name); catNorthwind.Tables('Employees').Indexes.Delete(idxDescending.Name); } catch (error) { WScript.Echo(error); } finally { cnn = tryClose(cnn); catNorthwind = null; idxAscending = null; idxDescending = null; rstEmployees = tryClose(rstEmployees); } } // https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/views-and-fields-collections-example-vb { let cnn: ADODB.Connection | null = null; let cat: ADOX.Catalog | null; let rst: ADODB.Recordset | null = null; let fld: ADODB.Field | null; try { // Open the Connection cnn = new ActiveXObject('ADODB.Connection'); cnn.Open(connectionString); // Open the catalog cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = cnn; // Set the Source for the Recordset rst = new ActiveXObject('ADODB.Recordset'); rst.Source = cat.Views('AllCustomers').Command; // Retrieve Field information rst.Fields.Refresh(); for (fld of collectionToArray(rst.Fields)) { WScript.Echo(`${fld.Name}.${fld.Type}`); } } catch (error) { WScript.Echo(error); } finally { cnn = tryClose(cnn); cat = null; rst = tryClose(rst); fld = null; } } const flatten = <T>(arr: T[][], result: T[] = []) => { for (let i = 0, length = arr.length; i < length; i++) { const value: T | any[] = arr[i]; // any in this context is because the array might have an arbitrary depth if (Array.isArray(value)) { flatten(value, result); } else { result.push(value); } } return result; }; // List indexes with multiple columns { interface TableIndex { tbl: ADOX.Table; idx: ADOX.Index; } const cat = new ActiveXObject('ADOX.Catalog'); cat.ActiveConnection = connectionString; let multicolumnIndexes = flatten( collectionToArray(cat.Tables).map(tbl => collectionToArray(tbl.Indexes).map<TableIndex>(idx => ({ tbl, idx }) ) ) ).filter(x => x.idx.Columns.Count > 1); for (const x of multicolumnIndexes) { const columns = collectionToArray(x.idx.Columns).map(col => col.Name).join(', '); WScript.Echo(`${x.tbl.Name}.${x.idx.Name} -- ${columns}`); } multicolumnIndexes = []; }
the_stack
import * as os from 'os'; import * as path from 'path'; import * as im from 'immutable'; import * as ast from '../lexical-analysis/ast'; import * as lexer from '../lexical-analysis/lexer'; import * as lexical from '../lexical-analysis/lexical'; import * as service from './service'; import * as editor from '../editor'; // // Analyzer. // export interface EventedAnalyzer extends editor.DocumentEventListener, editor.UiEventListener { } // TODO: Rename this to `EventedAnalyzer`. export class Analyzer implements EventedAnalyzer { constructor( private documents: editor.DocumentManager, private compilerService: service.LexicalAnalyzerService, ) { } // // WorkspaceEventListener implementation. // public onDocumentOpen = this.compilerService.cache; public onDocumentSave = this.compilerService.cache; public onDocumentClose = this.compilerService.delete; // // AnalysisEventListener implementation. // public onHover = ( fileUri: string, cursorLoc: lexical.Location ): Promise<editor.HoverInfo> => { const emptyOnHover = Promise.resolve().then( () => <editor.HoverInfo>{ contents: [], }); const onHoverPromise = ( node: ast.Node | ast.IndexedObjectFields, ): Promise<editor.HoverInfo> => { if (node == null) { return emptyOnHover; } try { const msg = this.renderOnhoverMessage(fileUri, node); return Promise.resolve().then( () => <editor.HoverInfo> { contents: msg, }); } catch(err) { console.log(err); return emptyOnHover; } } try { const {text: docText, version: version, resolvedPath: resolvedUri} = this.documents.get(fileUri); const cached = this.compilerService.cache(fileUri, docText, version); if (service.isFailedParsedDocument(cached)) { return emptyOnHover; } // Get symbol we're hovering over. const nodeAtPos = getNodeAtPositionFromAst(cached.parse, cursorLoc); if (ast.isFindFailure(nodeAtPos)) { return emptyOnHover; } if (nodeAtPos.parent != null && ast.isFunctionParam(nodeAtPos.parent)) { // A function parameter is a free variable, so we can't resolve // it. Simply return. return onHoverPromise(nodeAtPos.parent); } if (!ast.isResolvable(nodeAtPos)) { return emptyOnHover; } const ctx = new ast.ResolutionContext( this.compilerService, this.documents, resolvedUri); const resolved = ast.tryResolveIndirections(nodeAtPos, ctx); // Handle the special cases. If we hover over a symbol that points // at a function of some sort (i.e., a `function` literal, a // `local` that has a bind that is a function, or an object field // that is a function), then we want to render the name and // parameters that function takes, rather than the definition of // the function itself. if (ast.isResolveFailure(resolved)) { if (ast.isUnresolved(resolved) || ast.isUnresolvedIndex(resolved)) { return emptyOnHover; } else if (ast.isResolvedFreeVar(resolved)) { return onHoverPromise(resolved.variable); } else if (ast.isResolvedFunction(resolved)) { return onHoverPromise(resolved.functionNode); } else { return onHoverPromise(resolved); } } else { return onHoverPromise(resolved.value); } } catch (err) { console.log(err); return emptyOnHover; } } public onComplete = ( fileUri: editor.FileUri, cursorLoc: lexical.Location ): Promise<editor.CompletionInfo[]> => { const doc = this.documents.get(fileUri); return Promise.resolve().then( (): editor.CompletionInfo[] => { // // Generate suggestions. This process follows three steps: // // 1. Try to parse the document text. // 2. If we succeed, go to cursor, select that node, and if // it's an identifier that can be completed, then return // the environment. // 3. If we fail, go try to go to the "hole" where the // identifier exists. // try { const compiled = this.compilerService.cache( fileUri, doc.text, doc.version); const lines = doc.text.split("\n"); // Lets us know whether the user has typed something like // `foo` or `foo.` (i.e., whether they are "dotting into" // `foo`). In the case of the latter, we will want to emit // suggestions from the members of `foo`. const lastCharIsDot = lines[cursorLoc.line-1][cursorLoc.column-2] === "."; let node: ast.Node | null = null; if (service.isParsedDocument(compiled)) { // Success case. The document parses, and we can offer // suggestions from a well-formed document. return this.completionsFromParse( fileUri, compiled, cursorLoc, lastCharIsDot); } else { const lastParse = this.compilerService.getLastSuccess(fileUri); if (lastParse == null) { return []; } return this.completionsFromFailedParse( fileUri, compiled, lastParse, cursorLoc, lastCharIsDot); } } catch (err) { console.log(err); return []; } }); } // -------------------------------------------------------------------------- // Completion methods. // -------------------------------------------------------------------------- // completionsFromParse takes a `ParsedDocument` (i.e., a // successfully-parsed document), a cursor location, and an // indication of whether the user is "dotting in" to a property, and // produces a list of autocomplete suggestions. public completionsFromParse = ( fileUri: editor.FileUri, compiled: service.ParsedDocument, cursorLoc: lexical.Location, lastCharIsDot: boolean, ): editor.CompletionInfo[] => { // IMPLEMENTATION NOTES: We have kept this method relatively free // of calls to `this` so that we don't have to mock out more of // the analyzer to test it. let foundNode = getNodeAtPositionFromAst( compiled.parse, cursorLoc); if (ast.isAnalyzableFindFailure(foundNode)) { if (foundNode.kind === "NotIdentifier") { return []; } if (foundNode.terminalNodeOnCursorLine != null) { foundNode = foundNode.terminalNodeOnCursorLine; } else { foundNode = foundNode.tightestEnclosingNode; } } else if (ast.isUnanalyzableFindFailure(foundNode)) { return []; } return this.completionsFromNode( fileUri, foundNode, cursorLoc, lastCharIsDot); } // completionsFromFailedParse takes a `FailedParsedDocument` (i.e., // a document that does not parse), a `ParsedDocument` (i.e., a // last-known good parse for the document), a cursor location, and // an indication of whether the user is "dotting in" to a property, // and produces a list of autocomplete suggestions. public completionsFromFailedParse = ( fileUri: editor.FileUri, compiled: service.FailedParsedDocument, lastParse: service.ParsedDocument, cursorLoc: lexical.Location, lastCharIsDot: boolean, ): editor.CompletionInfo[] => { // IMPLEMENTATION NOTES: We have kept this method relatively free // of calls to `this` so that we don't have to mock out more of // the analyzer to test it. // // Failure case. The document does not parse, so we need // to: // // 1. Obtain a partial parse from the parser. // 2. Get our "best guess" for where in the AST the user's // cursor would be, if the document did parse. // 3. Use the partial parse and the environment "best // guess" to create suggestions based on the context // of where the user is typing. if ( service.isLexFailure(compiled.parse) || compiled.parse.parseError.rest == null ) { return []; } // Step 1, get the "rest" of the parse, i.e., the partial // parse emitted by the parser. const rest = compiled.parse.parseError.rest; const restEnd = rest.loc.end; if (rest == null) { throw new Error(`INTERNAL ERROR: rest should never be null`); } else if ( !cursorLoc.inRange(rest.loc) && !(restEnd.line === cursorLoc.line && cursorLoc.column === restEnd.column + 1) ) { // NOTE: the `+ 1` correctly captures the case of the // user typing `.`. // Explicitly handle the case that the user has pressed a // newline and `.` character. For example, in the third line // below: // // metadata.withAnnotations({foo: "bar"}) // // .; // // Return no suggestions if the parse is not broken at the // cursor. const lines = compiled.text.split(/\r\n|\r|\n/g); const gapLines = lines.slice(restEnd.line, cursorLoc.line); if (gapLines.length == 0) { return []; } else if (gapLines.length === 1) { const gap = gapLines[0].slice(cursorLoc.column, restEnd.column); if (gap.trim().length != 0) { return []; } } else { const firstGap = gapLines[0].slice(restEnd.column); const lastGap = gapLines[gapLines.length - 1] .slice( 0, cursorLoc.column - (lastCharIsDot ? 2 : 1)); const middleGapLengths = gapLines .slice(1, gapLines.length - 2) .reduce((gapLenAcc: number, line: string) => gapLenAcc + line.trim().length, 0); if (firstGap.trim().length !== 0 || middleGapLengths !== 0 || lastGap.trim().length !== 0) { return []; } } cursorLoc = restEnd; } // Step 2, try to find the "best guess". let foundNode = getNodeAtPositionFromAst( lastParse.parse, cursorLoc); if (ast.isAnalyzableFindFailure(foundNode)) { if (foundNode.terminalNodeOnCursorLine != null) { foundNode = foundNode.terminalNodeOnCursorLine; } else { foundNode = foundNode.tightestEnclosingNode; } } else if (ast.isUnanalyzableFindFailure(foundNode)) { return []; } // Step 3, combine the partial parse and the environment // of the "best guess" to attempt to create meaningful // suggestions for the user. if (foundNode.env == null) { throw new Error("INTERNAL ERROR: Node environment can't be null"); } new ast .InitializingVisitor(rest, foundNode, foundNode.env) .visit(); // Create suggestions. return this.completionsFromNode(fileUri, rest, cursorLoc, lastCharIsDot); } // completionsFromNode takes a `Node`, a cursor location, and an // indication of whether the user is "dotting in" to a property, and // produces a list of autocomplete suggestions. private completionsFromNode = ( fileUri: editor.FileUri, node: ast.Node, cursorLoc: lexical.Location, lastCharIsDot: boolean, ): editor.CompletionInfo[] => { // Attempt to resolve the node. const ctx = new ast.ResolutionContext( this.compilerService, this.documents, fileUri); const resolved = ast.tryResolveIndirections(node, ctx); if (ast.isUnresolved(resolved)) { // If we could not even partially resolve a node (as we do, // e.g., when an index target resolves, but the ID doesn't), // then create suggestions from the environment. return node.env != null ? envToSuggestions(node.env) : []; } else if (ast.isUnresolvedIndexTarget(resolved)) { // One of the targets in some index expression failed to // resolve, so we have no suggestions. For example, in // `foo.bar.baz.bat`, if any of `foo`, `bar`, or `baz` fail, // then we have nothing to suggest as the user is typing `bat`. return []; } else if (ast.isUnresolvedIndexId(resolved)) { // We have successfully resolved index target, but not the index // ID, so generate suggestions from the resolved target. For // example, if the user types `foo.b`, then we would generate // suggestions from the members of `foo`. return this.completionsFromFields(resolved.resolvedTarget); } else if ( ast.isResolvedFunction(resolved) || ast.isResolvedFreeVar(resolved) || (!lastCharIsDot && ast.isIndexedObjectFields(resolved.value) || ast.isNode(resolved.value)) ) { // Our most complex case. One of two things is true: // // 1. Resolved the ID to a function or a free param, in which // case we do not want to emit any suggestions, or // 2. The user has NOT typed a dot, AND the resolve node is not // fields addressable, OR it's a node. In other words, the // user has typed something like `foo` (and specifically not // `foo.`, which is covered in another case), and `foo` // completely resolves, either to a value (e.g., a number // like 3) or a set of fields (i.e., `foo` is an object). In // both cases the user has type variable, and we don't want // to suggest anything; if they wanted to see the members of // `foo`, they should type `foo.`. return []; } else if (lastCharIsDot && ast.isIndexedObjectFields(resolved.value)) { // User has typed a dot, and the resolved symbol is // fields-resolvable, so we can return the fields of the // expression. For example, if the user types `foo.`, then we // can suggest the members of `foo`. return this.completionsFromFields(resolved.value); } // Catch-all case. Suggest nothing. return []; } private completionsFromFields = ( fieldSet: ast.IndexedObjectFields ): editor.CompletionInfo[] => { // Attempt to get all the possible fields we could suggest. If the // resolved item is an `ObjectNode`, just use its fields; if it's // a mixin of two objects, merge them and use the merged fields // instead. return im.List(fieldSet.values()) .filter((field: ast.ObjectField) => field != null && field.id != null && field.expr2 != null && field.kind !== "ObjectLocal") .map((field: ast.ObjectField) => { if (field == null || field.id == null || field.expr2 == null) { throw new Error( `INTERNAL ERROR: Filtered out null fields, but found field null`); } let kind: editor.CompletionType = "Field"; if (field.methodSugar) { kind = "Method"; } const comments = this.getComments(field); return { label: field.id.name, kind: kind, documentation: comments || undefined, }; }) .toArray(); } // -------------------------------------------------------------------------- // Completion methods. // -------------------------------------------------------------------------- private renderOnhoverMessage = ( fileUri: editor.FileUri, node: ast.Node | ast.IndexedObjectFields, ): editor.LanguageString[] => { if (ast.isIndexedObjectFields(node)) { if (node.count() === 0) { return []; } const first = node.first(); if (first.parent == null) { return []; } node = first.parent; } const commentText: string | null = this.resolveComments(node); const doc = this.documents.get(fileUri); let line: string = doc.text.split(os.EOL) .slice(node.loc.begin.line - 1, node.loc.end.line) .join("\n"); if (ast.isFunctionParam(node)) { // A function parameter is either a free variable, or a free // variable with a default value. Either way, there's not more // we can know statically, so emit that. line = node.prettyPrint(); } line = node.prettyPrint(); return <editor.LanguageString[]>[ {language: 'jsonnet', value: line}, commentText, ]; } // -------------------------------------------------------------------------- // Comment resolution. // -------------------------------------------------------------------------- // resolveComments takes a node as argument, and attempts to find the // comments that correspond to that node. For example, if the node // passed in exists inside an object field, we will explore the parent // nodes until we find the object field, and return the comments // associated with that (if any). public resolveComments = (node: ast.Node | null): string | null => { while (true) { if (node == null) { return null; } switch (node.type) { case "ObjectFieldNode": { // Only retrieve comments for. const field = <ast.ObjectField>node; if (field.kind != "ObjectFieldID" && field.kind == "ObjectFieldStr") { return null; } // Convert to field object, pull comments out. return this.getComments(field); } default: { node = node.parent; continue; } } } } private getComments = (field: ast.ObjectField): string | null => { // Convert to field object, pull comments out. const comments = field.headingComments; if (comments == null) { return null; } return comments.text.join(os.EOL); } } // // Utilities. // export const getNodeAtPositionFromAst = ( rootNode: ast.Node, pos: lexical.Location ): ast.Node | ast.FindFailure => { // Special case. Make sure that if the cursor is beyond the range // of text of the last good parse, we just return the last node. // For example, if the user types a `.` character at the end of // the document, the document now fails to parse, and the cursor // is beyond the range of text of the last good parse. const endLoc = rootNode.loc.end; if (endLoc.line < pos.line || (endLoc.line == pos.line && endLoc.column < pos.column)) { pos = endLoc; } const visitor = new ast.CursorVisitor(pos, rootNode); visitor.visit(); const tightestNode = visitor.nodeAtPosition; return tightestNode; } const envToSuggestions = (env: ast.Environment): editor.CompletionInfo[] => { return env.map((value: ast.LocalBind | ast.FunctionParam, key: string) => { // TODO: Fill in documentation later. This might involve trying // to parse function comment to get comments about different // parameters. return <editor.CompletionInfo>{ label: key, kind: "Variable", }; }) .toArray(); }
the_stack
import EventEmitter from "events"; import lt from "long-timeout"; import fetch from "node-fetch"; import { URLSearchParams } from "url"; import { ChannelManager, EmoteManager, UserManager } from "../classes/"; import ClientUser from "../classes/users/ClientUser"; import { BASE_URL, ExternalError, HTTPError, InternalError, MILLISECONDS, snakeCasify, TwitchAPIError, } from "../shared"; import type { Awaited, ClientEvents, ClientOptions, ClientScope, ErrorResponse, LoginResponse, UserData, ValidateResponse, } from "../types"; /** * The main client to interact with the Twitch API. * Supports app and user access tokens and is configurable. * Delegates API endpoints to different managers. * @class * @extends {EventEmitter} */ export default class Client extends EventEmitter { private accessToken?: string; private refreshToken?: string; private loginTimeout?: lt.Timeout; private validateInterval?: lt.Interval; private timeouts = new Set<lt.Timeout>(); private intervals = new Set<lt.Interval>(); public readonly options: Required<Omit<ClientOptions, "redirectUri" | "forceVerify" | "state">> & { redirectUri?: string; forceVerify?: boolean; state?: string; }; public readonly scope: ClientScope[]; public readonly channels: ChannelManager; public readonly users: UserManager; public readonly emotes: EmoteManager; public user?: ClientUser; private authType?: "app" | "user"; /** * Creates a new client to interact with the Twitch API. * @param {ClientOptions} options Options for the client. */ public constructor(options: ClientOptions) { super({ captureRejections: options.suppressRejections ?? false, }); /** * Options given to the client. * @type {ClientOptions} * @readonly */ this.options = { debug: false, scope: [], suppressRejections: false, update: { users: MILLISECONDS.DAY, channels: MILLISECONDS.HOUR, emotes: MILLISECONDS.HOUR, channelEmotes: MILLISECONDS.HOUR, channelRewards: MILLISECONDS.HOUR, }, ttl: { users: MILLISECONDS.WEEK, channels: MILLISECONDS.DAY, emotes: MILLISECONDS.DAY, channelEmotes: MILLISECONDS.DAY, channelRewards: MILLISECONDS.DAY, }, ...options, }; /** * Client's token's current scopes. * @type {string[]} * @readonly */ this.scope = this.options.scope ?? []; /** * Client's channel manager. * @type {ChannelManager} * @readonly */ this.channels = new ChannelManager(this); /** * Client's user manager. * @type {UserManager} * @readonly */ this.users = new UserManager(this); /** * Client's emote manager. * @type {EmoteManager} * @readonly */ this.emotes = new EmoteManager(this); /** * Client's current authenticated user. * @type {ClientUser} * @readonly */ this.user = undefined; } /** * Logs in the client and retrieves an app access token. * * @example * ```js * const token = await client.login(); * ``` */ public async login(): Promise<string>; /** * Uses the OAuth implicit credentials flow to generate a URL and callback. * @param {string} oauth Must be `"implicit"` to use the implicit credentials flow. * * @example * ```js * const { url, callback } = await client.login("implicit"); * * app.get("/auth/twitch", (req, res) => { * res.redirect(url); * }); * * app.get("/auth/twitch/callback", (req, res) => { * callback(new URL(req.protocol + '://' + req.get('host') + req.originalUrl).hash.slice("access_token=".length + 1)); * }); * ``` */ public async login(oauth: "implicit"): Promise<{ url: string; callback: (token: string) => Promise<void> }>; /** * Uses the OAuth authorization credentials flow to generate a URL and callback. * @param {string} oauth Must be `"authorization"` to use the authorization credentials flow. * * @example * ```js * const { url, callback } = await client.login("authorization"); * * app.get("/auth/twitch", (req, res) => { * res.redirect(url); * }); * * app.get("/auth/twitch/callback", (req, res) => { * callback(new URL(req.protocol + '://' + req.get('host') + req.originalUrl).searchParams.get("code")); * }); * ``` */ public async login(oauth: "authorization"): Promise<{ url: string; callback: (code: string) => Promise<void> }>; /** * Logs in the client and retrieves an app access token. * * @example * ```js * const token = await client.login(); * ``` * * @returns {Promise<string | object>} The new access token or OAuth details object. */ public async login( oauth?: "implicit" | "authorization" ): Promise< | string | { url: string; callback: (token: string) => Promise<void> } | { url: string; callback: (code: string) => Promise<void> } > { if (typeof oauth === "undefined") { const { clientId, clientSecret } = this.options; const response = await fetch( `https://id.twitch.tv/oauth2/token?${new URLSearchParams( snakeCasify({ clientId, clientSecret, scope: this.scope.join(" "), grantType: "client_credentials", }) ).toString()}`, { method: "POST", } ).catch((e) => { throw new HTTPError(e); }); if (!response.ok) throw new HTTPError("unable to login"); const data: LoginResponse & ErrorResponse = await response.json(); if (data.status && data.status !== 200) throw new TwitchAPIError(`(${data.status}) ${data.message ?? `unable to login`}`); if (!data.access_token) throw new TwitchAPIError(`unable to obtain access token`); this.accessToken = data.access_token; this.loginTimeout = lt.setTimeout(this.login.bind(this), (data.expires_in ?? 3600) * 1000 * 0.9); this.validateInterval = lt.setInterval(this.validate.bind(this), 3600 * 1000 * 0.9); this.authType = "app"; this.emit("ready"); return this.accessToken; } if (oauth === "implicit") { if (!this.options.redirectUri) throw new ExternalError(`no redirect uri provided`); this.authType = "user"; return { url: `https://id.twitch.tv/oauth2/authorize?client_id=${new URLSearchParams( snakeCasify({ clientId: this.options.clientId, redirectUri: this.options.redirectUri, responseType: "token", scope: this.options.scope.join(" "), forceVerify: typeof this.options.forceVerify !== "undefined" ? this.options.forceVerify?.toString() : undefined, state: this.options.state, }) ).toString()}`, callback: async (token: string) => { if (!(await this.validate({ token }))) throw new ExternalError(`invalid token provided`); this.accessToken = token; if (this.token) { const response = await fetch(`${BASE_URL}/users`, { headers: { authorization: `Bearer ${this.token}`, "client-id": this.options.clientId, }, }); if (response.ok) { const data: UserData = (await response.json()).data[0]; this.user = new ClientUser(this, data); } } this.emit("ready"); return; }, }; } if (oauth === "authorization") { this.authType = "user"; return { url: `https://id.twitch.tv/oauth2/authorize?client_id=${new URLSearchParams( snakeCasify({ clientId: this.options.clientId, redirectUri: this.options.redirectUri, responseType: "code", scope: this.options.scope.join(" "), forceVerify: typeof this.options.forceVerify !== "undefined" ? this.options.forceVerify?.toString() : undefined, state: this.options.state, }) ).toString()}`, callback: async (code: string) => { const response = await fetch( `https://id.twitch.tv/oauth2/token?${new URLSearchParams( snakeCasify({ clientId: this.options.clientId, clientSecret: this.options.clientSecret, code, grantType: "authorization_code", redirectUri: this.options.redirectUri, }) ).toString()}`, { method: "POST", } ).catch((e) => { throw new HTTPError(e); }); const data: LoginResponse & ErrorResponse = await response.json(); if (!response.ok || data.status !== 200 || data.message) throw new HTTPError(`unable to retrieve token with authorization code`); this.accessToken = data.access_token; this.refreshToken = data.refresh_token; this.validateInterval = lt.setInterval( this.refresh.bind(this), (data.expires_in ?? 3600) * 1000 * 0.9 ); if (this.token) { const response = await fetch(`${BASE_URL}/users`, { headers: { authorization: `Bearer ${this.token}`, "client-id": this.options.clientId, }, }); if (response.ok) { const data: UserData = (await response.json()).data[0]; this.user = new ClientUser(this, data); } } this.emit("ready"); }, }; } throw new Error(`invalid oauth type; valid types are 'implicit' and 'authorization'`); } /** * Destroys the client and revokes its access token. * * TODO: Add a destroy method on managers as well and call it here. * @returns {Promise<undefined>} Nothing. */ public async destroy() { if (this.accessToken) await fetch( `https://id.twitch.tv/oauth2/revoke?${new URLSearchParams( snakeCasify({ clientId: this.options.clientId, token: this.accessToken, }) ).toString()}`, { method: "POST", } ).catch((e) => { throw new HTTPError(e); }); for (const timeout of this.timeouts) lt.clearTimeout(timeout); for (const interval of this.intervals) lt.clearInterval(interval); this.accessToken = undefined; this.timeouts.clear(); this.intervals.clear(); if (this.loginTimeout) lt.clearTimeout(this.loginTimeout); if (this.validateInterval) lt.clearInterval(this.validateInterval); this.loginTimeout = undefined; this.validateInterval = undefined; this.user = undefined; this.emit("destroy"); } private async refresh() { if (!this.refreshToken) { if (!this.options.suppressRejections) throw new InternalError(`attempted to refresh access token when no refresh token was available`); return; } const response = await fetch( `https://id.twitch.tv/oauth2/token?${new URLSearchParams( snakeCasify({ clientId: this.options.clientId, clientSecret: this.options.clientSecret, grantType: "refresh_token", refreshToken: this.refreshToken, }) ).toString()}`, { method: "POST", } ).catch((e) => { throw new HTTPError(e); }); if (!response.ok) throw new HTTPError("unable to login"); const data: LoginResponse & ErrorResponse = await response.json(); if (data.status && data.status !== 200) throw new TwitchAPIError(`(${data.status}) ${data.message ?? `unable to login`}`); if (!data.access_token) throw new TwitchAPIError(`unable to obtain access token`); this.clearTimeout(this.loginTimeout!); this.clearInterval(this.validateInterval!); this.accessToken = data.access_token; this.refreshToken = data.refresh_token; return; } private async validate({ relogin, token }: { relogin?: boolean; token?: string } = {}) { const response = await fetch(`https://id.twitch.tv/oauth2/validate`, { headers: { authorization: `OAuth ${token ?? this.accessToken}`, }, }).catch((e) => { throw new HTTPError(e); }); if (!response.ok) { if (!this.options.suppressRejections) throw new TwitchAPIError(`unable to validate access token`); return false; } const data: ValidateResponse & ErrorResponse = await response.json(); if (data.status && data.status !== 200 && (relogin ?? true)) { this.emit("debug", `[Client] Access token validation failed. Retrying login...`); this.clearTimeout(this.loginTimeout!); this.clearInterval(this.validateInterval!); await this.login(); return false; } return true; } /** * Current token being used. * @type {string} * @readonly */ public get token() { return this.accessToken; } /** * Authentication type; either `"app"` or `"user"`. * @type {string} * @readonly */ public get type() { return this.authType; } /** * Sets an interval to be managed by the client. * @returns {Timeout} * @private */ public setInterval(...args: Parameters<typeof lt.setInterval>) { const interval = lt.setInterval(...args); this.intervals.add(interval); return interval; } /** * Sets a timeout to be managed by the client. * @returns {Timeout} * @private */ public setTimeout(...args: Parameters<typeof lt.setTimeout>) { const timeout = lt.setTimeout(...args); this.timeouts.add(timeout); return timeout; } /** * Clears an interval managed by the client. * @returns {undefined} * @private */ public clearInterval(...args: Parameters<typeof lt.clearInterval>) { lt.clearInterval(...args); this.intervals.delete(...args); return; } /** * Clears a timeout managed by the client. * @returns {undefined} * @private */ public clearTimeout(...args: Parameters<typeof lt.clearTimeout>) { lt.clearTimeout(...args); this.timeouts.delete(...args); return; } /** * Adds an event listener to the client. * @param {string} event Event to listen to. * @param {Function} listener Callback for the event. * @returns {Client} The client instance. */ public on<K extends keyof ClientEvents>(event: K, listener: (...args: ClientEvents[K]) => Awaited<unknown>): this; /** * Adds an event listener to the client. * @param {string} event Event to listen to. * @param {Function} listener Callback for the event. * @returns {Client} The client instance. */ public on<S extends string | symbol>( event: Exclude<S, keyof ClientEvents>, listener: (...args: any[]) => Awaited<void> ): this { return super.on(event, listener); } /** * Adds an event listener to the client, but the listener gets removed as soon as an event is received. * @param {string} event Event to listen to. * @param {Function} listener Callback for the event. * @returns {Client} The client instance. */ public once<K extends keyof ClientEvents>(event: K, listener: (...args: ClientEvents[K]) => Awaited<unknown>): this; /** * Adds an event listener to the client, but the listener gets removed as soon as an event is received. * @param {string} event Event to listen to. * @param {Function} listener Callback for the event. * @returns {Client} The client instance. */ public once<S extends string | symbol>( event: Exclude<S, keyof ClientEvents>, listener: (...args: any[]) => Awaited<void> ): this { return super.once(event, listener); } /** * Emits a new event on the client to be captured by its listeners. * @param {string} event Event to emit. * @param {any[]} args Data for the event. * @returns {boolean} True if the emission was successful. */ public emit<K extends keyof ClientEvents>(event: K, ...args: ClientEvents[K]): boolean; public emit<S extends string | symbol>(event: Exclude<S, keyof ClientEvents>, ...args: any[]): boolean { return super.emit(event, ...args); } }
the_stack
import * as assert from 'assert' import * as fs from 'fs' import * as util from 'util' import { Communication } from 'diat-live-inspector' import { snippets } from './Snippets' import { NodeInspectWrapper } from './NodeInspectWrapper' import { TcpProxy, ITcpProxyOptions } from './TcpProxy' import { getAbsolutePath, getDefaultFileName, isNodeVersionLE8 } from './utils' import { DiatError } from './Error' import { InspectorWorker } from './InspectorWorker' import { Metric } from './Metric' import { IPostFunc } from './Types' interface IAttachOptions { host: string port: number } interface ITakeHeapsnapshotOptions { file: string } interface IProfileOptions { file: string duration: number interval: number } interface IHeapTimelineOptions { file: string duration: number track: boolean } interface IFileResult { file: string } interface IOpenInspectInfo { host: string port: number tcpProxy: TcpProxy } interface IOpenInspectOptions { port?: number } interface IEvaluteResult { type: 'error' | 'success' content: string } const kFileTypes = { cpuprofile: '.cpuprofile', heapsnapshot: '.heapsnapshot', heapprofile: '.heapprofile', heaptimeline: '.heaptimeline', } function createUnknownResult(ret: any): IEvaluteResult { return { type: 'error', content: 'unexpected structure' + (ret ? JSON.stringify(ret) : ''), } } export function getEvaluateResult(ret: any): IEvaluteResult { if (!ret.result) { return createUnknownResult(ret) } const { result } = ret if (result.type === 'object' && result.subtype === 'error') { return { type: 'error', content: result.description, } } if (result.type !== 'string') { return createUnknownResult(ret) } return { type: 'success', content: result.value, } } export class Comm { public nodeVersion: string | null = null private pid: number | undefined = undefined private addr: string | undefined = undefined private handle: Communication private tcpProxy: null | TcpProxy = null private inspectorWorker: InspectorWorker | null = null private metric: Metric | null = null constructor(pid: number | undefined, addr: string | undefined) { if (!pid && !addr) { throw new DiatError(`invalid options`) } this.pid = pid this.addr = addr // TODO(oyyd): We need to handle `LiveInspector.close` at an appropriate time. this.handle = new Communication({ pid: this.pid, inspectorAddr: this.addr, }) } connect = async () => { const ret = await this.handle.connect() if (ret !== null) { this.nodeVersion = ret.version } return } releaseWs = () => { this.handle.releaseWs() } disconnect = (forceCloseInpsector: boolean = false) => { /* istanbul ignore next */ if (this.inspectorWorker) { this.inspectorWorker.destroy() this.inspectorWorker = null } if (this.tcpProxy) { this.tcpProxy.destroy() this.inspectorWorker = null } if (this.metric) { this.metric.destroy() this.metric = null } // NOTE(oyyd): For Node.js 8, calling disconnect() might cause aborting. // TODO test if ( !forceCloseInpsector && this.nodeVersion && isNodeVersionLE8(this.nodeVersion) ) { /* istanbul ignore next */ return this.handle.disconnect(false) } return this.handle.disconnect() } private getPidOrZero = (): number => { return this.handle.getUsePid() ? (this.pid as number) : 0 } takeHeapsnapshot = async ( options_: Partial<ITakeHeapsnapshotOptions> ): Promise<IFileResult> => { const options = Object.assign( { // default }, options_ ) const { file } = options const absPath = file ? getAbsolutePath(file) : getDefaultFileName(this.getPidOrZero(), kFileTypes.heapsnapshot) const fileStream = fs.createWriteStream(absPath) return new Promise<IFileResult>((resolve, reject) => { const addChunk = (data) => { const { chunk } = data fileStream.write(chunk) } this.handle.event.addListener( 'HeapProfiler.addHeapSnapshotChunk', addChunk ) this.handle.post('HeapProfiler.takeHeapSnapshot', null, (err, b) => { this.handle.event.removeListener( 'HeapProfiler.addHeapSnapshotChunk', addChunk ) fileStream.end() /* istanbul ignore next */ if (err) { reject(err) return } resolve({ file: absPath, }) }) }) } cpuProfile = async ( options_: Partial<IProfileOptions> ): Promise<IFileResult> => { const options = Object.assign( { duration: 5000, interval: 1000, }, options_ ) const { file, duration, interval } = options if (typeof duration !== 'number') { throw new DiatError( `expect "duration" to be number, receive: ${duration}` ) } const absPath = file ? getAbsolutePath(file) : getDefaultFileName(this.getPidOrZero(), kFileTypes.cpuprofile) const fileStream = fs.createWriteStream(absPath) const post = util.promisify(this.handle.post) await post('Profiler.enable', null) await post('Profiler.setSamplingInterval', { interval }) await post('Profiler.start', null) await new Promise((resolve) => setTimeout(resolve, duration)) const res: any = await post('Profiler.stop', null) fileStream.write(JSON.stringify(res.profile)) fileStream.end() return { file: absPath, } } heapProfile = async ( options_: Partial<IProfileOptions> ): Promise<IFileResult> => { const options = Object.assign( { duration: 5000, interval: 1000, }, options_ ) const { file, duration, interval } = options if (typeof duration !== 'number') { throw new DiatError( `expect "duration" to be number, receive: ${duration}` ) } const absPath = file ? getAbsolutePath(file) : getDefaultFileName(this.getPidOrZero(), kFileTypes.heapprofile) const fileStream = fs.createWriteStream(absPath) const post = util.promisify(this.handle.post) await post('HeapProfiler.enable', null) await post('HeapProfiler.startSampling', { samplingInterval: interval, }) await new Promise((resolve) => setTimeout(resolve, duration)) const res: any = await post('HeapProfiler.stopSampling', null) fileStream.write(JSON.stringify(res.profile)) fileStream.end() return { file: absPath, } } heapTimeline = async ( options_: Partial<IHeapTimelineOptions> ): Promise<IFileResult> => { const options = Object.assign( { track: true, duration: 5000, }, options_ ) const { file, duration, track } = options if (typeof duration !== 'number') { throw new DiatError( `expect "duration" to be number, receive: ${duration}` ) } const absPath = file ? getAbsolutePath(file) : getDefaultFileName(this.getPidOrZero(), kFileTypes.heaptimeline) const fileStream = fs.createWriteStream(absPath) const post = util.promisify(this.handle.post) await post('HeapProfiler.enable', null) const addChunk = (data) => { const { chunk } = data fileStream.write(chunk) } this.handle.event.addListener('HeapProfiler.addHeapSnapshotChunk', addChunk) await post('HeapProfiler.startTrackingHeapObjects', { trackAllocations: track, }) await new Promise((resolve) => setTimeout(resolve, duration)) const res: any = await post('HeapProfiler.stopTrackingHeapObjects', null) fileStream.end() return { file: absPath, } } attachRepl = async (options: IAttachOptions) => { const wrapper = new NodeInspectWrapper(options) return wrapper.startInspect() } getMainThreadInspectorAddr = async ( port: undefined | number ): Promise<{ host: undefined | string; port: undefined | number }> => { const usePid = this.handle.getUsePid() let targetHost: undefined | string = undefined let targetPort: undefined | number = undefined if (!usePid) { const addr = this.handle.getAddr() as any targetHost = addr.host targetPort = addr.port } else { targetPort = port } return { host: targetHost, port: targetPort, } } openInspect = async ( options: IOpenInspectOptions = {} ): Promise<IOpenInspectInfo> => { const port = options.port || 9229 const tcpProxyOptions: Partial<ITcpProxyOptions> = {} // for Node.js 8, only one ws could connect at a time if (this.nodeVersion && isNodeVersionLE8(this.nodeVersion)) { this.releaseWs() } const { host: targetHost, port: targetPort, } = await this.getMainThreadInspectorAddr(port) tcpProxyOptions.targetHost = targetHost tcpProxyOptions.targetPort = targetPort this.tcpProxy = new TcpProxy(tcpProxyOptions) const addr = await this.tcpProxy.listen() const info = { ...addr, tcpProxy: this.tcpProxy, } return info } /** * required Node.js >= 10.12 */ getWorkers = async () => { // get worker infos -> choose worker -> proxy inspecting if (!this.inspectorWorker) { const post: IPostFunc = util.promisify(this.handle.post) this.inspectorWorker = new InspectorWorker({ event: this.handle.event, post: post, }) } const infos = await this.inspectorWorker.getWorkers() return infos } inspectWorker = async (sessionId: string) => { if (!this.inspectWorker) { throw new Error('expect "this.inspectWorker"') } const { inspectorWorker } = this if (!inspectorWorker) { return } const addr = await inspectorWorker.createWorkerSession(sessionId) return addr } run = async (name: string, options?: any): Promise<IEvaluteResult> => { const code = await snippets.getSnippet(name, options) return this.exec(code) } exec = async (code: string) => { const ret = await this.handle.execCode(code) return getEvaluateResult(ret) } startMetric = async ( options: { socketPath?: string } = {} ): Promise<Metric> => { const { socketPath: p } = options assert(!this.metric, 'this.metric already exist') this.metric = p ? new Metric({ socketPath: p, }) : new Metric({}) const socketPath = await this.metric.createServer() this.metric.once('close', () => { // TODO }) await this.run('metric_collect', { socketPath, }) return this.metric } }
the_stack
module Humanizer { "use strict"; export interface InUnit { second(): Date; secondFrom(date: Date): Date; minute(): Date; minuteFrom(date: Date): Date; hour(): Date; hourFrom(date: Date): Date; day(): Date; dayFrom(date: Date): Date; week(): Date; weekFrom(date: Date): Date; month(): Date; monthFrom(date: Date): Date; year(): Date; yearFrom(date: Date): Date; } export interface InUnits { seconds(): Date; secondsFrom(date: Date): Date; minutes(): Date; minutesFrom(date: Date): Date; hours(): Date; hoursFrom(date: Date): Date; days(): Date; daysFrom(date: Date): Date; weeks(): Date; weeksFrom(date: Date): Date; months(): Date; monthsFrom(date: Date): Date; years(): Date; yearsFrom(date: Date): Date; } var someTime: any = {}; var MILLIS_PER_SECOND: number = 1000; var MILLIS_PER_MINUTE: number = MILLIS_PER_SECOND * 60; var MILLIS_PER_HOUR: number = MILLIS_PER_MINUTE * 60; var MILLIS_PER_DAY: number = MILLIS_PER_HOUR * 24; var MILLIS_PER_WEEK: number = MILLIS_PER_DAY * 7; for (var i: number = 1; i <= 10; i++) { var plural: string = i > 1 ? "s" : ""; var second: string = "second" + plural; var minute: string = "minute" + plural; var hour: string = "hour" + plural; var day: string = "day" + plural; var week: string = "week" + plural; var month: string = "month" + plural; var year: string = "year" + plural; someTime[i] = {}; someTime[i][second] = (function (j: number): () => Date { var fn: () => Date = function (): Date { return new Date((new Date()).getTime() + j * MILLIS_PER_SECOND); }; return fn; } (i)); someTime[i][second + "From"] = (function (j: number): (date: Date) => Date { var fn: (date: Date) => Date = function (date: Date): Date { return new Date(date.getTime() + j * MILLIS_PER_SECOND); }; return fn; } (i)); someTime[i][minute] = (function (j: number): () => Date { var fn: () => Date = function (): Date { return new Date((new Date()).getTime() + j * MILLIS_PER_MINUTE); }; return fn; } (i)); someTime[i][minute + "From"] = (function (j: number): (date: Date) => Date { var fn: (date: Date) => Date = function (date: Date): Date { return new Date(date.getTime() + j * MILLIS_PER_MINUTE); }; return fn; } (i)); someTime[i][hour] = (function (j: number): () => Date { var fn: () => Date = function (): Date { return new Date((new Date()).getTime() + j * MILLIS_PER_HOUR); }; return fn; } (i)); someTime[i][hour + "From"] = (function (j: number): (date: Date) => Date { var fn: (date: Date) => Date = function (date: Date): Date { return new Date(date.getTime() + j * MILLIS_PER_HOUR); }; return fn; } (i)); someTime[i][day] = (function (j: number): () => Date { var fn: () => Date = function (): Date { return new Date((new Date()).getTime() + j * MILLIS_PER_DAY); }; return fn; } (i)); someTime[i][day + "From"] = (function (j: number): (date: Date) => Date { var fn: (date: Date) => Date = function (date: Date): Date { return new Date(date.getTime() + j * MILLIS_PER_DAY); }; return fn; } (i)); someTime[i][week] = (function (j: number): () => Date { var fn: () => Date = function (): Date { return new Date((new Date()).getTime() + j * MILLIS_PER_WEEK); }; return fn; } (i)); someTime[i][week + "From"] = (function (j: number): (date: Date) => Date { var fn: (date: Date) => Date = function (date: Date): Date { return new Date(date.getTime() + j * MILLIS_PER_WEEK); }; return fn; } (i)); someTime[i][month] = (function (j: number): () => Date { var fn: () => Date = function (): Date { var now: Date = new Date(); now.setMonth(now.getMonth() + j); return now; }; return fn; } (i)); someTime[i][month + "From"] = (function (j: number): (date: Date) => Date { var fn: (date: Date) => Date = function (date: Date): Date { var newDate: Date = new Date(date.getTime()); newDate.setMonth(date.getMonth() + j); return newDate; }; return fn; } (i)); someTime[i][year] = (function (j: number): () => Date { var fn: () => Date = function (): Date { var now: Date = new Date(); now.setFullYear(now.getFullYear() + j); return now; }; return fn; } (i)); someTime[i][year + "From"] = (function (j: number): (date:Date) => Date { var fn: (date: Date) => Date = function (date: Date): Date { var newDate: Date = new Date(date.getTime()); newDate.setFullYear(newDate.getFullYear() + j); return newDate; }; return fn; } (i)); } export class In { static one: InUnit = someTime[1]; static two: InUnits = someTime[2]; static three: InUnits = someTime[3]; static four: InUnits = someTime[4]; static five: InUnits = someTime[5]; static six: InUnits = someTime[6]; static seven: InUnits = someTime[7]; static eight: InUnits = someTime[8]; static nine: InUnits = someTime[9]; static ten: InUnits = someTime[10]; static theYear(year: number): Date { return new Date(year, 0, 1, 0, 0, 0, 0); } /** * Returns the 1st of January of the current year */ static january(): Date { /// <summary> /// Returns the 1st of January of the current year /// </summary> return new Date((new Date()).getFullYear(), 0, 1, 0, 0, 0, 0); } /** * Returns the 1st of February of the current year */ static february(): Date { /// <summary> /// Returns the 1st of February of the current year /// </summary> return new Date((new Date()).getFullYear(), 1, 1, 0, 0, 0, 0); } /** * Returns the 1st of March of the current year */ static march(): Date { /// <summary> /// Returns the 1st of March of the current year /// </summary> return new Date((new Date()).getFullYear(), 2, 1, 0, 0, 0, 0); } /** * Returns the 1st of April of the current year */ static april(): Date { /// <summary> /// Returns the 1st of April of the current year /// </summary> return new Date((new Date()).getFullYear(), 3, 1, 0, 0, 0, 0); } /** * Returns the 1st of May of the current year */ static may(): Date { /// <summary> /// Returns the 1st of May of the current year /// </summary> return new Date((new Date()).getFullYear(), 4, 1, 0, 0, 0, 0); } /** * Returns the 1st of June of the current year */ static june(): Date { /// <summary> /// Returns the 1st of June of the current year /// </summary> return new Date((new Date()).getFullYear(), 5, 1, 0, 0, 0, 0); } /** * Returns the 1st of July of the current year */ static july(): Date { /// <summary> /// Returns the 1st of July of the current year /// </summary> return new Date((new Date()).getFullYear(), 6, 1, 0, 0, 0, 0); } /** * Returns the 1st of August of the current year */ static august(): Date { /// <summary> /// Returns the 1st of August of the current year /// </summary> return new Date((new Date()).getFullYear(), 7, 1, 0, 0, 0, 0); } /** * Returns the 1st of September of the current year */ static september(): Date { /// <summary> /// Returns the 1st of September of the current year /// </summary> return new Date((new Date()).getFullYear(), 8, 1, 0, 0, 0, 0); } /** * Returns the 1st of October of the current year */ static october(): Date { /// <summary> /// Returns the 1st of October of the current year /// </summary> return new Date((new Date()).getFullYear(), 9, 1, 0, 0, 0, 0); } /** * Returns the 1st of November of the current year */ static november(): Date { /// <summary> /// Returns the 1st of November of the current year /// </summary> return new Date((new Date()).getFullYear(), 10, 1, 0, 0, 0, 0); } /** * Returns the 1st of December of the current year */ static december(): Date { /// <summary> /// Returns the 1st of December of the current year /// </summary> return new Date((new Date()).getFullYear(), 11, 1, 0, 0, 0, 0); } } }
the_stack
import {BaseFileSystem, FileSystem, BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system'; import {ApiError, ErrorCode} from '../core/api_error'; import {FileFlag} from '../core/file_flag'; import {buffer2ArrayBuffer, arrayBuffer2Buffer, emptyBuffer} from '../core/util'; import {File, BaseFile} from '../core/file'; import {default as Stats} from '../core/node_fs_stats'; import PreloadFile from '../generic/preload_file'; import global from '../core/global'; import fs from '../core/node_fs'; /** * @hidden */ declare const importScripts: Function; /** * @hidden */ interface IBrowserFSMessage { browserfsMessage: boolean; } /** * @hidden */ enum SpecialArgType { // Callback CB, // File descriptor FD, // API error API_ERROR, // Stats object STATS, // Initial probe for file system information. PROBE, // FileFlag object. FILEFLAG, // Buffer object. BUFFER, // Generic Error object. ERROR } /** * @hidden */ interface ISpecialArgument { type: SpecialArgType; } /** * @hidden */ interface IProbeResponse extends ISpecialArgument { isReadOnly: boolean; supportsLinks: boolean; supportsProps: boolean; } /** * @hidden */ interface ICallbackArgument extends ISpecialArgument { // The callback ID. id: number; } /** * Converts callback arguments into ICallbackArgument objects, and back * again. * @hidden */ class CallbackArgumentConverter { private _callbacks: { [id: number]: Function } = {}; private _nextId: number = 0; public toRemoteArg(cb: Function): ICallbackArgument { const id = this._nextId++; this._callbacks[id] = cb; return { type: SpecialArgType.CB, id: id }; } public toLocalArg(id: number): Function { const cb = this._callbacks[id]; delete this._callbacks[id]; return cb; } } /** * @hidden */ interface IFileDescriptorArgument extends ISpecialArgument { // The file descriptor's id on the remote side. id: number; // The entire file's data, as an array buffer. data: ArrayBuffer | SharedArrayBuffer; // The file's stat object, as an array buffer. stat: ArrayBuffer | SharedArrayBuffer; // The path to the file. path: string; // The flag of the open file descriptor. flag: string; } /** * @hidden */ class FileDescriptorArgumentConverter { private _fileDescriptors: { [id: number]: File } = {}; private _nextId: number = 0; public toRemoteArg(fd: File, p: string, flag: FileFlag, cb: BFSCallback<IFileDescriptorArgument>): void { const id = this._nextId++; let data: ArrayBuffer | SharedArrayBuffer; let stat: ArrayBuffer | SharedArrayBuffer; this._fileDescriptors[id] = fd; // Extract needed information asynchronously. fd.stat((err, stats) => { if (err) { cb(err); } else { stat = bufferToTransferrableObject(stats!.toBuffer()); // If it's a readable flag, we need to grab contents. if (flag.isReadable()) { fd.read(Buffer.alloc(stats!.size), 0, stats!.size, 0, (err?: ApiError | null, bytesRead?: number, buff?: Buffer) => { if (err) { cb(err); } else { data = bufferToTransferrableObject(buff!); cb(null, { type: SpecialArgType.FD, id: id, data: data, stat: stat, path: p, flag: flag.getFlagString() }); } }); } else { // File is not readable, which means writing to it will append or // truncate/replace existing contents. Return an empty arraybuffer. cb(null, { type: SpecialArgType.FD, id: id, data: new ArrayBuffer(0), stat: stat, path: p, flag: flag.getFlagString() }); } } }); } public applyFdAPIRequest(request: IAPIRequest, cb: BFSOneArgCallback): void { const fdArg = <IFileDescriptorArgument> request.args[0]; this._applyFdChanges(fdArg, (err, fd?) => { if (err) { cb(err); } else { // Apply method on now-changed file descriptor. (<any> fd)[request.method]((e?: ApiError) => { if (request.method === 'close') { delete this._fileDescriptors[fdArg.id]; } cb(e); }); } }); } private _applyFdChanges(remoteFd: IFileDescriptorArgument, cb: BFSCallback<File>): void { const fd = this._fileDescriptors[remoteFd.id], data = transferrableObjectToBuffer(remoteFd.data), remoteStats = Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat)); // Write data if the file is writable. const flag = FileFlag.getFileFlag(remoteFd.flag); if (flag.isWriteable()) { // Appendable: Write to end of file. // Writeable: Replace entire contents of file. fd.write(data, 0, data.length, flag.isAppendable() ? fd.getPos()! : 0, (e?: ApiError | null) => { function applyStatChanges() { // Check if mode changed. fd.stat((e, stats?) => { if (e) { cb(e); } else { if (stats!.mode !== remoteStats.mode) { fd.chmod(remoteStats.mode, (e: any) => { cb(e, fd); }); } else { cb(e, fd); } } }); } if (e) { cb(e); } else { // If writeable & not appendable, we need to ensure file contents are // identical to those from the remote FD. Thus, we truncate to the // length of the remote file. if (!flag.isAppendable()) { fd.truncate(data.length, () => { applyStatChanges(); }); } else { applyStatChanges(); } } }); } else { cb(null, fd); } } } /** * @hidden */ interface IAPIErrorArgument extends ISpecialArgument { // The error object, as an array buffer. errorData: ArrayBuffer | SharedArrayBuffer; } /** * @hidden */ function apiErrorLocal2Remote(e: ApiError): IAPIErrorArgument { return { type: SpecialArgType.API_ERROR, errorData: bufferToTransferrableObject(e.writeToBuffer()) }; } /** * @hidden */ function apiErrorRemote2Local(e: IAPIErrorArgument): ApiError { return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData)); } /** * @hidden */ interface IErrorArgument extends ISpecialArgument { // The name of the error (e.g. 'TypeError'). name: string; // The message associated with the error. message: string; // The stack associated with the error. stack: string; } /** * @hidden */ function errorLocal2Remote(e: Error): IErrorArgument { return { type: SpecialArgType.ERROR, name: e.name, message: e.message, stack: e.stack! }; } /** * @hidden */ function errorRemote2Local(e: IErrorArgument): Error { let cnstr: { new (msg: string): Error; } = global[e.name]; if (typeof(cnstr) !== 'function') { cnstr = Error; } const err = new cnstr(e.message); err.stack = e.stack; return err; } /** * @hidden */ interface IStatsArgument extends ISpecialArgument { // The stats object as an array buffer. statsData: ArrayBuffer | SharedArrayBuffer; } /** * @hidden */ function statsLocal2Remote(stats: Stats): IStatsArgument { return { type: SpecialArgType.STATS, statsData: bufferToTransferrableObject(stats.toBuffer()) }; } /** * @hidden */ function statsRemote2Local(stats: IStatsArgument): Stats { return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData)); } /** * @hidden */ interface IFileFlagArgument extends ISpecialArgument { flagStr: string; } /** * @hidden */ function fileFlagLocal2Remote(flag: FileFlag): IFileFlagArgument { return { type: SpecialArgType.FILEFLAG, flagStr: flag.getFlagString() }; } /** * @hidden */ function fileFlagRemote2Local(remoteFlag: IFileFlagArgument): FileFlag { return FileFlag.getFileFlag(remoteFlag.flagStr); } /** * @hidden */ interface IBufferArgument extends ISpecialArgument { data: ArrayBuffer | SharedArrayBuffer; } /** * @hidden */ function bufferToTransferrableObject(buff: Buffer): ArrayBuffer | SharedArrayBuffer { return buffer2ArrayBuffer(buff); } /** * @hidden */ function transferrableObjectToBuffer(buff: ArrayBuffer | SharedArrayBuffer): Buffer { return arrayBuffer2Buffer(buff); } /** * @hidden */ function bufferLocal2Remote(buff: Buffer): IBufferArgument { return { type: SpecialArgType.BUFFER, data: bufferToTransferrableObject(buff) }; } /** * @hidden */ function bufferRemote2Local(buffArg: IBufferArgument): Buffer { return transferrableObjectToBuffer(buffArg.data); } /** * @hidden */ interface IAPIRequest extends IBrowserFSMessage { method: string; args: Array<number | string | ISpecialArgument>; } /** * @hidden */ function isAPIRequest(data: any): data is IAPIRequest { return data && typeof data === 'object' && data.hasOwnProperty('browserfsMessage') && data['browserfsMessage']; } /** * @hidden */ interface IAPIResponse extends IBrowserFSMessage { cbId: number; args: Array<number | string | ISpecialArgument>; } /** * @hidden */ function isAPIResponse(data: any): data is IAPIResponse { return data && typeof data === 'object' && data.hasOwnProperty('browserfsMessage') && data['browserfsMessage']; } /** * Represents a remote file in a different worker/thread. */ class WorkerFile extends PreloadFile<WorkerFS> { private _remoteFdId: number; constructor(_fs: WorkerFS, _path: string, _flag: FileFlag, _stat: Stats, remoteFdId: number, contents?: Buffer) { super(_fs, _path, _flag, _stat, contents); this._remoteFdId = remoteFdId; } public getRemoteFdId() { return this._remoteFdId; } /** * @hidden */ public toRemoteArg(): IFileDescriptorArgument { return { type: SpecialArgType.FD, id: this._remoteFdId, data: bufferToTransferrableObject(this.getBuffer()), stat: bufferToTransferrableObject(this.getStats().toBuffer()), path: this.getPath(), flag: this.getFlag().getFlagString() }; } public sync(cb: BFSOneArgCallback): void { this._syncClose('sync', cb); } public close(cb: BFSOneArgCallback): void { this._syncClose('close', cb); } private _syncClose(type: string, cb: BFSOneArgCallback): void { if (this.isDirty()) { (<WorkerFS> this._fs).syncClose(type, this, (e?: ApiError) => { if (!e) { this.resetDirty(); } cb(e); }); } else { cb(); } } } export interface WorkerFSOptions { // The target worker that you want to connect to, or the current worker if in a worker context. worker: Worker; } /** * WorkerFS lets you access a BrowserFS instance that is running in a different * JavaScript context (e.g. access BrowserFS in one of your WebWorkers, or * access BrowserFS running on the main page from a WebWorker). * * For example, to have a WebWorker access files in the main browser thread, * do the following: * * MAIN BROWSER THREAD: * * ```javascript * // Listen for remote file system requests. * BrowserFS.FileSystem.WorkerFS.attachRemoteListener(webWorkerObject); * ``` * * WEBWORKER THREAD: * * ```javascript * // Set the remote file system as the root file system. * BrowserFS.configure({ fs: "WorkerFS", options: { worker: self }}, function(e) { * // Ready! * }); * ``` * * Note that synchronous operations are not permitted on the WorkerFS, regardless * of the configuration option of the remote FS. */ export default class WorkerFS extends BaseFileSystem implements FileSystem { public static readonly Name = "WorkerFS"; public static readonly Options: FileSystemOptions = { worker: { type: "object", description: "The target worker that you want to connect to, or the current worker if in a worker context.", validator: function(v: object, cb: BFSOneArgCallback): void { // Check for a `postMessage` function. if ((<any> v)['postMessage']) { cb(); } else { cb(new ApiError(ErrorCode.EINVAL, `option must be a Web Worker instance.`)); } } } }; public static Create(opts: WorkerFSOptions, cb: BFSCallback<WorkerFS>): void { const fs = new WorkerFS(opts.worker); fs._initialize(() => { cb(null, fs); }); } public static isAvailable(): boolean { return typeof(importScripts) !== 'undefined' || typeof(Worker) !== 'undefined'; } /** * Attaches a listener to the remote worker for file system requests. */ public static attachRemoteListener(worker: Worker) { const fdConverter = new FileDescriptorArgumentConverter(); function argLocal2Remote(arg: any, requestArgs: any[], cb: BFSCallback<any>): void { switch (typeof arg) { case 'object': if (arg instanceof Stats) { cb(null, statsLocal2Remote(arg)); } else if (arg instanceof ApiError) { cb(null, apiErrorLocal2Remote(arg)); } else if (arg instanceof BaseFile) { // Pass in p and flags from original request. cb(null, fdConverter.toRemoteArg(<File> arg, requestArgs[0], requestArgs[1], cb)); } else if (arg instanceof FileFlag) { cb(null, fileFlagLocal2Remote(arg)); } else if (arg instanceof Buffer) { cb(null, bufferLocal2Remote(arg)); } else if (arg instanceof Error) { cb(null, errorLocal2Remote(arg)); } else { cb(null, arg); } break; default: cb(null, arg); break; } } function argRemote2Local(arg: any, fixedRequestArgs: any[]): any { if (!arg) { return arg; } switch (typeof arg) { case 'object': if (typeof arg['type'] === 'number') { const specialArg = <ISpecialArgument> arg; switch (specialArg.type) { case SpecialArgType.CB: const cbId = (<ICallbackArgument> arg).id; return function() { let i: number; const fixedArgs = new Array(arguments.length); let message: IAPIResponse, countdown = arguments.length; function abortAndSendError(err: ApiError) { if (countdown > 0) { countdown = -1; message = { browserfsMessage: true, cbId: cbId, args: [apiErrorLocal2Remote(err)] }; worker.postMessage(message); } } for (i = 0; i < arguments.length; i++) { // Capture i and argument. ((i: number, arg: any) => { argLocal2Remote(arg, fixedRequestArgs, (err, fixedArg?) => { fixedArgs[i] = fixedArg; if (err) { abortAndSendError(err); } else if (--countdown === 0) { message = { browserfsMessage: true, cbId: cbId, args: fixedArgs }; worker.postMessage(message); } }); })(i, arguments[i]); } if (arguments.length === 0) { message = { browserfsMessage: true, cbId: cbId, args: fixedArgs }; worker.postMessage(message); } }; case SpecialArgType.API_ERROR: return apiErrorRemote2Local(<IAPIErrorArgument> specialArg); case SpecialArgType.STATS: return statsRemote2Local(<IStatsArgument> specialArg); case SpecialArgType.FILEFLAG: return fileFlagRemote2Local(<IFileFlagArgument> specialArg); case SpecialArgType.BUFFER: return bufferRemote2Local(<IBufferArgument> specialArg); case SpecialArgType.ERROR: return errorRemote2Local(<IErrorArgument> specialArg); default: // No idea what this is. return arg; } } else { return arg; } default: return arg; } } worker.addEventListener('message', (e: MessageEvent) => { const request: object = e.data; if (isAPIRequest(request)) { const args = request.args, fixedArgs = new Array<any>(args.length); switch (request.method) { case 'close': case 'sync': (() => { // File descriptor-relative methods. const remoteCb = <ICallbackArgument> args[1]; fdConverter.applyFdAPIRequest(request, (err?: ApiError) => { // Send response. const response: IAPIResponse = { browserfsMessage: true, cbId: remoteCb.id, args: err ? [apiErrorLocal2Remote(err)] : [] }; worker.postMessage(response); }); })(); break; case 'probe': (() => { const rootFs = <FileSystem> fs.getRootFS(), remoteCb = <ICallbackArgument> args[1], probeResponse: IProbeResponse = { type: SpecialArgType.PROBE, isReadOnly: rootFs.isReadOnly(), supportsLinks: rootFs.supportsLinks(), supportsProps: rootFs.supportsProps() }, response: IAPIResponse = { browserfsMessage: true, cbId: remoteCb.id, args: [probeResponse] }; worker.postMessage(response); })(); break; default: // File system methods. for (let i = 0; i < args.length; i++) { fixedArgs[i] = argRemote2Local(args[i], fixedArgs); } const rootFS = fs.getRootFS(); (<Function> (<any> rootFS)[request.method]).apply(rootFS, fixedArgs); break; } } }); } private _worker: Worker; private _callbackConverter = new CallbackArgumentConverter(); private _isInitialized: boolean = false; private _isReadOnly: boolean = false; private _supportLinks: boolean = false; private _supportProps: boolean = false; /** * Constructs a new WorkerFS instance that connects with BrowserFS running on * the specified worker. */ private constructor(worker: Worker) { super(); this._worker = worker; this._worker.addEventListener('message', (e: MessageEvent) => { const resp: object = e.data; if (isAPIResponse(resp)) { let i: number; const args = resp.args; const fixedArgs = new Array(args.length); // Dispatch event to correct id. for (i = 0; i < fixedArgs.length; i++) { fixedArgs[i] = this._argRemote2Local(args[i]); } this._callbackConverter.toLocalArg(resp.cbId).apply(null, fixedArgs); } }); } public getName(): string { return WorkerFS.Name; } public isReadOnly(): boolean { return this._isReadOnly; } public supportsSynch(): boolean { return false; } public supportsLinks(): boolean { return this._supportLinks; } public supportsProps(): boolean { return this._supportProps; } public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void { this._rpc('rename', arguments); } public stat(p: string, isLstat: boolean, cb: BFSCallback<Stats>): void { this._rpc('stat', arguments); } public open(p: string, flag: FileFlag, mode: number, cb: BFSCallback<File>): void { this._rpc('open', arguments); } public unlink(p: string, cb: Function): void { this._rpc('unlink', arguments); } public rmdir(p: string, cb: Function): void { this._rpc('rmdir', arguments); } public mkdir(p: string, mode: number, cb: Function): void { this._rpc('mkdir', arguments); } public readdir(p: string, cb: BFSCallback<string[]>): void { this._rpc('readdir', arguments); } public exists(p: string, cb: (exists: boolean) => void): void { this._rpc('exists', arguments); } public realpath(p: string, cache: { [path: string]: string }, cb: BFSCallback<string>): void { this._rpc('realpath', arguments); } public truncate(p: string, len: number, cb: Function): void { this._rpc('truncate', arguments); } public readFile(fname: string, encoding: string, flag: FileFlag, cb: BFSCallback<any>): void { this._rpc('readFile', arguments); } public writeFile(fname: string, data: any, encoding: string, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void { this._rpc('writeFile', arguments); } public appendFile(fname: string, data: any, encoding: string, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void { this._rpc('appendFile', arguments); } public chmod(p: string, isLchmod: boolean, mode: number, cb: Function): void { this._rpc('chmod', arguments); } public chown(p: string, isLchown: boolean, uid: number, gid: number, cb: Function): void { this._rpc('chown', arguments); } public utimes(p: string, atime: Date, mtime: Date, cb: Function): void { this._rpc('utimes', arguments); } public link(srcpath: string, dstpath: string, cb: Function): void { this._rpc('link', arguments); } public symlink(srcpath: string, dstpath: string, type: string, cb: Function): void { this._rpc('symlink', arguments); } public readlink(p: string, cb: Function): void { this._rpc('readlink', arguments); } public syncClose(method: string, fd: File, cb: BFSOneArgCallback): void { this._worker.postMessage({ browserfsMessage: true, method: method, args: [(<WorkerFile> fd).toRemoteArg(), this._callbackConverter.toRemoteArg(cb)] }); } /** * Called once both local and remote sides are set up. */ private _initialize(cb: () => void): void { if (!this._isInitialized) { const message: IAPIRequest = { browserfsMessage: true, method: 'probe', args: [this._argLocal2Remote(emptyBuffer()), this._callbackConverter.toRemoteArg((probeResponse: IProbeResponse) => { this._isInitialized = true; this._isReadOnly = probeResponse.isReadOnly; this._supportLinks = probeResponse.supportsLinks; this._supportProps = probeResponse.supportsProps; cb(); })] }; this._worker.postMessage(message); } else { cb(); } } private _argRemote2Local(arg: any): any { if (!arg) { return arg; } switch (typeof arg) { case 'object': if (typeof arg['type'] === 'number') { const specialArg = <ISpecialArgument> arg; switch (specialArg.type) { case SpecialArgType.API_ERROR: return apiErrorRemote2Local(<IAPIErrorArgument> specialArg); case SpecialArgType.FD: const fdArg = <IFileDescriptorArgument> specialArg; return new WorkerFile(this, fdArg.path, FileFlag.getFileFlag(fdArg.flag), Stats.fromBuffer(transferrableObjectToBuffer(fdArg.stat)), fdArg.id, transferrableObjectToBuffer(fdArg.data)); case SpecialArgType.STATS: return statsRemote2Local(<IStatsArgument> specialArg); case SpecialArgType.FILEFLAG: return fileFlagRemote2Local(<IFileFlagArgument> specialArg); case SpecialArgType.BUFFER: return bufferRemote2Local(<IBufferArgument> specialArg); case SpecialArgType.ERROR: return errorRemote2Local(<IErrorArgument> specialArg); default: return arg; } } else { return arg; } default: return arg; } } private _rpc(methodName: string, args: IArguments) { const fixedArgs = new Array(args.length); for (let i = 0; i < args.length; i++) { fixedArgs[i] = this._argLocal2Remote(args[i]); } const message: IAPIRequest = { browserfsMessage: true, method: methodName, args: fixedArgs }; this._worker.postMessage(message); } /** * Converts a local argument into a remote argument. Public so WorkerFile objects can call it. */ private _argLocal2Remote(arg: any): any { if (!arg) { return arg; } switch (typeof arg) { case "object": if (arg instanceof Stats) { return statsLocal2Remote(arg); } else if (arg instanceof ApiError) { return apiErrorLocal2Remote(arg); } else if (arg instanceof WorkerFile) { return (<WorkerFile> arg).toRemoteArg(); } else if (arg instanceof FileFlag) { return fileFlagLocal2Remote(arg); } else if (arg instanceof Buffer) { return bufferLocal2Remote(arg); } else if (arg instanceof Error) { return errorLocal2Remote(arg); } else { return "Unknown argument"; } case "function": return this._callbackConverter.toRemoteArg(arg); default: return arg; } } }
the_stack
import BinomialNode from './binomial-node' import * as utils from '../../utils' /******************************************************************************* * A binomial heap is a forest of binomial trees. * * A binomial tree of degree 0 is a single node. * A binomial tree of degree k has a root node with k children. The degrees of those * children are k-1, k-2,..., 2, 1, 0. * * A binomial tree of degree k has 2^k nodes. * * A binomial heap is a forest of binomial trees that satisfy the heap invariant. * There can be only 0 or 1 binomial tree of degree k in the forest. * * The two key features of binomial heaps are: * * 1. The roots of the forest are <= log(n) * 2. Merging two heaps is binary addition * * This brings merge() from O(n + m) to O(logn + logm)!!! * * But because we now have a forest instead of one single tree, findMin() now * takes O(logn) to traverse the entire forest :( Check out the lazy binomial heap * to see how we can bring this back down to O(1) * * enqueue() - O(1) ~~ down from O(logn) due to being lazy * extractMin() - O(logn) ~~ ammortized * findMin() - O(1) * merge() - O(1) ~~ down from O(logn + logm) due to being lazy * decreaseKey() - O(logn) * * More info can be found here: https://en.wikipedia.org/wiki/Binomial_heap * The Implementation belowbased off Binomial Heap pseudocode from CLRS ed 2 (Chapter 19) ******************************************************************************/ class LazyMinBinomialHeap<T> { head: BinomialNode<T> | null size: number minRoot: BinomialNode<T> | null // smallestValue for deleteNode(node) // deleteNode will decrease the node to the smallest value so it swims up to // the root, and then calls dequeue() private smallestValue: T // comparison function if the generic type T is non-primitive private compare: utils.CompareFunction<T> constructor(smallestValue: T, compareFunction?: utils.CompareFunction<T>) { this.head = null this.minRoot = null this.size = 0 this.smallestValue = smallestValue this.compare = compareFunction || utils.defaultCompare } /***************************************************************************** INSPECTION *****************************************************************************/ /** * Returns true if the heap is empty, false otherwise - O(1) * @returns {boolean} */ isEmpty(): boolean { return this.size === 0 } /***************************************************************************** INSERTION/DELETION *****************************************************************************/ /** * Enqueues element onto the heap - O(1) * @param {T} element * @returns {void} */ enqueue(element: T): BinomialNode<T> { const newRoot = new BinomialNode(element) // lazily enqueue the element to the forest if (this.head) newRoot.sibling = this.head this.head = newRoot this.size += 1 // set minRoot pointer if (!this.minRoot) this.minRoot = this.head if (this.compare(this.head.value, this.minRoot.value) < 0) this.minRoot = this.head return this.head } /** * Dequeues the smallest element from the heap // O(logn) * @param {T} element * @returns {void} */ dequeue(): BinomialNode<T> | null { // remove smallest root of smallest tree B_k from heap const smallestRoot = this.removeSmallestRoot() // O(logn) this.size -= 1 if (!smallestRoot) return smallestRoot // if the root has children, add it to the forest if (smallestRoot.child) { // delete all parent pointers in children let child: BinomialNode<T> | null = smallestRoot.child let lastChild: BinomialNode<T> | null = null while (child) { lastChild = child child.parent = null child = child.sibling } if (this.head) { lastChild!.sibling = this.head } this.head = smallestRoot.child } this.head = this.consolidate() // if we removed the smallest root, recalculate the minRoot pointer if (this.minRoot === smallestRoot) this.recalculateMin() // return the removed root return smallestRoot } /** * Deletes the given node - O(logn) * @param {BinomialNode<T>} node * @returns {void} */ deleteNode(node: BinomialNode<T>): BinomialNode<T> | null { // make it the smallest node in the heap so it swims up this.decreaseKey(node, this.smallestValue) // O(logn) // dequeue the smallest node from the heap return this.dequeue() // O(logn) } // O(logn) private removeSmallestRoot(): BinomialNode<T> | null { if (!this.head) return null let cur: BinomialNode<T> | null = this.head let prev = cur let min = cur let prevMin = null cur = cur.sibling // O(logn) since we traverse entire forest while (cur) { const currentIsLessThanMin = this.compare(cur.value, min.value) < 0 if (currentIsLessThanMin) { min = cur prevMin = prev } prev = cur cur = cur.sibling } // if smallest root is head, then move heap.head pointer one root forwards if (prev === null || prevMin === null) { this.head = this.head.sibling } else { // otherwise link prev root with min's right root prevMin.sibling = min.sibling } return min } // O(logn) private recalculateMin(): void { if (!this.head) return let cur = this.head.sibling let min = this.head while (cur) { if (cur.value < min.value) min = cur cur = cur.sibling } this.minRoot = min } /***************************************************************************** READING *****************************************************************************/ /** * Returns the smallest node in the heap, null if the heap is empty O(1) * @returns {BinomialNode<T> | null} */ peek(): BinomialNode<T> | null { if (!this.head) return null return this.minRoot } /***************************************************************************** UPDATING *****************************************************************************/ /** * Unions supplied heap with current heap - O(1). Current implementation * is destructive. * @param {BinomialHeap<T>} otherHeap * @returns {BinomialHeap<T>} */ union(otherHeap: LazyMinBinomialHeap<T>): LazyMinBinomialHeap<T> { const unionedHeap = new LazyMinBinomialHeap<T>(this.smallestValue) unionedHeap.head = this.head let cur = unionedHeap.head while (cur && cur.sibling) { cur = cur.sibling } cur!.sibling = otherHeap.head unionedHeap.size = this.size + otherHeap.size return unionedHeap } /** * Consolidates the current state of the heap such that only one tree exists * for degree k - O(t + logn) * @returns {LazyMinBinomialHeap<T>} */ private consolidate(): BinomialNode<T> | null { // 1. sort the trees according to degree with bucket sort O(t + logn) const sortedTrees = this.sortForest() // O(t + logn) // 2. link trees until at most one tree remains for a specific degree k - O(t) for (let k = 0; k < sortedTrees.length; k++) { const degreeKTrees = sortedTrees[k] if (!degreeKTrees) continue let numberOfDegreeKTrees = degreeKTrees.length while (numberOfDegreeKTrees >= 2) { const treeA = degreeKTrees.pop()! const treeB = degreeKTrees.pop()! const linkedTree = treeA.value < treeB.value ? this.linkTrees(treeA, treeB) : this.linkTrees(treeB, treeA) sortedTrees[k + 1].push(linkedTree) numberOfDegreeKTrees -= 2 } } let cur = null let head = null for (let i = sortedTrees.length - 1; i >= 0; i--) { const trees = sortedTrees[i] if (trees.length === 0) continue const tree = trees[0] if (!cur) { cur = tree head = cur } else { cur.sibling = tree cur = cur.sibling } } return head } // Links two trees with degree k-1, B_(k-1), and makes one tree with degree // k, B_k, where nodeA becomes the root of the new tree. // It does this by making treeB the new head of treeA's children in O(1) private linkTrees(treeA: BinomialNode<T>, treeB: BinomialNode<T>): BinomialNode<T> { treeB.parent = treeA treeB.sibling = treeA.child treeA.child = treeB treeA.degree += 1 treeA.sibling = null return treeA } // Sorts the list of trees (forest) in O(t + logn) time using bucket sort. // Bucket sort is used because we have a cap on the degrees of our tree - logt. // Using a traditional sorting algorithm would take O(tlogt). private sortForest(): Array<Array<BinomialNode<T>>> { // Initialize an array of size logn - O(logn) const sortedTrees = new Array<Array<BinomialNode<T>>>(Math.ceil(Math.log2(this.size + 1))) // intialize buckets in sortedTrees for (let i = 0; i < sortedTrees.length; i++) { sortedTrees[i] = [] } let cur = this.head // distribute the trees into buckets - O(t) while (cur) { const nextCur = cur.sibling cur.sibling = null const index = cur.degree sortedTrees[index].push(cur) cur = nextCur } return sortedTrees } /** * Decreases the value of the given node to the new value. Returns true if * successful, and false otherwise - O(logn) * @param {BinomialNode<T>} node * @param {T} newValue * @returns {boolean} */ decreaseKey(node: BinomialNode<T>, newValue: T): boolean { // if newKey >= key, don't update if (this.compare(node.value, newValue) < 0) return false node.value = newValue let cur = node let parent = cur.parent // swim in O(logn) while (parent && cur.value < parent.value) { const temp = parent.value parent.value = cur.value cur.value = temp cur = parent parent = cur.parent } return true } } export default LazyMinBinomialHeap
the_stack
import type { Context, Request, Response } from "../deps.ts"; import type { DI } from "../main-core/dependency-injection/di.ns.ts"; import type { MandarineSessionContainer } from "../main-core/mandarine-native/sessions/mandarineSessionContainer.ts"; import type { Mandarine } from "../mod.ts"; import type { Cookie as MandarineCookie } from "./core/interfaces/http/cookie.ts"; import { MandarineMVCContext } from "./core/mandarineMvcContext.ts"; import { RenderEngineClass } from "./core/modules/view-engine/renderEngine.ts"; import type { NonComponentMiddlewareTarget } from "../main-core/internals/interfaces/middlewareTarget.ts"; import type { GuardTarget } from "../main-core/internals/interfaces/guardTarget.ts"; import { MandarineMVCCache } from "./core/internal/mvcCacheManager.ts"; /** * This namespace contains all the essentials for Mandarine MVC to work */ export namespace MandarineMvc { export const MVC_ABORT_CONTROLLER = new AbortController(); /** * Hypertext Transfer Protocol (HTTP) response status codes. * @see {@link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes} */ export enum HttpStatusCode { /** * The server has received the request headers and the client should proceed to send the request body * (in the case of a request for which a body needs to be sent; for example, a POST request). * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient. * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates the request should not be continued. */ CONTINUE = 100, /** * The requester has asked the server to switch protocols and the server has agreed to do so. */ SWITCHING_PROTOCOLS = 101, /** * A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. * This code indicates that the server has received and is processing the request, but no response is available yet. * This prevents the client from timing out and assuming the request was lost. */ PROCESSING = 102, /** * Standard response for successful HTTP requests. * The actual response will depend on the request method used. * In a GET request, the response will contain an entity corresponding to the requested resource. * In a POST request, the response will contain an entity describing or containing the result of the action. */ OK = 200, /** * The request has been fulfilled, resulting in the creation of a new resource. */ CREATED = 201, /** * The request has been accepted for processing, but the processing has not been completed. * The request might or might not be eventually acted upon, and may be disallowed when processing occurs. */ ACCEPTED = 202, /** * SINCE HTTP/1.1 * The server is a transforming proxy that received a 200 OK from its origin, * but is returning a modified version of the origin's response. */ NON_AUTHORITATIVE_INFORMATION = 203, /** * The server successfully processed the request and is not returning any content. */ NO_CONTENT = 204, /** * The server successfully processed the request, but is not returning any content. * Unlike a 204 response, this response requires that the requester reset the document view. */ RESET_CONTENT = 205, /** * The server is delivering only part of the resource (byte serving) due to a range header sent by the client. * The range header is used by HTTP clients to enable resuming of interrupted downloads, * or split a download into multiple simultaneous streams. */ PARTIAL_CONTENT = 206, /** * The message body that follows is an XML message and can contain a number of separate response codes, * depending on how many sub-requests were made. */ MULTI_STATUS = 207, /** * The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response, * and are not being included again. */ ALREADY_REPORTED = 208, /** * The server has fulfilled a request for the resource, * and the response is a representation of the result of one or more instance-manipulations applied to the current instance. */ IM_USED = 226, /** * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation). * For example, this code could be used to present multiple video format options, * to list files with different filename extensions, or to suggest word-sense disambiguation. */ MULTIPLE_CHOICES = 300, /** * This and all future requests should be directed to the given URI. */ MOVED_PERMANENTLY = 301, /** * This is an example of industry practice contradicting the standard. * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 * to distinguish between the two behaviours. However, some Web applications and frameworks * use the 302 status code as if it were the 303. */ FOUND = 302, /** * SINCE HTTP/1.1 * The response to the request can be found under another URI using a GET method. * When received in response to a POST (or PUT/DELETE), the client should presume that * the server has received the data and should issue a redirect with a separate GET message. */ SEE_OTHER = 303, /** * Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match. * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy. */ NOT_MODIFIED = 304, /** * SINCE HTTP/1.1 * The requested resource is available only through a proxy, the address for which is provided in the response. * Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons. */ USE_PROXY = 305, /** * No longer used. Originally meant "Subsequent requests should use the specified proxy." */ SWITCH_PROXY = 306, /** * SINCE HTTP/1.1 * In this case, the request should be repeated with another URI; however, future requests should still use the original URI. * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request. * For example, a POST request should be repeated using another POST request. */ TEMPORARY_REDIRECT = 307, /** * The request and all future requests should be repeated using another URI. * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change. * So, for example, submitting a form to a permanently redirected resource may continue smoothly. */ PERMANENT_REDIRECT = 308, /** * The server cannot or will not process the request due to an apparent client error * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing). */ BAD_REQUEST = 400, /** * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet * been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means * "unauthenticated",i.e. the user does not have the necessary credentials. */ UNAUTHORIZED = 401, /** * Reserved for future use. The original intention was that this code might be used as part of some form of digital * cash or micro payment scheme, but that has not happened, and this code is not usually used. * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests. */ PAYMENT_REQUIRED = 402, /** * The request was valid, but the server is refusing action. * The user might not have the necessary permissions for a resource. */ FORBIDDEN = 403, /** * The requested resource could not be found but may be available in the future. * Subsequent requests by the client are permissible. */ NOT_FOUND = 404, /** * A request method is not supported for the requested resource; * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource. */ METHOD_NOT_ALLOWED = 405, /** * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request. */ NOT_ACCEPTABLE = 406, /** * The client must first authenticate itself with the proxy. */ PROXY_AUTHENTICATION_REQUIRED = 407, /** * The server timed out waiting for the request. * According to HTTP specifications: * "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time." */ REQUEST_TIMEOUT = 408, /** * Indicates that the request could not be processed because of conflict in the request, * such as an edit conflict between multiple simultaneous updates. */ CONFLICT = 409, /** * Indicates that the resource requested is no longer available and will not be available again. * This should be used when a resource has been intentionally removed and the resource should be purged. * Upon receiving a 410 status code, the client should not request the resource in the future. * Clients such as search engines should remove the resource from their indices. * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead. */ GONE = 410, /** * The request did not specify the length of its content, which is required by the requested resource. */ LENGTH_REQUIRED = 411, /** * The server does not meet one of the preconditions that the requester put on the request. */ PRECONDITION_FAILED = 412, /** * The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large". */ PAYLOAD_TOO_LARGE = 413, /** * The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request, * in which case it should be converted to a POST request. * Called "Request-URI Too Long" previously. */ URI_TOO_LONG = 414, /** * The request entity has a media type which the server or resource does not support. * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format. */ UNSUPPORTED_MEDIA_TYPE = 415, /** * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion. * For example, if the client asked for a part of the file that lies beyond the end of the file. * Called "Requested Range Not Satisfiable" previously. */ RANGE_NOT_SATISFIABLE = 416, /** * The server cannot meet the requirements of the Expect request-header field. */ EXPECTATION_FAILED = 417, /** * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com. */ I_AM_A_TEAPOT = 418, /** * The request was directed at a server that is not able to produce a response (for example because a connection reuse). */ MISDIRECTED_REQUEST = 421, /** * The request was well-formed but was unable to be followed due to semantic errors. */ UNPROCESSABLE_ENTITY = 422, /** * The resource that is being accessed is locked. */ LOCKED = 423, /** * The request failed due to failure of a previous request (e.g., a PROPPATCH). */ FAILED_DEPENDENCY = 424, /** * The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field. */ UPGRADE_REQUIRED = 426, /** * The origin server requires the request to be conditional. * Intended to prevent "the 'lost update' problem, where a client * GETs a resource's state, modifies it, and PUTs it back to the server, * when meanwhile a third party has modified the state on the server, leading to a conflict." */ PRECONDITION_REQUIRED = 428, /** * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes. */ TOO_MANY_REQUESTS = 429, /** * The server is unwilling to process the request because either an individual header field, * or all the header fields collectively, are too large. */ REQUEST_HEADER_FIELDS_TOO_LARGE = 431, /** * A server operator has received a legal demand to deny access to a resource or to a set of resources * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451. */ UNAVAILABLE_FOR_LEGAL_REASONS = 451, /** * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. */ INTERNAL_SERVER_ERROR = 500, /** * The server either does not recognize the request method, or it lacks the ability to fulfill the request. * Usually this implies future availability (e.g., a new feature of a web-service API). */ NOT_IMPLEMENTED = 501, /** * The server was acting as a gateway or proxy and received an invalid response from the upstream server. */ BAD_GATEWAY = 502, /** * The server is currently unavailable (because it is overloaded or down for maintenance). * Generally, this is a temporary state. */ SERVICE_UNAVAILABLE = 503, /** * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. */ GATEWAY_TIMEOUT = 504, /** * The server does not support the HTTP protocol version used in the request */ HTTP_VERSION_NOT_SUPPORTED = 505, /** * Transparent content negotiation for the request results in a circular reference. */ VARIANT_ALSO_NEGOTIATES = 506, /** * The server is unable to store the representation needed to complete the request. */ INSUFFICIENT_STORAGE = 507, /** * The server detected an infinite loop while processing the request. */ LOOP_DETECTED = 508, /** * Further extensions to the request are required for the server to fulfill it. */ NOT_EXTENDED = 510, /** * The client needs to authenticate to gain network access. * Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used * to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot). */ NETWORK_AUTHENTICATION_REQUIRED = 511 } /** * Contains all the Media Types possible in the internet */ export enum MediaTypes { APPLICATION_JAVA_ARCHIVE = "application/java-archive", APPLICATION_MSWORD = "application/msword", APPLICATION_EDI_X12 = "application/EDI-X12", APPLICATION_EDIFACT = "application/EDIFACT", APPLICATION_JAVASCRIPT = "application/javascript", APPLICATION_OCTET_STREAM = "application/octet-stream", APPLICATION_OGG = "application/ogg", APPLICATION_PDF = "application/pdf", APPLICATION_XHTML_XML = "application/xhtml+xml", APPLICATION_X_SHOCKWAVE_FLASH = "application/x-shockwave-flash", APPLICATION_JSON = "application/json", APPLICATION_LD_JSON = "application/ld+json", APPLICATION_XML = "application/xml", APPLICATION_ZIP = "application/zip", APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded", AUDIO_MPEG = "audio/mpeg", AUDIO_X_MS_WMA = "audio/x-ms-wma", AUDIO_VND_RN_REALAUDIO = "audio/vnd.rn-realaudio", AUDIO_X_WAV = "audio/x-wav", IMAGE_GIF = "image/gif", IMAGE_JPEG = "image/jpeg", IMAGE_PNG = "image/png", IMAGE_TIFF = "image/tiff", IMAGE_VND_MICROSOFT_ICON = "image/vnd.microsoft.icon", IMAGE_X_ICON = "image/x-icon", IMAGE_VND_DJVU = "image/vnd.djvu", IMAGE_SVG_XML = "image/svg+xml", MULTIPART_MIXED = "multipart/mixed", MULTIPART_ALTERNATIVE = "multipart/alternative", MULTIPART_RELATED = "multipart/related", MULTIPART_FORM_DATA = "multipart/form-data", TEXT_CSS = "text/css", TEXT_CSV = "text/csv", TEXT_HTML = "text/html", TEXT_PLAIN = "text/plain", TEXT_XML = "text/xml", VIDEO_MPEG = "video/mpeg", VIDEO_MP4 = "video/mp4", VIDEO_QUICKTIME = "video/quicktime", VIDEO_X_MS_WMV = "video/x-ms-wmv", VIDEO_X_MSVIDEO = "video/x-msvideo", VIDEO_X_FLV = "video/x-flv", VIDEO_WEBM = "video/webm", VND_ANDROID_PACKAGE_ARCHIVE = "application/vnd.android.package-archive", VND_OASIS_OPENDOCUMENT_TEXT = "application/vnd.oasis.opendocument.text", VND_OASIS_OPENDOCUMENT_SPREADSHEET = "application/vnd.oasis.opendocument.spreadsheet", VND_OASIS_OPENDOCUMENT_PRESENTATION = "application/vnd.oasis.opendocument.presentation", VND_OASIS_OPENDOCUMENT_GRAPHICS = "application/vnd.oasis.opendocument.graphics", VND_MSEXCEL = "application/vnd.ms-excel", VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", VND_MS_POWERPOINT = "application/vnd.ms-powerpoint", VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = "application/vnd.openxmlformats-officedocument.presentationml.presentation", VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", VND_MOZILLA_XUL_XML = "application/vnd.mozilla.xul+xml" } /** * Contains all the HTTP Methods available. */ export enum HttpMethods { GET, POST, PUT, HEAD, DELETE, PATCH, OPTIONS } /** * Refers to all the information the Routing handlers need to work out. */ export namespace Routing { /** * Refers to the status of a route at compile-time. */ export enum RouteInitializationStatus { PRECREATED, CREATED } /** * Refers to the possible configurations a route can have. */ export interface RoutingOptions { responseStatus?: HttpStatusCode, cors?: CorsMiddlewareOption, withPermissions?: Mandarine.Security.Auth.Permissions, middleware?: Array<NonComponentMiddlewareTarget | Mandarine.Types.MiddlewareComponent>; guards?: Array<Function | GuardTarget> [key: string]: any }; /** * Refers to the information of a param in a route. * /:name <----- for example */ export interface RoutingParams { relation?: { controller: string; methodName?: string; }; routeName?: string; routeIndex?: number; } /** * Contains the information the Mandarine MVC engine will need in order to read & execute an endpoint. * When an endpoint is requested, the routing action indicates how the Mandarine MVC engine should behave. */ export interface RoutingAction { actionParent?: string; actionType: HttpMethods, actionMethodName: string; route: string; routingOptions?: RoutingOptions; routeParams?: RoutingParams[]; routeSignature: Array<string>; initializationStatus: RouteInitializationStatus; } /** * Contains the metadata information of a route. Like its controller and the method that should be executed. * @GET, @POST, @PUT, and the others contain this information at compile-time */ export interface RoutingAnnotationContext { route: string; methodType: HttpMethods; methodName: string; options: RoutingOptions; className?: string; } } /** * Refers to all the internal functioning (in MVC) that is used by Mandarine's core. */ export namespace Internal { export enum MiddlewareType { CORS, RESPONSE_TIME, SESSION_COOKIE, SESSION_STORE } export type InternalMiddlewareFunc = (context: Mandarine.Types.RequestContext, data?: any) => boolean; export type InternalMiddlewareLifecycle = "PRE" | "POST" | "ALL"; export interface InternalMiddleware { type: MiddlewareType; caller: InternalMiddlewareFunc; configurationFlag: { key: string, expectedValue: any }; enabled: boolean; lifecycle: InternalMiddlewareLifecycle; } export namespace Core { export interface CacheItem { key: string; object: any; expiration: Date; } export const getCacheManager = () => { return MandarineMVCCache.getInstance(); } } } export interface ResponseStatusMetadataContext { responseStatus: Mandarine.MandarineMVC.HttpStatusCode; methodName?: string; } export interface routingParamContext { methodName: string; parameterName: string; parameterIndex: number; parameterType: DI.InjectionTypes; className?: string; } /** * Information used by CORS decorator & CORS Middleware for functionality */ export interface CorsMiddlewareOption { origin: string | RegExp | Array<string | RegExp>; methods?: Array<string>; allowedHeaders?: Array<string>; exposedHeaders?: Array<string>; credentials?: boolean; maxAge?: number; optionsSuccessStatus?: number; } /** * Interface of object returned when using decorator `@RequestBody()` in request which data is of `Multipart/form-data` */ export interface MultipartFormData { fields?: { [prop: string]: any }, files?: { [filename: string]: Uint8Array | Uint16Array | Uint32Array | BigUint64Array } } export interface MultipartHeader { name: string, isFile: boolean }; export interface Cookie extends MandarineCookie { } /** * Interface of object returned when using decorator `@Parameters()`. * @field `query` returns an object with keys & values of query parameters * @field `route` returns an object with keys & values of route parameters. */ export interface AllParameters { query: { [prop: string]: any; }, route: { [prop: string]: any; } } export interface ResponseContext extends Response {} export interface RequestDataContext extends Request { authentication: Mandarine.Security.Auth.RequestAuthObj; sessionContext: Mandarine.Security.Sessions.MandarineSession; sessionID: string; session: any; } export interface RequestTimeContext { startedAt: number; finishedAt: number; } export interface RequestContext extends Context { params: any; request: RequestDataContext; isResource: boolean; timeMetadata: RequestTimeContext; } export interface RequestContextAccessor { getFullContext(): RequestContext; getRequest(): RequestDataContext; getResponse(): ResponseContext; } /** * Interface used for the custom decorator executor. * Custom Decorator Executor refers to the context of a mandarine-powered decorator created by the user. */ export type CustomDecoratorExecutor<DecoratorData = any, DecoratorReturn = any> = (context: Mandarine.Types.RequestContextAcessor, ...data: Array<DecoratorData>) => DecoratorReturn; /** * Metadata & information of a Mandarine-generated decorator through custom decorators */ export interface DecoratorFactoryData<DecoratorData, DecoratorReturn> { provider: CustomDecoratorExecutor; paramData: Array<any>; } /** * Refers to all the information that the rendering engine needs to work out. */ export namespace TemplateEngine { /** * Supported view engines by mandarine */ export enum Engines { HANDLEBARS = "handlebars", EJS = "ejs" } /** * Decorators information related to the view engine/template engine */ export namespace Decorators { export interface RenderData { className: string, template: string, engine: TemplateEngine.Engines, options: RenderingOptions } } /** * Information of the template registered in the templates' registry */ export interface Template { templateFullPath: string, engine: TemplateEngine.Engines, content: string } /** * If manual is set to true then the template is defined in the decorator @Render */ export interface RenderingOptions { manual: boolean; customPath?: boolean; } export class RenderEngine extends RenderEngineClass {} } export namespace Configurers { export interface WebMVCConfigurer { getSessionContainer?(): MandarineSessionContainer; addResourceHandlers?(): Mandarine.MandarineCore.IResourceHandlerRegistry; authManagerBuilder?(provider?: Mandarine.Security.Auth.AuthenticationManagerBuilder): Mandarine.Security.Auth.AuthenticationManagerBuilder; httpLoginBuilder?(provider?: Mandarine.Security.Core.Modules.LoginBuilder): Mandarine.Security.Core.Modules.LoginBuilder; } } export namespace HTTPResolvers { /** * Resolves the requested resource. * @param httpContext is injected * @param resourcePath is injected */ export interface ResourceResolver { resolve(httpContext: Mandarine.Types.RequestContext, resourcePath: string): Promise<Uint8Array | undefined>; } } } (() => { // Initialize MVC Context MandarineMVCContext.getInstance(); })();
the_stack
import { FastTracker } from "../lib/fast-tracker"; import { PeerContext } from "../lib/tracker"; import { expect } from "chai"; import { mock, instance, anything, verify, capture, resetCalls } from "ts-mockito"; class PeerContextClass implements PeerContext { public id?: string; public swarm1?: any; public swarm2?: any; public swarm3?: any; public sendMessage: (json: any, peer: PeerContext) => void = () => {}; } describe("announce", () => { it("should add peers to swarms on announce", () => { const tracker = new FastTracker(); const peer0 = new PeerContextClass(); let announceMessage: any = { action: "announce", event: "started", info_hash: "swarm1", peer_id: "0", offers: new Array<any>(), numwant: 100, }; tracker.processMessage(announceMessage, peer0); expect(tracker.swarms).to.have.all.keys("swarm1"); expect(tracker.swarms.get("swarm1")!.peers).to.have.lengthOf(1); expect(tracker.swarms.get("swarm1")!.peers).to.include.members([peer0]); const peer1 = new PeerContextClass(); announceMessage = { action: "announce", info_hash: "swarm1", peer_id: "1", offers: new Array<any>(), numwant: 100, }; tracker.processMessage(announceMessage, peer1); expect(tracker.swarms).to.have.all.keys("swarm1"); expect(tracker.swarms.get("swarm1")!.peers).to.have.lengthOf(2); expect(tracker.swarms.get("swarm1")!.peers).to.include.members([peer0, peer1]); announceMessage = { action: "announce", event: "started", info_hash: "swarm1", peer_id: "1", offers: new Array<any>(), numwant: 100, }; tracker.processMessage(announceMessage, peer1); expect(tracker.swarms).to.have.all.keys("swarm1"); expect(tracker.swarms.get("swarm1")!.peers).to.have.lengthOf(2); expect(tracker.swarms.get("swarm1")!.peers).to.include.members([peer0, peer1]); const peer2 = new PeerContextClass(); announceMessage = { action: "announce", event: "completed", info_hash: "swarm2", peer_id: "2_0", offers: new Array<any>(), numwant: 100, }; tracker.processMessage(announceMessage, peer2); expect(tracker.swarms).to.have.all.keys("swarm1", "swarm2"); expect(tracker.swarms.get("swarm1")!.peers).to.have.lengthOf(2); expect(tracker.swarms.get("swarm1")!.peers).to.include.members([peer0, peer1]); expect(tracker.swarms.get("swarm2")!.peers).to.have.lengthOf(1); expect(tracker.swarms.get("swarm2")!.peers).to.include.members([peer2]); const peer3 = new PeerContextClass(); announceMessage = { action: "announce", event: "completed", info_hash: "swarm2", peer_id: "2_1", offers: new Array<any>(), numwant: 100, }; tracker.processMessage(announceMessage, peer3); expect(tracker.swarms).to.have.all.keys("swarm1", "swarm2"); expect(tracker.swarms.get("swarm1")!.peers).to.have.lengthOf(2); expect(tracker.swarms.get("swarm1")!.peers).to.include.members([peer0, peer1]); expect(tracker.swarms.get("swarm2")!.peers).to.have.lengthOf(2); expect(tracker.swarms.get("swarm2")!.peers).to.include.members([peer2, peer3]); announceMessage = { action: "announce", event: "completed", info_hash: "swarm2", peer_id: "1", offers: new Array<any>(), numwant: 100, }; tracker.processMessage(announceMessage, peer1); expect(tracker.swarms).to.have.all.keys("swarm1", "swarm2"); expect(tracker.swarms.get("swarm1")!.peers).to.have.lengthOf(2); expect(tracker.swarms.get("swarm1")!.peers).to.include.members([peer0, peer1]); expect(tracker.swarms.get("swarm2")!.peers).to.have.lengthOf(3); expect(tracker.swarms.get("swarm2")!.peers).to.include.members([peer1, peer2, peer3]); }); it("should send offers to peers in a swarm", () => { const tracker = new FastTracker(); const offers: any[] = []; for (let i = 0; i < 10; i++) { offers.push({ offer: { sdp: "x" }, offer_id: "y", }); } const mockedPeer0 = mock(PeerContextClass); const peer0 = instance(mockedPeer0); peer0.id = undefined; peer0.swarm1 = undefined; let announceMessage: any = { action: "announce", event: "started", info_hash: "swarm1", peer_id: "0", offers: offers, numwant: offers.length, }; tracker.processMessage(announceMessage, peer0); verify(mockedPeer0.sendMessage(anything(), peer0)).once(); let [json] = capture(mockedPeer0.sendMessage).first(); expect(json.info_hash).to.be.equal("swarm1"); expect(json.complete).to.be.equal(0); expect(json.incomplete).to.be.equal(1); resetCalls(mockedPeer0); const mockedPeer1 = mock(PeerContextClass); const peer1 = instance(mockedPeer1); peer1.id = undefined; peer1.swarm1 = undefined; peer1.swarm2 = undefined; announceMessage = { action: "announce", event: "completed", info_hash: "swarm1", peer_id: "1", offers: offers, numwant: offers.length, }; tracker.processMessage(announceMessage, peer1); verify(mockedPeer1.sendMessage(anything(), peer1)).once(); [json] = capture(mockedPeer1.sendMessage).first(); expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm1"); expect(json.complete).to.be.equal(1); expect(json.incomplete).to.be.equal(1); verify(mockedPeer0.sendMessage(anything(), peer0)).once(); [json] = capture(mockedPeer0.sendMessage).first(); expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm1"); expect(json.peer_id).to.be.equal("1"); expect(json.offer_id).to.be.equal("y"); expect(json.offer).to.exist; expect(json.offer.type).to.be.equal("offer"); expect(json.offer.sdp).to.be.equal("x"); resetCalls(mockedPeer0); resetCalls(mockedPeer1); const mockedPeer2 = mock(PeerContextClass); const peer2 = instance(mockedPeer2); peer2.id = undefined; peer2.swarm2 = undefined; announceMessage = { action: "announce", event: "started", info_hash: "swarm2", peer_id: "2", offers: offers, numwant: offers.length, }; tracker.processMessage(announceMessage, peer2); verify(mockedPeer2.sendMessage(anything(), peer2)).once(); [json] = capture(mockedPeer2.sendMessage).first(); expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm2"); expect(json.complete).to.be.equal(0); expect(json.incomplete).to.be.equal(1); verify(mockedPeer0.sendMessage(anything(), peer0)).never(); verify(mockedPeer1.sendMessage(anything(), peer1)).never(); resetCalls(mockedPeer0); resetCalls(mockedPeer1); resetCalls(mockedPeer2); const mockedPeer3 = mock(PeerContextClass); const peer3 = instance(mockedPeer3); peer3.id = undefined; peer3.swarm2 = undefined; announceMessage = { action: "announce", event: "completed", info_hash: "swarm2", peer_id: "3", offers: offers, numwant: offers.length, }; tracker.processMessage(announceMessage, peer3); verify(mockedPeer3.sendMessage(anything(), peer3)).once(); const [json3] = capture(mockedPeer3.sendMessage).first(); expect(json.action).to.be.equal("announce"); expect(json3.info_hash).to.be.equal("swarm2"); expect(json3.complete).to.be.equal(1); expect(json3.incomplete).to.be.equal(1); verify(mockedPeer0.sendMessage(anything(), peer0)).never(); verify(mockedPeer1.sendMessage(anything(), peer1)).never(); verify(mockedPeer2.sendMessage(anything(), peer2)).once(); [json] = capture(mockedPeer2.sendMessage).first(); expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm2"); expect(json.peer_id).to.be.equal("3"); expect(json.offer_id).to.be.equal("y"); expect(json.offer).to.exist; expect(json.offer.type).to.be.equal("offer"); expect(json.offer.sdp).to.be.equal("x"); resetCalls(mockedPeer0); resetCalls(mockedPeer1); resetCalls(mockedPeer2); resetCalls(mockedPeer3); const mockedPeer4 = mock(PeerContextClass); const peer4 = instance(mockedPeer4); peer4.id = undefined; peer4.swarm2 = undefined; announceMessage = { action: "announce", event: "completed", info_hash: "swarm2", peer_id: "4", offers: offers, numwant: 1, }; tracker.processMessage(announceMessage, peer4); verify(mockedPeer4.sendMessage(anything(), peer4)).once(); [json] = capture(mockedPeer4.sendMessage).first(); expect(json.info_hash).to.be.equal("swarm2"); expect(json.complete).to.be.equal(2); expect(json.incomplete).to.be.equal(1); verify(mockedPeer0.sendMessage(anything(), peer0)).never(); verify(mockedPeer1.sendMessage(anything(), peer1)).never(); try { verify(mockedPeer2.sendMessage(anything(), peer2)).once(); verify(mockedPeer3.sendMessage(anything(), peer3)).never(); [json] = capture(mockedPeer2.sendMessage).first(); } catch { verify(mockedPeer3.sendMessage(anything(), peer3)).once(); verify(mockedPeer2.sendMessage(anything(), peer2)).never(); [json] = capture(mockedPeer3.sendMessage).first(); } expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm2"); expect(json.peer_id).to.be.equal("4"); expect(json.offer_id).to.be.equal("y"); expect(json.offer).to.exist; expect(json.offer.type).to.be.equal("offer"); expect(json.offer.sdp).to.be.equal("x"); resetCalls(mockedPeer0); resetCalls(mockedPeer1); resetCalls(mockedPeer2); resetCalls(mockedPeer3); resetCalls(mockedPeer4); announceMessage = { action: "announce", event: "completed", info_hash: "swarm2", peer_id: "1", offers: offers, numwant: offers.length, }; tracker.processMessage(announceMessage, peer1); verify(mockedPeer0.sendMessage(anything(), peer0)).never(); verify(mockedPeer1.sendMessage(anything(), peer1)).once(); verify(mockedPeer2.sendMessage(anything(), peer2)).once(); verify(mockedPeer3.sendMessage(anything(), peer3)).once(); verify(mockedPeer4.sendMessage(anything(), peer4)).once(); }); it("should process answer messages", () => { const tracker = new FastTracker(); const peer1 = { sendMessage: (json: any) => { if (!json.offer) { return; } const answerMessage = { action: "announce", info_hash: json.info_hash, peer_id: "1", to_peer_id: json.peer_id, answer: { type: "answer", sdp: "sdp1", }, offer_id: json.offer_id, }; tracker.processMessage(answerMessage, peer1); }, }; let announceMessage: any = { action: "announce", event: "started", info_hash: "swarm1", peer_id: "1", }; tracker.processMessage(announceMessage, peer1); const peer2 = { sendMessage: (json: any) => { if (!json.offer) { return; } const answerMessage = { action: "announce", info_hash: json.info_hash, peer_id: "2", to_peer_id: json.peer_id, answer: { type: "answer", sdp: "sdp2", }, offer_id: json.offer_id, }; tracker.processMessage(answerMessage, peer2); }, }; announceMessage = { action: "announce", event: "started", info_hash: "swarm1", peer_id: "2", }; tracker.processMessage(announceMessage, peer2); const peer3 = { sendMessage: (json: any) => { if (!json.offer) { return; } const answerMessage = { action: "announce", info_hash: json.info_hash, peer_id: "3", to_peer_id: json.peer_id, answer: { type: "answer", sdp: "sdp3", }, offer_id: json.offer_id, }; tracker.processMessage(answerMessage, peer3); }, }; announceMessage = { action: "announce", event: "started", info_hash: "swarm1", peer_id: "3", }; tracker.processMessage(announceMessage, peer3); const mockedPeer0 = mock(PeerContextClass); const peer0 = instance(mockedPeer0); peer0.id = undefined; peer0.swarm1 = undefined; announceMessage = { action: "announce", event: "started", info_hash: "swarm1", peer_id: "0", offers: [{ offer: { sdp: "sdp01" }, offer_id: "1", }, { offer: { sdp: "sdp02" }, offer_id: "2", }, { offer: { sdp: "sdp03" }, offer_id: "3", }], numwant: 100, }; tracker.processMessage(announceMessage, peer0); verify(mockedPeer0.sendMessage(anything(), peer0)).times(4); let [json] = capture(mockedPeer0.sendMessage).byCallIndex(1); expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm1"); expect(json.peer_id).to.be.equal("1"); expect(json.offer_id).to.be.equal("1"); expect(json.answer.type).to.be.equal("answer"); expect(json.answer.sdp).to.be.equal("sdp1"); [json] = capture(mockedPeer0.sendMessage).byCallIndex(2); expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm1"); expect(json.peer_id).to.be.equal("2"); expect(json.offer_id).to.be.equal("2"); expect(json.answer.type).to.be.equal("answer"); expect(json.answer.sdp).to.be.equal("sdp2"); [json] = capture(mockedPeer0.sendMessage).byCallIndex(3); expect(json.action).to.be.equal("announce"); expect(json.info_hash).to.be.equal("swarm1"); expect(json.peer_id).to.be.equal("3"); expect(json.offer_id).to.be.equal("3"); expect(json.answer.type).to.be.equal("answer"); expect(json.answer.sdp).to.be.equal("sdp3"); }); });
the_stack
import { AsyncQueue as async } from '../src/base/AsyncQueue'; // testing internal package! import { expect } from 'chai'; describe('async', () => { describe('queue', () => { it('basics', (done: () => void) => { const callOrder: Array<string> = []; const delays = [40, 20, 60, 20]; // worker1: --1-4 // worker2: -2---3 // order of completion: 2,1,4,3 const q = async.queue((task: any, callback: (...args: any) => void): void => { setTimeout(() => { callOrder.push(`process ${task}`); callback('error', 'arg'); }, delays.shift()); }, 2); q.push(1, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(1); callOrder.push('callback 1'); }); q.push(2, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(2); callOrder.push('callback 2'); }); q.push(3, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(0); callOrder.push('callback 3'); }); q.push(4, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(0); callOrder.push('callback 4'); }); expect(q.length()).to.equal(4); expect(q.concurrency).to.equal(2); q.drain = () => { expect(callOrder).to.eql([ 'process 2', 'callback 2', 'process 1', 'callback 1', 'process 4', 'callback 4', 'process 3', 'callback 3', ]); expect(q.concurrency).to.equal(2); expect(q.length()).to.equal(0); done(); }; }); it('default concurrency', (done: () => void) => { const callOrder: Array<string> = []; const delays = [40, 20, 60, 20]; // order of completion: 1,2,3,4 const q = async.queue((task: any, callback: (...args: any) => void): void => { setTimeout(() => { callOrder.push(`process ${task}`); callback('error', 'arg'); }, delays.shift()); }); q.push(1, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(3); callOrder.push('callback 1'); }); q.push(2, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(2); callOrder.push('callback 2'); }); q.push(3, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(1); callOrder.push('callback 3'); }); q.push(4, (err, arg) => { expect(err).to.equal('error'); expect(arg).to.equal('arg'); expect(q.length()).to.equal(0); callOrder.push('callback 4'); }); expect(q.length()).to.equal(4); expect(q.concurrency).to.equal(1); q.drain = () => { expect(callOrder).to.eql([ 'process 1', 'callback 1', 'process 2', 'callback 2', 'process 3', 'callback 3', 'process 4', 'callback 4', ]); expect(q.concurrency).to.equal(1); expect(q.length()).to.equal(0); done(); }; }); it('zero concurrency', (done: () => void) => { expect(() => { async.queue((task: any, callback: (...args: any) => void): void => { callback(null, task); }, 0); }).to.throw(); done(); }); it('error propagation', (done: () => void) => { const results: Array<string> = []; const q = async.queue((task: any, callback: (...args: any) => void): void => { callback(task.name === 'foo' ? new Error('fooError') : null); }, 2); q.drain = () => { expect(results).to.eql(['bar', 'fooError']); done(); }; q.push({ name: 'bar' }, (err) => { if (err) { results.push('barError'); return; } results.push('bar'); }); q.push({ name: 'foo' }, (err) => { if (err) { results.push('fooError'); return; } results.push('foo'); }); }); it('global error handler', (done: () => void) => { const results: Array<string> = []; const q = async.queue((task: any, callback: (...args: any) => void): void => { callback(task.name === 'foo' ? new Error('fooError') : null); }, 2); q.error = (error, task) => { expect(error).to.exist; expect(error.message).to.equal('fooError'); expect(task.name).to.equal('foo'); results.push('fooError'); }; q.drain = () => { expect(results).to.eql(['fooError', 'bar']); done(); }; q.push({ name: 'foo' }); q.push({ name: 'bar' }, (err) => { expect(err).to.not.exist; results.push('bar'); }); }); // The original queue implementation allowed the concurrency to be changed only // on the same event loop during which a task was added to the queue. This // test attempts to be a more robust test. // Start with a concurrency of 1. Wait until a leter event loop and change // the concurrency to 2. Wait again for a later loop then verify the concurrency // Repeat that one more time by chaning the concurrency to 5. it('changing concurrency', (done: () => void) => { const q = async.queue((_task: any, callback: (...args: any) => void): void => { setTimeout(() => { callback(); }, 10); }, 1); for (let i = 0; i < 50; ++i) { q.push(''); } q.drain = () => { done(); }; setTimeout(() => { expect(q.concurrency).to.equal(1); q.concurrency = 2; setTimeout(() => { expect(q.running()).to.equal(2); q.concurrency = 5; setTimeout(() => { expect(q.running()).to.equal(5); }, 40); }, 40); }, 40); }); it('push without callback', (done: () => void) => { const callOrder: Array<string> = []; const delays = [40, 20, 60, 20]; // worker1: --1-4 // worker2: -2---3 // order of completion: 2,1,4,3 const q = async.queue((task: any, callback: (...args: any) => void): void => { setTimeout(() => { callOrder.push(`process ${task}`); callback('error', 'arg'); }, delays.shift()); }, 2); q.push(1); q.push(2); q.push(3); q.push(4); q.drain = () => { expect(callOrder).to.eql([ 'process 2', 'process 1', 'process 4', 'process 3', ]); done(); }; }); it('push with non-function', (done: () => void) => { const q = async.queue(() => { /* empty */ }, 1); expect(() => { q.push({}, 1); }).to.throw(); done(); }); it('unshift', (done: () => void) => { const queueOrder: Array<number> = []; const q = async.queue((task: any, callback: (...args: any) => void): void => { queueOrder.push(task); callback(); }, 1); q.unshift(4); q.unshift(3); q.unshift(2); q.unshift(1); setTimeout(() => { expect(queueOrder).to.eql([1, 2, 3, 4]); done(); }, 100); }); it('too many callbacks', (done: () => void) => { const q = async.queue((_task: any, callback: (...args: any) => void): void => { callback(); expect(() => { callback(); }).to.throw(); done(); }, 2); q.push(1); }); it('idle', (done: () => void) => { const q = async.queue((_task: any, callback: (...args: any) => void): void => { // Queue is busy when workers are running expect(q.idle()).to.equal(false); callback(); }, 1); // Queue is idle before anything added expect(q.idle()).to.equal(true); q.unshift(4); q.unshift(3); q.unshift(2); q.unshift(1); // Queue is busy when tasks added expect(q.idle()).to.equal(false); q.drain = () => { // Queue is idle after drain expect(q.idle()).to.equal(true); done(); }; }); it.skip('pause', (done: () => void) => { const callOrder: Array<string> = []; const taskTimeout = 80; const pauseTimeout = taskTimeout * 2.5; const resumeTimeout = taskTimeout * 4.5; const tasks = [1, 2, 3, 4, 5, 6]; const elapsed = (() => { const start = Date.now(); return () => Math.round((Date.now() - start) / taskTimeout) * taskTimeout; })(); const q = async.queue((task: any, callback: (...args: any) => void): void => { callOrder.push(`process ${task}`); callOrder.push(`timeout ${elapsed()}`); callback(); }); function pushTask() { const task = tasks.shift(); if (!task) { return; } setTimeout(() => { q.push(task); pushTask(); }, taskTimeout); } pushTask(); setTimeout(() => { q.pause(); expect(q.paused).to.equal(true); }, pauseTimeout); setTimeout(() => { q.resume(); expect(q.paused).to.equal(false); }, resumeTimeout); setTimeout(() => { expect(callOrder).to.eql([ 'process 1', `timeout ${taskTimeout}`, 'process 2', `timeout ${(taskTimeout * 2)}`, 'process 3', `timeout ${(taskTimeout * 5)}`, 'process 4', `timeout ${(taskTimeout * 5)}`, 'process 5', `timeout ${(taskTimeout * 5)}`, 'process 6', `timeout ${(taskTimeout * 6)}`, ]); done(); }, (taskTimeout * tasks.length) + pauseTimeout + resumeTimeout); }); it('pause in worker with concurrency', (done: () => void) => { const callOrder: Array<string> = []; const q = async.queue((task: any, callback: (...args: any) => void): void => { if (task.isLongRunning) { q.pause(); setTimeout(() => { callOrder.push(task.id); q.resume(); callback(); }, 50); } else { callOrder.push(task.id); setTimeout(callback, 10); } }, 10); q.push({ id: 1, isLongRunning: true }); q.push({ id: 2 }); q.push({ id: 3 }); q.push({ id: 4 }); q.push({ id: 5 }); q.drain = () => { expect(callOrder).to.eql([1, 2, 3, 4, 5]); done(); }; }); it('pause with concurrency', (done: () => void) => { const callOrder: Array<string> = []; const taskTimeout = 40; const pauseTimeout = taskTimeout / 2; const resumeTimeout = taskTimeout * 2.75; const tasks = [1, 2, 3, 4, 5, 6]; const elapsed = (() => { const start = Date.now(); return () => Math.round((Date.now() - start) / taskTimeout) * taskTimeout; })(); const q = async.queue((task: any, callback: (...args: any) => void): void => { setTimeout(() => { callOrder.push(`process ${task}`); callOrder.push(`timeout ${elapsed()}`); callback(); }, taskTimeout); }, 2); for (let i = 0; i < tasks.length; ++i) { q.push(tasks[i]); } setTimeout(() => { q.pause(); expect(q.paused).to.equal(true); }, pauseTimeout); setTimeout(() => { q.resume(); expect(q.paused).to.equal(false); }, resumeTimeout); setTimeout(() => { expect(q.running()).to.equal(2); }, resumeTimeout + 10); setTimeout(() => { expect(callOrder).to.eql([ 'process 1', `timeout ${taskTimeout}`, 'process 2', `timeout ${taskTimeout}`, 'process 3', `timeout ${(taskTimeout * 4)}`, 'process 4', `timeout ${(taskTimeout * 4)}`, 'process 5', `timeout ${(taskTimeout * 5)}`, 'process 6', `timeout ${(taskTimeout * 5)}`, ]); done(); }, (taskTimeout * tasks.length) + pauseTimeout + resumeTimeout); }); it('start paused', (done: () => void) => { const q = async.queue((_task: any, callback: (...args: any) => void): void => { setTimeout(() => { callback(); }, 40); }, 2); q.pause(); q.push(1); q.push(2); q.push(3); setTimeout(() => { q.resume(); }, 5); setTimeout(() => { expect(q._tasks.length).to.equal(1); expect(q.running()).to.equal(2); q.resume(); }, 15); q.drain = () => { done(); }; }); it('kill', (done: () => void) => { const q = async.queue((/* task, callback */) => { setTimeout(() => { throw new Error('Function should never be called'); }, 20); }, 1); q.drain = () => { throw new Error('Function should never be called'); }; q.push(0); q.kill(); setTimeout(() => { expect(q.length()).to.equal(0); done(); }, 40); }); it('events', (done: () => void) => { const calls: Array<string> = []; const q = async.queue((task, cb) => { // nop calls.push(`process ${task}`); setTimeout(cb, 10); }, 3); q.concurrency = 3; q.saturated = () => { expect(q.running()).to.equal(3, 'queue should be saturated now'); calls.push('saturated'); }; q.empty = () => { expect(q.length()).to.equal(0, 'queue should be empty now'); calls.push('empty'); }; q.drain = () => { expect(q.length() === 0 && q.running() === 0) .to.equal(true, 'queue should be empty now and no more workers should be running'); calls.push('drain'); expect(calls).to.eql([ 'process foo', 'process bar', 'saturated', 'process zoo', 'foo cb', 'saturated', 'process poo', 'bar cb', 'empty', 'saturated', 'process moo', 'zoo cb', 'poo cb', 'moo cb', 'drain', ]); done(); }; q.push('foo', () => calls.push('foo cb')); q.push('bar', () => calls.push('bar cb')); q.push('zoo', () => calls.push('zoo cb')); q.push('poo', () => calls.push('poo cb')); q.push('moo', () => calls.push('moo cb')); }); it('empty', (done: () => void) => { const calls: Array<string> = []; const q = async.queue((task, cb) => { // nop calls.push(`process ${task}`); setTimeout(cb, 1); }, 3); q.drain = () => { expect(q.length() === 0 && q.running() === 0) .to.equal(true, 'queue should be empty now and no more workers should be running'); calls.push('drain'); expect(calls).to.eql([ 'drain', ]); done(); }; q.push(); }); it('saturated', (done: () => void) => { let saturatedCalled = false; const q = async.queue((task, cb) => { setTimeout(cb, 1); }, 2); q.saturated = () => { saturatedCalled = true; }; q.drain = () => { expect(saturatedCalled).to.equal(true, 'saturated not called'); done(); }; q.push('foo'); q.push('bar'); q.push('baz'); q.push('moo'); }); it('started', (done: () => void) => { const q = async.queue((task, cb) => { cb(null, task); }); expect(q.started).to.equal(false); q.push(undefined); expect(q.started).to.equal(true); done(); }); context('q.saturated(): ', () => { it('should call the saturated callback if tasks length is concurrency', (done: () => void) => { const calls: Array<string> = []; const q = async.queue((task, cb) => { calls.push(`process ${task}`); setTimeout(cb, 1); }, 4); q.saturated = () => { calls.push('saturated'); }; q.empty = () => { expect(calls.indexOf('saturated')).to.be.above(-1); setTimeout(() => { expect(calls).eql([ 'process foo0', 'process foo1', 'process foo2', 'saturated', 'process foo3', 'foo0 cb', 'saturated', 'process foo4', 'foo1 cb', 'foo2 cb', 'foo3 cb', 'foo4 cb', ]); done(); }, 50); }; q.push('foo0', () => calls.push('foo0 cb')); q.push('foo1', () => calls.push('foo1 cb')); q.push('foo2', () => calls.push('foo2 cb')); q.push('foo3', () => calls.push('foo3 cb')); q.push('foo4', () => calls.push('foo4 cb')); }); }); context('q.unsaturated(): ', () => { it('should have a default buffer property that equals 25% of the concurrenct rate', (done: () => void) => { const calls: Array<string> = []; const q = async.queue((task, cb) => { // nop calls.push(`process ${task}`); setTimeout(cb, 1); }, 10); expect(q.buffer).to.equal(2.5); done(); }); it('should allow a user to change the buffer property', (done: () => void) => { const calls: Array<string> = []; const q = async.queue((task, cb) => { // nop calls.push(`process ${task}`); setTimeout(cb, 1); }, 10); q.buffer = 4; expect(q.buffer).to.not.equal(2.5); expect(q.buffer).to.equal(4); done(); }); it('should call the unsaturated callback if tasks length is less than concurrency minus buffer', (done: () => void) => { // eslint-disable-line max-len const calls: Array<string> = []; const q = async.queue((task: any, cb: () => void) => { calls.push(`process ${task}`); setTimeout(cb, 1); }, 4); q.unsaturated = () => { calls.push('unsaturated'); }; q.empty = () => { expect(calls.indexOf('unsaturated')).to.be.above(-1); setTimeout(() => { expect(calls).eql([ 'process foo0', 'process foo1', 'process foo2', 'process foo3', 'foo0 cb', 'unsaturated', 'process foo4', 'foo1 cb', 'unsaturated', 'foo2 cb', 'unsaturated', 'foo3 cb', 'unsaturated', 'foo4 cb', 'unsaturated', ]); done(); }, 50); }; q.push('foo0', () => calls.push('foo0 cb')); q.push('foo1', () => calls.push('foo1 cb')); q.push('foo2', () => calls.push('foo2 cb')); q.push('foo3', () => calls.push('foo3 cb')); q.push('foo4', () => calls.push('foo4 cb')); }); }); }); describe('eachSeries', () => { function eachIteratee(args: Array<any>, x: number, callback: () => void) { setTimeout(() => { args.push(x); callback(); }, x * 25); } function eachNoCallbackIteratee(done: () => void, x: number, callback: () => void) { expect(x).to.equal(1); callback(); done(); } it('eachSeries', (done: () => void) => { const args: Array<number> = []; async.eachSeries([1, 3, 2], eachIteratee.bind({ }, args), (err) => { expect(err).to.equal(undefined, `${err} passed instead of 'null'`); expect(args).to.eql([1, 3, 2]); done(); }); }); it('empty array', (done: () => void) => { async.eachSeries([], (x: number, callback: () => void) => { expect(false).to.equal(true, 'iteratee should not be called'); callback(); }, (err) => { if (err) { throw err; } expect(true).to.equal(true, 'should call callback'); }); setTimeout(done, 25); }); it('array modification', (done: () => void) => { const arr = [1, 2, 3, 4]; async.eachSeries(arr, (x, callback) => { setTimeout(callback, 1); }, () => { expect(true).to.equal(true, 'should call callback'); }); arr.pop(); arr.splice(0, 1); setTimeout(done, 50); }); // bug #782. Remove in next major release it('single item', (done: () => void) => { let sync = true; async.eachSeries( [1], (i, cb) => { cb(null); }, () => { expect(sync).to.equal(true, 'callback not called on same tick'); } ); sync = false; done(); }); // bug #782. Remove in next major release it('single item', (done: () => void) => { let sync = true; async.eachSeries( [1], (i, cb) => { cb(null); }, () => { expect(sync).to.equal(true, 'callback not called on same tick'); } ); sync = false; done(); }); it('error', (done: () => void) => { const callOrder: Array<string> = []; async.eachSeries( [1, 2, 3], (x: any, callback: (x: string) => void) => { callOrder.push(x); callback('error'); }, (err: string) => { expect(callOrder).to.eql([1]); expect(err).to.equal('error'); } ); setTimeout(done, 50); }); it('no callback', (done: () => void) => { async.eachSeries([1], eachNoCallbackIteratee.bind(this, done)); }); }); });
the_stack
import { OutputChunk, rollup, OutputAsset, RollupOptions, OutputOptions } from 'rollup'; import { expect } from 'chai'; import fs from 'fs'; import path from 'path'; import html from '@web/rollup-plugin-html'; import polyfillsLoader from '../../src/index'; type Output = (OutputChunk | OutputAsset)[]; const relativeUrl = `./${path.relative(process.cwd(), path.join(__dirname, '..'))}`; const updateSnapshots = process.argv.includes('--update-snapshots'); function getAsset(output: Output, name: string) { return output.find(o => o.fileName === name && o.type === 'asset') as OutputAsset & { source: string; }; } interface SnapshotArgs { name: string; fileName: string; inputOptions: RollupOptions; outputOptions: OutputOptions[]; } async function testSnapshot({ name, fileName, inputOptions, outputOptions }: SnapshotArgs) { const snapshotPath = path.join(__dirname, '..', 'snapshots', `${name}.html`); const bundle = await rollup(inputOptions); let output; for (const outputConfig of outputOptions) { ({ output } = await bundle.generate(outputConfig)); } if (!output) throw new Error(''); const file = getAsset(output, fileName); if (!file) throw new Error(`Build did not output ${fileName}`); if (updateSnapshots) { fs.writeFileSync(snapshotPath, file.source, 'utf-8'); } else { const snapshot = fs.readFileSync(snapshotPath, 'utf-8'); expect(file.source.trim()).to.equal(snapshot.trim()); // expect(file.source.replace(/\s/g, '')).to.equal(snapshot.replace(/\s/g, '')); } return output; } const defaultOutputOptions: OutputOptions[] = [ { format: 'es', dir: 'dist', }, ]; describe('rollup-plugin-polyfills-loader', function describe() { // bootup of the first test can take a long time in CI to load all the polyfills this.timeout(5000); it('can inject a polyfills loader with a single output', async () => { const inputOptions: RollupOptions = { plugins: [ html({ input: { html: `<script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script>`, }, }), polyfillsLoader({ polyfills: { hash: false, fetch: true }, }), ], }; await testSnapshot({ name: 'single-output', fileName: 'index.html', inputOptions, outputOptions: defaultOutputOptions, }); }); it('can inject a polyfills loader with multiple entrypoints', async () => { const inputOptions: RollupOptions = { plugins: [ html({ input: { html: ` <script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script> <script type="module" src="${relativeUrl}/fixtures/entrypoint-b.js"></script>`, }, }), polyfillsLoader({ polyfills: { hash: false, fetch: true }, }), ], }; await testSnapshot({ name: 'multiple-entrypoints', fileName: 'index.html', inputOptions, outputOptions: defaultOutputOptions, }); }); it('retains attributes on script tags when injecting a polyfills loader with multiple entrypoints', async () => { const inputOptions: RollupOptions = { plugins: [ html({ input: { html: ` <script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js" keep-this-attribute></script> <script type="module" src="${relativeUrl}/fixtures/entrypoint-b.js"></script>`, }, }), polyfillsLoader({ polyfills: { hash: false, fetch: true }, }), ], }; await testSnapshot({ name: 'multiple-entrypoints-retain-attributes', fileName: 'index.html', inputOptions, outputOptions: defaultOutputOptions, }); }); it('can inject a polyfills loader with non-flat inputs, flattenOutput: true', async () => { const inputOptions: RollupOptions = { plugins: [ html({ rootDir: `${relativeUrl}/fixtures/`, input: `non-flat/index.html`, flattenOutput: true, }), polyfillsLoader({ polyfills: { hash: false, fetch: true }, }), ], }; await testSnapshot({ name: 'flattened', fileName: `index.html`, inputOptions, outputOptions: defaultOutputOptions, }); }); it('can inject a polyfills loader with non-flat inputs, flattenOutput: false', async () => { const inputOptions: RollupOptions = { plugins: [ html({ rootDir: `${relativeUrl}/fixtures/`, input: `non-flat/index.html`, flattenOutput: false, }), polyfillsLoader({ polyfills: { hash: false, fetch: true }, }), ], }; await testSnapshot({ name: 'non-flattened', fileName: path.normalize(`non-flat/index.html`), inputOptions, outputOptions: defaultOutputOptions, }); }); it('injects the correct preload for systemjs output', async () => { const inputOptions: RollupOptions = { plugins: [ html({ input: { html: ` <script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script> <script type="module" src="${relativeUrl}/fixtures/entrypoint-b.js"></script>`, }, }), polyfillsLoader(), ], }; await testSnapshot({ name: 'systemjs', fileName: 'index.html', inputOptions, outputOptions: [ { format: 'system', dir: 'dist', }, ], }); }); it('can set polyfills to load', async () => { const inputOptions = { plugins: [ html({ input: { html: `<script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script>`, }, }), polyfillsLoader({ polyfills: { hash: false, webcomponents: true, fetch: true, }, }), ], }; const output = await testSnapshot({ name: 'polyfills', fileName: 'index.html', inputOptions, outputOptions: defaultOutputOptions, }); expect(output.find(o => o.fileName.startsWith('polyfills/webcomponents'))).to.exist; expect(output.find(o => o.fileName.startsWith('polyfills/fetch'))).to.exist; }); it('can inject with multiple build outputs', async () => { const htmlPlugin = html({ input: { html: `<script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script>`, }, }); const inputOptions = { plugins: [ htmlPlugin, polyfillsLoader({ modernOutput: { name: 'modern' }, legacyOutput: [{ name: 'legacy', test: "!('noModule' in HTMLScriptElement.prototype)" }], polyfills: { hash: false, webcomponents: true, fetch: true }, }), ], }; const outputOptions: OutputOptions[] = [ { format: 'system', dir: 'dist', plugins: [htmlPlugin.api.addOutput('legacy')], }, { format: 'es', dir: 'dist', plugins: [htmlPlugin.api.addOutput('modern')], }, ]; await testSnapshot({ name: 'multiple-outputs', fileName: 'index.html', inputOptions, outputOptions, }); }); it('can customize the file type', async () => { const htmlPlugin = html({ input: { html: `<script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script>`, }, }); const inputOptions = { plugins: [ htmlPlugin, polyfillsLoader({ modernOutput: { name: 'modern', type: 'systemjs' }, polyfills: { hash: false, webcomponents: true, fetch: true }, }), ], }; const outputOptions: OutputOptions[] = [ { format: 'es', dir: 'dist', }, ]; await testSnapshot({ name: 'customize-filetype', fileName: 'index.html', inputOptions, outputOptions, }); }); it('can customize the file type for multiple outputs', async () => { const htmlPlugin = html({ input: { html: `<script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script>`, }, }); const inputOptions = { plugins: [ htmlPlugin, polyfillsLoader({ modernOutput: { name: 'modern', type: 'script' }, legacyOutput: [ { name: 'legacy', type: 'script', test: "!('noModule' in HTMLScriptElement.prototype)", }, ], polyfills: { hash: false, webcomponents: true, fetch: true }, }), ], }; const outputOptions: OutputOptions[] = [ { format: 'system', dir: 'dist', plugins: [htmlPlugin.api.addOutput('legacy')], }, { format: 'es', dir: 'dist', plugins: [htmlPlugin.api.addOutput('modern')], }, ]; await testSnapshot({ name: 'customize-filetype-multi-output', fileName: 'index.html', inputOptions, outputOptions, }); }); it('injects preload when there are no polyfills to inject', async () => { const inputOptions: RollupOptions = { plugins: [ html({ input: { html: ` <script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js"></script> <script type="module" src="${relativeUrl}/fixtures/entrypoint-b.js"></script>`, }, }), polyfillsLoader(), ], }; await testSnapshot({ name: 'no-polyfills', fileName: 'index.html', inputOptions, outputOptions: defaultOutputOptions, }); }); it('will retain attributes of script tags if there are no polyfills to inject', async () => { const inputOptions: RollupOptions = { plugins: [ html({ input: { html: ` <script type="module" src="${relativeUrl}/fixtures/entrypoint-a.js" keep-this-attribute></script> <script type="module" src="${relativeUrl}/fixtures/entrypoint-b.js"></script>`, }, }), polyfillsLoader(), ], }; await testSnapshot({ name: 'no-polyfills-retain-attributes', fileName: 'index.html', inputOptions, outputOptions: defaultOutputOptions, }); }); });
the_stack
import Tooltip, { DEFAULT_TOOLTIP_PLUGIN, TooltipPlugin } from '../views/tooltip' import PostEditor from './post' import ImageCard from '../cards/image' import { Direction } from '../utils/key' import mobiledocParsers from '../parsers/mobiledoc' import HTMLParser from '../parsers/html' import DOMParser from '../parsers/dom' import Renderer from '../renderers/editor-dom' import RenderTree from '../models/render-tree' import mobiledocRenderers, { MobiledocVersion } from '../renderers/mobiledoc' import { MOBILEDOC_VERSION } from '../renderers/mobiledoc' import { mergeWithOptions } from '../utils/merge' import { normalizeTagName, clearChildNodes, serializeHTML } from '../utils/dom-utils' import { forEach, filter, contains, values, detect } from '../utils/array-utils' import { setData } from '../utils/element-utils' import Cursor from '../utils/cursor' import Range from '../utils/cursor/range' import Position from '../utils/cursor/position' import Environment from '../utils/environment' import PostNodeBuilder from '../models/post-node-builder' import { DEFAULT_TEXT_INPUT_HANDLERS } from './text-input-handlers' import { DEFAULT_KEY_COMMANDS, buildKeyCommand, findKeyCommands, validateKeyCommand, KeyCommand, CompiledKeyCommand, } from './key-commands' import Card, { CardMode, CardPayload } from '../models/card' import assert from '../utils/assert' import MutationHandler from '../editor/mutation-handler' import EditHistory from '../editor/edit-history' import EventManager, { DOMEventType, DOMEventForType } from '../editor/event-manager' import EditState from '../editor/edit-state' import DOMRenderer from 'mobiledoc-dom-renderer' import TextRenderer from 'mobiledoc-text-renderer' import LifecycleCallbacks, { LifecycleCallback } from '../models/lifecycle-callbacks' import LogManager from '../utils/log-manager' import toRange from '../utils/to-range' import MobiledocError from '../utils/mobiledoc-error' import Post from '../models/post' import { Mobiledoc } from '../renderers/mobiledoc' import { SectionParserPlugin } from '../parsers/section' import { CardData, CardRenderHook } from '../models/card-node' import { AtomData } from '../models/atom-node' import { Option, Maybe, Dict } from '../utils/types' import Markup from '../models/markup' import View from '../views/view' import Atom, { AtomPayload } from '../models/atom' import Section, { isNested } from '../models/_section' import { TextInputHandlerListener } from './text-input-handler' // This export may later be deprecated, but re-export it from the renderer here // for consumers that may depend on it. export { EDITOR_ELEMENT_CLASS_NAME } from '../renderers/editor-dom' export interface EditorOptions { parserPlugins?: SectionParserPlugin[] placeholder?: string spellcheck?: boolean autofocus?: boolean showLinkTooltips?: boolean undoDepth?: number undoBlockTimeout?: number cards?: CardData[] atoms?: AtomData[] cardOptions?: {} unknownCardHandler?: CardRenderHook unknownAtomHandler?: CardRenderHook mobiledoc?: Option<Mobiledoc> html?: Option<string> tooltipPlugin?: TooltipPlugin /** @internal */ nodeType?: number } const defaults: EditorOptions = { placeholder: 'Write here...', spellcheck: true, autofocus: true, showLinkTooltips: true, undoDepth: 5, undoBlockTimeout: 5000, // ms for an undo event cards: [], atoms: [], cardOptions: {}, unknownCardHandler: ({ env }) => { throw new MobiledocError(`Unknown card encountered: ${env.name}`) }, unknownAtomHandler: ({ env }) => { throw new MobiledocError(`Unknown atom encountered: ${env.name}`) }, mobiledoc: null, html: null, tooltipPlugin: DEFAULT_TOOLTIP_PLUGIN, } const CALLBACK_QUEUES = { DID_UPDATE: 'didUpdate', WILL_RENDER: 'willRender', DID_RENDER: 'didRender', WILL_DELETE: 'willDelete', DID_DELETE: 'didDelete', WILL_HANDLE_NEWLINE: 'willHandleNewline', CURSOR_DID_CHANGE: 'cursorDidChange', DID_REPARSE: 'didReparse', POST_DID_CHANGE: 'postDidChange', INPUT_MODE_DID_CHANGE: 'inputModeDidChange', WILL_COPY: 'willCopy', } export enum Format { MOBILEDOC = 'mobiledoc', HTML = 'html', TEXT = 'text', } export interface SerializeOptions { version?: MobiledocVersion } export interface InputHandler { /** Used by identifying handlers. */ name: string /** Required if `match` is not provided. */ text?: string /** Required if `text` is not provided. */ match?: RegExp /** * This callback is invoked with the {@link Editor} instance and an array of * matches. If `text` was provided, the matches array will equal [`text`], * and if a `match` regex was provided the matches array will be the result * of `match.exec` on the matching text. The callback is called after the * matching text has been inserted. */ run: (editor: Editor, matches: string[]) => void } export enum TextUnit { CHAR = 'char', WORD = 'word', } interface DeleteOperation { direction: Direction unit: TextUnit } interface BeforeHooks { toggleMarkup: LifecycleCallback[] } /** * The Editor is a core component of mobiledoc-kit. After instantiating * an editor, use {@link Editor#render} to display the editor on the web page. * * An editor uses a {@link Post} internally to represent the displayed document. * The post can be serialized as mobiledoc using {@link Editor#serialize}. Mobiledoc * is the transportable "over-the-wire" format (JSON) that is suited for persisting * and sharing between editors and renderers (for display, e.g.), whereas the Post * model is better suited for programmatic editing. * * The editor will call registered callbacks for certain state changes. These are: * * {@link Editor#cursorDidChange} -- The cursor position or selection changed. * * {@link Editor#postDidChange} -- The contents of the post changed due to user input or * programmatic editing. This hook can be used with {@link Editor#serialize} * to auto-save a post as it is being edited. * * {@link Editor#inputModeDidChange} -- The active section(s) or markup(s) at the current cursor * position or selection have changed. This hook can be used with * {@link Editor#activeMarkups} and {@link Editor#activeSections} to implement * a custom toolbar. * * {@link Editor#onTextInput} -- Register callbacks when the user enters text * that matches a given string or regex. * * {@link Editor#beforeToggleMarkup} -- Register callbacks that will be run before * applying changes from {@link Editor#toggleMarkup} */ export default class Editor implements EditorOptions { post: Post cards!: CardData[] atoms!: AtomData[] element!: HTMLElement isEditable: boolean hasRendered: boolean isDestroyed: boolean undoDepth!: number parserPlugins!: SectionParserPlugin[] placeholder!: string spellcheck!: boolean autofocus!: boolean showLinkTooltips!: boolean undoBlockTimeout!: number cardOptions!: {} unknownCardHandler!: CardRenderHook unknownAtomHandler!: CardRenderHook mobiledoc!: Option<Mobiledoc> html!: Option<string> text!: Option<string> tooltipPlugin!: TooltipPlugin _views: View[] _keyCommands?: CompiledKeyCommand[] _parserPlugins: SectionParserPlugin[] _logManager: LogManager _parser: DOMParser _builder!: PostNodeBuilder _renderer: Renderer _renderTree: RenderTree _editHistory: EditHistory _eventManager: EventManager _mutationHandler: MutationHandler _editState: EditState _callbacks: LifecycleCallbacks _beforeHooks: BeforeHooks _isComposingOnBlankLine: boolean /** * @param {Object} [options] * @param {Object} [options.mobiledoc] The mobiledoc to load into the editor. * Supersedes `options.html`. * @param {String|DOM} [options.html] The html (as a string or DOM fragment) * to parse and load into the editor. * Will be ignored if `options.mobiledoc` is also passed. * @param {Array} [options.parserPlugins=[]] * @param {Array} [options.cards=[]] The cards that the editor may render. * @param {Array} [options.atoms=[]] The atoms that the editor may render. * @param {Function} [options.unknownCardHandler] Invoked by the editor's renderer * whenever it encounters an unknown card. * @param {Function} [options.unknownAtomHandler] Invoked by the editor's renderer * whenever it encounters an unknown atom. * @param {String} [options.placeholder] Default text to show before user starts typing. * @param {Boolean} [options.spellcheck=true] Whether to enable spellcheck * @param {Boolean} [options.autofocus=true] Whether to focus the editor when it is first rendered. * @param {Boolean} [options.showLinkTooltips=true] Whether to show the url tooltip for links * @param {number} [options.undoDepth=5] How many undo levels will be available. * Set to 0 to disable undo/redo functionality. * @public */ constructor(options: EditorOptions = {}) { assert( 'editor create accepts an options object. For legacy usage passing an element for the first argument, consider the `html` option for loading DOM or HTML posts. For other cases call `editor.render(domNode)` after editor creation', options && !options.nodeType ) this._views = [] this.isEditable = true this._parserPlugins = options.parserPlugins || [] // FIXME: This should merge onto this.options mergeWithOptions(this, defaults, options) this.cards.push(ImageCard) DEFAULT_KEY_COMMANDS.forEach(kc => this.registerKeyCommand(kc)) this._logManager = new LogManager() this._parser = new DOMParser(this.builder) let { cards, atoms, unknownCardHandler, unknownAtomHandler, cardOptions } = this this._renderer = new Renderer(this, cards, atoms, unknownCardHandler, unknownAtomHandler, cardOptions) this.post = this.loadPost() this._renderTree = new RenderTree(this.post) this._editHistory = new EditHistory(this, this.undoDepth, this.undoBlockTimeout) this._eventManager = new EventManager(this) this._mutationHandler = new MutationHandler(this) this._editState = new EditState(this) this._callbacks = new LifecycleCallbacks(values(CALLBACK_QUEUES)) this._beforeHooks = { toggleMarkup: [] } this._isComposingOnBlankLine = false DEFAULT_TEXT_INPUT_HANDLERS.forEach(handler => this.onTextInput(handler)) this.hasRendered = false this.isDestroyed = false } /** * Turns on verbose logging for the editor. * @param {Array} [logTypes=[]] If present, only the given log types will be logged. * @public */ enableLogging(logTypes: string[] = []): void { if (logTypes.length === 0) { this._logManager.enableAll() } else { this._logManager.enableTypes(logTypes) } } /** * Disable all logging * @public */ disableLogging() { this._logManager.disable() } /** * @private */ loggerFor(type: string) { return this._logManager.for(type) } /** * The editor's instance of a post node builder. * @type {PostNodeBuilder} */ get builder() { if (!this._builder) { this._builder = new PostNodeBuilder() } return this._builder } loadPost() { let { mobiledoc, html } = this if (mobiledoc) { return mobiledocParsers.parse(this.builder, mobiledoc) } else if (html) { if (typeof html === 'string') { let options = { plugins: this._parserPlugins } return new HTMLParser(this.builder, options).parse(html) } else { let dom = html return this._parser.parse(dom) } } else { return this.builder.createPost([this.builder.createMarkupSection()]) } } rerender() { let postRenderNode = this.post.renderNode // if we haven't rendered this post's renderNode before, mark it dirty if (!postRenderNode.element) { assert('Must call `render` before `rerender` can be called', this.hasRendered) postRenderNode.element = this.element postRenderNode.markDirty() } this.runCallbacks(CALLBACK_QUEUES.WILL_RENDER) this._mutationHandler.suspendObservation(() => { this._renderer.render(this._renderTree) }) this.runCallbacks(CALLBACK_QUEUES.DID_RENDER) } /** * @param {Element} element The DOM element to render into. * Its contents will be replaced by the editor's rendered post. * @public */ render(element: HTMLElement) { assert( 'Cannot render an editor twice. Use `rerender` to update the ' + 'rendering of an existing editor instance.', !this.hasRendered ) element.spellcheck = this.spellcheck clearChildNodes(element) this.element = element if (this.showLinkTooltips) { this._addTooltip() } // A call to `run` will trigger the didUpdatePostCallbacks hooks with a // postEditor. this.run(() => {}) // Only set `hasRendered` to true after calling `run` to ensure that // no cursorDidChange or other callbacks get fired before the editor is // done rendering this.hasRendered = true this.rerender() this._mutationHandler.init() this._eventManager.init() if (this.isEditable === false) { this.disableEditing() } else { this.enableEditing() } if (this.autofocus) { this.selectRange(this.post.headPosition()) } } _addTooltip() { this.addView( new Tooltip({ rootElement: this.element, showForTag: 'a', editor: this, }) ) } get keyCommands() { if (!this._keyCommands) { this._keyCommands = [] } return this._keyCommands } /** * @param {Object} keyCommand The key command to register. It must specify a * modifier key (meta, ctrl, etc), a string representing the ascii key, and * a `run` method that will be passed the editor instance when the key command * is invoked * @public */ registerKeyCommand(rawKeyCommand: KeyCommand) { const keyCommand = buildKeyCommand(rawKeyCommand) assert('Key Command is not valid', validateKeyCommand(keyCommand)) this.keyCommands.unshift(keyCommand) } /** * @param {String} name If the keyCommand event has a name attribute it can be removed. * @public */ unregisterKeyCommands(name: string) { for (let i = this.keyCommands.length - 1; i > -1; i--) { let keyCommand = this.keyCommands[i] if (keyCommand.name === name) { this.keyCommands.splice(i, 1) } } } /** * Convenience for {@link PostEditor#deleteAtPosition}. Deletes and puts the * cursor in the new position. * @public */ deleteAtPosition(position: Position, direction: number, { unit }: { unit: TextUnit }) { this.run(postEditor => { let nextPosition = postEditor.deleteAtPosition(position, direction, { unit }) postEditor.setRange(nextPosition) }) } /** * Convenience for {@link PostEditor#deleteRange}. Deletes and puts the * cursor in the new position. * @param {Range} range * @public */ deleteRange(range: Range) { this.run(postEditor => { let nextPosition = postEditor.deleteRange(range) postEditor.setRange(nextPosition) }) } /** * @private */ performDelete({ direction, unit }: DeleteOperation = { direction: Direction.BACKWARD, unit: TextUnit.CHAR }) { const { range } = this this.runCallbacks(CALLBACK_QUEUES.WILL_DELETE, [range, direction, unit]) if (range.isCollapsed) { this.deleteAtPosition(range.head, direction, { unit }) } else { this.deleteRange(range) } this.runCallbacks(CALLBACK_QUEUES.DID_DELETE, [range, direction, unit]) } handleNewline(event: KeyboardEvent) { if (!this.hasCursor()) { return } event.preventDefault() let { range } = this this.run(postEditor => { let cursorSection: Option<Section> if (!range.isCollapsed) { let nextPosition = postEditor.deleteRange(range) cursorSection = nextPosition.section if (cursorSection && cursorSection.isBlank) { postEditor.setRange(cursorSection.headPosition()) return } } // Above logic might delete redundant range, so callback must run after it. let defaultPrevented = false const event = { preventDefault() { defaultPrevented = true }, } this.runCallbacks(CALLBACK_QUEUES.WILL_HANDLE_NEWLINE, [event]) if (defaultPrevented) { return } cursorSection = postEditor.splitSection(range.head)[1] postEditor.setRange(cursorSection!.headPosition()) }) } /** * Notify the editor that the post did change, and run associated * callbacks. * @private */ _postDidChange() { this.runCallbacks(CALLBACK_QUEUES.POST_DID_CHANGE) } /** * Selects the given range or position. If given a collapsed range or a position, this positions the cursor * at the range's position. Otherwise a selection is created in the editor * surface encompassing the range. * @param {Range|Position} range */ selectRange(range: Range | Position) { range = toRange(range) this.cursor.selectRange(range) this.range = range } get cursor() { return new Cursor(this) } /** * Return the current range for the editor (may be cached). * @return {Range} */ get range(): Range { return this._editState.range } set range(newRange) { this._editState.updateRange(newRange) if (this._editState.rangeDidChange()) { this._rangeDidChange() } if (this._editState.inputModeDidChange()) { this._inputModeDidChange() } } _readRangeFromDOM() { this.range = this.cursor.offsets } setPlaceholder(placeholder: string) { setData(this.element, 'placeholder', placeholder) } _reparsePost() { let post = this._parser.parse(this.element) this.run(postEditor => { postEditor.removeAllSections() postEditor.migrateSectionsFromPost(post) postEditor.setRange(Range.blankRange()) }) this.runCallbacks(CALLBACK_QUEUES.DID_REPARSE) this._postDidChange() } _reparseSections(sections: Section[] = []) { let currentRange: Maybe<Range> sections.forEach(section => { this._parser.reparseSection(section, this._renderTree) }) this._removeDetachedSections() if (this._renderTree.isDirty) { currentRange = this.range } // force the current snapshot's range to remain the same rather than // rereading it from DOM after the new character is applied and the browser // updates the cursor position const editHistory = this._editHistory! const pendingSnapshot = editHistory._pendingSnapshot! const range = pendingSnapshot.range this.run(() => { pendingSnapshot.range = range }) this.rerender() if (currentRange) { this.selectRange(currentRange) } this.runCallbacks(CALLBACK_QUEUES.DID_REPARSE) this._postDidChange() } // FIXME this should be able to be removed now -- if any sections are detached, // it's due to a bug in the code. _removeDetachedSections() { forEach( filter(this.post.sections, s => !s.renderNode.isAttached()), s => s.renderNode.scheduleForRemoval() ) } /** * The sections from the cursor's selection start to the selection end * @type {Section[]} */ get activeSections() { return this._editState.activeSections } get activeSection() { const { activeSections } = this return activeSections[activeSections.length - 1] } get activeSectionAttributes() { return this._editState.activeSectionAttributes } detectMarkupInRange(range: Range, markupTagName: string) { let markups = this.post.markupsInRange(range) return detect(markups, markup => { return markup.hasTag(markupTagName) }) } /** * @type {Markup[]} * @public */ get activeMarkups() { return this._editState.activeMarkups } /** * @param {Markup|String} markup A markup instance, or a string (e.g. "b") * @return {boolean} */ hasActiveMarkup(markup: Markup | string): boolean { let matchesFn: (markup: Markup) => boolean if (typeof markup === 'string') { let tagName = normalizeTagName(markup) matchesFn = m => m.tagName === tagName } else { matchesFn = m => m === markup } return !!detect(this.activeMarkups, matchesFn) } /** * @param {String} version The mobiledoc version to serialize to. * @return {Mobiledoc} Serialized mobiledoc * @public */ serialize(version: MobiledocVersion = MOBILEDOC_VERSION): Mobiledoc { return this.serializePost(this.post, Format.MOBILEDOC, { version }) } /** * Serialize the editor's post to the requested format. * Note that only mobiledoc format is lossless. If cards or atoms are present * in the post, the html and text formats will omit them in output because * the editor does not have access to the html and text versions of the * cards/atoms. * @param {string} format The format to serialize ('mobiledoc', 'text', 'html') * @return {Object|String} The editor's post, serialized to {format} * @public */ serializeTo(format: Format.MOBILEDOC): Mobiledoc serializeTo(format: Format.TEXT | Format.HTML): string serializeTo(format: Format): Mobiledoc | string { let post = this.post return this.serializePost(post, format) } /** * @param {Post} * @param {String} format Same as {serializeTo} * @param {Object} [options] * @param {String} [options.version=MOBILEDOC_VERSION] version to serialize to * @return {Object|String} * @private */ serializePost(post: Post, format: Format.MOBILEDOC, options?: SerializeOptions): Mobiledoc serializePost(post: Post, format: Format.TEXT | Format.HTML, options?: SerializeOptions): string serializePost(post: Post, format: Format, options?: SerializeOptions): string | Mobiledoc serializePost(post: Post, format: Format, options: SerializeOptions = {}): string | Mobiledoc { assert(`Unrecognized serialization format ${format}`, contains(Object.values(Format), format)) if (format === Format.MOBILEDOC) { let version: MobiledocVersion = options.version || MOBILEDOC_VERSION return mobiledocRenderers.render(post, version) } else { let mobiledoc = this.serializePost(post, Format.MOBILEDOC) let unknownCardHandler = () => {} let unknownAtomHandler = () => {} let rendererOptions = { unknownCardHandler, unknownAtomHandler } switch (format) { case Format.HTML: { if (Environment.hasDOM()) { const rendered = new DOMRenderer(rendererOptions).render(mobiledoc) return `<div>${serializeHTML(rendered.result)}</div>` } else { // Fallback to text serialization return this.serializePost(post, Format.TEXT, options) } } case Format.TEXT: { let rendered = new TextRenderer(rendererOptions).render(mobiledoc) return rendered.result } } } } addView(view: View) { this._views.push(view) } removeAllViews() { this._views.forEach(v => v.destroy()) this._views = [] } /** * Whether the editor has a cursor (or a selected range). * It is possible for the editor to be focused but not have a selection. * In this case, key events will fire but the editor will not be able to * determine a cursor position, so they will be ignored. * @return {boolean} * @public */ hasCursor(): boolean { return this.cursor.hasCursor() } /** * Tears down the editor's attached event listeners and views. * @public */ destroy() { this.isDestroyed = true if (this._hasSelection()) { this.cursor.clearSelection() } if (this._hasFocus()) { this.element.blur() // FIXME This doesn't blur the element on IE11 } this._mutationHandler.destroy() this._eventManager.destroy() this.removeAllViews() this._renderer.destroy() this._editState.destroy() } /** * Keep the user from directly editing the post using the keyboard and mouse. * Modification via the programmatic API is still permitted. * @see Editor#enableEditing * @public */ disableEditing() { this.isEditable = false if (this.hasRendered) { this._eventManager.stop() this.element.setAttribute('contentEditable', 'false') this.setPlaceholder('') this.selectRange(Range.blankRange()) } } /** * Allow the user to directly interact with editing a post via keyboard and mouse input. * Editor instances are editable by default. Use this method to re-enable * editing after disabling it. * @see Editor#disableEditing * @public */ enableEditing() { this.isEditable = true if (this.hasRendered) { this._eventManager.start() this.element.setAttribute('contentEditable', 'true') this.setPlaceholder(this.placeholder) } } /** * Change a cardSection into edit mode * If called before the card has been rendered, it will be marked so that * it is rendered in edit mode when it gets rendered. * @param {CardSection} cardSection * @public */ editCard(cardSection: Card) { this._setCardMode(cardSection, CardMode.EDIT) } /** * Change a cardSection into display mode * If called before the card has been rendered, it will be marked so that * it is rendered in display mode when it gets rendered. * @param {CardSection} cardSection * @return undefined * @public */ displayCard(cardSection: Card) { this._setCardMode(cardSection, CardMode.DISPLAY) } /** * Run a new post editing session. Yields a block with a new {@link PostEditor} * instance. This instance can be used to interact with the post abstract. * Rendering will be deferred until after the callback is completed. * * Usage: * ``` * let markerRange = this.range; * editor.run((postEditor) => { * postEditor.deleteRange(markerRange); * // editing surface not updated yet * postEditor.schedule(() => { * console.log('logs during rerender flush'); * }); * // logging not yet flushed * }); * // editing surface now updated. * // logging now flushed * ``` * * @param {Function} callback Called with an instance of * {@link PostEditor} as its argument. * @return {Mixed} The return value of `callback`. * @public */ run<T>(callback: (postEditor: PostEditor) => T): T { const postEditor = new PostEditor(this) postEditor.begin() this._editHistory.snapshot() const result = callback(postEditor) this.runCallbacks(CALLBACK_QUEUES.DID_UPDATE, [postEditor]) postEditor.complete() this._readRangeFromDOM() if (postEditor._shouldCancelSnapshot) { this._editHistory._pendingSnapshot = null } this._editHistory.storeSnapshot(postEditor.editActionTaken) return result } /** * @param {Function} callback Called with `postEditor` as its argument. * @public */ didUpdatePost(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.DID_UPDATE, callback) } /** * @param {Function} callback Called when the post has changed, either via * user input or programmatically. Use with {@link Editor#serialize} to * retrieve the post in portable mobiledoc format. */ postDidChange(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.POST_DID_CHANGE, callback) } /** * Register a handler that will be invoked by the editor after the user enters * matching text. * @param {Object} inputHandler * @param {String} inputHandler.name Required. Used by identifying handlers. * @param {String} [inputHandler.text] Required if `match` is not provided * @param {RegExp} [inputHandler.match] Required if `text` is not provided * @param {Function} inputHandler.run This callback is invoked with the {@link Editor} * instance and an array of matches. If `text` was provided, * the matches array will equal [`text`], and if a `match` * regex was provided the matches array will be the result of * `match.exec` on the matching text. The callback is called * after the matching text has been inserted. * @public */ onTextInput(inputHandler: TextInputHandlerListener) { this._eventManager.registerInputHandler(inputHandler) } /** * Unregister all text input handlers * * @public */ unregisterAllTextInputHandlers() { this._eventManager.unregisterAllTextInputHandlers() } /** * Unregister text input handler by name * @param {String} name The name of handler to be removed * * @public */ unregisterTextInputHandler(name: string) { this._eventManager.unregisterInputHandler(name) } /** * @param {Function} callback Called when the editor's state (active markups or * active sections) has changed, either via user input or programmatically */ inputModeDidChange(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.INPUT_MODE_DID_CHANGE, callback) } /** * @param {Function} callback This callback will be called before the editor * is rendered. * @public */ willRender(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.WILL_RENDER, callback) } /** * @param {Function} callback This callback will be called after the editor * is rendered. * @public */ didRender(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.DID_RENDER, callback) } willCopy(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.WILL_COPY, callback) } /** * @param {Function} callback This callback will be called before deleting. * @public */ willDelete(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.WILL_DELETE, callback) } /** * @param {Function} callback This callback will be called after deleting. * @public */ didDelete(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.DID_DELETE, callback) } /** * @param {Function} callback This callback will be called before handling new line. * @public */ willHandleNewline(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.WILL_HANDLE_NEWLINE, callback) } /** * @param {Function} callback This callback will be called every time the cursor * position (or selection) changes. * @public */ cursorDidChange(callback: LifecycleCallback) { this.addCallback(CALLBACK_QUEUES.CURSOR_DID_CHANGE, callback) } _rangeDidChange() { if (this.hasRendered) { this.runCallbacks(CALLBACK_QUEUES.CURSOR_DID_CHANGE) } } _inputModeDidChange() { this.runCallbacks(CALLBACK_QUEUES.INPUT_MODE_DID_CHANGE) } _insertEmptyMarkupSectionAtCursor() { this.run(postEditor => { const section = postEditor.builder.createMarkupSection('p') postEditor.insertSectionBefore(this.post.sections, section) postEditor.setRange(section.toRange()) }) } /** * @callback editorBeforeCallback * @param { Object } details * @param { Markup } details.markup * @param { Range } details.range * @param { boolean } details.willAdd Whether the markup will be applied */ /** * Register a callback that will be run before {@link Editor#toggleMarkup} is applied. * If any callback returns literal `false`, the toggling of markup will be canceled. * Note this only applies to calling `editor#toggleMarkup`. Using `editor.run` and * modifying markup with the `postEditor` will skip any `beforeToggleMarkup` callbacks. * @param {editorBeforeCallback} */ beforeToggleMarkup(callback: LifecycleCallback) { this._beforeHooks.toggleMarkup.push(callback) } /** * Toggles the given markup at the editor's current {@link Range}. * If the range is collapsed this changes the editor's state so that the * next characters typed will be affected. If there is text selected * (aka a non-collapsed range), the selections' markup will be toggled. * If the editor is not focused and has no active range, nothing happens. * Hooks added using #beforeToggleMarkup will be run before toggling, * and if any of them returns literal false, toggling the markup will be canceled * and no change will be applied. * @param {String} markup E.g. "b", "em", "a" * @param {Object} [attributes={}] E.g. {href: "http://bustle.com"} * @public * @see PostEditor#toggleMarkup */ toggleMarkup(markupTag: string, attributes: Dict<string> = {}) { const markup = this.builder.createMarkup(markupTag, attributes) const { range } = this const willAdd = !this.detectMarkupInRange(range, markup.tagName) const shouldCancel = this._runBeforeHooks('toggleMarkup', { markup, range, willAdd }) if (shouldCancel) { return } if (range.isCollapsed) { this._editState.toggleMarkupState(markup) this._inputModeDidChange() // when clicking a button to toggle markup, the button can end up being focused, // so ensure the editor is focused this._ensureFocus() } else { this.run(postEditor => postEditor.toggleMarkup(markup, range)) } } // If the editor has a selection but is not focused, focus it _ensureFocus() { if (this._hasSelection() && !this._hasFocus()) { this.focus() } } focus() { this.element.focus() } /** * Whether there is a selection inside the editor's element. * It's possible to have a selection but not have focus. * @see #_hasFocus * @return {Boolean} */ _hasSelection(): boolean { const { cursor } = this return this.hasRendered && (cursor._hasCollapsedSelection() || cursor._hasSelection()) } /** * Whether the editor's element is focused * It's possible to be focused but have no selection * @see #_hasSelection * @return {Boolean} */ _hasFocus(): boolean { return document.activeElement === this.element } /** * Toggles the tagName for the current active section(s). This will skip * non-markerable sections. E.g. if the editor's range includes a "P" MarkupSection * and a CardSection, only the MarkupSection will be toggled. * @param {String} tagName The new tagname to change to. * @public * @see PostEditor#toggleSection */ toggleSection(tagName: string) { this.run(postEditor => postEditor.toggleSection(tagName, this.range)) } /** * Sets an attribute for the current active section(s). * * @param {String} key The attribute. The only valid attribute is 'text-align'. * @param {String} value The value of the attribute. * @public * @see PostEditor#setAttribute */ setAttribute(key: string, value: string) { this.run(postEditor => postEditor.setAttribute(key, value, this.range)) } /** * Removes an attribute from the current active section(s). * * @param {String} key The attribute. The only valid attribute is 'text-align'. * @public * @see PostEditor#removeAttribute */ removeAttribute(key: string) { this.run(postEditor => postEditor.removeAttribute(key, this.range)) } /** * Finds and runs the first matching key command for the event * * If multiple commands are bound to a key combination, the * first matching one is run. * * If a command returns `false` then the next matching command * is run instead. * * @param {Event} event The keyboard event triggered by the user * @return {Boolean} true when a command was successfully run * @private */ handleKeyCommand(event: KeyboardEvent): boolean { const keyCommands = findKeyCommands(this.keyCommands, event) for (let i = 0; i < keyCommands.length; i++) { let keyCommand = keyCommands[i] if (keyCommand.run(this) !== false) { event.preventDefault() return true } } return false } /** * Inserts the text at the current cursor position. If the editor has * no current cursor position, nothing will be inserted. If the editor's * range is not collapsed, it will be deleted before insertion. * * @param {String} text * @public */ insertText(text: string) { if (!this.hasCursor()) { return } if (this.post.isBlank) { this._insertEmptyMarkupSectionAtCursor() } let { activeMarkups, range, range: { head: position }, } = this this.run(postEditor => { if (!range.isCollapsed) { position = postEditor.deleteRange(range) } postEditor.insertTextWithMarkup(position, text, activeMarkups) }) } /** * Inserts an atom at the current cursor position. If the editor has * no current cursor position, nothing will be inserted. If the editor's * range is not collapsed, it will be deleted before insertion. * @param {String} atomName * @param {String} [atomText=''] * @param {Object} [atomPayload={}] * @return {Atom} The inserted atom. * @public */ insertAtom(atomName: string, atomText: string = '', atomPayload: AtomPayload = {}): Maybe<Atom> { if (!this.hasCursor()) { return } if (this.post.isBlank) { this._insertEmptyMarkupSectionAtCursor() } let atom: Atom let { range } = this this.run(postEditor => { let position = range.head atom = postEditor.builder.createAtom(atomName, atomText, atomPayload) if (!range.isCollapsed) { position = postEditor.deleteRange(range) } postEditor.insertMarkers(position, [atom]) }) return atom! } /** * Inserts a card at the section after the current cursor position. If the editor has * no current cursor position, nothing will be inserted. If the editor's * range is not collapsed, it will be deleted before insertion. If the cursor is in * a blank section, it will be replaced with a card section. * The editor's cursor will be placed at the end of the inserted card. * @param {String} cardName * @param {Object} [cardPayload={}] * @param {Boolean} [inEditMode=false] Whether the card should be inserted in edit mode. * @return {Card} The inserted Card section. * @public */ insertCard(cardName: string, cardPayload: CardPayload = {}, inEditMode: boolean = false): Maybe<Card> { if (!this.hasCursor()) { return } if (this.post.isBlank) { this._insertEmptyMarkupSectionAtCursor() } let card: Card let { range } = this this.run(postEditor => { let position = range.tail card = postEditor.builder.createCardSection(cardName, cardPayload) if (inEditMode) { this.editCard(card) } if (!range.isCollapsed) { position = postEditor.deleteRange(range) } let section = position.section! if (isNested(section)) { section = section.parent } if (section.isBlank) { postEditor.replaceSection(section, card) } else { let collection = this.post.sections postEditor.insertSectionBefore(collection, card, section.next) } // It is important to explicitly set the range to the end of the card. // Otherwise it is possible to create an inconsistent state in the // browser. For instance, if the user clicked a button that // called `editor.insertCard`, the editor surface may retain // the selection but lose focus, and the next keystroke by the user // will cause an unexpected DOM mutation (which can wipe out the // card). // See: https://github.com/bustle/mobiledoc-kit/issues/286 postEditor.setRange(card.tailPosition()) }) return card! } /** * @param {integer} x x-position in viewport * @param {integer} y y-position in viewport * @return {Position|null} */ positionAtPoint(x: number, y: number): Position | null { return Position.atPoint(x, y, this) } /** * @private */ _setCardMode(cardSection: Card, mode: CardMode) { const renderNode = cardSection.renderNode if (renderNode && renderNode.isRendered) { const cardNode = renderNode.cardNode! cardNode[mode]() } else { cardSection.setInitialMode(mode) } } triggerEvent(context: HTMLElement, eventName: DOMEventType, event: DOMEventForType<typeof eventName>) { this._eventManager._trigger(context, eventName, event) } addCallback(queueName: string, callback: LifecycleCallback) { this._callbacks.addCallback(queueName, callback) } addCallbackOnce(queueName: string, callback: LifecycleCallback) { this._callbacks.addCallbackOnce(queueName, callback) } runCallbacks(queueName: string, args?: unknown[]) { if (this.isDestroyed) { // TODO warn that callback attempted after editor was destroyed return } this._callbacks.runCallbacks(queueName, args) } /** * Runs each callback for the given hookName. * Only the hookName 'toggleMarkup' is currently supported * @return {Boolean} shouldCancel Whether the action in `hookName` should be canceled * @private */ _runBeforeHooks(hookName: keyof BeforeHooks, ...args: unknown[]): true | undefined { let hooks = this._beforeHooks[hookName] || [] for (let i = 0; i < hooks.length; i++) { if (hooks[i](...args) === false) { return true } } } }
the_stack
import {exec} from 'child_process'; import {promisify} from 'util'; import {EnvironmentInfo, getEnvInfo} from './environmentInfo'; export {EnvironmentInfo, getEnvInfo} from './environmentInfo'; import * as watchman from 'fb-watchman'; import * as fs from 'fs'; import * as path from 'path'; export type HealthcheckCategory = { label: string; isSkipped: false; isRequired: boolean; healthchecks: Healthcheck[]; }; export type SkippedHealthcheckCategory = { label: string; isSkipped: true; skipReason: string; }; export type Healthchecks = { common: HealthcheckCategory | SkippedHealthcheckCategory; android: HealthcheckCategory | SkippedHealthcheckCategory; ios: HealthcheckCategory | SkippedHealthcheckCategory; }; export type Settings = { idbPath: string; enablePhysicalIOS: boolean; }; export type Healthcheck = { key: string; label: string; isRequired?: boolean; run: ( env: EnvironmentInfo, settings?: Settings, ) => Promise<HealthcheckRunResult>; }; export type HealthcheckRunResult = { hasProblem: boolean; message: string; }; export type CategoryResult = [ string, { label: string; results: Array<{ key: string; label: string; isRequired: boolean; result: {hasProblem: boolean}; }>; }, ]; export function getHealthchecks(): Healthchecks { return { common: { label: 'Common', isRequired: true, isSkipped: false, healthchecks: [ { key: 'common.openssl', label: 'OpenSSL Installed', run: async (_: EnvironmentInfo) => { const result = await tryExecuteCommand('openssl version'); const hasProblem = result.hasProblem; const message = hasProblem ? `OpenSSL (https://wiki.openssl.org/index.php/Binaries) is not installed or not added to PATH. ${result.message}.` : `OpenSSL (https://wiki.openssl.org/index.php/Binaries) is installed and added to PATH. ${result.message}.`; return { hasProblem, message, }; }, }, { key: 'common.watchman', label: 'Watchman Installed', run: async (_: EnvironmentInfo) => { const isAvailable = await isWatchmanAvailable(); return { hasProblem: !isAvailable, message: isAvailable ? 'Watchman file watching service (https://facebook.github.io/watchman/) is installed and added to PATH. Live reloading after changes during Flipper plugin development is enabled.' : 'Watchman file watching service (https://facebook.github.io/watchman/) is not installed or not added to PATH. Live reloading after changes during Flipper plugin development is disabled.', }; }, }, ], }, android: { label: 'Android', isRequired: false, isSkipped: false, healthchecks: [ { key: 'android.sdk', label: 'SDK Installed', isRequired: true, run: async (_: EnvironmentInfo) => { const androidHome = process.env.ANDROID_HOME; const androidSdkRoot = process.env.ANDROID_SDK_ROOT; let androidHomeResult: HealthcheckRunResult; if (!androidHome) { androidHomeResult = { hasProblem: true, message: `ANDROID_HOME is not defined. You can use Flipper Settings (File > Preferences) to point to its location.`, }; } else if (!fs.existsSync(androidHome)) { androidHomeResult = { hasProblem: true, message: `ANDROID_HOME point to a folder which does not exist: ${androidHome}. You can use Flipper Settings (File > Preferences) to point to a different location.`, }; } else { const platformToolsDir = path.join(androidHome, 'platform-tools'); if (!fs.existsSync(platformToolsDir)) { androidHomeResult = { hasProblem: true, message: `Android SDK Platform Tools not found at the expected location "${platformToolsDir}". Probably they are not installed.`, }; } else { androidHomeResult = await tryExecuteCommand( `"${path.join(platformToolsDir, 'adb')}" version`, ); } } if (androidHomeResult.hasProblem == false) { return androidHomeResult; } let androidSdkRootResult: HealthcheckRunResult; if (!androidSdkRoot) { androidSdkRootResult = { hasProblem: true, message: `ANDROID_SDK_ROOT is not defined. You can use Flipper Settings (File > Preferences) to point to its location.`, }; } else if (!fs.existsSync(androidSdkRoot)) { androidSdkRootResult = { hasProblem: true, message: `ANDROID_SDK_ROOT point to a folder which does not exist: ${androidSdkRoot}. You can use Flipper Settings (File > Preferences) to point to a different location.`, }; } else { const platformToolsDir = path.join( androidSdkRoot, 'platform-tools', ); if (!fs.existsSync(platformToolsDir)) { androidSdkRootResult = { hasProblem: true, message: `Android SDK Platform Tools not found at the expected location "${platformToolsDir}". Probably they are not installed.`, }; } else { androidSdkRootResult = await tryExecuteCommand( `"${path.join(platformToolsDir, 'adb')}" version`, ); } } return androidSdkRootResult; }, }, ], }, ios: { label: 'iOS', ...(process.platform === 'darwin' ? { isRequired: false, isSkipped: false, healthchecks: [ { key: 'ios.sdk', label: 'SDK Installed', isRequired: true, run: async (e: EnvironmentInfo) => { const hasProblem = !e.SDKs['iOS SDK'] || !e.SDKs['iOS SDK'].Platforms || !e.SDKs['iOS SDK'].Platforms.length; const message = hasProblem ? 'iOS SDK is not installed. You can install it using Xcode (https://developer.apple.com/xcode/).' : `iOS SDK is installed for the following platforms: ${JSON.stringify( e.SDKs['iOS SDK'].Platforms, )}.`; return { hasProblem, message, }; }, }, { key: 'ios.xcode', label: 'XCode Installed', isRequired: true, run: async (e: EnvironmentInfo) => { const hasProblem = e.IDEs == null || e.IDEs.Xcode == null; const message = hasProblem ? 'Xcode (https://developer.apple.com/xcode/) is not installed.' : `Xcode version ${e.IDEs.Xcode.version} is installed at "${e.IDEs.Xcode.path}".`; return { hasProblem, message, }; }, }, { key: 'ios.xcode-select', label: 'xcode-select set', isRequired: true, run: async (_: EnvironmentInfo) => { const result = await tryExecuteCommand('xcode-select -p'); const hasProblem = result.hasProblem; const message = hasProblem ? `Xcode version is not selected. You can select it using command "sudo xcode-select -switch <path/to/>Xcode.app". ${result.message}.` : `Xcode version is selected. ${result.message}.`; return { hasProblem, message, }; }, }, { key: 'ios.xctrace', label: 'xctrace exists', isRequired: true, run: async (_: EnvironmentInfo) => { const result = await tryExecuteCommand( 'xcrun xctrace version', ); const hasProblem = result.hasProblem; const message = hasProblem ? `xctrace is not available. Please ensure you have Xcode installed and are running a recent version (https://developer.apple.com/xcode/). ${result.message}.` : `xctrace is available. ${result.message}.`; return { hasProblem, message, }; }, }, { key: 'ios.idb', label: 'IDB installed', isRequired: false, run: async ( _: EnvironmentInfo, settings?: {enablePhysicalIOS: boolean; idbPath: string}, ) => { if (!settings) { return { hasProblem: false, message: 'Not enough context to check IDB installation. Needs to be run through Flipper UI.', }; } if (!settings.enablePhysicalIOS) { return { hasProblem: false, message: 'Using physical iOS devices is disabled in settings. So IDB is not required.', }; } const result = await tryExecuteCommand( `${settings?.idbPath} --help`, ); const hasProblem = result.hasProblem; const message = hasProblem ? `IDB is required to use Flipper with iOS devices. It can be installed from https://github.com/facebook/idb and configured in Flipper settings. You can also disable physical iOS device support in settings. Current setting: ${settings.idbPath} isn't a valid IDB installation.` : 'Flipper is configured to use your IDB installation.'; return { hasProblem, message, }; }, }, ], } : { isSkipped: true, skipReason: `Healthcheck is skipped, because iOS development is not supported on the current platform "${process.platform}".`, }), }, }; } export async function runHealthchecks(): Promise< Array<CategoryResult | SkippedHealthcheckCategory> > { const environmentInfo = await getEnvInfo(); const healthchecks: Healthchecks = getHealthchecks(); const results: Array<CategoryResult | SkippedHealthcheckCategory> = await Promise.all( Object.entries(healthchecks).map(async ([key, category]) => { if (category.isSkipped) { return category; } const categoryResult: CategoryResult = [ key, { label: category.label, results: await Promise.all( category.healthchecks.map( async ({key, label, run, isRequired}) => ({ key, label, isRequired: isRequired ?? true, result: await run(environmentInfo).catch((e) => { console.warn( `Health check ${key}/${label} failed with:`, e, ); // TODO Improve result type to be: OK | Problem(message, fix...) return { hasProblem: true, }; }), }), ), ), }, ]; return categoryResult; }), ); return results; } async function tryExecuteCommand( command: string, ): Promise<HealthcheckRunResult> { try { const output = await promisify(exec)(command); return { hasProblem: false, message: `Command "${command}" successfully executed with output: ${output.stdout}`, }; } catch (err) { return { hasProblem: true, message: `Command "${command}" failed to execute with output: ${err.message}`, }; } } async function isWatchmanAvailable(): Promise<boolean> { const client = new watchman.Client(); return new Promise((resolve) => { const complete = (result: boolean) => { resolve(result); client.removeAllListeners('error'); client.end(); }; client.once('error', () => complete(false)); client.capabilityCheck( {optional: [], required: ['relative_root']}, (error) => { if (error) { complete(false); return; } complete(true); }, ); }); }
the_stack
import { Rule, SchematicContext, Tree, chain, externalSchematic, noop } from '@angular-devkit/schematics'; import { NodePackageInstallTask, RunSchematicTask } from '@angular-devkit/schematics/tasks'; import { hasPackage, getSourceTreePath } from '../utils/package-utils'; import { addPackageJsonDependency, NodeDependency, NodeDependencyType } from '@schematics/angular/utility/dependencies'; import { writeToAngularConfig, createExtractionFiles, replaceLibPaths, addLocalizeLib, callLocalizeSchematic } from '../utils/translation-utils'; import { supportedLanguages } from '../utils/supported-languages'; /** * ng add schematic that * - adds Core and Platform lib and their dependencies to package.json * - adds `ng add @fundamental-ngx/core` external schematic to task list * - adds `@angular/localize` to package.json * - adds `ng add @angular/localize` external schematic to task list * - adds lib translations and angular.json locale configurations to host app if no translations available * - updates lib translations to host app's translations if available by appending at the end of host app's files * - replaces lib source paths with node_modules source paths for lib-related trans units * - installs dependent libraries and runs their external schematics * @param _options options passed for this schematic */ export function ngAdd(_options: any): Rule { return (_tree: Tree, _context: SchematicContext) => { return chain([ addCoreLib(_options), addLocalizeLib(_options), readTranslationFiles(_options), _options.installations ? callCoreSchematic(_options) : noop(), _options.installations ? callLocalizeSchematic(_options) : noop(), endInstallTask() ]); }; } /** * installs `@fundamental-ngx/core` lib and makes call to core's schematic * @param options options passed for this schematic */ export function callCoreSchematic(options: any): Rule { return (_tree: Tree, context: SchematicContext) => { context.logger.info('Adding Fundamental NGX Core schematic to tasks'); const installTaskId = context.addTask( new NodePackageInstallTask({ packageName: '@fundamental-ngx/core' }) ); // Chain won't work here since we need the externals to be actually installed before we call their schemas // This ensures the externals are a dependency of the node install, so they exist when their schemas run. context.addTask(new RunSchematicTask('addCoreSchematic', options), [installTaskId]); return _tree; }; } /** * runs the core library's ng-add schematic * @param options options passed for this schematic */ export function addCoreSchematic(options: any): Rule { return (_tree: Tree, _context: SchematicContext) => { _context.logger.info('Running core schematics...\n'); return chain([externalSchematic('@fundamental-ngx/core', 'ng-add', options)]); }; } /** * adds the latest versions of core and platform libraries to package.json * @param _options options passed for this schematic */ function addCoreLib(_options: any): Rule { return (tree: Tree, context: SchematicContext) => { context.logger.info('***** Adding Platform dependencies to your application *****'); const dependencies: NodeDependency[] = []; if (!hasPackage(tree, '@fundamental-ngx/core')) { dependencies.push({ type: NodeDependencyType.Default, version: `latest`, name: '@fundamental-ngx/core' }); } dependencies.forEach((dependency) => { addPackageJsonDependency(tree, dependency); console.log(`✅️ Added ${dependency.name} to ${dependency.type} to your application`); }); return tree; }; } /** * adds/updates translations to host app if host app opts to have translations added to their app * @param options options passed for this schematic */ export function readTranslationFiles(options: any): any { return async (_tree: Tree, _context: SchematicContext) => { const translationPromise = new Promise<Tree>((resolve, reject) => { if (options.translations) { try { const angularJsonFile = _tree.read('angular.json'); if (angularJsonFile) { const angularJsonFileObject = JSON.parse(angularJsonFile.toString('utf-8')); const project = options.project ? options.project : Object.keys(angularJsonFileObject['projects'])[0]; // set default project path if (!options.project) { options.name = project; } const projectObject = angularJsonFileObject.projects[project]; // todo get the languages supported from platform, and fetch from a separate file probably const languages = supportedLanguages; let availableLanguages = 0; languages.forEach((language) => { if (projectObject.architect.build.configurations[language]) { availableLanguages++; } }); languages.forEach(async (language) => { if (availableLanguages === 0 || languages.length > availableLanguages) { if (!projectObject.architect.build.configurations[language]) { _context.logger.info( 'Adding translations for language "' + language + '" from ngx/platform to ' + project ); // not present, add the language settings to serve and build configurations in angular.json await writeToAngularConfig(_tree, options, angularJsonFileObject, language); // create the extraction .xlf files from the platform lib and place in host app's locale folder await createExtractionFiles(_tree, options, language); } } else { const languageObject = projectObject.architect.build.configurations[language].i18nFile; const hostAppXlfContent = _tree.read(languageObject.toString()); if (hostAppXlfContent) { // merge the extraction .xlf files from the platform lib into the host app's files await updateExtractionFiles(_tree, options, hostAppXlfContent, language); } } resolve(_tree); }); } else { reject('error in promise'); } } catch (e) { _context.logger.log('info', e + '\n🚫 Failed to add translations correctly.'); } } }); _tree = await translationPromise; return _tree; }; } /** * Merges the extraction .xlf files from the platform lib into the host app's files * @param tree the file tree * @param options options passed for this schematic * @param fileContent the host applications language .xlf file * @param language the language for which translations from lib will be applied to */ async function updateExtractionFiles(tree: Tree, options: any, fileContent: any, language: string): Promise<Tree> { const srcPath = await getSourceTreePath(tree, options); const libXlfFileContent = tree.read( 'node_modules/@fundamental-ngx/platform/schematics/locale/' + language + '/messages.' + language + '.xlf' ); if (libXlfFileContent) { const builder = new (require('xml2js').Builder)(); let finalXlfContent: any; require('xml2js').parseString(libXlfFileContent.toString(), function (err: any, libFile: any): void { if (err) { console.log(err); } // replace lib paths with node_modules paths const modifiedLibFile = replaceLibPaths(libFile); if (fileContent) { // don't simply overwrite, merge here with existing file // add the transUnits from lib to this file require('xml2js').parseString(fileContent.toString(), function (error: any, hostFile: any): void { if (error) { console.log(error); } // compare the host file with the lib file to check if host file already has some lib trans-units // and append these trans units only if it is not already existing modifiedLibFile.xliff.file[0].body[0]['trans-unit'].forEach((libTransUnit: any) => { // append trans-unit only if not found let matchFound = false; hostFile.xliff.file[0].body[0]['trans-unit'].forEach((transUnit: any) => { if (transUnit['$'].id === libTransUnit['$'].id) { // lib trans unit already present in host file, don't add it matchFound = true; } }); // if not found, add this trans unit to host file if (!matchFound) { hostFile.xliff.file[0].body[0]['trans-unit'][ hostFile.xliff.file[0].body[0]['trans-unit'].length ] = libTransUnit; } }); // write modified file as xml object finalXlfContent = builder.buildObject(hostFile); }); try { tree.overwrite(srcPath + '/locale/' + language + '/messages.' + language + '.xlf', finalXlfContent); } catch (e) { console.log(e + '\n🚫 There was a problem writing to file. '); } } }); } return tree; } /** * Runs npm install. Called as the last rule. */ function endInstallTask(): Rule { return (tree: Tree, context: SchematicContext) => { context.addTask(new NodePackageInstallTask()); return tree; }; }
the_stack
import { bkHttpRequest } from '@/common/js/ajax'; import { HttpRequestParams } from '@/controller/common'; import { IDataModelManage } from '../Interface/index'; import { ICalculationAtomsCanBeQuoted, ICreateIndexParams, IFieldTypeListRes, ISqlFuncs, } from '../Interface/indexDesign'; const moduleName = 'dataModelManage'; /** * * @param methodName * @param requestParams * @param queryParams * @param exts */ const bkHttp = (methodName: string, requestParams = {}, queryParams = {}, ext = {}): Promise<IBKResponse<any>> => { return bkHttpRequest( `${moduleName}/${methodName}`, new HttpRequestParams(requestParams, queryParams, false, true, ext) ); }; /** * 获取数据模型列表 * @param query IDataModelManageQuery.IModelListQuery */ export const getModelList = ( query: IDataModelManageQuery.IModelListQuery = {} ): Promise<IBKResponse<IDataModelManage.IModelList[]>> => { return bkHttp('getModelList', {}, query); }; /** * 模型置顶 * @param model_id 模型ID * @param description 置顶描述 */ export const topModel = (model_id: string, description?: string): Promise<IBKResponse<boolean>> => { return bkHttp('topModel', { model_id, description }, {}); }; /** * 取消模型置顶 * @param model_id 模型ID * @param description 置顶描述 */ export const cancelTop = (model_id: string, description?: string): Promise<IBKResponse<boolean>> => { return bkHttp('cancelTop', { model_id, description }, {}); }; /** * 数据模型详情 * @param model_id 模型ID * @param with_details 展示模型主表字段、模型关联关系、统计口径、指标等详情, 取值['master_table', 'calculation_atoms', 'indicators'] * @param ext 其他配置 */ export const getModelInfo = (model_id: string, with_details?: string[], ext = {}): Promise<IBKResponse<any>> => { return bkHttp('getModelInfo', { model_id }, { with_details }, ext); }; /** * 修改数据模型 * @param model_id 模型ID * @param model_alias 模型别名 * @param description 模型描述 * @param tag_codes 标签 */ export const updateModel = (model_id: string, model_alias?: string, description?: string, tags?: object[]) => { return bkHttp('updateModel', { model_id, model_alias, description, tags }, {}); }; /** * 删除数据模型 * @param model_id 模型ID */ export const deleteModel = (model_id: string) => { return bkHttp('deleteModel', { model_id }, {}); }; /** * 创建数据模型 * @param model_name 模型名称 * @param model_alias 模型别名 * @param model_type 模型类型 * @param project_id 项目id * @param description 模型描述 * @param tag_codes 标签 */ export const createModel = ( model_name: string, model_alias: string, model_type: string, project_id: number, description: string, tags: object[] ) => { return bkHttp('createModel', { model_name, model_alias, description, tags, model_type, project_id }, {}); }; /** * 拉取主表详情 * @param model_id 模型id * @param with_time_field 是否带有time字段 * @param allow_field_type 允许的字段类型 string | array * @param with_details 返回结果是否带有可删除/删除信息 */ export const getMasterTableInfo = ( model_id: string, with_time_field = false, allow_field_type?: string | Array<string>, with_details?: Array<string>, latest_version?: boolean ): Promise<IBKResponse<IDataModelManage.IMasterTableInfo>> => { return bkHttp( 'getMasterTableInfo', { model_id }, { with_time_field, allow_field_type, with_details, latest_version }, { format: true } ); }; /** * 修改主表 * @param model_id 模型id * @param fields 模型主表字段列表 * @param model_relation 模型主表关联信息 */ export const updateMasterTableInfo = ( model_id: string, fields: IDataModelManage.IMasterTableField[], model_relation: IModelRelation[] = [] ): Promise<IBKResponse<any>> => { return bkHttp('updateMasterTableInfo', { model_id, fields, model_relation }, {}); }; /** * 数据模型字段加工校验 * @param table_name 表名称 * @param verify_fields 需要执行校验的列表语句 * @param scope_field_list 语句执行背景依赖表 */ export const verifyFieldProcessingLogic = (table_name: string, verify_fields: [], scope_field_list: []) => { return bkHttp('verifyFieldProcessingLogic', { table_name, verify_fields, scope_field_list }, {}); }; /** 字段约束配置列表 */ export const getFieldContraintConfigs = (): Promise<IBKResponse<IDataModelManage.IFieldContraintConfig[]>> => { return bkHttp('getFieldContraintConfigs', {}, {}, { format: true }); }; /** 判断数据模型名称是否存在 */ export const validateModelName = (model_name: string): Promise<IBKResponse<any>> => { return bkHttp('validateModelName', {}, { model_name }); }; /** * 统计口径列表 * @param model_id 模型id * @param with_indicators 是否返回指标信息,默认不返回 */ export const getCalculationAtoms = ( model_id?: string | number, with_indicators?: boolean ): Promise<IBKResponse<any[]>> => { return bkHttpRequest( 'dataModelManage/getCalculationAtoms', new HttpRequestParams({}, { model_id, with_indicators }, false, true, {}) ); }; /** * 可以被引用的统计口径列表 * @param model_id 模型id */ export const getCalculationAtomsCanBeQuoted = ( model_id?: string | number ): Promise<IBKResponse<ICalculationAtomsCanBeQuoted>> => { return bkHttpRequest( 'dataModelManage/getCalculationAtomsCanBeQuoted', new HttpRequestParams({}, { model_id }, false, true, {}) ); }; /** * 创建统计口径 * @param model_id 模型id * @param calculation_atom_name 统计口径名称 * @param calculation_atom_alias 统计口径别名 * @param description 统计口径描述 * @param field_type 数据类型 * @param calculation_content 统计方式 */ export const createCalculationAtom = ( model_id: string | number, field_type: string, description: string, calculation_atom_name: string, calculation_atom_alias: string, calculation_content: object ): Promise<IBKResponse<any[]>> => { return bkHttpRequest( 'dataModelManage/createCalculationAtom', new HttpRequestParams( { model_id, calculation_atom_name, calculation_atom_alias, description, field_type, calculation_content }, {}, false, true, {} ) ); }; /** * 修改统计口径 * @param model_id 模型id * @param calculation_atom_alias 统计口径别名 * @param description 统计口径描述 * @param field_type 数据类型 * @param calculation_content 统计方式 */ export const editCalculationAtom = ( model_id: string | number, field_type: string, description: string, calculation_atom_name: string, calculation_atom_alias: string, calculation_content: object ): Promise<IBKResponse<any[]>> => { return bkHttpRequest( 'dataModelManage/editCalculationAtom', new HttpRequestParams( { model_id, field_type, description, calculation_atom_name, calculation_atom_alias, calculation_content }, {}, false, true, {} ) ); }; /** * 统计口径详情 * @param calculation_atom_name 统计口径名称 * @param with_indicators 是否返回指标信息,默认不返回 */ export const calculationAtomDetail = ( calculation_atom_name: string, with_indicators?: boolean ): Promise<IBKResponse<any[]>> => { return bkHttpRequest( 'dataModelManage/calculationAtomDetail', new HttpRequestParams({ calculation_atom_name }, { with_indicators }, false, true, {}) ); }; /** * 删除统计口径 * @param calculation_atom_name 统计口径名称 * @param model_id 模型id */ export const deleteCalculationAtom = ( calculation_atom_name: string, model_id: string | number ): Promise<IBKResponse<any[]>> => { return bkHttpRequest( 'dataModelManage/deleteCalculationAtom', new HttpRequestParams({ calculation_atom_name, model_id }, {}, false, true, {}) ); }; /** * 引用集市统计口径 * @param model_id 模型id * @param calculation_atom_names 引用的统计口径名称列表 */ export const quoteCalculationAtom = ( model_id: string | number, calculation_atom_names: string[] ): Promise<IBKResponse<any[]>> => { return bkHttpRequest( 'dataModelManage/quoteCalculationAtom', new HttpRequestParams({ model_id, calculation_atom_names }, {}, false, true, {}) ); }; /** * SQL统计函数列表 * @param function_name 模型id * @param output_type 输出字段类型 */ export const sqlFuncs = (function_name?: string | number, output_type?: string): Promise<IBKResponse<ISqlFuncs[]>> => { return bkHttpRequest( 'dataModelManage/sqlFuncs', new HttpRequestParams({}, { function_name, output_type }, false, true, {}) ); }; /** * 指标列表 * @param calculation_atom_name 统计口径名称 * @param model_id 模型id * @param parent_indicator_name 父指标名称 * @param indicator_name 指标名称 * @param with_sub_indicators 是否显示子指标 */ export const getIndicatorList = ( calculation_atom_name?: string, model_id?: string | number, parent_indicator_name?: string, indicator_name?: string, with_sub_indicators?: boolean ): Promise<IBKResponse<ISqlFuncs[]>> => { return bkHttpRequest( 'dataModelManage/getIndicatorList', new HttpRequestParams( {}, { calculation_atom_name, model_id, parent_indicator_name, indicator_name, with_sub_indicators }, false, true, {} ) ); }; /** * 删除指标 * @param indicator_name 指标名称 */ export const deleteIndicator = (indicator_name: string, model_id: number): Promise<IBKResponse<ISqlFuncs[]>> => { return bkHttpRequest( 'dataModelManage/deleteIndicator', new HttpRequestParams({ indicator_name, model_id }, {}, false, true, {}) ); }; /** * 创建指标 * @param model_id 模型id * @param indicator_name 指标名称 * @param indicator_alias 指标别名 * @param description 指标描述 * @param calculation_atom_name 统计口径名称 * @param aggregation_fields 聚合字段 * @param filter_formula 过滤SQL * @param scheduling_content 调度内容 * @param parent_indicator_name 父指标名称 */ export const createIndicator = (params: ICreateIndexParams): Promise<IBKResponse<ISqlFuncs[]>> => { return bkHttpRequest('dataModelManage/createIndicator', new HttpRequestParams(params, {}, false, true, {})); }; /** * 修改指标 * @param indicator_alias 指标别名 * @param description 指标描述 * @param calculation_atom_name 统计口径名称 * @param aggregation_fields 聚合字段 * @param filter_formula 过滤SQL * @param scheduling_content 调度内容 */ export const editIndicator = (params: ICreateIndexParams): Promise<IBKResponse<ISqlFuncs[]>> => { return bkHttpRequest('dataModelManage/editIndicator', new HttpRequestParams(params, {}, false, true, {})); }; /** * 获取指标详情 * @param indicator_name 指标名称 * @param with_sub_indicators 是否显示子指标 */ export const getIndicatorDetail = ( indicator_name: string, with_sub_indicators?: boolean, model_id?: string | number ): Promise<IBKResponse<any[]>> => { return bkHttpRequest( 'dataModelManage/getIndicatorDetail', new HttpRequestParams( { indicator_name, with_sub_indicators, }, { model_id, }, false, true, {} ) ); }; /** * 拉取数据类型列表 * @param exclude_field_type string | Array */ export const getFieldTypeConfig = ( exclude_field_type: string | Array<string> ): Promise<IBKResponse<IFieldTypeListRes>> => { return bkHttp('getFieldTypeConfig', {}, { exclude_field_type }); }; /** * 结果数据表结构预览 * @param rt_id */ export const getResultTablesFields = (rt_id: string | number): Promise<IBKResponse<any>> => { return bkHttp('getResultTablesFields', { rt_id }, {}); }; /** * 获取模型预览数据 * @param model_id */ export const getModelOverview = (model_id: string, latest_version: boolean | undefined): Promise<IBKResponse<any>> => { return bkHttp('getModelOverview', { model_id }, { latest_version }); }; /** * 确认模型预览 * @param model_id */ export const confirmModelOverview = (model_id: string): Promise<IBKResponse<any>> => { return bkHttp('confirmModelOverview', { model_id }, {}); }; /** * 确认模型指标 * @param model_id */ export const confirmModelIndicators = (model_id: string): Promise<IBKResponse<any>> => { return bkHttp('confirmModelIndicators', { model_id }, {}); }; /** * 获取数据模型变更内容 * @param model_id */ export const getModelVersionDiff = ( model_id: string | number, orig_version_id: string | undefined | null, new_version_id: string | undefined, ext = {} ): Promise<IBKResponse<any>> => { return bkHttp( 'getModelVersionDiff', { model_id }, { orig_version_id, new_version_id }, Object.assign({ format: true }, ext) ); }; /** * 数据模型发布 * @param model_id */ export const releaseModelVersion = (model_id: string, version_log: string): Promise<IBKResponse<any>> => { return bkHttp('releaseModelVersion', { model_id, version_log }, {}); }; /** * 获取可被关联的维度表模型 * @param model_id */ export const getDimensionModelsCanBeRelated = ( model_id: string, related_model_id: string | undefined, published: boolean | undefined ): Promise<IBKResponse<any>> => { return bkHttp('getDimensionModelsCanBeRelated', { model_id }, { related_model_id, published }); }; /** * 数据模型操作记录 * @param model_id * @param conditions 搜索条件参数,object_operation操作类型,object_type操作对象类型,created_by操作者, 操作对象待定 * @param start_time 启始时间 * @param end_time 终止时间 * @param page 页码 * @param page_size 每页条数 */ export const operationRecords = ( model_id: number, page: string | number, page_size: string | number, conditions?: object, start_time?: string, end_time?: string, order_by_created_at?: string ): Promise<IBKResponse<any>> => { return bkHttp( 'operationRecords', { model_id, page, page_size, conditions, start_time, end_time, order_by_created_at }, {}, { format: true } ); }; /** * 操作者列表 * @param model_id */ export const getOperators = (model_id: number): Promise<IBKResponse<any>> => { return bkHttp('getOperators', { model_id }, {}, { format: true }); }; /** * 数据模型操作前后diff * @param model_id * @param operation_id */ export const getOperationDiff = ( model_id: number, operation_id: string | number, ext = {} ): Promise<IBKResponse<any>> => { return bkHttp('getOperationDiff', { model_id, operation_id }, {}, Object.assign({ format: true }, ext)); }; /** * 获取模型查看态数据 * @param model_id */ export const getModelViewData = (model_id: number, with_details?: string, ext = {}): Promise<IBKResponse<any>> => { return bkHttp('getModelViewData', { model_id }, { with_details }, Object.assign({ format: true }, ext)); }; /** * 获取版本列表 * @param model_id */ export const getReleaseList = (model_id: number, ext = {}): Promise<IBKResponse<any>> => { return bkHttp('getReleaseList', { model_id }, {}, Object.assign({ format: true }, ext)); }; /** * 获取指标字段信息 * @param indicator_name */ export const getIndicatorFields = (indicator_name: number, model_id: number, ext = {}): Promise<IBKResponse<any>> => { return bkHttp('getIndicatorFields', { indicator_name }, { model_id }, Object.assign({ format: true }, ext)); };
the_stack
import * as React from 'react'; import { WorkloadOverview } from '../../types/ServiceInfo'; import Rules, { MOVE_TYPE, Rule } from './RequestRouting/Rules'; import RuleBuilder from './RequestRouting/RuleBuilder'; import { ANYTHING, EXACT, HEADERS, PRESENCE, REGEX } from './RequestRouting/MatchBuilder'; import { MSG_WEIGHTS_NOT_VALID, WorkloadWeight } from './TrafficShifting'; import { getDefaultWeights } from './WizardActions'; import { FaultInjectionRoute } from './FaultInjection'; import { TimeoutRetryRoute } from './RequestTimeouts'; type Props = { serviceName: string; workloads: WorkloadOverview[]; initRules: Rule[]; onChange: (valid: boolean, rules: Rule[]) => void; }; type State = { category: string; operator: string; workloadWeights: WorkloadWeight[]; matches: string[]; headerName: string; matchValue: string; faultInjectionRoute: FaultInjectionRoute; timeoutRetryRoute: TimeoutRetryRoute; rules: Rule[]; validationMsg: string; }; const MSG_SAME_MATCHING = 'A Rule with same matching criteria is already added.'; const MSG_HEADER_NAME_NON_EMPTY = 'Header name must be non empty'; const MSG_HEADER_VALUE_NON_EMPTY = 'Header value must be non empty'; class RequestRouting extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { category: HEADERS, operator: PRESENCE, workloadWeights: getDefaultWeights(this.props.workloads), faultInjectionRoute: { workloads: [], delayed: false, delay: { percentage: { value: 100 }, fixedDelay: '5s' }, isValidDelay: true, aborted: false, abort: { percentage: { value: 100 }, httpStatus: 503 }, isValidAbort: true }, timeoutRetryRoute: { workloads: [], isTimeout: false, timeout: '2s', isValidTimeout: true, isRetry: false, retries: { attempts: 3, perTryTimeout: '2s', retryOn: 'gateway-error,connect-failure,refused-stream' }, isValidRetry: true }, matches: [], headerName: '', matchValue: '', rules: this.props.initRules, validationMsg: '' }; } isMatchesIncluded = (rules: Rule[], rule: Rule) => { let found = false; for (let i = 0; i < rules.length; i++) { const item = rules[i]; if (item.matches.length !== rule.matches.length) { continue; } found = item.matches.every(value => rule.matches.includes(value)); if (found) { break; } } return found; }; isValid = (rules: Rule[]): boolean => { // Corner case, an empty rules shouldn't be a valid scenario to create a VS/DR if (rules.length === 0) { return false; } const matchAll: number = this.matchAllIndex(rules); let isValid: boolean = true; for (let index = 0; index < this.state.rules.length; index++) { isValid = matchAll === -1 || index <= matchAll; if (!isValid) { return isValid; } } return isValid; }; onAddMatch = () => { this.setState(prevState => { let newMatch: string; if (this.state.matchValue !== '') { newMatch = prevState.category + (prevState.category === HEADERS ? ' [' + prevState.headerName + '] ' : ' ') + prevState.operator + ' ' + prevState.matchValue; } else { newMatch = prevState.category + ' [' + prevState.headerName + '] ' + REGEX + ' ' + ANYTHING; } if (!prevState.matches.includes(newMatch)) { prevState.matches.push(newMatch); } return { matches: prevState.matches, headerName: '', matchValue: '' }; }); }; onAddRule = () => { this.setState( prevState => { const newWorkloadWeights: WorkloadWeight[] = []; prevState.workloadWeights.forEach(ww => newWorkloadWeights.push({ name: ww.name, weight: ww.weight, locked: ww.locked, maxWeight: ww.maxWeight, mirrored: ww.mirrored }) ); const newRule: Rule = { matches: Object.assign([], prevState.matches), workloadWeights: newWorkloadWeights }; if (prevState.faultInjectionRoute.delayed && prevState.faultInjectionRoute.isValidDelay) { newRule.delay = prevState.faultInjectionRoute.delay; } if (prevState.faultInjectionRoute.aborted && prevState.faultInjectionRoute.isValidAbort) { newRule.abort = prevState.faultInjectionRoute.abort; } if (prevState.timeoutRetryRoute.isTimeout && prevState.timeoutRetryRoute.isValidTimeout) { newRule.timeout = prevState.timeoutRetryRoute.timeout; } if (prevState.timeoutRetryRoute.isRetry && prevState.timeoutRetryRoute.isValidRetry) { newRule.retries = prevState.timeoutRetryRoute.retries; } if (!this.isMatchesIncluded(prevState.rules, newRule)) { prevState.rules.push(newRule); return { matches: prevState.matches, headerName: prevState.headerName, matchValue: prevState.matchValue, rules: prevState.rules, validationMsg: '', faultInjectionRoute: prevState.faultInjectionRoute, timeoutRetryRoute: prevState.timeoutRetryRoute }; } else { return { matches: prevState.matches, headerName: prevState.headerName, matchValue: prevState.matchValue, rules: prevState.rules, validationMsg: MSG_SAME_MATCHING, faultInjectionRoute: prevState.faultInjectionRoute, timeoutRetryRoute: prevState.timeoutRetryRoute }; } }, () => this.props.onChange(this.isValid(this.state.rules), this.state.rules) ); }; onRemoveMatch = (matchToRemove: string) => { this.setState(prevState => { return { matches: prevState.matches.filter(m => matchToRemove !== m), validationMsg: prevState.validationMsg === MSG_SAME_MATCHING ? '' : prevState.validationMsg }; }); }; onRemoveRule = (index: number) => { this.setState( prevState => { prevState.rules.splice(index, 1); return { rules: prevState.rules, validationMsg: '' }; }, () => this.props.onChange(this.isValid(this.state.rules), this.state.rules) ); }; onHeaderNameChange = (headerName: string) => { let validationMsg = ''; if (this.state.matchValue !== '' && headerName === '') { validationMsg = MSG_HEADER_NAME_NON_EMPTY; } if (this.state.matchValue === '' && headerName !== '' && this.state.operator !== PRESENCE) { validationMsg = MSG_HEADER_VALUE_NON_EMPTY; } this.setState({ headerName: headerName, validationMsg: validationMsg }); }; onMatchValueChange = (matchValue: string) => { let validationMsg = ''; if (this.state.category === HEADERS) { if (this.state.headerName === '' && matchValue !== '') { validationMsg = MSG_HEADER_NAME_NON_EMPTY; } if (this.state.headerName !== '' && matchValue === '') { validationMsg = MSG_HEADER_VALUE_NON_EMPTY; } } if (matchValue === '') { validationMsg = ''; } this.setState({ matchValue: matchValue, validationMsg: validationMsg }); }; onSelectWeights = (valid: boolean, workloads: WorkloadWeight[]) => { this.setState({ workloadWeights: workloads, validationMsg: !valid ? MSG_WEIGHTS_NOT_VALID : '' }); }; onMoveRule = (index: number, move: MOVE_TYPE) => { this.setState( prevState => { const sourceRule = prevState.rules[index]; const targetIndex = move === MOVE_TYPE.UP ? index - 1 : index + 1; const targetRule = prevState.rules[targetIndex]; prevState.rules[targetIndex] = sourceRule; prevState.rules[index] = targetRule; return { rules: prevState.rules }; }, () => this.props.onChange(this.isValid(this.state.rules), this.state.rules) ); }; matchAllIndex = (rules: Rule[]): number => { let matchAll: number = -1; for (let index = 0; index < rules.length; index++) { const rule = rules[index]; if (rule.matches.length === 0) { matchAll = index; break; } } return matchAll; }; componentDidMount() { if (this.props.initRules.length > 0) { this.setState( { rules: this.props.initRules }, () => this.props.onChange(this.isValid(this.state.rules), this.state.rules) ); } } render() { return ( <> <RuleBuilder category={this.state.category} operator={this.state.operator} headerName={this.state.headerName} matchValue={this.state.matchValue} isValid={this.state.validationMsg === ''} onSelectCategory={(category: string) => { this.setState(prevState => { // PRESENCE operator only applies to HEADERS return { category: category, operator: prevState.operator === PRESENCE && category !== HEADERS ? EXACT : prevState.operator }; }); }} onHeaderNameChange={this.onHeaderNameChange} onSelectOperator={(operator: string) => this.setState({ operator: operator })} onMatchValueChange={this.onMatchValueChange} onAddMatch={this.onAddMatch} matches={this.state.matches} onRemoveMatch={this.onRemoveMatch} workloads={this.props.workloads} weights={this.state.workloadWeights} onSelectWeights={this.onSelectWeights} faultInjectionRoute={this.state.faultInjectionRoute} onSelectFaultInjection={(valid, faultInjectionRoute) => { this.setState(_prevState => { return { faultInjectionRoute: faultInjectionRoute, validationMsg: !valid ? 'Fault Injection not valid' : '' }; }); }} timeoutRetryRoute={this.state.timeoutRetryRoute} onSelectTimeoutRetry={(valid, timeoutRetryRoute) => { this.setState(_prevState => { return { timeoutRetryRoute: timeoutRetryRoute, validationMsg: !valid ? 'Request Timeout not valid' : '' }; }); }} validationMsg={this.state.validationMsg} onAddRule={this.onAddRule} /> <Rules rules={this.state.rules} onRemoveRule={this.onRemoveRule} onMoveRule={this.onMoveRule} /> </> ); } } export default RequestRouting;
the_stack
import * as React from 'react'; import { resetIds } from '../../Utilities'; import { fireEvent, render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Slider } from './Slider'; import { isConformant } from '../../common/isConformant'; import type { ISlider } from './Slider.types'; const MIN_PREFIX = 'min'; const MAX_PREFIX = 'max'; const DOWN = 'arrowdown'; const UP = 'arrowup'; describe('Slider', () => { beforeEach(() => { resetIds(); }); afterEach(() => { if ((setTimeout as any).mock) { jest.useRealTimers(); } }); isConformant({ Component: Slider, displayName: 'Slider', }); it('renders correctly', () => { const { container } = render(<Slider label="I am a slider" />); expect(container).toMatchSnapshot(); }); it('renders range slider correctly', () => { const { container } = render(<Slider label="I am a ranged slider" ranged defaultValue={5} />); expect(container).toMatchSnapshot(); }); it('can set aria-labelledby attribute', () => { const { getByRole } = render(<Slider aria-labelledby="custom-label" />); expect(getByRole('slider').getAttribute('aria-labelledby')).toBe('custom-label'); }); it('can provide the current value', () => { const slider = React.createRef<ISlider>(); render(<Slider defaultValue={12} min={0} max={100} componentRef={slider} />); expect(slider.current?.value).toEqual(12); }); it('can provide the current range', () => { const slider = React.createRef<ISlider>(); render(<Slider defaultValue={12} min={0} max={100} componentRef={slider} ranged />); expect(slider.current?.range).toEqual([0, 12]); }); it('can set id', () => { const { container, getByRole } = render(<Slider id="test_id" styles={{ titleLabel: 'test_label' }} />); expect(getByRole('slider').id).toEqual('test_id'); // properly associates label with custom id const label = container.getElementsByClassName('test_label')[0]; expect(label.getAttribute('for')).toBe('test_id'); }); it('can set id via buttonProps', () => { // Not the recommended way of doing things, but it should work consistently still const { container, getByRole } = render( <Slider buttonProps={{ id: 'test_id' }} styles={{ titleLabel: 'test_label' }} />, ); expect(getByRole('slider').id).toEqual('test_id'); // properly associates label with custom id const label = container.getElementsByClassName('test_label')[0]; expect(label.getAttribute('for')).toBe('test_id'); }); it('handles zero default value', () => { const slider = React.createRef<ISlider>(); render(<Slider defaultValue={0} min={-100} max={100} componentRef={slider} />); expect(slider.current!.value).toEqual(0); }); it('handles zero value', () => { const slider = React.createRef<ISlider>(); render(<Slider value={0} min={-100} max={100} componentRef={slider} />); expect(slider.current!.value).toEqual(0); }); it('calls onChange and onChanged when slider value changes with mouse', () => { const onChange = jest.fn(); const onChanged = jest.fn(); const slider = React.createRef<ISlider>(); const { container, getByRole } = render( <Slider onChange={onChange} defaultValue={5} onChanged={onChanged} componentRef={slider} />, ); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = getByRole('slider'); sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 0, clientY: 0 }); // Default min is 0. expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][0]).toEqual(0); expect(onChanged).toHaveBeenCalledTimes(0); // not called yet expect(slider.current!.value).toBe(0); // have to use a real event to trigger onChanged fireEvent.mouseUp(sliderThumb); expect(onChange).toHaveBeenCalledTimes(1); // not called again expect(onChanged).toHaveBeenCalledTimes(1); expect(onChanged.mock.calls[0][1]).toEqual(0); }); it('calls onChange and onChanged when range slider range changes with mouse', () => { const onChange = jest.fn(); const onChanged = jest.fn(); const slider = React.createRef<ISlider>(); const { container } = render( <Slider onChange={onChange} onChanged={onChanged} defaultValue={5} ranged componentRef={slider} />, ); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = container.getElementsByClassName('ms-Slider-slideBox')[0]; sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 0, clientY: 0 }); // Default min is 0. expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][1]).toEqual([0, 5]); expect(onChanged).toHaveBeenCalledTimes(0); expect(slider.current!.range).toEqual([0, 5]); fireEvent.mouseUp(sliderThumb); expect(onChange).toHaveBeenCalledTimes(1); expect(onChanged).toHaveBeenCalledTimes(1); expect(onChanged.mock.calls[0][2]).toEqual([0, 5]); }); it('does not call onChange or onChanged with range when ranged is false', () => { const onChange = jest.fn(); const onChanged = jest.fn(); const { container } = render(<Slider onChange={onChange} onChanged={onChanged} defaultValue={5} />); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = container.getElementsByClassName('ms-Slider-slideBox')[0]; sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 0, clientY: 0 }); expect(onChange.mock.calls[0][1]).toBeUndefined(); fireEvent.mouseUp(sliderThumb); expect(onChanged.mock.calls[0][2]).toBeUndefined(); }); it('can slide to default min/max and execute onChange', () => { const onChange = jest.fn(); const { container } = render(<Slider onChange={onChange} />); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = container.getElementsByClassName('ms-Slider-slideBox')[0]; sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 100, clientY: 0 }); // Default max is 10. expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][0]).toEqual(10); fireEvent.mouseDown(sliderThumb, { clientX: 0, clientY: 0 }); // Default min is 0. expect(onChange).toHaveBeenCalledTimes(2); expect(onChange.mock.calls[1][0]).toEqual(0); }); it('updates the upper value thumb when click to the right side of it', () => { const onChange = jest.fn(); const { container } = render(<Slider onChange={onChange} ranged defaultValue={5} />); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = container.getElementsByClassName('ms-Slider-slideBox')[0]; sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 80, clientY: 0 }); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][1]).toEqual([0, 8]); }); it('updates the upper value thumb when click close to it', () => { const onChange = jest.fn(); const { container } = render(<Slider onChange={onChange} ranged defaultValue={5} />); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = container.getElementsByClassName('ms-Slider-slideBox')[0]; sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 40, clientY: 0 }); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][1]).toEqual([0, 4]); }); it('updates the lower value thumb when click close to it', () => { const onChange = jest.fn(); const onChanged = jest.fn(); const { container } = render(<Slider onChange={onChange} onChanged={onChanged} ranged defaultValue={5} />); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = container.getElementsByClassName('ms-Slider-slideBox')[0]; sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 10, clientY: 0 }); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][1]).toEqual([1, 5]); // test onChanged here too, since the earlier tests don't cover the lower thumb fireEvent.mouseUp(sliderThumb); expect(onChanged).toHaveBeenCalledTimes(1); expect(onChanged.mock.calls[0][2]).toEqual([1, 5]); }); it('updates the lower value thumb when click to the left of it', () => { let range; const onChange = (val: number, sliderRange: [number, number]) => { range = sliderRange; }; const { container } = render(<Slider onChange={onChange} ranged defaultValue={5} />); const sliderLine = container.getElementsByClassName('ms-Slider-line')[0]; const sliderThumb = container.getElementsByClassName('ms-Slider-slideBox')[0]; sliderLine.getBoundingClientRect = () => ({ left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 } as DOMRect); fireEvent.mouseDown(sliderThumb, { clientX: 10, clientY: 0 }); fireEvent.mouseDown(sliderThumb, { clientX: 20, clientY: 0 }); expect(range).toEqual([2, 5]); }); it('renders correct aria-valuetext', () => { const { getByRole, rerender } = render(<Slider value={0} />); expect(getByRole('slider').getAttribute('aria-valuetext')).toEqual('0'); const values = ['small', 'medium', 'large']; const selected = 1; const getTextValue = (value: number) => values[value]; rerender(<Slider value={selected} ariaValueText={getTextValue} />); expect(getByRole('slider').getAttribute('aria-valuetext')).toEqual(values[selected]); }); it('renders correct aria properties for range slider', () => { const { getAllByRole } = render(<Slider ranged defaultValue={5} aria-label={'range'} />); const lowerValueThumb = getAllByRole('slider')[0]; expect(lowerValueThumb.getAttribute('aria-valuemax')).toEqual('5'); expect(lowerValueThumb.getAttribute('aria-valuemin')).toEqual('0'); expect(lowerValueThumb.getAttribute('aria-valuenow')).toEqual('0'); expect(lowerValueThumb.getAttribute('aria-label')).toEqual(`${MIN_PREFIX} range`); const upperValueThumb = getAllByRole('slider')[1]; expect(upperValueThumb.getAttribute('aria-valuemax')).toEqual('10'); expect(upperValueThumb.getAttribute('aria-valuemin')).toEqual('0'); expect(upperValueThumb.getAttribute('aria-valuenow')).toEqual('5'); expect(upperValueThumb.getAttribute('aria-label')).toEqual(`${MAX_PREFIX} range`); }); it('formats the value when a format function is passed', () => { const value = 10; const valueFormat = (val: number) => `${val}%`; const { container } = render(<Slider value={value} min={0} max={100} showValue={true} valueFormat={valueFormat} />); expect(container.getElementsByClassName('ms-Slider-value')[0].textContent).toEqual(valueFormat(value)); }); it('updates value of upperthumb for range slider correctly when down and up are pressed', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); render( <Slider label="slider" componentRef={slider} defaultValue={12} min={0} max={100} onChange={onChange} ranged />, ); // move keyboard focus to upperthumb of slider userEvent.tab({ shift: true }); //press up and down keys to modify slider value userEvent.keyboard(`{${DOWN}}{${DOWN}}{${DOWN}}{${UP}}{${DOWN}}`); expect(slider.current?.value).toEqual(9); expect(onChange).toHaveBeenCalledTimes(5); }); it('updates value of upperthumb for range slider correctly when down and up are pressed', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); render( <Slider label="slider" componentRef={slider} defaultValue={20} min={12} max={100} onChange={onChange} ranged />, ); // move keyboard focus to upperthumb of slider userEvent.tab({ shift: true }); userEvent.keyboard(`{${DOWN}}{${DOWN}}{${DOWN}}{${UP}}{${DOWN}}`); expect(slider.current?.value).toEqual(17); expect(onChange).toHaveBeenCalledTimes(5); }); it('calls onChanged after keyboard event', () => { jest.useFakeTimers(); const onChanged = jest.fn(); const { container } = render(<Slider label="slider" defaultValue={12} min={0} max={100} onChanged={onChanged} />); const sliderSlideBox = container.getElementsByClassName('ms-Slider-slideBox')[0]; userEvent.tab(); userEvent.keyboard(`{${DOWN}}{${DOWN}}{${DOWN}}{${UP}}{${DOWN}}`); expect(sliderSlideBox.getAttribute('aria-valuenow')).toEqual('9'); // onChanged should only be called after a delay expect(onChanged).toHaveBeenCalledTimes(0); jest.runOnlyPendingTimers(); expect(onChanged).toHaveBeenCalledTimes(1); }); it('onChanged returns the correct value', () => { jest.useFakeTimers(); const onChanged = jest.fn(); render(<Slider label="slider" defaultValue={5} min={0} max={100} onChanged={onChanged} />); userEvent.tab(); userEvent.keyboard(`{${DOWN}}{${DOWN}}{${DOWN}}{${UP}}{${DOWN}}`); // onChanged should only be called after a delay expect(onChanged).toHaveBeenCalledTimes(0); jest.runOnlyPendingTimers(); expect(onChanged).toHaveBeenCalledTimes(1); expect(onChanged.mock.calls[0][1]).toEqual(2); }); it('does not update the value when slider is controlled', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); render(<Slider label="slider" componentRef={slider} value={3} min={0} max={100} onChange={onChange} />); userEvent.tab(); userEvent.keyboard(`{${DOWN}}`); expect(slider.current?.value).toEqual(3); expect(onChange).toHaveBeenCalledTimes(1); }); it('calls onChange with correct value when controlled', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); render(<Slider label="slider" componentRef={slider} value={3} min={0} max={100} onChange={onChange} />); userEvent.tab(); userEvent.keyboard(`{${DOWN}}`); expect(slider.current?.value).toEqual(3); // Get the first argument passed into the call expect(onChange.mock.calls[0][0]).toEqual(2); }); it('calls onChange with correct range when controlled', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); render(<Slider label="slider" componentRef={slider} value={3} min={0} max={100} onChange={onChange} ranged />); // move keyboard focus to upperthumb of slider userEvent.tab({ shift: true }); userEvent.keyboard(`{${DOWN}}`); expect(slider.current?.range).toEqual([0, 3]); // Get the second argument passed into the call expect(onChange.mock.calls[0][1]).toEqual([0, 2]); }); it('calls onChange on multiple calls with correct value when controlled', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); render(<Slider label="slider" componentRef={slider} value={3} min={0} max={100} onChange={onChange} />); userEvent.tab(); userEvent.keyboard(`{${UP}}{${UP}}{${UP}}`); expect(slider.current?.value).toEqual(3); // Get the first argument passed into the third call expect(onChange.mock.calls[2][0]).toEqual(4); }); it('correctly changes value with negative steps', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); render( <Slider label="slider" defaultValue={10} componentRef={slider} step={-3} min={0} max={100} onChange={onChange} />, ); userEvent.tab(); userEvent.keyboard(`{${UP}}`); expect(slider.current?.value).toEqual(7); }); it('correctly changes value with decimal steps', () => { const slider = React.createRef<ISlider>(); const onChange = jest.fn(); const step = 0.0000001; const defaultValue = 10; render( <Slider label="slider" defaultValue={defaultValue} componentRef={slider} step={step} min={0} max={100} onChange={onChange} />, ); userEvent.tab(); userEvent.keyboard(`{${UP}}`); expect(slider.current?.value).toEqual(defaultValue + step); }); });
the_stack
export const EXCHANGE_BUILD_NUMBER_TO_CPE = { // Converts Microsoft Exchange short build numbers (which are detected by wappalyzer) to their corresponding CPEs. // Taken from: https://docs.microsoft.com/en-us/exchange/new-features/build-numbers-and-release-dates?view=exchserver-2019 '15.2.792.3': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_8', '15.2.721.2': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_7', '15.2.659.4': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_6', '15.2.595.3': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_5', '15.2.529.5': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_4', '15.2.464.5': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_3', '15.2.397.3': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_2', '15.2.330.5': 'cpe:/a:microsoft:exchange_server:2019:cumulative_update_1', '15.2.221.12': 'cpe:/a:microsoft:exchange_server:2019:-', '15.2.196.0': 'cpe:/a:microsoft:exchange_server:2019:-', '15.1.2176.2': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_19', '15.1.2106.2': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_18', '15.1.2044.4': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_17', '15.1.1979.3': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_16', '15.1.1913.5': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_15', '15.1.1847.3': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_14', '15.1.1779.2': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_13', '15.1.1713.5': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_12', '15.1.1591.10': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_11', '15.1.1531.3': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_10', '15.1.1466.3': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_9', '15.1.1415.2': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_8', '15.1.1261.35': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_7', '15.1.1034.26': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_6', '15.1.845.34': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_5', '15.1.669.32': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_4', '15.1.544.27': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_3', '15.1.466.34': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_2', '15.1.396.30': 'cpe:/a:microsoft:exchange_server:2016:cumulative_update_1', '15.1.225.42': 'cpe:/a:microsoft:exchange_server:2016:-', '15.1.225.16': 'cpe:/a:microsoft:exchange_server:2016:-', '15.0.1497.2': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_23', '15.0.1473.3': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_22', '15.0.1395.4': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_21', '15.0.1367.3': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_20', '15.0.1365.1': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_19', '15.0.1347.2': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_18', '15.0.1320.4': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_17', '15.0.1293.2': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_16', '15.0.1263.5': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_15', '15.0.1236.3': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_14', '15.0.1210.3': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_13', '15.0.1178.4': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_12', '15.0.1156.6': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_11', '15.0.1130.7': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_10', '15.0.1104.5': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_9', '15.0.1076.9': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_8', '15.0.1044.25': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_7', '15.0.995.29': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_6', '15.0.913.22': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_5', '15.0.847.32': 'cpe:/a:microsoft:exchange_server:2013:sp1', '15.0.775.38': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_3', '15.0.712.24': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_2', '15.0.620.29': 'cpe:/a:microsoft:exchange_server:2013:cumulative_update_1', '15.0.516.32': 'cpe:/a:microsoft:exchange_server:2013:rtm', '14.3.509.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_31', '14.3.496.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_30', '14.3.468.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_29', '14.3.461.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_28', '14.3.452.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_27', '14.3.442.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_26', '14.3.435.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_25', '14.3.419.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_24', '14.3.417.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_23', '14.3.411.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_22', '14.3.399.2': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_21', '14.3.389.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_20', '14.3.382.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_19', '14.3.361.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_18', '14.3.352.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_17', '14.3.336.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_16', '14.3.319.2': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_15', '14.3.301.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_14', '14.3.294.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_13', '14.3.279.2': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_12', '14.3.266.2': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_11', '14.3.248.2': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_10', '14.3.235.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_9', '14.3.224.2': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_8', '14.3.224.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_8', '14.3.210.2': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_7', '14.3.195.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_6', '14.3.181.6': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_5', '14.3.174.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_4', '14.3.169.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_3', '14.3.158.1': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_2', '14.3.146.0': 'cpe:/a:microsoft:exchange_server:2010:sp3_rollup_1', '14.3.123.4': 'cpe:/a:microsoft:exchange_server:2010:sp3', '14.2.390.3': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.375.0': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.342.3': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.328.10': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.3.328.5': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.318.4': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.318.2': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.309.2': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.298.4': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.283.3': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.2.247.5': 'cpe:/a:microsoft:exchange_server:2010:sp2', '14.1.438.0': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.421.3': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.421.2': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.421.0': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.355.2': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.339.1': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.323.6': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.289.7': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.270.1': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.255.2': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.1.218.15': 'cpe:/a:microsoft:exchange_server:2010:sp1', '14.0.726.0': 'cpe:/a:microsoft:exchange_server:2010:-', '14.0.702.1': 'cpe:/a:microsoft:exchange_server:2010:-', '14.0.694.0': 'cpe:/a:microsoft:exchange_server:2010:-', '14.0.689.0': 'cpe:/a:microsoft:exchange_server:2010:-', '14.0.682.1': 'cpe:/a:microsoft:exchange_server:2010:-', '14.0.639.21': 'cpe:/a:microsoft:exchange_server:2010:-', '8.3.517.0': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.502.0': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.485.1': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.468.0': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.459.0': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.445.0': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.417.1': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.406.0': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.389.2': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.379.2': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.348.2': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.342.4': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.327.1': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.298.3': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.297.2': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.279.6': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.279.5': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.279.3': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.264.0': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.245.2': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.213.1': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.192.1': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.159.2': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.137.3': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.106.2': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.3.83.6': 'cpe:/a:microsoft:exchange_server:2007:sp3', '8.2.305.3': 'cpe:/a:microsoft:exchange_server:2007:sp2', '8.2.254.0': 'cpe:/a:microsoft:exchange_server:2007:sp2', '8.2.247.2': 'cpe:/a:microsoft:exchange_server:2007:sp2', '8.2.234.1': 'cpe:/a:microsoft:exchange_server:2007:sp2', '8.2.217.3': 'cpe:/a:microsoft:exchange_server:2007:sp2', '8.2.176.2': 'cpe:/a:microsoft:exchange_server:2007:sp2', '8.1.436.0': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.393.1': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.375.2': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.359.2': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.340.1': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.336.1': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.311.3': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.291.2': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.278.2': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.263.1': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.1.240.6': 'cpe:/a:microsoft:exchange_server:2007:sp1', '8.0.813.0': 'cpe:/a:microsoft:exchange_server:2007:-', '8.0.783.2': 'cpe:/a:microsoft:exchange_server:2007:-', '8.0.754.0': 'cpe:/a:microsoft:exchange_server:2007:-', '8.0.744.0': 'cpe:/a:microsoft:exchange_server:2007:-', '8.0.730.1': 'cpe:/a:microsoft:exchange_server:2007:-', '8.0.711.2': 'cpe:/a:microsoft:exchange_server:2007:-', '8.0.708.3': 'cpe:/a:microsoft:exchange_server:2007:-', '8.0.685.25': 'cpe:/a:microsoft:exchange_server:2007:-', '6.5.7654.4': 'cpe:/a:microsoft:exchange_server:2003:sp2', '6.5.7653.33': 'cpe:/a:microsoft:exchange_server:2003:sp2', '6.5.7683': 'cpe:/a:microsoft:exchange_server:2003:sp2', '6.5.7226': 'cpe:/a:microsoft:exchange_server:2003:sp1', '6.5.6944': 'cpe:/a:microsoft:exchange_server:2003', '6.0.6620.7': 'cpe:/a:microsoft:exchange_server:2000:sp3', '6.0.6620.5': 'cpe:/a:microsoft:exchange_server:2000:sp3', '6.0.6603': 'cpe:/a:microsoft:exchange_server:2000:sp3', '6.0.6556': 'cpe:/a:microsoft:exchange_server:2000:sp3', '6.0.6487': 'cpe:/a:microsoft:exchange_server:2000:sp3', '6.0.6249': 'cpe:/a:microsoft:exchange_server:2000:sp3', '6.0.5762': 'cpe:/a:microsoft:exchange_server:2000:sp2', '6.0.4712': 'cpe:/a:microsoft:exchange_server:2000:sp1', '6.0.4417': 'cpe:/a:microsoft:exchange_server:2000:-', '5.5.2653': 'cpe:/a:microsoft:exchange_server:5.5:sp4', '5.5.2650': 'cpe:/a:microsoft:exchange_server:5.5:sp3', '5.5.2448': 'cpe:/a:microsoft:exchange_server:5.5:sp2', '5.5.2232': 'cpe:/a:microsoft:exchange_server:5.5:sp1', '5.5.1960': 'cpe:/a:microsoft:exchange_server:5.5:-', '5.0.1460': 'cpe:/a:microsoft:exchange_server:5.0:sp2', '5.0.1458': 'cpe:/a:microsoft:exchange_server:5.0:sp1', '5.0.1457': 'cpe:/a:microsoft:exchange_server:5.0:-', '4.0.996': 'cpe:/a:microsoft:exchange_server:4.0:sp5', '4.0.995': 'cpe:/a:microsoft:exchange_server:4.0:sp4', '4.0.994': 'cpe:/a:microsoft:exchange_server:4.0:sp3', '4.0.993': 'cpe:/a:microsoft:exchange_server:4.0:sp2', '4.0.838': 'cpe:/a:microsoft:exchange_server:4.0:sp1', '4.0.837': 'cpe:/a:microsoft:exchange_server:4.0:-' };
the_stack
import { Image } from '@nativescript/core/ui/image'; import { StackLayout } from '@nativescript/core/ui/layouts/stack-layout'; import { GridLayout } from '@nativescript/core/ui/layouts/grid-layout'; import { PropertyChangeData } from '@nativescript/core'; import * as utils from '@nativescript/core/utils'; import * as TKUnit from '../../tk-unit'; import { getColor } from '../../ui-helper'; // >> img-require import * as ImageModule from '@nativescript/core/ui/image'; // << img-require import * as types from '@nativescript/core/utils/types'; import { ImageSource } from '@nativescript/core/image-source'; import * as ViewModule from '@nativescript/core/ui/core/view'; import * as helper from '../../ui-helper'; import * as color from '@nativescript/core/color'; import * as backgroundModule from '@nativescript/core/ui/styling/background'; import { android as androidApp } from '@nativescript/core/application'; const imagePath = '~/assets/logo.png'; export function test_recycling() { helper.nativeView_recycling_test(() => new Image()); } if (global.isAndroid) { (<any>backgroundModule).initImageCache(androidApp.startActivity, (<any>backgroundModule).CacheMode.memory); // use memory cache only. } export const test_Image_Members = function () { const image = new ImageModule.Image(); TKUnit.assert(types.isUndefined(image.src), 'Image.src is defined'); TKUnit.assert(types.isDefined(image.isLoading), 'Image.isLoading is not defined'); TKUnit.assert(image.isLoading === false, 'Image.isLoading is default value should be false.'); }; export const test_setting_src_to_resource = function () { // >> img-create const image = new ImageModule.Image(); image.src = 'res://icon'; // << img-create const testFunc = function (views: Array<ViewModule.View>) { TKUnit.waitUntilReady(() => image.isLayoutValid); const width = image.getMeasuredWidth(); const height = image.getMeasuredHeight(); TKUnit.assert(width > 0, 'Width should be greater than 0.'); TKUnit.assert(height > 0, 'Height should be greater than 0.'); }; helper.buildUIAndRunTest(image, testFunc); }; const IMAGE_LOADED_EVENT = 'isLoadingChange'; function runImageTestSync(image: ImageModule.Image, src: string) { image.loadMode = 'sync'; image.src = null; const page = helper.getCurrentPage(); page.content = image; image.src = src; let imageSourceAvailable = global.isIOS ? !!image.imageSource : true; TKUnit.assertFalse(image.isLoading, 'Image.isLoading should be false.'); TKUnit.assertTrue(imageSourceAvailable, 'imageSource should be set.'); } function runImageTestAsync(image: ImageModule.Image, src: string, done: (e: any) => void) { image.loadMode = 'async'; image.src = null; let handler = function (data: PropertyChangeData) { image.off(IMAGE_LOADED_EVENT, handler); try { let imageSourceAvailable = global.isIOS ? !!image.imageSource : true; TKUnit.assertFalse(image.isLoading, 'Image.isLoading should be false.'); TKUnit.assertTrue(imageSourceAvailable, 'imageSource should be set.'); done(null); } catch (e) { done(e); } }; let page = helper.getCurrentPage(); page.content = image; image.src = src; image.on(IMAGE_LOADED_EVENT, handler); TKUnit.assertTrue(image.isLoading, 'Image.isLoading should be true.'); } export const test_SettingImageSrcToURL_async = function (done) { // >> img-create-src const image = new ImageModule.Image(); image.src = 'https://www.google.com/images/errors/logo_sm_2.png'; // << img-create-src (<any>image).useCache = false; runImageTestAsync(image, image.src, done); }; export const test_SettingImageSrcToFileWithinApp_sync = function () { // >> img-create-local const image = new ImageModule.Image(); image.src = '~/assets/logo.png'; // << img-create-local runImageTestSync(image, image.src); }; export const test_SettingImageSrcToFileWithinApp_async = function (done) { const image = new ImageModule.Image(); (<any>image).useCache = false; image.src = '~/assets/logo.png'; runImageTestAsync(image, image.src, done); }; export const test_SettingImageSrcToDataURI_sync = function () { // >> img-create-datauri const image = new ImageModule.Image(); image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAAXNSR0IArs4c6QAAABxpRE9UAAAAAgAAAAAAAAACAAAAKAAAAAIAAAACAAAARiS4uJEAAAASSURBVBgZYvjPwABHSMz/DAAAAAD//0GWpK0AAAAOSURBVGNgYPiPhBgQAACEvQv1D5y/pAAAAABJRU5ErkJggg=='; // << img-create-datauri runImageTestSync(image, image.src); }; export const test_SettingImageSrcToDataURI_async = function (done) { const image = new ImageModule.Image(); image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAAXNSR0IArs4c6QAAABxpRE9UAAAAAgAAAAAAAAACAAAAKAAAAAIAAAACAAAARiS4uJEAAAASSURBVBgZYvjPwABHSMz/DAAAAAD//0GWpK0AAAAOSURBVGNgYPiPhBgQAACEvQv1D5y/pAAAAABJRU5ErkJggg=='; runImageTestAsync(image, image.src, done); }; export const test_SettingImageSrcToFontIconCode_sync = function () { const image = new ImageModule.Image(); image.style.fontFamily = 'FontAwesome'; image.src = 'font://&#xF10B'; runImageTestSync(image, image.src); }; export function test_imageSourceNotResetAfterCreateUI() { let image = new ImageModule.Image(); let imageSource = ImageSource.fromResourceSync('splashscreen'); TKUnit.assertNotEqual(null, imageSource); image.imageSource = imageSource; helper.buildUIAndRunTest(image, () => { TKUnit.waitUntilReady(() => image.isLoaded); TKUnit.assertEqual(image.imageSource, imageSource); }); } // NOTE: This tests that setting multiple times src will not show the imageSource of a previous src value. // It however will never be reliable as to properly detect failure we need to use somewhat large timeout // waiting for imageSource to be set to the wrong value. export const __test_SettingImageSrcTwiceMustNotMismatch = function (done) { const image = new Image(); image.on('propertyChange', (args: PropertyChangeData) => { if (args.propertyName === 'isLoading' && args.value === false) { setTimeout(() => { if (image.imageSource) { done(new Error('Images source set from previous async src setting')); } else { done(); } }, 50); /* Slow! */ } }); image.loadMode = 'async'; image.src = '~/assets/logo.png'; image.src = null; // At somepoint image.imageSource was set to "~/assets/logo.png"; }; export const test_SettingStretch_AspectFit = function () { // There are 4 modes of stretching none, fill, aspectFill, aspectFit // The default value is aspectFit. // Image stretch can be set by using ImageModule.stretch enum. // >> img-set-stretch const image = new ImageModule.Image(); image.stretch = 'aspectFit'; // << img-set-stretch const testFunc = function (views: Array<ViewModule.View>) { if (image.android) { TKUnit.assertEqual(image.android.getScaleType(), android.widget.ImageView.ScaleType.FIT_CENTER); } else if (image.ios) { TKUnit.assertEqual(image.ios.contentMode, UIViewContentMode.ScaleAspectFit); } }; helper.buildUIAndRunTest(image, testFunc); }; export const test_SettingStretch_Default = function () { const image = new ImageModule.Image(); const testFunc = function (views: Array<ViewModule.View>) { if (image.android) { TKUnit.assertEqual(image.android.getScaleType(), android.widget.ImageView.ScaleType.FIT_CENTER); } else if (image.ios) { TKUnit.assertEqual(image.ios.contentMode, UIViewContentMode.ScaleAspectFit); } }; helper.buildUIAndRunTest(image, testFunc); }; export const test_SettingStretch_AspectFill = function () { const image = new ImageModule.Image(); image.stretch = 'aspectFill'; const testFunc = function (views: Array<ViewModule.View>) { if (image.android) { TKUnit.assertEqual(image.android.getScaleType(), android.widget.ImageView.ScaleType.CENTER_CROP); } else if (image.ios) { TKUnit.assertEqual(image.ios.contentMode, UIViewContentMode.ScaleAspectFill); } }; helper.buildUIAndRunTest(image, testFunc); }; export const test_SettingStretch_Fill = function () { const image = new ImageModule.Image(); image.stretch = 'fill'; const testFunc = function (views: Array<ViewModule.View>) { if (image.android) { TKUnit.assertEqual(image.android.getScaleType(), android.widget.ImageView.ScaleType.FIT_XY); } else if (image.ios) { TKUnit.assertEqual(image.ios.contentMode, UIViewContentMode.ScaleToFill); } }; helper.buildUIAndRunTest(image, testFunc); }; export const test_SettingStretch_none = function () { const image = new ImageModule.Image(); image.stretch = 'none'; const testFunc = function (views: Array<ViewModule.View>) { if (image.android) { TKUnit.assertEqual(image.android.getScaleType(), android.widget.ImageView.ScaleType.MATRIX); } else if (image.ios) { TKUnit.assertEqual(image.ios.contentMode, UIViewContentMode.TopLeft); } }; helper.buildUIAndRunTest(image, testFunc); }; function ios<T>(func: T): T { return global.isIOS ? func : undefined; } export const test_SettingImageSourceWhenSizedToParentDoesNotRequestLayout = ios(() => { let host = new GridLayout(); let image = new Image(); host.width = { value: 300, unit: 'dip' }; host.height = { value: 300, unit: 'dip' }; host.addChild(image); let mainPage = helper.getCurrentPage(); mainPage.content = host; TKUnit.waitUntilReady(() => host.isLoaded); let called = false; image.requestLayout = () => (called = true); image.src = '~/assets/logo.png'; TKUnit.assertFalse(called, 'image.requestLayout should not be called.'); }); export const test_SettingImageSourceWhenFixedWidthAndHeightDoesNotRequestLayout = ios(() => { let host = new StackLayout(); let image = new Image(); image.width = { value: 100, unit: 'dip' }; image.height = { value: 100, unit: 'dip' }; host.addChild(image); let mainPage = helper.getCurrentPage(); mainPage.content = host; TKUnit.waitUntilReady(() => host.isLoaded); let called = false; image.requestLayout = () => (called = true); image.src = '~/assets/logo.png'; TKUnit.assertFalse(called, 'image.requestLayout should not be called.'); }); export const test_SettingImageSourceWhenSizedToContentShouldInvalidate = ios(() => { let host = new StackLayout(); let image = new Image(); host.addChild(image); let mainPage = helper.getCurrentPage(); mainPage.content = host; TKUnit.waitUntilReady(() => host.isLoaded); let called = false; image.requestLayout = () => (called = true); image.src = '~/assets/logo.png'; TKUnit.assertTrue(called, 'image.requestLayout should be called.'); }); export const test_DimensionsAreRoundedAfterScale = function () { let host = new StackLayout(); let image = new Image(); (<any>image).useCache = false; image.loadMode = 'sync'; image.src = '~/ui/image/700x50.png'; let imageWidth = 700; let imageHeight = 50; let density = utils.layout.getDisplayDensity(); let hostWidth = 320; host.width = { value: hostWidth / density, unit: 'dip' }; host.height = { value: hostWidth / density, unit: 'dip' }; host.addChild(image); let mainPage = helper.getCurrentPage(); mainPage.content = host; TKUnit.waitUntilReady(() => host.isLayoutValid); let scale = hostWidth / imageWidth; let expectedHeight = Math.round(imageHeight * scale); TKUnit.assertEqual(image.getMeasuredWidth(), hostWidth, 'Actual width is different from expected width.'); TKUnit.assertEqual(image.getMeasuredHeight(), expectedHeight, 'Actual height is different from expected height.'); }; export const test_tintColor = function () { const colorRed = new color.Color('red'); const image = new ImageModule.Image(); image.src = imagePath; const testFunc = function (views: Array<ViewModule.View>) { const testImage = <ImageModule.Image>views[0]; if (image.android) { const tintColor = testImage.android.getColorFilter(); TKUnit.assert(tintColor === null, 'tintColor expected to be set to null'); } else if (image.ios) { const imageColor = getColor(testImage.ios.tintColor); TKUnit.assert(!imageColor.equals(colorRed), 'imageColor expected to be different than tintColor'); } image.tintColor = colorRed; if (image.android) { TKUnit.assert(testImage.android.getColorFilter() !== null, 'tintColor expected to be set to a nonnull value'); } else if (image.ios) { const imageColor = getColor(testImage.ios.tintColor); TKUnit.assert(imageColor.equals(colorRed), 'tintColor expected to be set to: ' + colorRed); } }; helper.buildUIAndRunTest(image, testFunc); };
the_stack
import type { languages } from '../fillers/monaco-editor-core'; export const conf: languages.LanguageConfiguration = { comments: { lineComment: '#' }, brackets: [ ['{', '}'], ['[', ']'], ['(', ')'] ], autoClosingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '"', close: '"' }, { open: "'", close: "'" }, { open: '`', close: '`' } ], surroundingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '"', close: '"' }, { open: "'", close: "'" }, { open: '`', close: '`' } ] }; export const language = <languages.IMonarchLanguage>{ defaultToken: '', tokenPostfix: '.perl', brackets: [ { token: 'delimiter.bracket', open: '{', close: '}' }, { token: 'delimiter.parenthesis', open: '(', close: ')' }, { token: 'delimiter.square', open: '[', close: ']' } ], // https://learn.perl.org/docs/keywords.html // Perl syntax keywords: [ '__DATA__', 'else', 'lock', '__END__', 'elsif', 'lt', '__FILE__', 'eq', '__LINE__', 'exp', 'ne', 'sub', '__PACKAGE__', 'for', 'no', 'and', 'foreach', 'or', 'unless', 'cmp', 'ge', 'package', 'until', 'continue', 'gt', 'while', 'CORE', 'if', 'xor', 'do', 'le', '__DIE__', '__WARN__' ], // Perl functions builtinFunctions: [ '-A', 'END', 'length', 'setpgrp', '-B', 'endgrent', 'link', 'setpriority', '-b', 'endhostent', 'listen', 'setprotoent', '-C', 'endnetent', 'local', 'setpwent', '-c', 'endprotoent', 'localtime', 'setservent', '-d', 'endpwent', 'log', 'setsockopt', '-e', 'endservent', 'lstat', 'shift', '-f', 'eof', 'map', 'shmctl', '-g', 'eval', 'mkdir', 'shmget', '-k', 'exec', 'msgctl', 'shmread', '-l', 'exists', 'msgget', 'shmwrite', '-M', 'exit', 'msgrcv', 'shutdown', '-O', 'fcntl', 'msgsnd', 'sin', '-o', 'fileno', 'my', 'sleep', '-p', 'flock', 'next', 'socket', '-r', 'fork', 'not', 'socketpair', '-R', 'format', 'oct', 'sort', '-S', 'formline', 'open', 'splice', '-s', 'getc', 'opendir', 'split', '-T', 'getgrent', 'ord', 'sprintf', '-t', 'getgrgid', 'our', 'sqrt', '-u', 'getgrnam', 'pack', 'srand', '-w', 'gethostbyaddr', 'pipe', 'stat', '-W', 'gethostbyname', 'pop', 'state', '-X', 'gethostent', 'pos', 'study', '-x', 'getlogin', 'print', 'substr', '-z', 'getnetbyaddr', 'printf', 'symlink', 'abs', 'getnetbyname', 'prototype', 'syscall', 'accept', 'getnetent', 'push', 'sysopen', 'alarm', 'getpeername', 'quotemeta', 'sysread', 'atan2', 'getpgrp', 'rand', 'sysseek', 'AUTOLOAD', 'getppid', 'read', 'system', 'BEGIN', 'getpriority', 'readdir', 'syswrite', 'bind', 'getprotobyname', 'readline', 'tell', 'binmode', 'getprotobynumber', 'readlink', 'telldir', 'bless', 'getprotoent', 'readpipe', 'tie', 'break', 'getpwent', 'recv', 'tied', 'caller', 'getpwnam', 'redo', 'time', 'chdir', 'getpwuid', 'ref', 'times', 'CHECK', 'getservbyname', 'rename', 'truncate', 'chmod', 'getservbyport', 'require', 'uc', 'chomp', 'getservent', 'reset', 'ucfirst', 'chop', 'getsockname', 'return', 'umask', 'chown', 'getsockopt', 'reverse', 'undef', 'chr', 'glob', 'rewinddir', 'UNITCHECK', 'chroot', 'gmtime', 'rindex', 'unlink', 'close', 'goto', 'rmdir', 'unpack', 'closedir', 'grep', 'say', 'unshift', 'connect', 'hex', 'scalar', 'untie', 'cos', 'index', 'seek', 'use', 'crypt', 'INIT', 'seekdir', 'utime', 'dbmclose', 'int', 'select', 'values', 'dbmopen', 'ioctl', 'semctl', 'vec', 'defined', 'join', 'semget', 'wait', 'delete', 'keys', 'semop', 'waitpid', 'DESTROY', 'kill', 'send', 'wantarray', 'die', 'last', 'setgrent', 'warn', 'dump', 'lc', 'sethostent', 'write', 'each', 'lcfirst', 'setnetent' ], // File handlers builtinFileHandlers: ['ARGV', 'STDERR', 'STDOUT', 'ARGVOUT', 'STDIN', 'ENV'], // Perl variables builtinVariables: [ '$!', '$^RE_TRIE_MAXBUF', '$LAST_REGEXP_CODE_RESULT', '$"', '$^S', '$LIST_SEPARATOR', '$#', '$^T', '$MATCH', '$$', '$^TAINT', '$MULTILINE_MATCHING', '$%', '$^UNICODE', '$NR', '$&', '$^UTF8LOCALE', '$OFMT', "$'", '$^V', '$OFS', '$(', '$^W', '$ORS', '$)', '$^WARNING_BITS', '$OS_ERROR', '$*', '$^WIDE_SYSTEM_CALLS', '$OSNAME', '$+', '$^X', '$OUTPUT_AUTO_FLUSH', '$,', '$_', '$OUTPUT_FIELD_SEPARATOR', '$-', '$`', '$OUTPUT_RECORD_SEPARATOR', '$.', '$a', '$PERL_VERSION', '$/', '$ACCUMULATOR', '$PERLDB', '$0', '$ARG', '$PID', '$:', '$ARGV', '$POSTMATCH', '$;', '$b', '$PREMATCH', '$<', '$BASETIME', '$PROCESS_ID', '$=', '$CHILD_ERROR', '$PROGRAM_NAME', '$>', '$COMPILING', '$REAL_GROUP_ID', '$?', '$DEBUGGING', '$REAL_USER_ID', '$@', '$EFFECTIVE_GROUP_ID', '$RS', '$[', '$EFFECTIVE_USER_ID', '$SUBSCRIPT_SEPARATOR', '$\\', '$EGID', '$SUBSEP', '$]', '$ERRNO', '$SYSTEM_FD_MAX', '$^', '$EUID', '$UID', '$^A', '$EVAL_ERROR', '$WARNING', '$^C', '$EXCEPTIONS_BEING_CAUGHT', '$|', '$^CHILD_ERROR_NATIVE', '$EXECUTABLE_NAME', '$~', '$^D', '$EXTENDED_OS_ERROR', '%!', '$^E', '$FORMAT_FORMFEED', '%^H', '$^ENCODING', '$FORMAT_LINE_BREAK_CHARACTERS', '%ENV', '$^F', '$FORMAT_LINES_LEFT', '%INC', '$^H', '$FORMAT_LINES_PER_PAGE', '%OVERLOAD', '$^I', '$FORMAT_NAME', '%SIG', '$^L', '$FORMAT_PAGE_NUMBER', '@+', '$^M', '$FORMAT_TOP_NAME', '@-', '$^N', '$GID', '@_', '$^O', '$INPLACE_EDIT', '@ARGV', '$^OPEN', '$INPUT_LINE_NUMBER', '@INC', '$^P', '$INPUT_RECORD_SEPARATOR', '@LAST_MATCH_START', '$^R', '$LAST_MATCH_END', '$^RE_DEBUG_FLAGS', '$LAST_PAREN_MATCH' ], // operators symbols: /[:+\-\^*$&%@=<>!?|\/~\.]/, quoteLikeOps: ['qr', 'm', 's', 'q', 'qq', 'qx', 'qw', 'tr', 'y'], escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, // The main tokenizer for our languages tokenizer: { root: [ { include: '@whitespace' }, [ /[a-zA-Z\-_][\w\-_]*/, { cases: { '@keywords': 'keyword', '@builtinFunctions': 'type.identifier', '@builtinFileHandlers': 'variable.predefined', '@quoteLikeOps': { token: '@rematch', next: 'quotedConstructs' }, '@default': '' } } ], // Perl variables [ /[\$@%][*@#?\+\-\$!\w\\\^><~:;\.]+/, { cases: { '@builtinVariables': 'variable.predefined', '@default': 'variable' } } ], { include: '@strings' }, { include: '@dblStrings' }, // Perl Doc { include: '@perldoc' }, // Here Doc { include: '@heredoc' }, [/[{}\[\]()]/, '@brackets'], // RegExp [/[\/](?:(?:\[(?:\\]|[^\]])+\])|(?:\\\/|[^\]\/]))*[\/]\w*\s*(?=[).,;]|$)/, 'regexp'], [/@symbols/, 'operators'], { include: '@numbers' }, [/[,;]/, 'delimiter'] ], whitespace: [ [/\s+/, 'white'], [/(^#!.*$)/, 'metatag'], [/(^#.*$)/, 'comment'] ], numbers: [ [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'], [/0[xX][0-9a-fA-F_]*[0-9a-fA-F]/, 'number.hex'], [/\d+/, 'number'] ], // Single quote string strings: [[/'/, 'string', '@stringBody']], stringBody: [ [/'/, 'string', '@popall'], [/\\'/, 'string.escape'], [/./, 'string'] ], // Double quote string dblStrings: [[/"/, 'string', '@dblStringBody']], dblStringBody: [ [/"/, 'string', '@popall'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], { include: '@variables' }, [/./, 'string'] ], // Quoted constructs // Percent strings in Ruby are similar to quote-like operators in Perl. // This is adapted from pstrings in ../ruby/ruby.ts. quotedConstructs: [ [/(q|qw|tr|y)\s*\(/, { token: 'string.delim', switchTo: '@qstring.(.)' }], [/(q|qw|tr|y)\s*\[/, { token: 'string.delim', switchTo: '@qstring.[.]' }], [/(q|qw|tr|y)\s*\{/, { token: 'string.delim', switchTo: '@qstring.{.}' }], [/(q|qw|tr|y)\s*</, { token: 'string.delim', switchTo: '@qstring.<.>' }], [/(q|qw|tr|y)#/, { token: 'string.delim', switchTo: '@qstring.#.#' }], [ /(q|qw|tr|y)\s*([^A-Za-z0-9#\s])/, { token: 'string.delim', switchTo: '@qstring.$2.$2' } ], [/(q|qw|tr|y)\s+(\w)/, { token: 'string.delim', switchTo: '@qstring.$2.$2' }], [/(qr|m|s)\s*\(/, { token: 'regexp.delim', switchTo: '@qregexp.(.)' }], [/(qr|m|s)\s*\[/, { token: 'regexp.delim', switchTo: '@qregexp.[.]' }], [/(qr|m|s)\s*\{/, { token: 'regexp.delim', switchTo: '@qregexp.{.}' }], [/(qr|m|s)\s*</, { token: 'regexp.delim', switchTo: '@qregexp.<.>' }], [/(qr|m|s)#/, { token: 'regexp.delim', switchTo: '@qregexp.#.#' }], [ /(qr|m|s)\s*([^A-Za-z0-9_#\s])/, { token: 'regexp.delim', switchTo: '@qregexp.$2.$2' } ], [/(qr|m|s)\s+(\w)/, { token: 'regexp.delim', switchTo: '@qregexp.$2.$2' }], [/(qq|qx)\s*\(/, { token: 'string.delim', switchTo: '@qqstring.(.)' }], [/(qq|qx)\s*\[/, { token: 'string.delim', switchTo: '@qqstring.[.]' }], [/(qq|qx)\s*\{/, { token: 'string.delim', switchTo: '@qqstring.{.}' }], [/(qq|qx)\s*</, { token: 'string.delim', switchTo: '@qqstring.<.>' }], [/(qq|qx)#/, { token: 'string.delim', switchTo: '@qqstring.#.#' }], [/(qq|qx)\s*([^A-Za-z0-9#\s])/, { token: 'string.delim', switchTo: '@qqstring.$2.$2' }], [/(qq|qx)\s+(\w)/, { token: 'string.delim', switchTo: '@qqstring.$2.$2' }] ], // Non-expanded quoted string // qstring<open>.<close> // open = open delimiter // close = close delimiter qstring: [ [/\\./, 'string.escape'], [ /./, { cases: { '$#==$S3': { token: 'string.delim', next: '@pop' }, '$#==$S2': { token: 'string.delim', next: '@push' }, // nested delimiters '@default': 'string' } } ] ], // Quoted regexp // qregexp.<open>.<close> // open = open delimiter // close = close delimiter qregexp: [ { include: '@variables' }, [/\\./, 'regexp.escape'], [ /./, { cases: { '$#==$S3': { token: 'regexp.delim', next: '@regexpModifiers' }, '$#==$S2': { token: 'regexp.delim', next: '@push' }, // nested delimiters '@default': 'regexp' } } ] ], regexpModifiers: [[/[msixpodualngcer]+/, { token: 'regexp.modifier', next: '@popall' }]], // Expanded quoted string // qqstring.<open>.<close> // open = open delimiter // close = close delimiter qqstring: [{ include: '@variables' }, { include: '@qstring' }], heredoc: [ [ /<<\s*['"`]?([\w\-]+)['"`]?/, { token: 'string.heredoc.delimiter', next: '@heredocBody.$1' } ] ], heredocBody: [ [ /^([\w\-]+)$/, { cases: { '$1==$S2': [ { token: 'string.heredoc.delimiter', next: '@popall' } ], '@default': 'string.heredoc' } } ], [/./, 'string.heredoc'] ], perldoc: [[/^=\w/, 'comment.doc', '@perldocBody']], perldocBody: [ [/^=cut\b/, 'type.identifier', '@popall'], [/./, 'comment.doc'] ], variables: [ [/\$\w+/, 'variable'], // scalar [/@\w+/, 'variable'], // array [/%\w+/, 'variable'] // key/value ] } };
the_stack
import { Spreadsheet } from '../base/index'; import { contentLoaded, mouseDown, virtualContentLoaded, cellNavigate, getUpdateUsingRaf, IOffset, focusBorder, positionAutoFillElement, hideAutoFillOptions, performAutoFill, selectAutoFillRange } from '../common/index'; import { showAggregate, refreshImgElem, getRowIdxFromClientY, getColIdxFromClientX, clearChartBorder, hideAutoFillElement } from '../common/index'; import { SheetModel, updateSelectedRange, getColumnWidth, mergedRange, activeCellMergedRange, Workbook, getSelectedRange } from '../../workbook/index'; import { getRowHeight, isSingleCell, activeCellChanged, MergeArgs, checkIsFormula, getSheetIndex } from '../../workbook/index'; import { EventHandler, addClass, removeClass, isNullOrUndefined, Browser, closest, remove, detach } from '@syncfusion/ej2-base'; import { BeforeSelectEventArgs, getMoveEvent, getEndEvent, isTouchStart, isMouseUp, isDiscontinuousRange } from '../common/index'; import { isTouchEnd, isTouchMove, getClientX, getClientY, mouseUpAfterSelection, selectRange, rowHeightChanged } from '../common/index'; import { colWidthChanged, protectSelection, editOperation, initiateFormulaReference, initiateCur, clearCellRef } from '../common/index'; import { getRangeIndexes, getCellAddress, getRangeAddress, getCellIndexes, getSwapRange } from '../../workbook/common/address'; import { addressHandle, removeDesignChart, isMouseDown, isMouseMove, selectionStatus, setPosition, removeRangeEle } from '../common/index'; import { isCellReference, getSheetNameFromAddress, CellModel, isLocked, getColumn, getCell } from '../../workbook/index'; import { getIndexesFromAddress, selectionComplete, skipHiddenIdx } from '../../workbook/common/index'; /** * Represents selection support for Spreadsheet. */ export class Selection { private parent: Spreadsheet; private startCell: number[]; private isRowSelected: boolean; private isColSelected: boolean; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ private scrollInterval: any; private touchEvt: TouchEvent & MouseEvent; private mouseMoveEvt: EventListener; private uniqueOBracket: string = String.fromCharCode(129); private uniqueCBracket: string = String.fromCharCode(130); private uniqueCSeparator: string = String.fromCharCode(131); private uniqueCOperator: string = String.fromCharCode(132); private uniquePOperator: string = String.fromCharCode(133); private uniqueSOperator: string = String.fromCharCode(134); private uniqueMOperator: string = String.fromCharCode(135); private uniqueDOperator: string = String.fromCharCode(136); private uniqueModOperator: string = String.fromCharCode(137); private uniqueConcateOperator: string = String.fromCharCode(138); private uniqueEqualOperator: string = String.fromCharCode(139); private uniqueExpOperator: string = String.fromCharCode(140); private uniqueGTOperator: string = String.fromCharCode(141); private uniqueLTOperator: string = String.fromCharCode(142); private invalidOperators: string[] = ['%']; private formulaRange: string[] = []; private tableRangesFormula: object = {}; private dStartCell: { rowIndex: number, colIndex: number }; private dEndCell: { rowIndex: number, colIndex: number }; private touchSelectionStarted: boolean; private isautoFillClicked: boolean; public dAutoFillCell: string; /** * Constructor for the Spreadsheet selection module. * * @param {Spreadsheet} parent - Constructor for the Spreadsheet selection module. * @private */ constructor(parent: Spreadsheet) { this.parent = parent; this.addEventListener(); this.mouseMoveEvt = this.mouseMoveHandler.bind(this); } private addEventListener(): void { this.parent.on(contentLoaded, this.init, this); this.parent.on(mouseDown, this.mouseDownHandler, this); this.parent.on(virtualContentLoaded, this.virtualContentLoadedHandler, this); this.parent.on(cellNavigate, this.cellNavigateHandler, this); this.parent.on(selectRange, this.selectRange, this); this.parent.on(rowHeightChanged, this.rowHeightChanged, this); this.parent.on(colWidthChanged, this.colWidthChanged, this); this.parent.on(protectSelection, this.protectHandler, this); this.parent.on(initiateFormulaReference, this.initiateFormulaSelection, this); this.parent.on(clearCellRef, this.clearBorder, this); this.parent.on(getRowIdxFromClientY, this.getRowIdxFromClientY, this); this.parent.on(getColIdxFromClientX, this.getColIdxFromClientX, this); this.parent.on(focusBorder, this.chartBorderHandler, this); this.parent.on(selectionStatus, this.isTouchSelectionStarted, this); } private removeEventListener(): void { if (!this.parent.isDestroyed) { this.parent.off(contentLoaded, this.init); this.parent.off(mouseDown, this.mouseDownHandler); this.parent.off(virtualContentLoaded, this.virtualContentLoadedHandler); this.parent.off(cellNavigate, this.cellNavigateHandler); this.parent.off(selectRange, this.selectRange); this.parent.off(rowHeightChanged, this.rowHeightChanged); this.parent.off(colWidthChanged, this.colWidthChanged); this.parent.off(protectSelection, this.protectHandler); this.parent.off(initiateFormulaReference, this.initiateFormulaSelection); this.parent.off(clearCellRef, this.clearBorder); this.parent.off(getRowIdxFromClientY, this.getRowIdxFromClientY); this.parent.off(getColIdxFromClientX, this.getColIdxFromClientX); this.parent.off(focusBorder, this.chartBorderHandler); this.parent.off(selectionStatus, this.isTouchSelectionStarted); } } private isTouchSelectionStarted(args: { touchSelectionStarted: boolean }): void { args.touchSelectionStarted = this.touchSelectionStarted; } private rowHeightChanged(args: { threshold: number, rowIdx: number }): void { if (!args.threshold) { return; } getUpdateUsingRaf((): void => { if (!this.parent) { return; } const sheet: SheetModel = this.parent.getActiveSheet(); let ele: HTMLElement = this.getActiveCell(); if (ele) { if (sheet.frozenRows || sheet.frozenColumns || sheet.selectedRange.includes(' ')) { this.selectRange({ address: sheet.selectedRange }); return; } const rowIdx: number = getCellIndexes(sheet.activeCell)[0]; if (rowIdx === args.rowIdx) { ele.style.height = `${parseFloat(ele.style.height) + args.threshold}px`; } else if (rowIdx > args.rowIdx) { ele.style.top = `${parseFloat(ele.style.top) + args.threshold}px`; } } ele = this.getSelectionElement(); if (ele) { const selectedRange: number[] = getRangeIndexes(sheet.selectedRange); const sRange: number[] = getSwapRange(selectedRange); const mergeArgs: MergeArgs = { range: sRange, isActiveCell: false, skipChecking: true }; this.parent.notify(mergedRange, mergeArgs); if (mergeArgs.isActiveCell || (sRange[0] === sRange[2] && sRange[1] === sRange[3])) { return; } const rowStart: number = sRange[0]; const rowEnd: number = sRange[2]; if (rowStart <= args.rowIdx && rowEnd >= args.rowIdx && ele) { ele.style.height = `${parseFloat(ele.style.height) + args.threshold}px`; } else if (rowStart > args.rowIdx && ele) { ele.style.top = `${parseFloat(ele.style.top) + args.threshold}px`; } } }); } private colWidthChanged(args: { threshold: number, colIdx: number }): void { if (!args.threshold) { return; } getUpdateUsingRaf((): void => { if (!this.parent) { return; } let ele: HTMLElement = this.getActiveCell(); const sheet: SheetModel = this.parent.getActiveSheet(); if (ele) { if (sheet.frozenRows || sheet.frozenColumns || sheet.selectedRange.includes(' ')) { this.selectRange({ address: sheet.selectedRange }); return; } const colIdx: number = getCellIndexes(sheet.activeCell)[1]; if (colIdx === args.colIdx) { ele.style.width = `${parseFloat(ele.style.width) + args.threshold}px`; } else if (colIdx > args.colIdx) { ele.style.left = `${parseFloat(ele.style.left) + args.threshold}px`; } } const selectedRange: number[] = getRangeIndexes(this.parent.getActiveSheet().selectedRange); const sRange: number[] = getSwapRange(selectedRange); const e: MergeArgs = { range: sRange, isActiveCell: false, skipChecking: true }; this.parent.notify(mergedRange, e); ele = this.getSelectionElement(); if (!ele || e.isActiveCell || (sRange[0] === sRange[2] && sRange[1] === sRange[3])) { return; } const colStart: number = sRange[1]; const colEnd: number = sRange[3]; if (colStart <= args.colIdx && colEnd >= args.colIdx && ele) { ele.style.width = `${parseFloat(ele.style.width) + args.threshold}px`; } else if (colStart > args.colIdx && ele) { ele.style.left = `${parseFloat(ele.style.left) + args.threshold}px`; } }); } private selectRange(args: { address: string, skipChecking?: boolean }): void { args.address = this.parent.selectionSettings.mode === 'Single' ? getRangeAddress(getCellIndexes(args.address)) : args.address; this.selectMultiRange(args.address, null, null, args.skipChecking); } private init(): void { this.createSelectionElement(); const sheet: SheetModel = this.parent.getActiveSheet(); const sRange: number[] = getSwapRange(getRangeIndexes(sheet.selectedRange)); const actRange: number[] = getCellIndexes(sheet.activeCell); const inRange: boolean = sRange[0] <= actRange[0] && sRange[2] >= actRange[0] && sRange[1] <= actRange[1] && sRange[3] >= actRange[1]; this.selectMultiRange(sheet.selectedRange, true, inRange); } private selectMultiRange(address: string, isInit?: boolean, inRange?: boolean, skipChecking?: boolean): void { let sheetIdx: number = this.parent.activeSheetIndex; if (address.indexOf('!') > -1) { sheetIdx = getSheetIndex(this.parent as Workbook, getSheetNameFromAddress(address)); address = address.split('!')[1]; } if (this.parent.activeSheetIndex === sheetIdx) { address.split(' ').forEach((rng: string, idx: number) => { this.selectRangeByIdx( getRangeIndexes(rng), { type: 'mousedown', ctrlKey: idx === 0 ? false : true } as MouseEvent, null, inRange, isInit, skipChecking); }); } else { updateSelectedRange(this.parent as Workbook, address, this.parent.sheets[sheetIdx]); } } private createSelectionElement(): void { const content: Element = this.parent.getMainContent(); let ele: Element = this.parent.createElement('div', { className: 'e-selection' }); content.appendChild(ele); ele = this.parent.createElement('div', { className: 'e-active-cell' }); content.appendChild(ele); } private mouseDownHandler(e: MouseEvent & TouchEvent): void { if (closest(e.target as Element, '.e-scrollbar') || (e.target as Element).classList.contains('e-main-panel') || (e.target as Element).classList.contains('e-sheet')) { return; } const eventArgs: { action: string, editedValue: string } = { action: 'getCurrentEditValue', editedValue: '' }; const sheet: SheetModel = this.parent.getActiveSheet(); this.parent.notify(editOperation, eventArgs); const isFormulaEdit: boolean = checkIsFormula(eventArgs.editedValue, true); if (!this.parent.isEdit || isFormulaEdit) { const overlayElem: HTMLElement = document.getElementById(this.parent.element.id + '_overlay'); if (typeof((e.target as HTMLElement).className) === 'string' ) { if ((e.target as HTMLElement).className.indexOf('e-ss-overlay') > -1) { return; } } else if (overlayElem) { overlayElem.classList.remove('e-ss-overlay-active'); } if (closest(e.target as Element, '.e-datavisualization-chart')) { return; } if (sheet.isProtected && !sheet.protectSettings.selectCells && !sheet.protectSettings.selectUnLockedCells) { return; } if (!closest(e.target as Element, '.e-findtool-dlg')) { if (this.getSheetElement().contains(e.target as Node) && !(e.target as HTMLElement).classList.contains('e-colresize') && !(e.target as HTMLElement).classList.contains('e-rowresize')) { const sheet: SheetModel = this.parent.getActiveSheet(); const mode: string = this.parent.selectionSettings.mode; const rowIdx: number = this.getRowIdxFromClientY({ clientY: getClientY(e), target: e.target as Element }); const colIdx: number = this.getColIdxFromClientX({ clientX: getClientX(e), target: e.target as Element }); const activeIdx: number[] = getCellIndexes(sheet.activeCell); const cell: CellModel = getCell(rowIdx, colIdx, sheet); let isRowSelected: boolean; let isColSelected: boolean; if (sheet.isProtected) { if (sheet.protectSettings.selectUnLockedCells && !sheet.protectSettings.selectCells) { if (!isNullOrUndefined(cell)) { if (cell.isLocked === true || isNullOrUndefined(cell.isLocked)){ return; } else { const sheetEle: Element = this.parent.element.getElementsByClassName('e-sheet-panel')[0]; if (sheetEle && sheetEle.classList.contains('e-protected')) { sheetEle.classList.remove('e-protected'); } } } else if (!sheet.protectSettings.selectCells) { return; } } } if (sheet.showHeaders) { const trgt: Element = e.target as Element; if (sheet.frozenColumns || sheet.frozenRows) { let headerEle: HTMLElement = this.parent.getSelectAllContent().querySelector('thead'); if (headerEle) { isColSelected = (this.parent.getColumnHeaderContent().contains(trgt) || headerEle.contains(trgt)) && trgt.classList.contains('e-header-cell'); } else { isColSelected = this.parent.getColumnHeaderContent().contains(trgt) && trgt.classList.contains('e-header-cell'); } headerEle = this.parent.getSelectAllContent().querySelector('tbody'); if (headerEle) { isRowSelected = (this.parent.getRowHeaderContent().contains(trgt) || headerEle.contains(trgt)) && trgt.classList.contains('e-header-cell'); } else { isRowSelected = this.parent.getRowHeaderContent().contains(trgt) && trgt.classList.contains('e-header-cell'); } } else { isRowSelected = this.parent.getRowHeaderContent().contains(e.target as Node); isColSelected = this.parent.getColumnHeaderContent().contains(e.target as Node); } } if (e.which === 3 && this.isSelected(rowIdx, colIdx)) { return; } if ((e.target as HTMLElement).classList.contains('e-autofill')) { this.isautoFillClicked = true; const autoFillDdb: Element = (e.target as HTMLElement).parentElement.querySelector('.e-dragfill-ddb'); if (!autoFillDdb || autoFillDdb.classList.contains('e-hide')) { this.dAutoFillCell = sheet.selectedRange; } } const topLeftIdx: number[] = getRangeIndexes(sheet.topLeftCell); let range: number[]; if (isRowSelected) { this.isRowSelected = true; if (!e.shiftKey || mode === 'Single') { this.startCell = [rowIdx, 0]; } range = [this.startCell[0], sheet.frozenColumns ? topLeftIdx[1] : 0, rowIdx, sheet.colCount - 1]; } else if (isColSelected) { this.isColSelected = true; if (!e.shiftKey || mode === 'Single') { this.startCell = [0, colIdx]; } range = [sheet.frozenRows ? topLeftIdx[0] : 0, this.startCell[1], sheet.rowCount - 1, colIdx]; } else if (closest(e.target as Element, '.e-select-all-cell')) { this.startCell = [sheet.frozenRows ? topLeftIdx[0] : 0, sheet.frozenColumns ? topLeftIdx[1] : 0]; range = [].concat(this.startCell, [sheet.rowCount - 1, sheet.colCount - 1]); } else if (!(e.target as Element).classList.contains('e-sheet-content')) { if (!e.shiftKey || mode === 'Single') { this.startCell = [rowIdx, colIdx]; } if (!this.isautoFillClicked && !closest(e.target as Element, '.e-filloption')) { range = [].concat(this.startCell ? this.startCell : getCellIndexes(sheet.activeCell), [rowIdx, colIdx]); } } const preventEvt: boolean = e.ctrlKey && range && sheet.selectedRange.includes(getRangeAddress(range)); if (!preventEvt && mode === 'Multiple' && (!isTouchEnd(e) && (!isTouchStart(e) || (isTouchStart(e) && activeIdx[0] === rowIdx && activeIdx[1] === colIdx)) || isColSelected || isRowSelected)) { document.addEventListener(getMoveEvent().split(' ')[0], this.mouseMoveEvt); if (!Browser.isPointer) { document.addEventListener(getMoveEvent().split(' ')[1], this.mouseMoveEvt, { passive: false }); } this.touchSelectionStarted = true; } else { this.touchSelectionStarted = false; } if (!preventEvt && !isTouchEnd(e)) { EventHandler.add(document, getEndEvent(), this.mouseUpHandler, this); } if (isTouchStart(e) && !(isColSelected || isRowSelected)) { this.touchEvt = e; return; } if (range) { this.selectRangeByIdx(range, e); } if (this.parent.isMobileView()) { this.parent.element.classList.add('e-mobile-focused'); this.parent.renderModule.setSheetPanelSize(); } } } } if (isFormulaEdit && ((e.target as HTMLElement).classList.contains('e-cell') || (e.target as HTMLElement).classList.contains('e-header-cell')) && this.parent.isEdit) { let range: string = this.parent.getActiveSheet().selectedRange; range = isSingleCell(getIndexesFromAddress(range)) ? range.split(':')[0] : range; this.parent.notify(addressHandle, { range: range, isSelect: false }); } } private mouseMoveHandler(e: MouseEvent & TouchEvent): void { const sheet: SheetModel = this.parent.getActiveSheet(); if (isTouchMove(e)) { e.preventDefault(); } const eventArgs: { action: string, editedValue: string } = { action: 'getCurrentEditValue', editedValue: '' }; this.parent.notify(editOperation, eventArgs); const isFormulaEdit: boolean = checkIsFormula(eventArgs.editedValue, true); const verticalContent: Element = this.parent.getMainContent().parentElement; const horizontalContent: Element = this.parent.element.getElementsByClassName('e-scroller')[0]; const clientRect: ClientRect = verticalContent.getBoundingClientRect(); const frozenCol: number = this.parent.frozenColCount(sheet); const left: number = clientRect.left + this.parent.sheetModule.getRowHeaderWidth(sheet); const top: number = clientRect.top; const right: number = clientRect.right; const bottom: number = clientRect.bottom; const clientX: number = getClientX(e); const clientY: number = getClientY(e); // remove math.min or handle top and left auto scroll let colIdx: number = this.isRowSelected ? sheet.colCount - 1 : this.getColIdxFromClientX({ clientX: Math.min(clientX, right), target: e.target as Element }); let rowIdx: number = this.isColSelected ? sheet.rowCount - 1 : this.getRowIdxFromClientY({ clientY: Math.min(clientY, bottom), target: e.target as Element }); let prevIndex: number[]; if (e.ctrlKey) { const selRanges: string[] = sheet.selectedRange.split(' '); prevIndex = getRangeIndexes(selRanges[selRanges.length - 1]); } else { prevIndex = getRangeIndexes(sheet.selectedRange); } const mergeArgs: MergeArgs = { range: [rowIdx, colIdx, rowIdx, colIdx] }; this.parent.notify(activeCellMergedRange, mergeArgs); if (mergeArgs.range[2] === prevIndex[2] && mergeArgs.range[3] === prevIndex[3]) { return; } const frozenRow: number = this.parent.frozenRowCount(sheet); const isScrollDown: boolean = clientY > bottom && rowIdx < sheet.rowCount; const isScrollUp: boolean = clientY < top && rowIdx >= 0 && !this.isColSelected && !!verticalContent.scrollTop; const isScrollRight: boolean = clientX > right && colIdx < sheet.colCount; const isScrollLeft: boolean = clientX < left && colIdx >= 0 && !this.isRowSelected && !!horizontalContent.scrollLeft; this.clearInterval(); let scrollUpRowIdx: number; let scrollUpColIdx: number; if (!isFormulaEdit && !this.isColSelected && !this.isRowSelected) { prevIndex = getCellIndexes(sheet.activeCell); } if (isScrollDown || isScrollUp || isScrollRight || isScrollLeft) { if (isScrollUp || isScrollLeft) { scrollUpRowIdx = rowIdx; scrollUpColIdx = colIdx; } this.scrollInterval = setInterval(() => { if ((isScrollDown || isScrollUp) && !this.isColSelected) { rowIdx = this.getRowIdxFromClientY({ clientY: isScrollDown ? bottom : top }); if (rowIdx >= sheet.rowCount) { // clear interval when scroll up this.clearInterval(); return; } verticalContent.scrollTop += (isScrollDown ? 1 : -1) * getRowHeight(sheet, rowIdx); } if ((isScrollRight || isScrollLeft) && !this.isRowSelected) { colIdx = this.getColIdxFromClientX({ clientX: isScrollRight ? right : left }); if (colIdx >= sheet.colCount) { // clear interval when scroll left this.clearInterval(); return; } horizontalContent.scrollLeft += (isScrollRight ? 1 : -1) * getColumnWidth(sheet, colIdx); } if ((isScrollUp && !verticalContent.scrollTop) || (isScrollLeft && !horizontalContent.scrollLeft)) { this.selectRangeByIdx([].concat(prevIndex[0], prevIndex[1], [scrollUpRowIdx, scrollUpColIdx]), e); this.clearInterval(); return; } this.selectRangeByIdx([].concat(prevIndex[0], prevIndex[1], [rowIdx, colIdx]), e); }, 100); } else { let indexes: number[] = [].concat(prevIndex[0], prevIndex[1], [rowIdx, colIdx]); if (frozenRow && indexes[0] < frozenRow && indexes[2] >= frozenRow && verticalContent.scrollTop) { verticalContent.scrollTop = 0; indexes[2] = frozenRow; } if (frozenCol && indexes[1] < frozenCol && indexes[3] >= frozenCol && horizontalContent.scrollLeft) { horizontalContent.scrollLeft = 0; indexes[3] = frozenCol; } if (this.isautoFillClicked) { if ((e.target as HTMLElement).classList.contains('e-autofill')) { this.dAutoFillCell = sheet.selectedRange; } const args: {e: MouseEvent & TouchEvent, indexes?: number[] } = { e: e, indexes: null }; this.parent.notify(selectAutoFillRange, args); indexes = args.indexes; } this.selectRangeByIdx(indexes, e); } if (isFormulaEdit && this.parent.isEdit && !closest(e.target as Element, '#' + this.parent.element.id + '_edit')) { const range: string = this.parent.getActiveSheet().selectedRange; this.parent.notify(addressHandle, { range: range, isSelect: false }); } } private mouseUpHandler(e: MouseEvent & TouchEvent): void { const rowIdx: number = this.getRowIdxFromClientY({ clientY: getClientY(e), target: e.target as Element }); const colIdx: number = this.getColIdxFromClientX({ clientX: getClientX(e), target: e.target as Element }); this.clearInterval(); if (isTouchEnd(e) && !(this.isColSelected || this.isRowSelected) && (this.getRowIdxFromClientY({ clientY: getClientY(this.touchEvt), target: e.target as Element }) === rowIdx && this.getColIdxFromClientX({ clientX: getClientX(this.touchEvt), target: e.target as Element }) === colIdx)) { this.mouseDownHandler(e); } document.removeEventListener(getMoveEvent().split(' ')[0], this.mouseMoveEvt); if (!Browser.isPointer) { document.removeEventListener(getMoveEvent().split(' ')[1], this.mouseMoveEvt); } EventHandler.remove(document, getEndEvent(), this.mouseUpHandler); const sheet: SheetModel = this.parent.getActiveSheet(); if (sheet.frozenRows || sheet.frozenColumns) { removeRangeEle(this.parent.element, null, 'e-cur-selection', true, true); } this.parent.notify(mouseUpAfterSelection, e); if (this.isautoFillClicked) { const sheet: SheetModel = this.parent.getActiveSheet(); const indexes: number[] = getRangeIndexes(sheet.selectedRange); if (!(this.isColSelected && indexes[1] === colIdx) && !(this.isRowSelected && indexes[0] === rowIdx)) { this.parent.notify(performAutoFill, { event: e, dAutoFillCell: this.dAutoFillCell }); } this.isautoFillClicked = false; } else if (!e.ctrlKey && !isDiscontinuousRange(getSelectedRange(this.parent.getActiveSheet()))) { this.parent.notify(positionAutoFillElement, null); } else { this.parent.notify(hideAutoFillElement, null); } const eventArgs: { action: string, editedValue: string } = { action: 'getCurrentEditValue', editedValue: '' }; this.parent.notify(editOperation, eventArgs); const isFormulaEdit: boolean = checkIsFormula(eventArgs.editedValue) || (eventArgs.editedValue && eventArgs.editedValue.toString().indexOf('=') === 0); if (isFormulaEdit && this.parent.isEdit) { this.parent.notify(initiateCur, { isCellEdit: (e.target as HTMLElement).classList.contains('e-spreadsheet-edit') }); } } private isSelected(rowIdx: number, colIdx: number): boolean { let isSelected: boolean = false; let indexes: number[]; const ranges: string[] = this.parent.getActiveSheet().selectedRange.split(' '); for (let i: number = 0; i < ranges.length; i++) { indexes = getSwapRange(getRangeIndexes(ranges[i])); if (indexes[0] <= rowIdx && rowIdx <= indexes[2] && indexes[1] <= colIdx && colIdx <= indexes[3]) { isSelected = true; break; } } return isSelected; } private virtualContentLoadedHandler(args: { prevRowColCnt: SheetModel }): void { // do only for scroll down const sheet: SheetModel = this.parent.getActiveSheet(); let indexes: number[] = getRangeIndexes(sheet.selectedRange); let isColSelected: boolean; let isRowSelected: boolean; sheet.selectedRange.split(' ').forEach((rng: string, idx: number) => { indexes = getRangeIndexes(rng); isRowSelected = (indexes[1] === 0 && indexes[3] === args.prevRowColCnt.colCount - 1); isColSelected = (indexes[0] === 0 && indexes[2] === args.prevRowColCnt.rowCount - 1); if (isColSelected && isRowSelected) { this.selectRangeByIdx([0, 0, sheet.rowCount - 1, sheet.colCount - 1], null, true, null, null, null, idx); } else if (isColSelected) { this.selectRangeByIdx([0, indexes[1], sheet.rowCount - 1, indexes[3]], null, true, null, null, null, idx); } else if (isRowSelected) { this.selectRangeByIdx([indexes[0], 0, indexes[2], sheet.colCount - 1], null, true, null, null, null, idx); } else { indexes = getRangeIndexes(rng); const topIdx: number = this.parent.viewport.topIndex + this.parent.frozenRowCount(sheet); const leftIdx: number = this.parent.viewport.leftIndex + this.parent.frozenColCount(sheet); this.highlightHdr( indexes, idx === 0 ? false : true, indexes[0] >= topIdx || indexes[2] >= topIdx, indexes[1] >= leftIdx || indexes[3] >= leftIdx); } }); } private clearInterval(): void { clearInterval(this.scrollInterval); this.scrollInterval = null; } private getScrollLeft(): number { return this.parent.scrollModule ? this.parent.scrollModule.prevScroll.scrollLeft : 0; } private cellNavigateHandler(args: { range: number[], preventAnimation?: boolean }): void { const sheet: SheetModel = this.parent.getActiveSheet(); if (sheet.isProtected && !sheet.protectSettings.selectCells && !sheet.protectSettings.selectUnLockedCells) { return; } this.selectRangeByIdx(args.range.concat(args.range), undefined, false, false, false, false, undefined, args.preventAnimation); } private getColIdxFromClientX(e: { clientX: number, isImage?: boolean, target?: Element, size?: number }): number { let width: number = 0; const sheet: SheetModel = this.parent.getActiveSheet(); let left: number = 0; if (e.isImage) { left = e.clientX; } else { const cliRect: ClientRect = document.getElementById(this.parent.element.id + '_sheet').getBoundingClientRect(); if (this.parent.enableRtl) { left = (cliRect.right - this.parent.sheetModule.getRowHeaderWidth(sheet, true) - 1) - e.clientX; } else { left = e.clientX - (cliRect.left + this.parent.sheetModule.getRowHeaderWidth(sheet, true) + 1); } left += this.parent.viewport.beforeFreezeWidth; if (!e.target || (!closest(e.target, '.e-row-header') && !closest(e.target, '.e-selectall-container')) || this.isScrollableArea(e.clientX, e.target, true)) { left += this.getScrollLeft(); } } for (let i: number = 0; ; i++) { width += getColumnWidth(sheet, i, null, true); if (left < width || (this.parent.scrollSettings.isFinite && i === sheet.colCount - 1)) { if (!e.isImage) { e.size = left; } e.clientX = i; return i; } } } private isScrollableArea(offset: number, target: Element, isclientX?: boolean): boolean { if (!target.classList.contains('e-table')) { return false; } if (isclientX) { return offset > this.parent.getMainContent().getBoundingClientRect().left; } else { return offset > this.parent.getMainContent().parentElement.getBoundingClientRect().top; } } private getRowIdxFromClientY(args: { clientY: number, isImage?: boolean, target?: Element, size?: number }): number { let height: number = 0; const sheet: SheetModel = this.parent.getActiveSheet(); let top: number = 0; if (args.isImage) { top = args.clientY; } else { const sheetEle: HTMLElement = document.getElementById(this.parent.element.id + '_sheet'); top = args.clientY + this.parent.viewport.beforeFreezeHeight - (sheetEle.getBoundingClientRect().top + (sheet.showHeaders ? 31 : 0)); if (!args.target || !closest(args.target, '.e-header-panel') || this.isScrollableArea(args.clientY, args.target)) { top += this.parent.getMainContent().parentElement.scrollTop; } } for (let i: number = 0; ; i++) { height += getRowHeight(sheet, i, true); if (top < height || (this.parent.scrollSettings.isFinite && i === sheet.rowCount - 1)) { if (!args.isImage) { args.size = top; } args.clientY = i; return i; } } } private initFormulaReferenceIndicator( range: number[]): void { if (this.parent.isEdit) { const forRefIndicator: HTMLElement = this.parent.createElement('div', { className: 'e-formularef-indicator' }); forRefIndicator.appendChild(this.parent.createElement('div', { className: 'e-top' })); forRefIndicator.appendChild(this.parent.createElement('div', { className: 'e-bottom' })); forRefIndicator.appendChild(this.parent.createElement('div', { className: 'e-left' })); forRefIndicator.appendChild(this.parent.createElement('div', { className: 'e-right' })); this.parent.getMainContent().appendChild(forRefIndicator); setPosition(this.parent, forRefIndicator, range, 'e-formularef-indicator'); } } private selectRangeByIdx( range: number[], e?: MouseEvent, isScrollRefresh?: boolean, isActCellChanged?: boolean, isInit?: boolean, skipChecking?: boolean, selectedRowColIdx?: number, preventAnimation?: boolean): void { if (e && e.target && closest(e.target as Element, '#' + this.parent.element.id + '_edit')) { return; } const eventArgs: { action: string, editedValue: string, endFormulaRef: boolean } = { action: 'getCurrentEditValue', editedValue: '', endFormulaRef: false }; this.parent.notify(editOperation, eventArgs); const isFormulaEdit: boolean = checkIsFormula(eventArgs.editedValue, true) && !eventArgs.endFormulaRef; const isMultiRange: boolean = e && e.ctrlKey && isMouseDown(e); let ele: HTMLElement; if (!isMultiRange) { ele = this.getSelectionElement(e, selectedRowColIdx); } const sheet: SheetModel = this.parent.getActiveSheet(); const formulaRefIndicator: HTMLElement = this.parent.element.querySelector('.e-formularef-indicator'); const mergeArgs: MergeArgs = { range: [].slice.call(range), isActiveCell: false, skipChecking: skipChecking }; let isMergeRange: boolean; const overlayEle: HTMLElement = document.querySelector('.e-datavisualization-chart.e-ss-overlay-active') as HTMLElement; if (!this.isColSelected && !this.isRowSelected) { this.parent.notify(mergedRange, mergeArgs); } if (range !== mergeArgs.range) { isMergeRange = true; } range = mergeArgs.range as number[]; let promise: Promise<null> = new Promise((resolve: Function) => { resolve((() => { /** */ })()); }); const args: BeforeSelectEventArgs = { range: getRangeAddress(range), cancel: false }; this.parent.trigger('beforeSelect', args); if (args.cancel) { return; } if (isFormulaEdit && formulaRefIndicator) { formulaRefIndicator.parentElement.removeChild(formulaRefIndicator); } this.parent.notify(hideAutoFillOptions, null ); if ((isSingleCell(range) || mergeArgs.isActiveCell) && !isMultiRange) { if (ele) { if (!ele.classList.contains('e-multi-range')) { ele.classList.add('e-hide'); } if (sheet.frozenRows || sheet.frozenColumns) { const clsName: string = isMouseMove(e) ? 'e-cur-selection' : 'e-selection'; removeRangeEle(this.parent.getSelectAllContent(), null, clsName, true); removeRangeEle(this.parent.getColumnHeaderContent(), null, clsName, true); removeRangeEle(this.parent.getRowHeaderContent(), null, clsName, true); } } if (!sheet.frozenColumns && !sheet.frozenRows && ele) { setPosition(this.parent, ele, range); } if (isFormulaEdit && e && e.target && !(e.target as HTMLElement).classList.contains('e-spreadsheet-edit') && this.parent.isEdit) { this.parent.notify(addressHandle, { range: getRangeAddress(range).split(':')[0], isSelect: true }); this.initFormulaReferenceIndicator(range); } } else { if (isMultiRange) { if (selectedRowColIdx === undefined) { let selRange: string = getRangeAddress(range); if (sheet.selectedRange.includes(selRange)) { const selRanges: string[] = sheet.selectedRange.split(' '); if (selRanges.length > 1) { selRanges.splice(selRanges.indexOf(selRange), 1); selRange = selRanges.join(' '); } else { selRange = sheet.activeCell + ':' + sheet.activeCell; } this.selectRange({ address: selRange }); return; } else { ele = this.getSelectionElement(e, selectedRowColIdx); } } else { ele = this.getSelectionElement(e, selectedRowColIdx); } } if (isFormulaEdit && this.parent.isEdit) { if (e && e.target && !(e.target as HTMLElement).classList.contains('e-spreadsheet-edit') && this.parent.isEdit) { this.parent.notify(addressHandle, { range: getRangeAddress(range), isSelect: true }); this.initFormulaReferenceIndicator(range); } } else { let clsName: string; if (ele) { ele.classList.remove('e-hide'); if (sheet.frozenRows || sheet.frozenColumns) { if (e && e.target || isMultiRange) { clsName = 'e-cur-selection'; if (isMouseMove(e) && ele.classList.contains('e-cur-selection')) { ele.classList.add('e-hide'); } else { ele.classList.add(clsName); } } if (!isMultiRange && (this.isColSelected || this.isRowSelected) && isMouseDown(e)) { removeRangeEle(this.parent.getSelectAllContent(), null, 'e-selection'); removeRangeEle(this.parent.getColumnHeaderContent(), null, 'e-selection'); removeRangeEle(this.parent.getRowHeaderContent(), null, 'e-selection'); } } } const offset: { left: IOffset, top: IOffset } = (this.isColSelected && this.isRowSelected) ? undefined : this.getOffset(range[2], range[3]); if (isMergeRange && offset) { // Need to handle half hidden merge cell in better way offset.left = { idx: 0, size: 0 }; } promise = setPosition(this.parent, ele, range, clsName, false, isMultiRange, isMultiRange && !e.target) as Promise<null> || promise; } } const eArgs: { action: string, sheetIndex: number } = { action: 'getCurrentEditSheetIdx', sheetIndex: null }; this.parent.notify(editOperation, eArgs); let selRange: string = getRangeAddress(range); if (e && e.ctrlKey && (isMouseMove(e) || isMouseUp(e))) { selRange = sheet.selectedRange.slice(0, sheet.selectedRange.lastIndexOf(' ')) + ' ' + selRange; } else if (selectedRowColIdx > -1) { const selRanges: string[] = sheet.selectedRange.split(' '); selRanges[selectedRowColIdx] = selRange; selRange = selRanges.join(' '); } if (!isFormulaEdit && !this.isautoFillClicked) { let isSelectRangeChange: boolean = false; if (sheet.selectedRange !== selRange) { isSelectRangeChange = true; } updateSelectedRange(this.parent as Workbook, selRange, sheet, isMultiRange); if (isSelectRangeChange) { promise.then((): void => { this.parent.trigger('select', { range: this.parent.getActiveSheet().selectedRange }); }); } } else if (!isInit && !this.isautoFillClicked) { updateSelectedRange(this.parent as Workbook, selRange, sheet, isMultiRange); } this.UpdateRowColSelected(range); this.highlightHdr(range, e && e.ctrlKey); if (!isScrollRefresh && !(e && (e.type === 'mousemove' || isTouchMove(e)))) { if (!isFormulaEdit) { this.updateActiveCell(isActCellChanged ? getRangeIndexes(sheet.activeCell) : range, isInit, preventAnimation); } else if (eArgs.sheetIndex === this.parent.getActiveSheet().id - 1 && isInit) { isActCellChanged = true; this.updateActiveCell(isActCellChanged ? getRangeIndexes(sheet.activeCell) : range, isInit, preventAnimation); } else if (!this.parent.isEdit) { this.updateActiveCell(isActCellChanged ? getRangeIndexes(sheet.activeCell) : range, isInit, preventAnimation); } } if (isNullOrUndefined(e)) { e = <MouseEvent>{ type: 'mousedown' }; } if (!isFormulaEdit) { this.parent.notify(selectionComplete, e); } else if (!isInit) { this.parent.notify(selectionComplete, e); } if (!isMultiRange && !isDiscontinuousRange(getSelectedRange(this.parent.getActiveSheet()))) { this.parent.notify(positionAutoFillElement, { preventAnimation: preventAnimation }); } else { this.parent.notify(hideAutoFillElement, null); } if (this.parent.showAggregate) { this.parent.notify(showAggregate, {}); } this.parent.notify(refreshImgElem, {}); if (overlayEle) { this.parent.notify(removeDesignChart, {}); } this.parent.notify(clearChartBorder, {}); } private UpdateRowColSelected(indexes: number[]): void { const sheet: SheetModel = this.parent.getActiveSheet(); this.isRowSelected = (indexes[1] === 0 && indexes[3] === sheet.colCount - 1); this.isColSelected = (indexes[0] === 0 && indexes[2] === sheet.rowCount - 1); } private updateActiveCell(range: number[], isInit?: boolean, preventAnimation?: boolean): void { const sheet: SheetModel = this.parent.getActiveSheet(); const topLeftIdx: number[] = getRangeIndexes(sheet.topLeftCell); let rowIdx: number; let colIdx: number; let isMergeRange: boolean; if (this.isColSelected) { rowIdx = topLeftIdx[0]; colIdx = range[1]; if (this.isRowSelected) { colIdx = topLeftIdx[1]; } } else { rowIdx = range[0]; colIdx = range[1]; if (this.isRowSelected) { colIdx = topLeftIdx[1]; } } const mergeArgs: MergeArgs = { range: [rowIdx, colIdx, ...[rowIdx, colIdx]] }; this.parent.notify(activeCellMergedRange, mergeArgs); if (range !== mergeArgs.range) { isMergeRange = true; } range = mergeArgs.range as number[]; if (sheet.activeCell !== getCellAddress(range[0], range[1]) || isInit) { this.parent.setSheetPropertyOnMute(sheet, 'activeCell', getCellAddress(range[0], range[1])); if (sheet.isProtected) { const element: HTMLTextAreaElement = this.parent.element.querySelector('.e-formula-bar') as HTMLTextAreaElement; const cell: CellModel = getCell(range[0], range[1], sheet); const isCellLocked: boolean = isLocked(cell, getColumn(sheet, range[1])); if (isCellLocked && element && !element.disabled) { element.disabled = true; } else if (!isCellLocked && element && element.disabled) { element.disabled = false; } } if (this.getActiveCell()) { const offset: { left: IOffset, top: IOffset } = this.getOffset(range[2], range[3]); if (isMergeRange) { offset.left = { idx: 0, size: 0 }; } setPosition(this.parent, this.getActiveCell(), range, 'e-active-cell', preventAnimation); } this.parent.notify(activeCellChanged, null); } else { setPosition(this.parent, this.getActiveCell(), range, 'e-active-cell', preventAnimation); } } private getOffset(rowIdx: number, colIdx: number): { left: IOffset, top: IOffset } { const offset: { left: IOffset, top: IOffset } = { left: { idx: 0, size: 0 }, top: { idx: 0, size: 0 } }; if (this.parent.scrollModule) { if (colIdx >= this.parent.scrollModule.offset.left.idx) { offset.left = this.parent.scrollModule.offset.left; } if (rowIdx >= this.parent.scrollModule.offset.top.idx) { offset.top = this.parent.scrollModule.offset.top; } } return offset; } private getSelectionElement(e?: MouseEvent, selectedRowColIdx?: number): HTMLElement { if (e && e.ctrlKey) { const sheet: SheetModel = this.parent.getActiveSheet(); if (isMouseUp(e) || isMouseMove(e)) { if (sheet.frozenColumns || sheet.frozenRows) { let ele: HTMLElement = this.parent.getMainContent().querySelector('.e-cur-selection'); if (ele) { return ele; } else { ele = this.parent.element.querySelector('.e-multi-range'); return ele && ele.cloneNode() as HTMLElement; } } else { return this.parent.getMainContent().querySelector('.e-selection:last-child'); } } else { const selElem: HTMLElement = this.parent.getMainContent().getElementsByClassName('e-selection')[0] as HTMLElement; const ele: HTMLElement = selElem.cloneNode() as HTMLElement; ele.classList.add('e-multi-range'); if (sheet.frozenColumns || sheet.frozenRows) { if (!sheet.selectedRange.includes(' ')) { selElem.classList.remove('e-hide'); setPosition(this.parent, selElem, getSwapRange(getRangeIndexes(sheet.selectedRange)), undefined, false, true); } if (!this.parent.getMainContent().querySelector('.e-multi-range') && selElem.classList.contains('e-hide')) { return selElem; } return ele; } else { selElem.classList.remove('e-hide'); return this.parent.getMainContent().appendChild(ele); } } } else if (selectedRowColIdx > -1) { return this.parent.getMainContent().getElementsByClassName('e-selection')[selectedRowColIdx] as HTMLElement; } else { const elems: NodeListOf<Element> = [].slice.call(this.parent.element.getElementsByClassName('e-multi-range')); elems.forEach((ele: Element) => { remove(ele); }); return this.parent.getMainContent().getElementsByClassName('e-selection')[0] as HTMLElement; } } private getActiveCell(): HTMLElement { return this.parent.getMainContent().getElementsByClassName('e-active-cell')[0] as HTMLElement; } private getSheetElement(): Element { return document.getElementById(this.parent.element.id + '_sheet'); } private highlightHdr(range: number[], isMultiRange?: boolean, isRowRefresh: boolean = true, isColRefresh: boolean = true): void { const sheet: SheetModel = this.parent.getActiveSheet(); if (sheet.showHeaders) { if (!isMultiRange) { removeClass(this.getSheetElement().querySelectorAll('.e-highlight'), 'e-highlight'); removeClass(this.getSheetElement().querySelectorAll('.e-prev-highlight'), 'e-prev-highlight'); } const selectAllEle: Element = this.parent.element.getElementsByClassName('e-select-all-cell')[0]; if (selectAllEle) { removeClass([selectAllEle], ['e-prev-highlight-right', 'e-prev-highlight-bottom']); } const rowHdr: Element[] = []; const colHdr: Element[] = []; const swapRange: number[] = getSwapRange(range); if (this.isRowSelected) { swapRange[1] = skipHiddenIdx(sheet, swapRange[1], true, 'columns'); } if (this.isColSelected) { swapRange[0] = skipHiddenIdx(sheet, swapRange[0], true); } const frozenIdx: number[] = [0, 0, 0, 0]; const indexes: number[] = [0, 0, 0, 0]; const topLeftIndex: number[] = getCellIndexes(sheet.topLeftCell); let i: number; let j: number; const updateIndex: Function = (freezePane: number, layout: string, offset: string): void => { let idx: number; let hiddenCount: number; if (freezePane && swapRange[i] < freezePane) { hiddenCount = this.parent.hiddenCount(topLeftIndex[i], swapRange[i], layout, sheet); frozenIdx[i] = swapRange[i] - hiddenCount - topLeftIndex[i]; idx = swapRange[j] < freezePane ? swapRange[j] : freezePane - 1; frozenIdx[j] = idx - this.parent.hiddenCount(swapRange[i], idx, layout, sheet) - hiddenCount - topLeftIndex[i] + 1; idx = this.parent.viewport[offset] + freezePane; if (swapRange[j] >= idx) { indexes[i] = 0; indexes[i] -= this.parent.hiddenCount(idx, idx, layout, sheet); indexes[j] = swapRange[j] - this.parent.hiddenCount(idx, swapRange[j], layout, sheet) - idx + 1; } } else { idx = this.parent.viewport[offset] + freezePane; hiddenCount = this.parent.hiddenCount(idx, swapRange[i], layout, sheet); indexes[i] = swapRange[i] - hiddenCount - idx; indexes[j] = swapRange[j] - this.parent.hiddenCount(swapRange[i], swapRange[j], layout, sheet) - hiddenCount - idx + 1; } }; const updateCell: Function = (idx: number[], parent: Element, hdrArr: Element[]): void => { const header: Element[] = [].slice.call(parent.getElementsByClassName('e-header-cell')); for (let k: number = idx[i]; k < idx[j]; k++) { if (header[k]) { hdrArr.push(header[k]); } } }; if (isRowRefresh) { i = 0; j = 2; updateIndex(this.parent.frozenRowCount(sheet), 'rows', 'topIndex'); if (sheet.frozenRows) { const selectAllBody: Element = this.parent.getSelectAllContent().querySelector('tbody'); if (selectAllBody) { updateCell(frozenIdx, selectAllBody, rowHdr); } } updateCell(indexes, this.parent.getRowHeaderContent(), rowHdr); } if (isColRefresh) { i = 1; j = 3; updateIndex(this.parent.frozenColCount(sheet), 'columns', 'leftIndex'); if (sheet.frozenColumns) { const selectAllHdr: Element = this.parent.getSelectAllContent().querySelector('thead'); if (selectAllHdr) { updateCell(frozenIdx, selectAllHdr, colHdr); } } updateCell(indexes, this.parent.getColumnHeaderContent(), colHdr); } if (sheet.isProtected && !sheet.protectSettings.selectCells) { removeClass([].concat(rowHdr, colHdr), 'e-highlight'); } else { addClass([].concat(rowHdr, colHdr), 'e-highlight'); } if (rowHdr.length && rowHdr[0].parentElement.previousElementSibling) { rowHdr[0].parentElement.previousElementSibling.classList.add('e-prev-highlight'); } if (colHdr.length && colHdr[0].previousElementSibling) { colHdr[0].previousElementSibling.classList.add('e-prev-highlight'); } if (this.isRowSelected && this.isColSelected) { if (sheet.isProtected && !sheet.protectSettings.selectCells) { document.getElementById(`${this.parent.element.id}_select_all`).classList.remove('e-highlight'); } else { document.getElementById(`${this.parent.element.id}_select_all`).classList.add('e-highlight'); } } if (selectAllEle) { if (swapRange[0] === 0) { selectAllEle.classList.add('e-prev-highlight-bottom'); } if (swapRange[1] === 0) { selectAllEle.classList.add('e-prev-highlight-right'); } } } } private protectHandler(): void { const range: number[] = getRangeIndexes(this.parent.getActiveSheet().selectedRange); const swapRange: number[] = getSwapRange(range); const actRange: number[] = getCellIndexes(this.parent.getActiveSheet().activeCell); const inRange: boolean = swapRange[0] <= actRange[0] && swapRange[2] >= actRange[0] && swapRange[1] <= actRange[1] && swapRange[3] >= actRange[1]; this.selectRangeByIdx(range, null, null, inRange); } private initiateFormulaSelection( args: { range: string, formulaSheetIdx: number }): void { this.processFormulaEditRange(args.range, args.formulaSheetIdx); } private processFormulaEditRange(val: string, formulaStartSheetIdx: number): void { let str: string; let formulaSheetIdx: number = formulaStartSheetIdx; let i: number = 0; const parsedVal: string[] = this.parseFormula(val); const len: number = parsedVal.length; let ctrlKeyCount: number = 0; const formulaBorder: string[][] = [['e-vborderright', 'e-vborderbottom'], ['e-pborderright', 'e-pborderbottom'], ['e-cborderright', 'e-cborderbottom'], ['e-gborderright', 'e-gborderbottom'], ['e-oborderright', 'e-oborderbottom'], ['e-bborderright', 'e-bborderbottom']]; this.clearBorder(); const actSheetIdx: number = this.parent.getActiveSheet().id - 1; while (i < len) { str = parsedVal[i]; if (this.invalidOperators.indexOf(str) > -1) { break; } if (isCellReference(str.toUpperCase())) { str = str.replace(/\$/g, ''); if (i > 0) { if (parsedVal[i - 1].indexOf('!') === parsedVal[i - 1].length - 1) { const splitStr: string[] = parsedVal[i - 1].split('!'); formulaSheetIdx = getSheetIndex(this.parent as Workbook, splitStr[0].substring(1, splitStr[0].length - 1)); } } if (parsedVal[i + 1] === ':') { i++; if (parsedVal[i + 1] && isCellReference(parsedVal[i + 1].toUpperCase())) { str = str + ':' + parsedVal[i + 1]; i++; } } if (actSheetIdx === formulaSheetIdx) { this.updateFormulaEditRange(str, ctrlKeyCount, formulaBorder); } formulaSheetIdx = formulaStartSheetIdx; ctrlKeyCount++; } i++; } } private updateFormulaEditRange(str: string, i: number, formulaBorder: string[][]): void { const indices: number[] = getRangeIndexes(str); this.formulaRange[i] = str; this.dStartCell = { rowIndex: indices[0], colIndex: indices[1] }; this.dEndCell = { rowIndex: indices[2], colIndex: indices[3] }; this.focusBorder(this.dStartCell, this.dEndCell, formulaBorder[i % 6] as string[]); } private chartBorderHandler(args: { startcell: { rowIndex: number, colIndex: number }, endcell: { rowIndex: number, colIndex: number }, classes: string[] }): void { this.focusBorder(args.startcell, args.endcell, args.classes, true); } private focusBorder( startcell: { rowIndex: number, colIndex: number }, endcell: { rowIndex: number, colIndex: number }, classes: string[], isChart?: boolean): void { isChart = isNullOrUndefined(isChart) ? false : isChart; const range: number[] = getSwapRange([startcell.rowIndex, startcell.colIndex, endcell.rowIndex, endcell.colIndex]); const sheet: SheetModel = this.parent.getActiveSheet(); if (sheet.frozenRows || sheet.frozenColumns) { const rangeReference: HTMLElement = this.parent.createElement('div', { className: isChart ? 'e-range-indicator e-chart-range' : 'e-range-indicator e-formuala-range' }); rangeReference.appendChild(this.parent.createElement('div', { className: 'e-top' })); rangeReference.appendChild(this.parent.createElement('div', { className: 'e-bottom' })); rangeReference.appendChild(this.parent.createElement('div', { className: 'e-left' })); rangeReference.appendChild(this.parent.createElement('div', { className: 'e-right' })); setPosition(this.parent, rangeReference, range, 'e-range-indicator'); return; } const minr: number = range[0]; const minc: number = range[1]; const maxr: number = range[2]; const maxc: number = range[3]; if (minr) { (this.getEleFromRange([minr - 1, minc, minr - 1, maxc])).forEach((td: HTMLElement): void => { if (td) { td.classList.add(classes[1]); if (!isChart) { td.classList.add('e-formularef-selection'); } } }); // top } (this.getEleFromRange([minr, maxc, maxr, maxc])).forEach((td: HTMLElement): void => { if (td) { td.classList.add(classes[0]); if (!isChart) { td.classList.add('e-formularef-selection'); } } }); // right this.getEleFromRange([maxr, minc, maxr, maxc]).forEach((td: HTMLElement): void => { if (td) { td.classList.add(classes[1]); if (!isChart) { td.classList.add('e-formularef-selection'); } } }); // bottom if (minc) { (this.getEleFromRange([minr, minc - 1, maxr, minc - 1])).forEach((td: HTMLElement): void => { if (td) { td.classList.add(classes[0]); if (!isChart) { td.classList.add('e-formularef-selection'); } } }); // left } } private getEleFromRange(range: number[]): HTMLElement[] { let startRIndex: number = range[0]; let startCIndex: number = range[1]; let endRIndex: number = range[2]; let endCIndex: number = range[3]; let i: number; let rowIdx: number; let temp: number; let tempCells: Element[] = []; let rowCells: HTMLCollectionOf<Element>; const cells: HTMLElement[] = []; if (startRIndex > endRIndex) { temp = startRIndex; startRIndex = endRIndex; endRIndex = temp; } if (startCIndex > endCIndex) { temp = startCIndex; startCIndex = endCIndex; endCIndex = temp; } if (this.parent.scrollSettings.enableVirtualization) { for (i = startRIndex; i <= endRIndex; i++) { rowIdx = i; if (rowIdx > -1) { const row: Element = this.parent.getRow(rowIdx, null ); if (row) { rowCells = row.getElementsByClassName('e-cell') as HTMLCollectionOf<Element>; tempCells = (endCIndex === startCIndex) ? [rowCells[endCIndex]] : this.getRowCells(rowCells, startCIndex, endCIndex + 1); this.merge(cells, tempCells); } } } } return cells; } private getRowCells(rowCells: HTMLCollectionOf<Element>, startCIndex: number, endCIndex: number): HTMLElement[] { const tdCol: HTMLElement[] = []; for (startCIndex; startCIndex < endCIndex; startCIndex++) { if (rowCells[startCIndex]) { tdCol.push(rowCells[startCIndex] as HTMLElement); } } return tdCol; } private merge(first: HTMLElement[], second: Element[]): void { if (!first || !second) { return; } Array.prototype.push.apply(first, second); } private clearBorder(): void { const sheet: SheetModel = this.parent.getActiveSheet(); if (sheet.frozenColumns || sheet.frozenRows) { const formualIndicator: Element[] = [].slice.call(this.parent.element.getElementsByClassName('e-formuala-range')); formualIndicator.forEach((indicator: Element): void => { detach(indicator); }); return; } const borderEleColl: HTMLCollectionOf<Element> = this.parent.element.getElementsByClassName('e-formularef-selection') as HTMLCollectionOf<Element>; for (let idx: number = 0; idx < borderEleColl.length; idx++) { const td: HTMLElement = borderEleColl[idx] as HTMLElement; const classArr: string[] = ['e-vborderright', 'e-vborderbottom', 'e-pborderright', 'e-pborderbottom', 'e-cborderright', 'e-cborderbottom', 'e-gborderright', 'e-gborderbottom', 'e-oborderright', 'e-oborderbottom', 'e-bborderright', 'e-bborderbottom']; for (let idx: number = 0; idx < classArr.length; idx++) { td.classList.remove(classArr[idx]); } } // for (let idx: number = 0; idx < borderEleColl.length; idx++) { // const td: HTMLElement = borderEleColl[idx] as HTMLElement; // } } private parseFormula(formulaStr: string): string[] { let tempStr: string; let str: string; let i: number = 0; const arr: string[] = []; formulaStr = this.markSpecialChar(formulaStr.replace('=', '')); const formula: string[] = formulaStr.split(/\(|\)|=|\^|>|<|,|:|\+|-|\*|\/|%|&/g); const len: number = formula.length; while (i < len) { tempStr = formula[i]; if (!tempStr) { i++; continue; } if (tempStr.length === 1) { arr.push(this.isUniqueChar(tempStr) ? this.getUniqueCharVal(tempStr) : tempStr); } else { str = tempStr[0]; if (tempStr.indexOf('!') > 0) { if (this.isUniqueChar(str)) { arr.push(this.getUniqueCharVal(str)); tempStr = tempStr.substr(1); } const strVal: number = tempStr.indexOf('!') + 1; arr.push(tempStr.substr(0, strVal)); arr.push(tempStr.substr(strVal)); } else if (this.isUniqueChar(str)) { arr.push(this.getUniqueCharVal(str)); arr.push(tempStr.substr(1)); } else { arr.push(tempStr); } } i++; } return arr; } private isUniqueChar(str: string): boolean { const code: number = str.charCodeAt(str.charAt[0]); return code >= 129 && code <= 142; } private getUniqueCharVal(tempStr: string): string { switch (tempStr) { case this.uniqueOBracket: return '('; case this.uniqueCBracket: return ')'; case this.uniqueCOperator: return ':'; case this.uniqueSOperator: return '-'; case this.uniquePOperator: return '+'; case this.uniqueMOperator: return '*'; case this.uniqueDOperator: return '/'; case this.uniqueModOperator: return '%'; case this.uniqueCSeparator: return ','; case this.uniqueConcateOperator: return '&'; case this.uniqueEqualOperator: return '='; case this.uniqueExpOperator: return '^'; case this.uniqueLTOperator: return '<'; case this.uniqueGTOperator: return '>'; } return ''; } private markSpecialChar(formulaVal: string): string { formulaVal = formulaVal.replace(/\(/g, '(' + this.uniqueOBracket).replace(/\)/g, ')' + this.uniqueCBracket); formulaVal = formulaVal.replace(/,/g, ',' + this.uniqueCSeparator).replace(/:/g, ':' + this.uniqueCOperator); formulaVal = formulaVal.replace(/\+/g, '+' + this.uniquePOperator).replace(/-/g, '-' + this.uniqueSOperator); formulaVal = formulaVal.replace(/\*/g, '*' + this.uniqueMOperator).replace(/\//g, '/' + this.uniqueDOperator); formulaVal = formulaVal.replace(/&/g, '&' + this.uniqueConcateOperator); formulaVal = formulaVal.replace(/=/g, '=' + this.uniqueEqualOperator); formulaVal = formulaVal.replace(/\^/g, '^' + this.uniqueExpOperator); formulaVal = formulaVal.replace(/>/g, '>' + this.uniqueGTOperator).replace(/</g, '<' + this.uniqueLTOperator); return formulaVal.replace(/%/g, '%' + this.uniqueModOperator); } /** * For internal use only - Get the module name. * * @private * @returns {string} - Get the module name. */ protected getModuleName(): string { return 'selection'; } public destroy(): void { this.removeEventListener(); this.parent = null; } }
the_stack
import { AST_NODE_TYPES, AST_TOKEN_TYPES, STORAGE_CLASS, } from '../ast/glsl-ast-node-types'; import { ArrayExpression, AssignmentExpression, BinaryExpression, CallExpression, DeclarationStatement, ExpressionStatement, ForStatement, FunctionDeclaration, Identifier, IfStatement, Literal, MemberExpression, NumThreadStatement, ReturnStatement, Scalar, UpdateExpression, VariableDeclaration, VariableDeclarator, } from '../ast/glsl-tree'; import { parse } from '../pegjs/g'; import { Transformer } from '../Transformer'; describe('Transformation', () => { const transformer = new Transformer(); describe('Statement', () => { describe('Variable Declaration', () => { test('should transform variable declaration statement correctly.', () => { const shaderProgram = transformer.transform(parse('let a = 10;')); expect(shaderProgram.body.length).toBe(1); const declaration = shaderProgram.body[0] as VariableDeclaration; expect(declaration.declarations.length).toBe(1); const declarator = declaration.declarations[0] as VariableDeclarator; expect(declarator.id.type).toBe(AST_NODE_TYPES.Identifier); expect(declarator.id.name).toBe('a'); expect(declarator.id.dataType).toBe(AST_TOKEN_TYPES.Float); // 未声明类型,默认使用 f32 expect((declarator.init as Literal).type).toBe(AST_TOKEN_TYPES.Float); expect((declarator.init as Literal).value).toBe(10); }); test('should transform variable declaration statement correctly.', () => { const shaderProgram = transformer.transform( parse('let a = [1, 2, 3];'), ); expect(shaderProgram.body.length).toBe(1); const declaration = shaderProgram.body[0] as VariableDeclaration; expect(declaration.declarations.length).toBe(1); const declarator = declaration.declarations[0] as VariableDeclarator; expect(declarator.id.type).toBe(AST_NODE_TYPES.Identifier); expect(declarator.id.name).toBe('a'); expect(declarator.id.dataType).toBe(AST_TOKEN_TYPES.Vector3Float); // 未声明类型,默认使用 f32 expect((declarator.init as ArrayExpression).type).toBe( AST_NODE_TYPES.ArrayExpression, ); expect((declarator.init as ArrayExpression).elements.length).toBe(3); expect((declarator.init as ArrayExpression).elements[0].type).toBe( AST_TOKEN_TYPES.Float, ); expect( ((declarator.init as ArrayExpression).elements[0] as Scalar).value, ).toBe(1); }); test('should transform const declaration statement correctly.', () => { const shaderProgram = transformer.transform(parse('const AAA = 10;')); expect(shaderProgram.body.length).toBe(1); const declaration = shaderProgram.body[0] as VariableDeclaration; expect(declaration.declarations.length).toBe(1); const declarator = declaration.declarations[0] as VariableDeclarator; expect(declarator.id.type).toBe(AST_NODE_TYPES.Identifier); expect(declarator.id.name).toBe('AAA'); expect(declarator.storageClass).toBe(STORAGE_CLASS.UniformConstant); expect(declarator.id.dataType).toBe(AST_TOKEN_TYPES.Float); // 未声明类型,默认使用 f32 expect((declarator.init as Literal).type).toBe(AST_TOKEN_TYPES.Float); expect((declarator.init as Literal).value).toBe(10); }); test('should transform variable declaration statement with type annotation correctly.', () => { const shaderProgram = transformer.transform( parse('const a: int = 10;\nconst b: bool = false;'), ); expect(shaderProgram.body.length).toBe(2); const declaration1 = shaderProgram.body[0] as VariableDeclaration; expect(declaration1.declarations.length).toBe(1); const declarator1 = declaration1.declarations[0] as VariableDeclarator; expect(declarator1.id.type).toBe(AST_NODE_TYPES.Identifier); expect(declarator1.id.name).toBe('a'); expect(declarator1.id.dataType).toBe(AST_TOKEN_TYPES.Int32); expect((declarator1.init as Literal).type).toBe(AST_TOKEN_TYPES.Int32); expect((declarator1.init as Literal).value).toBe(10); const declaration2 = shaderProgram.body[1] as VariableDeclaration; expect(declaration2.declarations.length).toBe(1); const declarator2 = declaration2.declarations[0] as VariableDeclarator; expect(declarator2.id.type).toBe(AST_NODE_TYPES.Identifier); expect(declarator2.id.name).toBe('b'); expect(declarator2.id.dataType).toBe(AST_TOKEN_TYPES.Boolean); expect((declarator2.init as Literal).type).toBe( AST_TOKEN_TYPES.Boolean, ); expect((declarator2.init as Literal).value).toBe(false); }); test('should generate numthreads statement correctly.', () => { const shaderProgram = transformer.transform( parse(` @numthreads(8, 1, 1) class Demo {}`), ); expect(shaderProgram.body.length).toBe(1); const numthreadsDeclaration = shaderProgram .body[0] as NumThreadStatement; expect(numthreadsDeclaration.type).toBe( AST_NODE_TYPES.NumThreadStatement, ); expect(numthreadsDeclaration.threadGroupSize).toEqual([8, 1, 1]); }); test('should generate variable declaration with storage class correctly.', () => { const shaderProgram = transformer.transform( parse(` class Demo { @in p1: float; @in @out p2: float[]; }`), ); expect(shaderProgram.body.length).toBe(1); const variableDeclaration = shaderProgram .body[0] as VariableDeclaration; expect(variableDeclaration.type).toBe( AST_NODE_TYPES.VariableDeclaration, ); expect(variableDeclaration.declarations.length).toBe(2); expect(variableDeclaration.declarations[0].id.name).toBe('p1'); expect(variableDeclaration.declarations[0].id.dataType).toBe( AST_TOKEN_TYPES.Float, ); expect(variableDeclaration.declarations[0].storageClass).toBe( STORAGE_CLASS.Uniform, ); expect(variableDeclaration.declarations[1].id.name).toBe('p2'); expect(variableDeclaration.declarations[1].id.dataType).toBe( AST_TOKEN_TYPES.FloatArray, ); expect(variableDeclaration.declarations[1].storageClass).toBe( STORAGE_CLASS.StorageBuffer, ); }); }); describe('Function Declaration', () => { test('should transform function declaration statement with type annotation correctly.', () => { const shaderProgram = transformer.transform( parse(`function f1(p1: int, p2: float): float { const a: int = 1; a = a + 2; return a + 2; }`), ); // scope 中最后一个变量是 f1 expect(shaderProgram.scope?.length).toBe(8); expect(shaderProgram.scope![7].isFunction).toBe(true); expect(shaderProgram.scope![7].id.name).toBe('f1'); expect(shaderProgram.scope![7].id.dataType).toBe(AST_TOKEN_TYPES.Float); expect(shaderProgram.body.length).toBe(1); const declaration1 = shaderProgram.body[0] as FunctionDeclaration; expect(declaration1.type).toBe(AST_NODE_TYPES.FunctionDeclaration); expect(declaration1.id.type).toBe(AST_NODE_TYPES.Identifier); expect(declaration1.id.name).toBe('f1'); expect(declaration1.params.length).toBe(2); expect(declaration1.params[0].name).toBe('p1'); expect(declaration1.params[0].dataType).toBe(AST_TOKEN_TYPES.Int32); expect(declaration1.params[1].name).toBe('p2'); expect(declaration1.params[1].dataType).toBe(AST_TOKEN_TYPES.Float); expect(declaration1.body.type).toBe(AST_NODE_TYPES.BlockStatement); expect(declaration1.body.body.length).toBe(3); // const a: int = 1; expect(declaration1.body.body[0].type).toBe( AST_NODE_TYPES.VariableDeclaration, ); // a = a + 2; const expressionStatement = declaration1.body .body[1] as ExpressionStatement; const assignment = expressionStatement.expression as AssignmentExpression; expect(assignment.operator).toBe('='); expect(assignment.left.type).toBe(AST_NODE_TYPES.Identifier); // @ts-ignore expect(assignment.left.dataType).toBe(AST_TOKEN_TYPES.Int32); expect(assignment.right.type).toBe(AST_NODE_TYPES.BinaryExpression); // @ts-ignore expect(assignment.right.left.dataType).toBe(AST_TOKEN_TYPES.Int32); // return a + 2; const returnStatement = declaration1.body.body[2] as ReturnStatement; expect(returnStatement.type).toBe(AST_NODE_TYPES.ReturnStatement); expect(returnStatement.argument?.type).toBe( AST_NODE_TYPES.BinaryExpression, ); const binaryExpression = returnStatement.argument as BinaryExpression; expect(binaryExpression.operator).toBe('+'); expect(binaryExpression.left.type).toBe(AST_NODE_TYPES.Identifier); expect((binaryExpression.left as Identifier).dataType).toBe( AST_TOKEN_TYPES.Int32, ); // expect(binaryExpression.right.type).toBe(AST_TOKEN_TYPES.Int32); expect(declaration1.returnType).toBe(AST_TOKEN_TYPES.Float); }); test('should use builtin variables in root scope correctly.', () => { const shaderProgram = transformer.transform( parse(`function f1(): int { const a = globalInvocationID; }`), ); // scope 中最后一个变量是 f1 expect(shaderProgram.scope?.length).toBe(8); expect(shaderProgram.scope![7].isFunction).toBe(true); expect(shaderProgram.scope![7].id.name).toBe('f1'); expect(shaderProgram.scope![7].id.dataType).toBe(AST_TOKEN_TYPES.Int32); expect(shaderProgram.body.length).toBe(1); const functionDeclaration = shaderProgram .body[0] as FunctionDeclaration; expect(functionDeclaration.type).toBe( AST_NODE_TYPES.FunctionDeclaration, ); // const a = globalInvocationID; const variableDeclaration = functionDeclaration.body .body[0] as VariableDeclaration; expect(variableDeclaration.type).toBe( AST_NODE_TYPES.VariableDeclaration, ); const declarator1 = variableDeclaration .declarations[0] as VariableDeclarator; expect(declarator1.id.type).toBe(AST_NODE_TYPES.Identifier); expect(declarator1.id.name).toBe('a'); // 这里不进行类型转换,在生成代码时进行 expect(declarator1.id.dataType).toBe(AST_TOKEN_TYPES.Vector3Int); expect((declarator1.init as Identifier).type).toBe( AST_NODE_TYPES.Identifier, ); expect((declarator1.init as Identifier).dataType).toBe( AST_TOKEN_TYPES.Vector3Int, ); }); }); // https://gpuweb.github.io/gpuweb/wgsl.html#control-flow describe('Control Flow', () => { test('should transform for statement correctly.', () => { const shaderProgram = transformer.transform( parse(`for (let i: int = 0; i < 10; i++) { }`), ); expect(shaderProgram.body.length).toBe(1); const forStatement = shaderProgram.body[0] as ForStatement; expect(forStatement.type).toBe(AST_NODE_TYPES.ForStatement); expect((forStatement.init as VariableDeclaration).type).toBe( AST_NODE_TYPES.VariableDeclaration, ); }); test('should transform for statement with AssignmentExpression correctly.', () => { const shaderProgram = transformer.transform( parse(` let i: int; for (i = 0; i < 10; i++) { }`), ); expect(shaderProgram.body.length).toBe(2); const forStatement = shaderProgram.body[1] as ForStatement; expect(forStatement.type).toBe(AST_NODE_TYPES.ForStatement); expect((forStatement.init as AssignmentExpression).type).toBe( AST_NODE_TYPES.AssignmentExpression, ); expect((forStatement.test as BinaryExpression).type).toBe( AST_NODE_TYPES.BinaryExpression, ); expect((forStatement.test as BinaryExpression).right.type).toBe( AST_TOKEN_TYPES.Int32, ); // @ts-ignore expect((forStatement.test as BinaryExpression).right.value).toBe(10); expect((forStatement.update as UpdateExpression).type).toBe( AST_NODE_TYPES.UpdateExpression, ); expect((forStatement.update as UpdateExpression).operator).toBe('++'); }); test('should transform if statement correctly.', () => { const shaderProgram = transformer.transform( parse('if (a > 0) {} else {}'), ); expect(shaderProgram.body.length).toBe(1); const ifStatement = shaderProgram.body[0] as IfStatement; expect(ifStatement.type).toBe(AST_NODE_TYPES.IfStatement); expect(ifStatement.consequent.type).toBe(AST_NODE_TYPES.BlockStatement); expect(ifStatement.alternate?.type).toBe(AST_NODE_TYPES.BlockStatement); }); test('should transform if statement without alternate correctly.', () => { const shaderProgram = transformer.transform(parse('if (a > 0) {}')); expect(shaderProgram.body.length).toBe(1); const ifStatement = shaderProgram.body[0] as IfStatement; expect(ifStatement.type).toBe(AST_NODE_TYPES.IfStatement); expect(ifStatement.consequent.type).toBe(AST_NODE_TYPES.BlockStatement); expect(ifStatement.alternate).toBeNull(); }); }); }); describe('Expression', () => { test('should transform call expression correctly.', () => { const shaderProgram = transformer.transform(parse('fn(1, 2);')); expect(shaderProgram.body.length).toBe(1); const expressionStatement = shaderProgram.body[0] as ExpressionStatement; const callExpression = expressionStatement.expression as CallExpression; expect(callExpression.type).toBe(AST_NODE_TYPES.CallExpression); // @ts-ignore expect(callExpression.callee.name).toBe('fn'); expect(callExpression.arguments.length).toBe(2); // @ts-ignore expect(callExpression.arguments[0].value).toBe(1); // @ts-ignore expect(callExpression.arguments[1].value).toBe(2); }); test('should transform non-computed member expression correctly.', () => { const shaderProgram = transformer.transform(parse('a.xyz;')); expect(shaderProgram.body.length).toBe(1); const expressionStatement = shaderProgram.body[0] as ExpressionStatement; const memberExpression = expressionStatement.expression as MemberExpression; expect(memberExpression.type).toBe(AST_NODE_TYPES.MemberExpression); expect(memberExpression.computed).toBe(false); // @ts-ignore expect(memberExpression.object.name).toBe('a'); // @ts-ignore expect(memberExpression.property.name).toBe('xyz'); }); test('should transform computed member expression correctly.', () => { const shaderProgram = transformer.transform(parse('a[c];')); expect(shaderProgram.body.length).toBe(1); const expressionStatement = shaderProgram.body[0] as ExpressionStatement; const memberExpression = expressionStatement.expression as MemberExpression; expect(memberExpression.type).toBe(AST_NODE_TYPES.MemberExpression); expect(memberExpression.computed).toBe(true); // @ts-ignore expect(memberExpression.object.name).toBe('a'); // @ts-ignore expect(memberExpression.property.name).toBe('c'); }); }); });
the_stack
import { MobxLitElement } from '@adobe/lit-mobx'; import { aTimeout, fixture, fixtureCleanup, html } from '@open-wc/testing/index-no-side-effects'; import { assert } from 'chai'; import { customElement, LitElement } from 'lit-element'; import * as sinon from 'sinon'; import './error_handler'; import { errorHandler, forwardWithoutMsg, reportError, reportErrorAsync } from './error_handler'; @customElement('milo-error-handler-test-default') @errorHandler() class ErrorHandlerTestDefaultElement extends LitElement { protected render() { return html`<slot></slot>`; } } @customElement('milo-error-handler-test-on-error-returns-prop') @errorHandler((err) => { err.stopPropagation(); return false; }) class ErrorHandlerTestOnErrorReturnsPropElement extends MobxLitElement { protected render() { return html`<slot></slot>`; } } describe('errorHandler', () => { it('should render error message by default', async () => { after(fixtureCleanup); const errorHandlerEle = await fixture<ErrorHandlerTestDefaultElement>(html` <milo-error-handler-test-default> <div></div> </milo-error-handler-test-default> `); const childEle = errorHandlerEle.querySelector('div')!; childEle.dispatchEvent(new ErrorEvent('error', { error: new Error(), message: 'error msg', bubbles: true })); await aTimeout(0); assert.include(errorHandlerEle.shadowRoot?.querySelector('pre')?.textContent, 'error msg'); }); it('should update error message when received a new error event', async () => { after(fixtureCleanup); const errorHandlerEle = await fixture<ErrorHandlerTestDefaultElement>(html` <milo-error-handler-test-default> <div></div> </milo-error-handler-test-default> `); const childEle = errorHandlerEle.querySelector('div')!; childEle.dispatchEvent(new ErrorEvent('error', { error: new Error(), message: 'error msg', bubbles: true })); await aTimeout(0); assert.include(errorHandlerEle.shadowRoot?.querySelector('pre')?.textContent, 'error msg'); childEle.dispatchEvent(new ErrorEvent('error', { error: new Error(), message: 'error msg 2', bubbles: true })); await aTimeout(0); assert.include(errorHandlerEle.shadowRoot?.querySelector('pre')?.textContent, 'error msg 2'); }); it('should render the original content when onErrorRender returns false', async () => { after(fixtureCleanup); const errorHandlerEle = await fixture<ErrorHandlerTestOnErrorReturnsPropElement>(html` <milo-error-handler-test-on-error-returns-prop> <div></div> </milo-error-handler-test-on-error-returns-prop> `); const childEle = errorHandlerEle.querySelector('div')!; childEle.dispatchEvent(new ErrorEvent('error', { error: new Error(), message: '', bubbles: true })); await aTimeout(0); assert.strictEqual(errorHandlerEle.shadowRoot!.querySelector('pre'), null); }); }); describe('reportError', () => { it('should dispatch an error event when the fn throws', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); assert.throw( reportError(div, () => { throw err; }), SpecialErrorClass ); assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); it('should not throw the error when fallbackFn is provided', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); reportError( div, () => { throw err; }, () => {} )(); assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); it('should still dispatch the original error event when fallbackFn throws', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} class FallbackErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); const fallbackErr = new FallbackErrorClass('fallback err msg'); assert.throw( reportError( div, () => { throw err; }, () => { throw fallbackErr; } ), FallbackErrorClass ); assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); }); describe('reportErrorAsync', () => { it('should dispatch an error event when the fn throws', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); try { await reportErrorAsync(div, async () => { throw err; })(); assert.fail("should've thrown an error"); } catch (e) { if (e instanceof SpecialErrorClass) { assert.strictEqual(e, err); } else { throw e; } } assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); it('should dispatch an error event when the fn throws immediately', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); try { await reportErrorAsync(div, () => { throw err; })(); assert.fail("should've thrown an error"); } catch (e) { if (e instanceof SpecialErrorClass) { assert.strictEqual(e, err); } else { throw e; } } assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); it('should not throw the error when fallbackFn is provided', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); await reportErrorAsync( div, () => { throw err; }, async () => {} )(); assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); it('should still dispatch the original error event when fallbackFn throws', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} class FallbackErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); const fallbackErr = new FallbackErrorClass('fallback err msg'); try { await reportErrorAsync( div, async () => { throw err; }, async () => { throw fallbackErr; } )(); assert.fail("should've thrown an error"); } catch (e) { if (e instanceof FallbackErrorClass) { assert.strictEqual(e, fallbackErr); } else { throw e; } } assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); it('should still dispatch the original error event when fallbackFn throws immediately', async () => { const div = document.createElement('div'); const dispatchEventStub = sinon.stub(div, 'dispatchEvent'); class SpecialErrorClass extends Error {} class FallbackErrorClass extends Error {} const err = new SpecialErrorClass('err msg'); const fallbackErr = new FallbackErrorClass('fallback err msg'); try { await reportErrorAsync( div, async () => { throw err; }, () => { throw fallbackErr; } )(); assert.fail("should've thrown an error"); } catch (e) { if (e instanceof FallbackErrorClass) { assert.strictEqual(e, fallbackErr); } else { throw e; } } assert.strictEqual(dispatchEventStub.callCount, 1); const event = dispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, 'err msg'); }); }); @customElement('milo-error-handler-test-forward-without-msg') @errorHandler(forwardWithoutMsg) class ErrorHandlerTestForwardWithoutMsgElement extends LitElement { protected render() { return html`<slot></slot>`; } } @customElement('milo-error-handler-test-recover') @errorHandler((e) => { e.stopImmediatePropagation(); e.preventDefault(); return false; }) class ErrorHandlerTestRecoverElement extends LitElement { protected render() { return html`<slot></slot>`; } } describe('forwardWithoutMsg', () => { it('should dispatch an error event to the parent element with the same error but no message', async () => { after(fixtureCleanup); const parentEle = await fixture(html` <div> <milo-error-handler-test-forward-without-msg> <div></div> </milo-error-handler-test-forward-without-msg> </div> `); const parentDispatchEventStub = sinon.stub(parentEle, 'dispatchEvent'); const errorHandlerEle = parentEle.querySelector<ErrorHandlerTestForwardWithoutMsgElement>( 'milo-error-handler-test-forward-without-msg' )!; const err = new Error('error msg'); const childEle = errorHandlerEle.querySelector('div')!; childEle.dispatchEvent(new ErrorEvent('error', { error: err, message: 'error msg', bubbles: true })); await aTimeout(0); assert.include(errorHandlerEle.shadowRoot?.querySelector('pre')?.textContent, 'error msg'); assert.strictEqual(parentDispatchEventStub.callCount, 1); const event = parentDispatchEventStub.getCall(0).args[0]; assert.instanceOf(event, ErrorEvent); assert.isTrue(event.bubbles); assert.isTrue(event.composed); assert.strictEqual((event as ErrorEvent).error, err); assert.strictEqual((event as ErrorEvent).message, ''); }); it('should recover from the error if e.preventDefault() is called', async () => { after(fixtureCleanup); const parentEle = await fixture(html` <milo-error-handler-test-recover> <milo-error-handler-test-forward-without-msg> <div></div> </milo-error-handler-test-forward-without-msg> </milo-error-handler-test-recover> `); const errorHandlerEle = parentEle.querySelector<ErrorHandlerTestForwardWithoutMsgElement>( 'milo-error-handler-test-forward-without-msg' )!; const err = new Error('error msg'); const childEle = errorHandlerEle.querySelector('div')!; childEle.dispatchEvent( new ErrorEvent('error', { error: err, message: 'error msg', bubbles: true, cancelable: true }) ); await aTimeout(0); assert.strictEqual(errorHandlerEle.shadowRoot?.querySelector('pre'), null); }); it('can recover from the error even when the error is forwarded multiple times', async () => { after(fixtureCleanup); const parentEle = await fixture<ErrorHandlerTestRecoverElement>(html` <milo-error-handler-test-recover> <milo-error-handler-test-forward-without-msg id="outer"> <div> <milo-error-handler-test-forward-without-msg id="inner"> <div id="child"></div> </milo-error-handler-test-forward-without-msg> </div> </milo-error-handler-test-forward-without-msg> </milo-error-handler-test-recover> `); const outerErrorHandlerEle = parentEle.querySelector<ErrorHandlerTestForwardWithoutMsgElement>('#outer')!; const innerErrorHandlerEle = parentEle.querySelector<ErrorHandlerTestForwardWithoutMsgElement>('#inner')!; const err = new Error('error msg'); const childEle = innerErrorHandlerEle.querySelector('#child')!; childEle.dispatchEvent( new ErrorEvent('error', { error: err, message: 'error msg', bubbles: true, cancelable: true }) ); await aTimeout(0); assert.strictEqual(outerErrorHandlerEle.shadowRoot?.querySelector('pre'), null); assert.strictEqual(innerErrorHandlerEle.shadowRoot?.querySelector('pre'), null); }); });
the_stack
/// <reference path="Atomic.d.ts" /> /// <reference path="Editor.d.ts" /> /// <reference path="ToolCore.d.ts" /> /// <reference path="WebView.d.ts" /> declare module Editor.Templates { // Commented out until the TSDoc gets updated to the latest version of TypeScript //export type TemplateType = "component" | "script"; /** * New file defintion */ export interface FileTemplateDefinition { /** name to display in the dropdown */ name: string; /** description */ desc: string; /** type of template */ templateType: string; /** file extension */ ext: string; /** file name/path of the source templage file to clone from. Note, needs to be in the atomic cache */ filename: string; } } declare module Editor.Extensions { /** * Base interface for any editor services. */ export interface EditorServiceExtension { /** * Unique name of this service * @type {string} */ name: string; /** * Description of this service * @type {string} */ description: string; } /** * Base Service Event Listener. Attach descendents of these to an EditorServiceExtension * to hook service events */ export interface ServiceEventListener extends EditorServiceExtension { } interface EventDispatcher { /** * Send a custom event. This can be used by services to publish custom events * @param {string} eventType * @param {any} data */ sendEvent(eventType: string, data: any); sendEvent<T extends Atomic.EventMetaData>(eventType:string, data?:T); sendEvent<T extends Atomic.EventCallbackMetaData>(eventCallbackMetaData:T); /** * Subscribe to an event and provide a callback. This can be used by services to subscribe to custom events * @param {string} eventType * @param {any} callback */ subscribeToEvent?(eventType: string, callback: (...params) => any); /** * Subscribe to an event with a pre-wrapped event object. This can be used by services to subscribe to custom events * @param {Atomic.EventMetaData} wrappedEvent */ subscribeToEvent?(wrappedEvent: Atomic.EventMetaData); } /** * Generic service locator of editor services that may be injected by either a plugin * or by the editor itself. */ export interface ServiceLoader extends EventDispatcher { /** * Loads a service into a service registry * @param {EditorService} service */ loadService(service: EditorServiceExtension): void; } /** * Service registry interface for registering services */ export interface ServicesProvider<T extends ServiceEventListener> { registeredServices: T[]; /** * Adds a service to the registered services list for this type of service * @param {T} service the service to register */ register(service: T); /** * Removes a service from the registered services list for this type of service * @param {T} service the service to unregister */ unregister(service: T); } /** * Interface that describes a Resource Editor Factory that will build out the editor for the relevant resource type */ export interface ResourceEditorBuilder { /** * Returns true if this builder can generate an editor for this resource type */ canHandleResource(resourcePath: string) : boolean; /** * Generates a resource editor for the provided resource type * @param resourceFrame * @param resourcePath * @param tabContainer * @param lineNumber */ getEditor(resourceFrame: Atomic.UIWidget, resourcePath: string, tabContainer: Atomic.UITabContainer, lineNumber: number) : Editor.ResourceEditor; } } declare module Editor.Modal { export interface ExtensionWindow extends Atomic.UIWindow { hide(); } } declare module Editor.HostExtensions { /** * Generic service locator of editor services that may be injected by either a plugin * or by the editor itself. */ export interface HostServiceLocator extends Editor.Extensions.ServiceLoader { resourceServices: ResourceServicesProvider; projectServices: ProjectServicesProvider; sceneServices: SceneServicesProvider; uiServices: UIServicesProvider; } export interface HostEditorService extends Editor.Extensions.EditorServiceExtension { /** * Called by the service locator at load time */ initialize(serviceLocator: HostServiceLocator); } export interface ResourceServicesEventListener extends Editor.Extensions.ServiceEventListener { /** * Called once a resource is saved */ save?(ev: Editor.EditorSaveResourceEvent); /** * Called when a resource is deleted */ delete?(ev: Editor.EditorDeleteResourceEvent); /** * Called when a resource is renamed */ rename?(ev: Editor.EditorRenameResourceNotificationEvent); /** * Called when a resource is about to be edited */ edit?(ev: Editor.EditorEditResourceEvent); } export interface ResourceServicesProvider extends Editor.Extensions.ServicesProvider<ResourceServicesEventListener> { createMaterial(resourcePath: string, materialName: string, reportError: boolean): boolean; } export interface ProjectServicesEventListener extends Editor.Extensions.ServiceEventListener { projectUnloaded?(); projectLoaded?(ev: Editor.EditorLoadProjectEvent); playerStarted?(); } export interface ProjectServicesProvider extends Editor.Extensions.ServicesProvider<ProjectServicesEventListener> { /** * Return a preference value or the provided default from the user settings file * @param {string} extensionName name of the extension the preference lives under * @param {string} preferenceName name of the preference to retrieve * @param {number | boolean | string} defaultValue value to return if pref doesn't exist * @return {number|boolean|string} */ getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number; getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string; getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean; /** * Return a preference value or the provided default from the global user settings file * @param {string} extensionName name of the section the preference lives under * @param {string} preferenceName name of the preference to retrieve * @param {number | boolean | string} defaultValue value to return if pref doesn't exist * @return {number|boolean|string} */ getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number; getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string; getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean; /** * Sets a user preference value in the project settings file * @param {string} extensionName name of the extension the preference lives under * @param {string} preferenceName name of the preference to set * @param {number | boolean | string} value value to set */ setUserPreference(extensionName: string, preferenceName: string, value: number | boolean | string); /** * Sets an editor preference value in the global editor settings file * @param {string} groupName name of the section the preference lives under * @param {string} preferenceName name of the preference to set * @param {number | boolean | string} value value to set */ setApplicationPreference(groupName: string, preferenceName: string, value: number | boolean | string); } export interface SceneServicesEventListener extends Editor.Extensions.ServiceEventListener { activeSceneEditorChanged?(ev: Editor.EditorActiveSceneEditorChangeEvent); editorSceneClosed?(ev: Editor.EditorSceneClosedEvent); } export interface SceneServicesProvider extends Editor.Extensions.ServicesProvider<SceneServicesEventListener> { } export interface UIServicesEventListener extends Editor.Extensions.ServiceEventListener { menuItemClicked?(refid: string): boolean; projectContextItemClicked?(asset: ToolCore.Asset, refid: string): boolean; projectAssetClicked?(asset: ToolCore.Asset): boolean; hierarchyContextItemClicked?(node: Atomic.Node, refid: string): boolean; /** * Handle messages that are submitted via Atomic.Query from within a web view editor. * @param message The message type that was submitted to be used to determine what the data contains if present * @param data any additional data that needs to be submitted with the message */ handleWebMessage?(messageType: string, data?: any): void; } export interface UIServicesProvider extends Editor.Extensions.ServicesProvider<UIServicesEventListener> { createPluginMenuItemSource(id: string, items: any): Atomic.UIMenuItemSource; removePluginMenuItemSource(id: string); createHierarchyContextMenuItemSource(id: string, items: any): Atomic.UIMenuItemSource; removeHierarchyContextMenuItemSource(id: string); createProjectContextMenuItemSource(id: string, items: any): Atomic.UIMenuItemSource; removeProjectContextMenuItemSource(id: string); refreshHierarchyFrame(); loadCustomInspector(customInspector: Atomic.UIWidget); showModalWindow(windowText: string, uifilename: string, handleWidgetEventCB: (ev: Atomic.UIWidgetEvent) => void): Editor.Modal.ExtensionWindow; showNonModalWindow(windowText: string, uifilename: string, handleWidgetEventCB: (ev: Atomic.UIWidgetEvent) => void): Editor.Modal.ExtensionWindow; showModalError(windowText: string, message: string):Atomic.UIMessageWindow; showResourceSelection(windowText: string, importerType: string, resourceType: string, callback: (retObject: any, args: any) => void, args?: any); /** * Returns the currently active resource editor or null * @return {Editor.ResourceEditor} */ getCurrentResourceEditor(): Editor.ResourceEditor; /** * Will load a resource editor or navigate to an already loaded resource editor by path * @param path The path to the resource to load * @param lineNumber optional line number to navigate to * @return {Editor.ResourceEditor} */ loadResourceEditor(path: string, lineNumber?: number): Editor.ResourceEditor; /** * Register a custom editor. These editors will override editors in the standard editor list if * they both resolve the ```canHandleResource``` call. */ registerCustomEditor(editorBuilder: Editor.Extensions.ResourceEditorBuilder); /** * Will unregister a previously registered editor builder * @param {Editor.Extensions.ResourceEditorBuilder} editorBuilder */ unregisterCustomEditor(editorBuilder: Editor.Extensions.ResourceEditorBuilder); } } /** * Interfaces for client extensions */ declare module Editor.ClientExtensions { export interface EditorFileEvent { filename: string; fileExt: string; editor: any; } export interface CodeLoadedEvent extends EditorFileEvent { code: string; } export interface CodeSavedEvent extends EditorFileEvent { code: string; } /** * Called once the resource has been deleted * @type {String} */ export interface DeleteResourceEvent { // The full path to the resource to edit path: string; } /** * Called once the resource has been renamed * @type {String} */ export interface RenameResourceEvent { /** * Original path of the resource * @type {string} */ path: string; /** * New path of the resource * @type {string} */ newPath: string; /** * New base name of the resource (no path or extension) * @type {string} */ newName?: string; } /** * Generic service locator of editor services that may be injected by either a plugin * or by the editor itself. */ export interface ClientServiceLocator extends Editor.Extensions.ServiceLoader { /** * Exposed services * @type {WebViewServicesProvider} */ clientServices: WebViewServicesProvider; } export interface ClientEditorService extends Editor.Extensions.EditorServiceExtension { /** * Called by the service locator at load time */ initialize(serviceLocator: ClientServiceLocator); } export interface PreferencesChangedEventData { applicationPreferences? : any; projectPreferences? : any; } export interface WebViewServiceEventListener extends Editor.Extensions.EditorServiceExtension { configureEditor?(ev: EditorFileEvent); codeLoaded?(ev: CodeLoadedEvent); save?(ev: CodeSavedEvent); delete?(ev: DeleteResourceEvent); rename?(ev: RenameResourceEvent); projectUnloaded?(); formatCode?(); preferencesChanged?(preferences: PreferencesChangedEventData); } /** * Available methods exposed to client services */ export interface WebViewServicesProvider extends Editor.Extensions.ServicesProvider<WebViewServiceEventListener> { /** * Get a reference to the interop to talk to the host * @return {HostInterop} */ getHostInterop(): HostInterop; /** * Return a preference value or the provided default from the user settings file * @param {string} extensionName name of the extension the preference lives under * @param {string} preferenceName name of the preference to retrieve * @param {number | boolean | string} defaultValue value to return if pref doesn't exist * @return {number|boolean|string} */ getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number; getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string; getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean; /** * Return a preference value or the provided default from the application settings file * @param {string} extensionName name of the extension the preference lives under * @param {string} preferenceName name of the preference to retrieve * @param {number | boolean | string} defaultValue value to return if pref doesn't exist * @return {number|boolean|string} */ getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number; getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string; getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean; } export interface AtomicErrorMessage { error_code: number; error_message: string; } /** * Interface for functions that are available from the client web view to call on the host */ export interface HostInterop { /** * Called from the host to notify the client what file to load * @param {string} codeUrl */ loadCode(codeUrl: string); /** * Save the contents of the editor * @return {Promise} */ saveCode(): PromiseLike<{}>; /** * Save the contents of a file as filename * @param {string} filename * @param {string} fileContents * @return {Promise} */ saveFile(filename: string, fileContents: string): PromiseLike<{}>; /** * Queries the host for a particular resource and returns it in a promise * @param {string} codeUrl * @return {Promise} */ getResource(codeUrl: string): PromiseLike<{}>; /** * Returns a file resource from the resources directory * @param {string} filename name and path of file under the project directory or a fully qualified file name * @return {Promise} */ getFileResource(filename: string): PromiseLike<{}>; /** * Notify the host that the contents of the editor has changed */ notifyEditorChange(); /** * This adds a global routine to the window object so that it can be called from the host * @param {string} routineName * @param {(} callback */ addCustomHostRoutine(routineName: string, callback: (...any) => void); } } declare module Editor { /** * Valid editor shortcuts that can be called from menus */ export type EditorShortcutType = "cut" | "copy" | "paste" | "undo" | "redo" | "close" | "frameselected" | "selectall"; }
the_stack
import { PdfDocument, PdfPage, PdfStandardFont,PdfColorSpace, PdfTrueTypeFont, PdfGraphics, SizeF, PdfDictionary} from './../../../src/index'; import { PdfSolidBrush, PdfColor, PdfFont,PointF, PdfFontFamily, PdfStringFormat , PdfSampledFunction} from './../../../src/index'; import { RectangleF, Rectangle,PdfPen, PdfGraphicsState, PdfFontStyle,PdfPath,GetResourceEventHandler, PdfTextAlignment, PdfColorBlend, PdfBlend, PdfFunction} from './../../../src/index'; import { PdfLinearGradientBrush } from '../../../src/implementation/graphics/brushes/pdf-linear-gradient-brush'; import { PdfLinearGradientMode, PdfExtend} from '../../../src/implementation/graphics/brushes/enum'; import { Utils } from './../utils.spec'; import { PdfTilingBrush } from '../../../src/implementation/graphics/brushes/pdf-tiling-brush'; import { PdfRadialGradientBrush } from '../../../src/implementation/graphics/brushes/pdf-radial-gradient-brush'; import { PdfBoolean } from '../../../src/implementation/primitives/pdf-boolean'; describe('UTC-01: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes1', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(200, 100), color1, color2); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_01.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_01.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-02: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes2', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(200, 100), color1, color2); graphics.drawPath(pen, brush1,path); //Save the document. //document.save('EJ2_38407_Linear_brush_02.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_02.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-03: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes3', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(200, 100), color1, color2); graphics.drawRectangle(pen,brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_03.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_03.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-04: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes4', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(200, 100), color1, color2); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // draw the text page1.graphics.drawString('Hello World!!!', font, null, brush1, 0, 0, null); //Save the document. //document.save('EJ2_38407_Linear_brush_04.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_04.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-05: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes4', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, PdfLinearGradientMode.Vertical); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_05.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_05.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-06: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes6', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, 90); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_06.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_06.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-07: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes7', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, 180); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_07.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_07.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-08: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes8', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, 270); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_08.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_08.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-09: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes9', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, 0); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_09.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_09.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-10: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes10', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, 210); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_10.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_10.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-11: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes_11', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(200, 100),color1, color2); //Create PDF blend let blend : PdfBlend= new PdfBlend(); //Set factors blend.factors = [1]; //Set poistions blend.positions = [0]; //Set blend to the brush. brush1.blend = blend; graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_11.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_11.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-12: Working with Linear brushes', () => { it('-EJ2-38407 Drawing Linear gradient brushes_12', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(200, 100),color1, color2); let cblend: PdfColorBlend = new PdfColorBlend(); // Set colors cblend.colors = [color1, color2]; // Set poistions cblend.positions = [0,1]; // Set internpolation colors to the brush. brush1.interpolationColors = cblend; graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38407_Linear_brush_12.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38407_Linear_brush_12.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('PdfLinearGradientBrush.ts', () => { describe('Constructor initializing',()=> { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); //Create new PDF path. let path : PdfPath = new PdfPath(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let brush1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new PointF(0, 0), new PointF(200, 100),color1, color2); brush1.extend = PdfExtend.Both; brush1.antiAlias = true; let bool : boolean = brush1.antiAlias; let rect : Rectangle = brush1.rectangle; let blend : PdfBlend= new PdfBlend(1); //Set factors blend.factors = [1]; //Set poistions blend.positions = [0]; //Set blend to the brush. brush1.blend = blend; let b1 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, PdfLinearGradientMode.ForwardDiagonal); let b2 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, PdfLinearGradientMode.BackwardDiagonal); let b3 : PdfLinearGradientBrush = new PdfLinearGradientBrush(new Rectangle(0, 0,200, 100),color1, color2, PdfLinearGradientMode.Horizontal); //Create new PDF path. let ppath : PdfPath = new PdfPath(); it('-PdfLinearGradientBrush() method calling)', () => { expect(function (): void {b1.blend = null; }).toThrowError(); }) it('-PdfLinearGradientBrush() linearColors calling)', () => { let startColor : PdfColor = new PdfColor(0,0,0); //Set linear colors. let colors : PdfColor[] = b1.linearColors; expect(function (): void {b1.linearColors = [ startColor ]; }).toThrowError(); }) it('-PdfLinearGradientBrush() liner calling)', () => { expect(function (): void {b1.linearColors = null; }).toThrowError(); }) it('-PdfLinearGradientBrush() blend calling)', () => { expect(function (): void {b1.blend = null; }).toThrowError(); }) path.pen = pen; }) }); //PdfRadialGradientBrush describe('UTC-01: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes1', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38408_radial_brush_01.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_01.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-02: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes2', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); //Create new PDF path. let path : PdfPath = new PdfPath(); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); graphics.drawPath(pen, brush1,path); //Save the document. //document.save('EJ2_38408_radial_brush_02.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_02.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-03: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes3', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); graphics.drawRectangle(pen,brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38408_radial_brush_03.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_03.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-04: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes4', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // draw the text page1.graphics.drawString('Hello World!!!', font, null, brush1, 0, 0, null); //Save the document. //document.save('EJ2_38408_radial_brush_04.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_04.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-05: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes5', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // draw the text page1.graphics.drawString('Hello World Radial brush!!!', font, null, brush1, 0, 0, null); //Save the document. //document.save('EJ2_38408_radial_brush_05.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_05.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-06: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes6', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); graphics.drawRectangle( brush1, 100, 100, 200, 100); //Save the document. //document.save('EJ2_38408_radial_brush_06.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_06.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-7: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes_7', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); //Create PDF blend let blend : PdfBlend= new PdfBlend(); //Set factors blend.factors = [1]; //Set poistions blend.positions = [0]; //Set blend to the brush. brush1.blend = blend; graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38408_radial_brush_7.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_7.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-08: Working with radial brushes', () => { it('-EJ2-38408 Drawing Radial gradient brushes_8', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); // set pen let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); let cblend: PdfColorBlend = new PdfColorBlend(); // Set colors cblend.colors = [color1, color2]; // Set poistions cblend.positions = [0,1]; // Set internpolation colors to the brush. brush1.interpolationColors = cblend; graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38408_radial_brush_8.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38408_radial_brush_8.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('PdfRadialGradientBrush.ts', () => { describe('Constructor initializing',()=> { // create a new PDF document. let document : PdfDocument = new PdfDocument(); // add a page to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let color1 : PdfColor = new PdfColor(255, 123, 0); let color2 : PdfColor = new PdfColor(0, 255, 255); //Create new PDF path. let path : PdfPath = new PdfPath(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); let brush1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); brush1.extend = PdfExtend.Both; brush1.rectangle = new RectangleF ( 0, 0, 200, 100); let rect : RectangleF = brush1.rectangle; let blend : PdfBlend= new PdfBlend(1); //Set factors blend.factors = [1]; //Set poistions blend.positions = [0]; //Set blend to the brush. brush1.blend = blend; let startColor : PdfColor = new PdfColor(0,0,0); let endColor : PdfColor= new PdfColor(0,255,0); //Clone the existing linear brush. let cBrush : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); //Set linear colors. cBrush.linearColors = [ startColor, endColor ]; cBrush.stroking = true; let stroke : boolean = cBrush.stroking; let stroke1 : PdfBoolean = new PdfBoolean(true); //Draw rectangle. let resources : GetResourceEventHandler; let value : PdfColorSpace = PdfColorSpace.GrayScale; //Create new PDF path. let b1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 0, new PointF(50, 50), 50, color1, color2); it('-PdfRadialGradientBrush() constructor calling)', () => { expect(function (): void { let b1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), -10, new PointF(50, 50), 50, color1, color2);  }).toThrowError(); }) it('-PdfRadialGradientBrush() constructor calling1 )', () => { expect(function (): void { let b1 : PdfRadialGradientBrush = new PdfRadialGradientBrush(new PointF(50, 50), 10, new PointF(50, 50), -50, color1, color2);  }).toThrowError(); }) it('-PdfRadialGradientBrush() method calling1 )', () => { expect(function (): void {b1.blend = null; }).toThrowError(); }) it('-PdfRadialGradientBrush() method calling2 )', () => { expect(function (): void {b1.interpolationColors = null; }).toThrowError(); }) it('-PdfRadialGradientBrush() linearColors calling)', () => { let startColor : PdfColor = new PdfColor(0,0,0); //Set linear colorss let colors : PdfColor[] = b1.linearColors; expect(function (): void {b1.linearColors = [ startColor ]; }).toThrowError(); }) it('-PdfRadialGradientBrush() linear calling)', () => { expect(function (): void {b1.linearColors = null; }).toThrowError(); }) it('-PdfRadialGradientBrush() blend calling)', () => { expect(function (): void {b1.blend = null; }).toThrowError(); }) b1.rectangle = new RectangleF(0,0,350, 200); }) }); //PdfTilingBrush describe('UTC-01: Working with Tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes1', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new Rectangle(0, 0, 11, 11)); brush1.graphics.drawRectangle(pen, 0, 0, 10, 10); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38409_Tiling_brush_01.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_01.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-02: Working with Tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes2', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); document.colorSpace = PdfColorSpace.GrayScale; // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new Rectangle(0, 0, 11, 11), page1); brush1.graphics.drawRectangle(pen, 0, 0, 10, 10); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38409_Tiling_brush_02.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_02.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-03: Working with tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes3', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new SizeF(11,11)); brush1.graphics.drawRectangle(pen, 0, 0, 10, 10); graphics.drawRectangle( brush1, 0, 0, 200, 100); //Save the document. //document.save('EJ2_38409_Tiling_brush_03.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_03.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-04: Working with tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes4', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); document.colorSpace = PdfColorSpace.GrayScale; // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new SizeF(11,11), page1); brush1.graphics.drawRectangle(pen, 0, 0, 10, 10); graphics.drawRectangle( brush1, 0, 0, 200, 100); //document.save('EJ2_38409_Tiling_brush_04.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_04.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-05: Working with Tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes5', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new Rectangle(0, 0, 21, 21)); brush1.graphics.drawRectangle(pen, 0, 0, 20, 20); let smallestCellBounds : Rectangle = brush1.rectangle; let smallestCellSize : SizeF= brush1.size; graphics.drawRectangle( brush1, 100, 100, 200, 100); //Save the document. //document.save('EJ2_38409_Tiling_brush_05.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_05.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-06: Working with Tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes6', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new SizeF(11,11)); brush1.graphics.drawRectangle(pen, 0, 0, 10, 10); graphics.drawRectangle( brush1, 0, 0, 200, 100); let cBrush : PdfTilingBrush = brush1.clone() as PdfTilingBrush; /// //Draw rectangle. graphics.drawRectangle(cBrush, 0, 150, 100, 100); //Save the document. //document.save('EJ2_38409_Tiling_brush_06.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_06.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-07: Working with tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes7', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); document.colorSpace = PdfColorSpace.GrayScale; // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new SizeF(11,11), page1); //Create new PDF path. let path : PdfPath = new PdfPath(brush1); //Add line path points. path.addLine(new PointF(10, 100), new PointF(10, 200)); path.addLine(new PointF(100, 100), new PointF(100, 200)); path.addLine(new PointF(100, 200), new PointF(55, 150)); //Draw PDF path to page. path.draw(page1, new PointF(0, 0)); //document.save('EJ2_38409_Tiling_brush_07.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_07.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-08: Working with tiling brushes', () => { it('-EJ2-38409 Drawing Tiling brushes8', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); document.colorSpace = PdfColorSpace.Cmyk; // add pages to the document. let page1 : PdfPage = document.pages.add(); let graphics : PdfGraphics = page1.graphics; let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); // set pen let brush1 : PdfTilingBrush = new PdfTilingBrush(new SizeF(11,11), page1); brush1.graphics.drawRectangle(pen, 0, 0, 10, 10); graphics.drawRectangle( brush1, 0, 0, 200, 100); //document.save('EJ2_38409_Tiling_brush_08.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38409_Tiling_brush_08.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('PdfTilingBrush.ts', () => { describe('Constructor initializing',()=> { let b1 : PdfTilingBrush = new PdfTilingBrush(new Rectangle(0, 0, 11, 11)); b1.stroking = true; let stroke : boolean = b1.stroking; let resources : GetResourceEventHandler; let value : PdfColorSpace.Rgb; let value1 : PdfColor = new PdfColor(255, 0, 0); value1.c = 1; value1.m = 1; value1.y = 1; value1.k = 1; let Kvalue : number = value1.k; let value2 : PdfColor = new PdfColor(255, 0, 0); value2.c = 0; value2.m = 0; value2.y = 0; value2.k = 0; let value3 : PdfColor = new PdfColor(255, 0, 0); value3.c = 2; value3.m = 2; value3.y = 2; value3.k = 2; let value4 : PdfColor = new PdfColor(255, 0, 0); value4.c = -2; value4.m = -2; value4.y = -2; value4.k = -2; let brush : PdfSolidBrush = null; it('-this.monitorChanges(PdfBrush, PdfStreamWriter,GetResourceEventHandler,boolean, PdfColorSpace) method calling', () => { expect(function (): void {b1.monitorChanges(null, null, resources, true, value); }).toThrowError(); }) }) });
the_stack
import * as cdk from '@aws-cdk/core'; import { App } from '@aws-cdk/core'; import { $TSAny, $TSContext, AmplifyCategories, buildOverrideDir, CLISubCommandType, IAmplifyResource, JSONUtilities, pathManager } from 'amplify-cli-core'; import { formatter, printer } from 'amplify-prompts'; import * as fs from 'fs-extra'; import * as path from 'path'; import * as vm from 'vm2'; import os from 'os'; import { S3PermissionType, S3UserInputs } from '../service-walkthrough-types/s3-user-input-types'; import { canResourceBeTransformed, S3CFNDependsOn, S3CFNPermissionType, S3InputState } from '../service-walkthroughs/s3-user-input-state'; import { AmplifyS3ResourceCfnStack } from './s3-stack-builder'; import { AmplifyS3ResourceTemplate } from '@aws-amplify/cli-extensibility-helper'; import { AmplifyBuildParamsPermissions, AmplifyCfnParamType, AmplifyS3ResourceInputParameters } from './types'; /** * Builds S3 resource stack, ingest overrides.ts and generates output-files. * @param context CLI - Flow context * @param resource S3 resource to be transformed ( ingest overrides.ts and generate cloudformation ) */ export async function transformS3ResourceStack(context: $TSContext, resource: IAmplifyResource): Promise<void> { if (canResourceBeTransformed(resource.resourceName)) { const stackGenerator = new AmplifyS3ResourceStackTransform(resource.resourceName, context); await stackGenerator.transform(CLISubCommandType.OVERRIDE); } } //Stack transformer for S3 export class AmplifyS3ResourceStackTransform { private app: App; private cliInputs: S3UserInputs; private resourceTemplateObj: AmplifyS3ResourceCfnStack | undefined; private cliInputsState: S3InputState; private cfn!: string; private cfnInputParams!: AmplifyS3ResourceInputParameters; private context: $TSContext; private resourceName: string; constructor(resourceName: string, context: $TSContext) { this.app = new App(); // Validate the cli-inputs.json for the resource this.cliInputsState = new S3InputState(resourceName, undefined); this.cliInputs = this.cliInputsState.getCliInputPayload(); this.context = context; this.resourceName = resourceName; } getCFN(): string | undefined { return this.cfn; } async transform(commandType: CLISubCommandType) { this.generateCfnInputParameters(); // Generate cloudformation stack from cli-inputs.json await this.generateStack(this.context); // Modify cloudformation files based on overrides await this.applyOverrides(); // Save generated cloudformation.json and parameters.json files this.saveBuildFiles(commandType); } /** * getS3DependsOn function is used to fetch all the dependencies of the S3 bucket (function, auth) * @returns All the dependsOn params to be inserted into amplify-meta by the category-level caller. */ public getS3DependsOn(): S3CFNDependsOn[] | undefined { return this.resourceTemplateObj ? this.resourceTemplateObj.getS3DependsOn() : undefined; } generateCfnInputParameters() { const userInput: S3UserInputs = this.cliInputsState.getUserInput(); //DEFAULT Parameters const defaultS3PermissionsUpload = [S3PermissionType.CREATE_AND_UPDATE]; this.cfnInputParams = { bucketName: userInput.bucketName, selectedGuestPermissions: S3InputState.getCfnPermissionsFromInputPermissions(userInput.guestAccess), selectedAuthenticatedPermissions: S3InputState.getCfnPermissionsFromInputPermissions(userInput.authAccess), unauthRoleName: { Ref: 'UnauthRoleName', }, authRoleName: { Ref: 'AuthRoleName', }, }; if (userInput.triggerFunction && userInput.triggerFunction !== 'NONE') { this.cfnInputParams.triggerFunction = userInput.triggerFunction; } if (userInput.adminTriggerFunction?.triggerFunction && userInput.adminTriggerFunction.triggerFunction !== 'NONE') { this.cfnInputParams.adminTriggerFunction = userInput.adminTriggerFunction.triggerFunction; } this.cfnInputParams.s3PrivatePolicy = `Private_policy_${userInput.policyUUID}`; this.cfnInputParams.s3ProtectedPolicy = `Protected_policy_${userInput.policyUUID}`; this.cfnInputParams.s3PublicPolicy = `Public_policy_${userInput.policyUUID}`; this.cfnInputParams.s3ReadPolicy = `read_policy_${userInput.policyUUID}`; this.cfnInputParams.s3UploadsPolicy = `Uploads_policy_${userInput.policyUUID}`; this.cfnInputParams.authPolicyName = `s3_amplify_${userInput.policyUUID}`; this.cfnInputParams.unauthPolicyName = `s3_amplify_${userInput.policyUUID}`; this.cfnInputParams.AuthenticatedAllowList = this._getAuthGuestListPermission(S3PermissionType.READ, userInput.authAccess); this.cfnInputParams.GuestAllowList = this._getAuthGuestListPermission(S3PermissionType.READ, userInput.guestAccess); this.cfnInputParams.s3PermissionsAuthenticatedPrivate = this._getPublicPrivatePermissions( userInput.authAccess, true, //exclude bucketList ); this.cfnInputParams.s3PermissionsAuthenticatedProtected = this._getPublicPrivatePermissions( userInput.authAccess, true, //exclude bucketList ); this.cfnInputParams.s3PermissionsAuthenticatedPublic = this._getPublicPrivatePermissions( userInput.authAccess, true, //exclude bucketList ); this.cfnInputParams.s3PermissionsAuthenticatedUploads = this._getUploadPermissions(userInput.authAccess); this.cfnInputParams.s3PermissionsGuestPublic = this._getPublicPrivatePermissions( userInput.guestAccess, true, //exclude bucketList ); this.cfnInputParams.s3PermissionsGuestUploads = this._getUploadPermissions(userInput.guestAccess); } _getAuthGuestListPermission(checkOperation: S3PermissionType, authPermissions: Array<S3PermissionType> | undefined) { if (authPermissions) { if (authPermissions.includes(checkOperation)) { return AmplifyBuildParamsPermissions.ALLOW; } else { return AmplifyBuildParamsPermissions.DISALLOW; } } else { return AmplifyBuildParamsPermissions.DISALLOW; } } _getPublicPrivatePermissions(authPermissions: Array<S3PermissionType> | undefined, excludeListBuckets: boolean) { if (authPermissions) { let cfnPermissions: Array<S3CFNPermissionType> = S3InputState.getCfnPermissionsFromInputPermissions(authPermissions); if (excludeListBuckets) { cfnPermissions = cfnPermissions.filter(permissions => permissions != S3CFNPermissionType.LIST); } return cfnPermissions && cfnPermissions.length > 0 ? cfnPermissions.join() : AmplifyBuildParamsPermissions.DISALLOW; } return AmplifyBuildParamsPermissions.DISALLOW; } _getUploadPermissions(authPermissions: Array<S3PermissionType> | undefined) { if (authPermissions) { if (!authPermissions.includes(S3PermissionType.CREATE_AND_UPDATE)) { return AmplifyBuildParamsPermissions.DISALLOW; } //For uploads only set "s3:PutObject" const cfnPermissions: Array<S3CFNPermissionType> = S3InputState.getCfnTypesFromPermissionType(S3PermissionType.CREATE_AND_UPDATE); return cfnPermissions.join(); } return AmplifyBuildParamsPermissions.DISALLOW; } // Modify cloudformation files based on overrides async applyOverrides() { const backendDir = pathManager.getBackendDirPath(); const resourceDirPath = pathManager.getResourceDirectoryPath(undefined, AmplifyCategories.STORAGE, this.resourceName); const overrideJSFilePath = path.resolve(path.join(resourceDirPath, 'build', 'override.js')); const isBuild = await buildOverrideDir(backendDir, resourceDirPath).catch(error => { printer.error(`Build error : ${error.message}`); throw new Error(error); }); //Skip if packageManager or override.ts not found if (isBuild) { const { override } = await import(overrideJSFilePath).catch(error => { formatter.list(['No override File Found', `To override ${this.resourceName} run amplify override auth ${this.resourceName} `]); return undefined; }); // Pass stack object if (override && typeof override === 'function') { const overrideCode: string = await fs.readFile(overrideJSFilePath, 'utf-8').catch(() => { formatter.list(['No override File Found', `To override ${this.resourceName} run amplify override auth`]); return ''; }); const sandboxNode = new vm.NodeVM({ console: 'inherit', timeout: 5000, sandbox: {}, require: { context: 'sandbox', builtin: ['path'], external: true, }, }); try { await sandboxNode.run(overrideCode, overrideJSFilePath).override(this.resourceTemplateObj as AmplifyS3ResourceTemplate); } catch (err: $TSAny) { const error = new Error(`Skipping override due to ${err}${os.EOL}`); printer.error(`${error}`); error.stack = undefined; throw error; } } } } saveBuildFiles(commandType: CLISubCommandType) { if (this.resourceTemplateObj) { // Render CFN Template string and store as member in this.cfn this.cfn = this.resourceTemplateObj.renderCloudFormationTemplate(); } //Store cloudformation-template.json, Parameters.json and Update BackendConfig this._saveFilesToLocalFileSystem('cloudformation-template.json', this.cfn); this._saveFilesToLocalFileSystem('parameters.json', this.cfnInputParams); /* ** Save DependsOn into Amplify-Meta: ** In case of ADD walkthrough, since the resource-entry in amplify-meta is created by the caller (addResource()) ** we don't save the dependsOn here. In all other cases, the resource-entry is updated with the new dependsOn entry */ if (commandType !== CLISubCommandType.ADD) { this._saveDependsOnToBackendConfig( ); } } async generateStack(context: $TSContext): Promise<void> { // Create Resource Stack from CLI Inputs in this._resourceTemplateObj this.resourceTemplateObj = new AmplifyS3ResourceCfnStack(this.app, 'AmplifyS3ResourceStack', this.cliInputs, this.cfnInputParams); // Add Parameters this.resourceTemplateObj.addParameters(); // Add Conditions this.resourceTemplateObj.addConditions(); // Add Outputs this.resourceTemplateObj.addOutputs(); /* ** Generate Stack Resources for the S3 resource ** * 1. Create the S3 bucket, configure CORS and create CFN Conditions * 2. Configure Notifications on the S3 bucket. * 3. Create IAM policies to control Cognito pool access to S3 bucket * 4. Configure Cognito User pool policies * 5. Configure Trigger policies */ await this.resourceTemplateObj.generateCfnStackResources(context); } _addOutputs() { this.resourceTemplateObj?.addCfnOutput( { value: cdk.Fn.ref('S3Bucket'), description: 'Bucket name for the S3 bucket', }, 'BucketName', ); this.resourceTemplateObj?.addCfnOutput( { value: cdk.Fn.ref('AWS::Region'), }, 'Region', ); } _addParameters() { let s3CfnParams: Array<AmplifyCfnParamType> = [ { params: ['env', 'bucketName', 'authPolicyName', 'unauthPolicyName', 'authRoleName', 'unauthRoleName', 'triggerFunction'], paramType: 'String', }, { params: ['s3PublicPolicy', 's3PrivatePolicy', 's3ProtectedPolicy', 's3UploadsPolicy', 's3ReadPolicy'], paramType: 'String', default: 'NONE', }, { params: [ 's3PermissionsAuthenticatedPublic', 's3PermissionsAuthenticatedProtected', 's3PermissionsAuthenticatedPrivate', 's3PermissionsAuthenticatedUploads', 's3PermissionsGuestPublic', 's3PermissionsGuestUploads', 'AuthenticatedAllowList', 'GuestAllowList', ], paramType: 'String', default: AmplifyBuildParamsPermissions.DISALLOW, }, { params: ['selectedGuestPermissions', 'selectedAuthenticatedPermissions'], paramType: 'CommaDelimitedList', default: 'NONE', }, ]; s3CfnParams.map(params => this._setCFNParams(params)); } //Helper: Add CFN Resource Param definitions as CfnParameter . _setCFNParams(paramDefinitions: AmplifyCfnParamType) { const resourceTemplateObj = this.resourceTemplateObj; if (resourceTemplateObj) { paramDefinitions.params.map(paramName => { //set param type let cfnParam: any = { type: paramDefinitions.paramType, }; //set param default if provided if (paramDefinitions.default) { cfnParam.default = paramDefinitions.default; } //configure param in resource template object resourceTemplateObj.addCfnParameter(cfnParam, paramName); }); } //else throw an exception TBD } //Helper: Save files in local-filesysten _saveFilesToLocalFileSystem(fileName: string, data: $TSAny) { fs.ensureDirSync(this.cliInputsState.buildFilePath); const cfnFilePath = path.resolve(path.join(this.cliInputsState.buildFilePath, fileName)); try { JSONUtilities.writeJson(cfnFilePath, data); } catch (e) { throw e; } } //Helper: Save DependsOn entries to amplify-meta _saveDependsOnToBackendConfig( ) { if (this.resourceTemplateObj) { //Get all collated resource dependencies const s3DependsOnResources = this.resourceTemplateObj.getS3DependsOn(); const dependsOn = [...s3DependsOnResources || []]; this.context.amplify.updateamplifyMetaAfterResourceUpdate( AmplifyCategories.STORAGE, this.resourceName, 'dependsOn', dependsOn, ); } } }
the_stack
import {default as createFilter, isExpressionFilter} from '.'; import convertFilter from './convert'; import Point from '@mapbox/point-geometry'; import MercatorCoordinate from '../../geo/mercator_coordinate'; import EXTENT from '../../data/extent'; import {CanonicalTileID} from '../../source/tile_id'; import {FilterSpecification} from '../types.g'; import {Feature} from '../expression'; describe('filter', () => { test('expression, zoom', () => { const f = createFilter(['>=', ['number', ['get', 'x']], ['zoom']]).filter; expect(f({zoom: 1}, {properties: {x: 0}} as any as Feature)).toBe(false); expect(f({zoom: 1}, {properties: {x: 1.5}} as any as Feature)).toBe(true); expect(f({zoom: 1}, {properties: {x: 2.5}} as any as Feature)).toBe(true); expect(f({zoom: 2}, {properties: {x: 0}} as any as Feature)).toBe(false); expect(f({zoom: 2}, {properties: {x: 1.5}} as any as Feature)).toBe(false); expect(f({zoom: 2}, {properties: {x: 2.5}} as any as Feature)).toBe(true); }); test('expression, compare two properties', () => { jest.spyOn(console, 'warn').mockImplementation(() => { }); const f = createFilter(['==', ['string', ['get', 'x']], ['string', ['get', 'y']]]).filter; expect(f({zoom: 0}, {properties: {x: 1, y: 1}} as any as Feature)).toBe(false); expect(f({zoom: 0}, {properties: {x: '1', y: '1'}} as any as Feature)).toBe(true); expect(f({zoom: 0}, {properties: {x: 'same', y: 'same'}} as any as Feature)).toBe(true); expect(f({zoom: 0}, {properties: {x: null}} as any as Feature)).toBe(false); expect(f({zoom: 0}, {properties: {x: undefined}} as any as Feature)).toBe(false); }); test('expression, collator comparison', () => { const caseSensitive = createFilter(['==', ['string', ['get', 'x']], ['string', ['get', 'y']], ['collator', {'case-sensitive': true}]]).filter; expect(caseSensitive({zoom: 0}, {properties: {x: 'a', y: 'b'}} as any as Feature)).toBe(false); expect(caseSensitive({zoom: 0}, {properties: {x: 'a', y: 'A'}} as any as Feature)).toBe(false); expect(caseSensitive({zoom: 0}, {properties: {x: 'a', y: 'a'}} as any as Feature)).toBe(true); const caseInsensitive = createFilter(['==', ['string', ['get', 'x']], ['string', ['get', 'y']], ['collator', {'case-sensitive': false}]]).filter; expect(caseInsensitive({zoom: 0}, {properties: {x: 'a', y: 'b'}} as any as Feature)).toBe(false); expect(caseInsensitive({zoom: 0}, {properties: {x: 'a', y: 'A'}} as any as Feature)).toBe(true); expect(caseInsensitive({zoom: 0}, {properties: {x: 'a', y: 'a'}} as any as Feature)).toBe(true); }); test('expression, any/all', () => { expect(createFilter(['all']).filter(undefined, undefined)).toBe(true); expect(createFilter(['all', true]).filter(undefined, undefined)).toBe(true); expect(createFilter(['all', true, false]).filter(undefined, undefined)).toBe(false); expect(createFilter(['all', true, true]).filter(undefined, undefined)).toBe(true); expect(createFilter(['any']).filter(undefined, undefined)).toBe(false); expect(createFilter(['any', true]).filter(undefined, undefined)).toBe(true); expect(createFilter(['any', true, false]).filter(undefined, undefined)).toBe(true); expect(createFilter(['any', false, false]).filter(undefined, undefined)).toBe(false); }); test('expression, type error', () => { expect(() => { createFilter(['==', ['number', ['get', 'x']], ['string', ['get', 'y']]]); }).toThrow(); expect(() => { createFilter(['number', ['get', 'x']]); }).toThrow(); expect(() => { createFilter(['boolean', ['get', 'x']]); }).not.toThrow(); }); test('expression, within', () => { const getPointFromLngLat = (lng, lat, canonical) => { const p = MercatorCoordinate.fromLngLat({lng, lat}, 0); const tilesAtZoom = Math.pow(2, canonical.z); return new Point( (p.x * tilesAtZoom - canonical.x) * EXTENT, (p.y * tilesAtZoom - canonical.y) * EXTENT); }; const withinFilter = createFilter(['within', {'type': 'Polygon', 'coordinates': [[[0, 0], [5, 0], [5, 5], [0, 5], [0, 0]]]}]); expect(withinFilter.needGeometry).toBe(true); const canonical = {z: 3, x: 3, y:3} as CanonicalTileID; expect( withinFilter.filter({zoom: 3}, {type: 1, geometry: [[getPointFromLngLat(2, 2, canonical)]]} as Feature, canonical) ).toBe(true); expect( withinFilter.filter({zoom: 3}, {type: 1, geometry: [[getPointFromLngLat(6, 6, canonical)]]} as Feature, canonical) ).toBe(false); expect( withinFilter.filter({zoom: 3}, {type: 1, geometry: [[getPointFromLngLat(5, 5, canonical)]]} as Feature, canonical) ).toBe(false); expect( withinFilter.filter({zoom: 3}, {type: 2, geometry: [[getPointFromLngLat(2, 2, canonical), getPointFromLngLat(3, 3, canonical)]]} as Feature, canonical) ).toBe(true); expect( withinFilter.filter({zoom: 3}, {type: 2, geometry: [[getPointFromLngLat(6, 6, canonical), getPointFromLngLat(2, 2, canonical)]]} as Feature, canonical) ).toBe(false); expect( withinFilter.filter({zoom: 3}, {type: 2, geometry: [[getPointFromLngLat(5, 5, canonical), getPointFromLngLat(2, 2, canonical)]]} as Feature, canonical) ).toBe(false); }); legacyFilterTests(createFilter); }); describe('legacy filter detection', () => { test('definitely legacy filters', () => { // Expressions with more than two arguments. expect(isExpressionFilter(['in', 'color', 'red', 'blue'])).toBeFalsy(); // Expressions where the second argument is not a string or array. expect(isExpressionFilter(['in', 'value', 42])).toBeFalsy(); expect(isExpressionFilter(['in', 'value', true])).toBeFalsy(); }); test('ambiguous value', () => { // Should err on the side of reporting as a legacy filter. Style authors can force filters // by using a literal expression as the first argument. expect(isExpressionFilter(['in', 'color', 'red'])).toBeFalsy(); }); test('definitely expressions', () => { expect(isExpressionFilter(['in', ['get', 'color'], 'reddish'])).toBeTruthy(); expect(isExpressionFilter(['in', ['get', 'color'], ['red', 'blue']])).toBeTruthy(); expect(isExpressionFilter(['in', 42, 42])).toBeTruthy(); expect(isExpressionFilter(['in', true, true])).toBeTruthy(); expect(isExpressionFilter(['in', 'red', ['get', 'colors']])).toBeTruthy(); }); }); describe('convert legacy filters to expressions', () => { beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(() => { }); }); legacyFilterTests(f => { const converted = convertFilter(f); return createFilter(converted); }); test('mimic legacy type mismatch semantics', () => { const filter = ['any', ['all', ['>', 'y', 0], ['>', 'y', 0]], ['>', 'x', 0] ] as FilterSpecification; const converted = convertFilter(filter); const f = createFilter(converted).filter; expect(f({zoom: 0}, {properties: {x: 0, y: 1, z: 1}} as any as Feature)).toBe(true); expect(f({zoom: 0}, {properties: {x: 1, y: 0, z: 1}} as any as Feature)).toBe(true); expect(f({zoom: 0}, {properties: {x: 0, y: 0, z: 1}} as any as Feature)).toBe(false); expect(f({zoom: 0}, {properties: {x: null, y: 1, z: 1}} as any as Feature)).toBe(true); expect(f({zoom: 0}, {properties: {x: 1, y: null, z: 1}} as any as Feature)).toBe(true); expect(f({zoom: 0}, {properties: {x: null, y: null, z: 1}} as any as Feature)).toBe(false); }); test('flattens nested, single child all expressions', () => { const filter: FilterSpecification = [ 'all', [ 'in', '$type', 'Polygon', 'LineString', 'Point' ], [ 'all', ['in', 'type', 'island'] ] ]; const expected: FilterSpecification = [ 'all', [ 'match', ['geometry-type'], ['LineString', 'Point', 'Polygon'], true, false ] as FilterSpecification, [ 'match', ['get', 'type'], ['island'], true, false ] as FilterSpecification ]; const converted = convertFilter(filter); expect(converted).toEqual(expected); }); test('removes duplicates when outputting match expressions', () => { const filter = [ 'in', '$id', 1, 2, 3, 2, 1 ] as FilterSpecification; const expected = [ 'match', ['id'], [1, 2, 3], true, false ]; const converted = convertFilter(filter); expect(converted).toEqual(expected); }); }); function legacyFilterTests(createFilterExpr) { test('degenerate', () => { expect(createFilterExpr().filter()).toBe(true); expect(createFilterExpr(undefined).filter()).toBe(true); expect(createFilterExpr(null).filter()).toBe(true); }); test('==, string', () => { const f = createFilterExpr(['==', 'foo', 'bar']).filter; expect(f({zoom: 0}, {properties: {foo: 'bar'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 'baz'}})).toBe(false); }); test('==, number', () => { const f = createFilterExpr(['==', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('==, null', () => { const f = createFilterExpr(['==', 'foo', null]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(true); // t.equal(f({zoom: 0}, {properties: {foo: undefined}}), false); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('==, $type', () => { const f = createFilterExpr(['==', '$type', 'LineString']).filter; expect(f({zoom: 0}, {type: 1})).toBe(false); expect(f({zoom: 0}, {type: 2})).toBe(true); }); test('==, $id', () => { const f = createFilterExpr(['==', '$id', 1234]).filter; expect(f({zoom: 0}, {id: 1234})).toBe(true); expect(f({zoom: 0}, {id: '1234'})).toBe(false); expect(f({zoom: 0}, {properties: {id: 1234}})).toBe(false); }); test('!=, string', () => { const f = createFilterExpr(['!=', 'foo', 'bar']).filter; expect(f({zoom: 0}, {properties: {foo: 'bar'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 'baz'}})).toBe(true); }); test('!=, number', () => { const f = createFilterExpr(['!=', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(true); expect(f({zoom: 0}, {properties: {}})).toBe(true); }); test('!=, null', () => { const f = createFilterExpr(['!=', 'foo', null]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); // t.equal(f({zoom: 0}, {properties: {foo: undefined}}), true); expect(f({zoom: 0}, {properties: {}})).toBe(true); }); test('!=, $type', () => { const f = createFilterExpr(['!=', '$type', 'LineString']).filter; expect(f({zoom: 0}, {type: 1})).toBe(true); expect(f({zoom: 0}, {type: 2})).toBe(false); }); test('<, number', () => { const f = createFilterExpr(['<', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('<, string', () => { const f = createFilterExpr(['<', 'foo', '0']).filter; expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); }); test('<=, number', () => { const f = createFilterExpr(['<=', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('<=, string', () => { const f = createFilterExpr(['<=', 'foo', '0']).filter; expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); }); test('>, number', () => { const f = createFilterExpr(['>', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('>, string', () => { const f = createFilterExpr(['>', 'foo', '0']).filter; expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); }); test('>=, number', () => { const f = createFilterExpr(['>=', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('>=, string', () => { const f = createFilterExpr(['>=', 'foo', '0']).filter; expect(f({zoom: 0}, {properties: {foo: -1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '1'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '-1'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); }); test('in, degenerate', () => { const f = createFilterExpr(['in', 'foo']).filter; expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); }); test('in, string', () => { const f = createFilterExpr(['in', 'foo', '0']).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('in, number', () => { const f = createFilterExpr(['in', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); }); test('in, null', () => { const f = createFilterExpr(['in', 'foo', null]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(true); // t.equal(f({zoom: 0}, {properties: {foo: undefined}}), false); }); test('in, multiple', () => { const f = createFilterExpr(['in', 'foo', 0, 1]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 3}})).toBe(false); }); test('in, large_multiple', () => { const values = Array.from({length: 2000}).map(Number.call, Number); values.reverse(); const f = createFilterExpr(['in', 'foo'].concat(values)).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1999}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 2000}})).toBe(false); }); test('in, large_multiple, heterogeneous', () => { const values = Array.from({length: 2000}).map(Number.call, Number); values.push('a'); values.unshift('b'); const f = createFilterExpr(['in', 'foo'].concat(values)).filter; expect(f({zoom: 0}, {properties: {foo: 'b'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 'a'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1999}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 2000}})).toBe(false); }); test('in, $type', () => { const f = createFilterExpr(['in', '$type', 'LineString', 'Polygon']).filter; expect(f({zoom: 0}, {type: 1})).toBe(false); expect(f({zoom: 0}, {type: 2})).toBe(true); expect(f({zoom: 0}, {type: 3})).toBe(true); const f1 = createFilterExpr(['in', '$type', 'Polygon', 'LineString', 'Point']).filter; expect(f1({zoom: 0}, {type: 1})).toBe(true); expect(f1({zoom: 0}, {type: 2})).toBe(true); expect(f1({zoom: 0}, {type: 3})).toBe(true); }); test('!in, degenerate', () => { const f = createFilterExpr(['!in', 'foo']).filter; expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); }); test('!in, string', () => { const f = createFilterExpr(['!in', 'foo', '0']).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(true); expect(f({zoom: 0}, {properties: {}})).toBe(true); }); test('!in, number', () => { const f = createFilterExpr(['!in', 'foo', 0]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(true); }); test('!in, null', () => { const f = createFilterExpr(['!in', 'foo', null]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); // t.equal(f({zoom: 0}, {properties: {foo: undefined}}), true); }); test('!in, multiple', () => { const f = createFilterExpr(['!in', 'foo', 0, 1]).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 3}})).toBe(true); }); test('!in, large_multiple', () => { const f = createFilterExpr(['!in', 'foo'].concat(Array.from({length: 2000}).map(Number.call, Number))).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1999}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 2000}})).toBe(true); }); test('!in, $type', () => { const f = createFilterExpr(['!in', '$type', 'LineString', 'Polygon']).filter; expect(f({zoom: 0}, {type: 1})).toBe(true); expect(f({zoom: 0}, {type: 2})).toBe(false); expect(f({zoom: 0}, {type: 3})).toBe(false); }); test('any', () => { const f1 = createFilterExpr(['any']).filter; expect(f1({zoom: 0}, {properties: {foo: 1}})).toBe(false); const f2 = createFilterExpr(['any', ['==', 'foo', 1]]).filter; expect(f2({zoom: 0}, {properties: {foo: 1}})).toBe(true); const f3 = createFilterExpr(['any', ['==', 'foo', 0]]).filter; expect(f3({zoom: 0}, {properties: {foo: 1}})).toBe(false); const f4 = createFilterExpr(['any', ['==', 'foo', 0], ['==', 'foo', 1]]).filter; expect(f4({zoom: 0}, {properties: {foo: 1}})).toBe(true); }); test('all', () => { const f1 = createFilterExpr(['all']).filter; expect(f1({zoom: 0}, {properties: {foo: 1}})).toBe(true); const f2 = createFilterExpr(['all', ['==', 'foo', 1]]).filter; expect(f2({zoom: 0}, {properties: {foo: 1}})).toBe(true); const f3 = createFilterExpr(['all', ['==', 'foo', 0]]).filter; expect(f3({zoom: 0}, {properties: {foo: 1}})).toBe(false); const f4 = createFilterExpr(['all', ['==', 'foo', 0], ['==', 'foo', 1]]).filter; expect(f4({zoom: 0}, {properties: {foo: 1}})).toBe(false); }); test('none', () => { const f1 = createFilterExpr(['none']).filter; expect(f1({zoom: 0}, {properties: {foo: 1}})).toBe(true); const f2 = createFilterExpr(['none', ['==', 'foo', 1]]).filter; expect(f2({zoom: 0}, {properties: {foo: 1}})).toBe(false); const f3 = createFilterExpr(['none', ['==', 'foo', 0]]).filter; expect(f3({zoom: 0}, {properties: {foo: 1}})).toBe(true); const f4 = createFilterExpr(['none', ['==', 'foo', 0], ['==', 'foo', 1]]).filter; expect(f4({zoom: 0}, {properties: {foo: 1}})).toBe(false); }); test('has', () => { const f = createFilterExpr(['has', 'foo']).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: true}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(true); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(true); expect(f({zoom: 0}, {properties: {}})).toBe(false); }); test('!has', () => { const f = createFilterExpr(['!has', 'foo']).filter; expect(f({zoom: 0}, {properties: {foo: 0}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: 1}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: '0'}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: false}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: null}})).toBe(false); expect(f({zoom: 0}, {properties: {foo: undefined}})).toBe(false); expect(f({zoom: 0}, {properties: {}})).toBe(true); }); }
the_stack
import { localForger } from '@taquito/local-forging'; import { valueDecoder } from '@taquito/local-forging/dist/lib/michelson/codec'; import { Uint8ArrayConsumer } from '@taquito/local-forging/dist/lib/uint8array-consumer'; import { emitMicheline } from '@taquito/michel-codec'; import { RpcClient } from '@taquito/rpc'; import { TezosOperationError } from '@taquito/taquito'; import { TempleDAppMessageType, TempleDAppErrorType, TempleDAppGetCurrentPermissionResponse, TempleDAppPermissionRequest, TempleDAppPermissionResponse, TempleDAppOperationRequest, TempleDAppOperationResponse, TempleDAppSignRequest, TempleDAppSignResponse, TempleDAppBroadcastRequest, TempleDAppBroadcastResponse, TempleDAppNetwork } from '@temple-wallet/dapp/dist/types'; import { nanoid } from 'nanoid'; import { browser, Runtime } from 'webextension-polyfill-ts'; import { addLocalOperation } from 'lib/temple/activity'; import { intercom } from 'lib/temple/back/defaults'; import { buildFinalOpParmas, dryRunOpParams } from 'lib/temple/back/dryrun'; import { withUnlocked } from 'lib/temple/back/store'; import * as Beacon from 'lib/temple/beacon'; import { loadChainId, isAddressValid } from 'lib/temple/helpers'; import { NETWORKS } from 'lib/temple/networks'; import { TempleMessageType, TempleRequest, TempleDAppPayload, TempleDAppSession, TempleDAppSessions } from 'lib/temple/types'; const CONFIRM_WINDOW_WIDTH = 380; const CONFIRM_WINDOW_HEIGHT = 632; const AUTODECLINE_AFTER = 120_000; const STORAGE_KEY = 'dapp_sessions'; const HEX_PATTERN = /^[0-9a-fA-F]+$/; const TEZ_MSG_SIGN_PATTERN = /^0501[a-f0-9]{8}54657a6f73205369676e6564204d6573736167653a20[a-f0-9]*$/; export async function getCurrentPermission(origin: string): Promise<TempleDAppGetCurrentPermissionResponse> { const dApp = await getDApp(origin); const permission = dApp ? { rpc: await getNetworkRPC(dApp.network), pkh: dApp.pkh, publicKey: dApp.publicKey } : null; return { type: TempleDAppMessageType.GetCurrentPermissionResponse, permission }; } export async function requestPermission( origin: string, req: TempleDAppPermissionRequest ): Promise<TempleDAppPermissionResponse> { if (![isAllowedNetwork(req?.network), typeof req?.appMeta?.name === 'string'].every(Boolean)) { throw new Error(TempleDAppErrorType.InvalidParams); } const networkRpc = await getNetworkRPC(req.network); const dApp = await getDApp(origin); if (!req.force && dApp && isNetworkEquals(req.network, dApp.network) && req.appMeta.name === dApp.appMeta.name) { return { type: TempleDAppMessageType.PermissionResponse, rpc: networkRpc, pkh: dApp.pkh, publicKey: dApp.publicKey }; } return new Promise(async (resolve, reject) => { const id = nanoid(); await requestConfirm({ id, payload: { type: 'connect', origin, networkRpc, appMeta: req.appMeta }, onDecline: () => { reject(new Error(TempleDAppErrorType.NotGranted)); }, handleIntercomRequest: async (confirmReq, decline) => { if (confirmReq?.type === TempleMessageType.DAppPermConfirmationRequest && confirmReq?.id === id) { const { confirmed, accountPublicKeyHash, accountPublicKey } = confirmReq; if (confirmed && accountPublicKeyHash && accountPublicKey) { await setDApp(origin, { network: req.network, appMeta: req.appMeta, pkh: accountPublicKeyHash, publicKey: accountPublicKey }); resolve({ type: TempleDAppMessageType.PermissionResponse, pkh: accountPublicKeyHash, publicKey: accountPublicKey, rpc: networkRpc }); } else { decline(); } return { type: TempleMessageType.DAppPermConfirmationResponse }; } return; } }); }); } export async function requestOperation( origin: string, req: TempleDAppOperationRequest ): Promise<TempleDAppOperationResponse> { if ( ![ isAddressValid(req?.sourcePkh), req?.opParams?.length > 0, req?.opParams?.every(op => typeof op.kind === 'string') ].every(Boolean) ) { throw new Error(TempleDAppErrorType.InvalidParams); } const dApp = await getDApp(origin); if (!dApp) { throw new Error(TempleDAppErrorType.NotGranted); } if (req.sourcePkh !== dApp.pkh) { throw new Error(TempleDAppErrorType.NotFound); } return new Promise(async (resolve, reject) => { const id = nanoid(); const networkRpc = await getNetworkRPC(dApp.network); await requestConfirm({ id, payload: { type: 'confirm_operations', origin, networkRpc, appMeta: dApp.appMeta, sourcePkh: req.sourcePkh, sourcePublicKey: dApp.publicKey, opParams: req.opParams }, onDecline: () => { reject(new Error(TempleDAppErrorType.NotGranted)); }, handleIntercomRequest: async (confirmReq, decline) => { if (confirmReq?.type === TempleMessageType.DAppOpsConfirmationRequest && confirmReq?.id === id) { if (confirmReq.confirmed) { try { const op = await withUnlocked(({ vault }) => vault.sendOperations( dApp.pkh, networkRpc, buildFinalOpParmas(req.opParams, confirmReq.modifiedTotalFee, confirmReq.modifiedStorageLimit) ) ); try { const chainId = await loadChainId(networkRpc); await addLocalOperation(chainId, op.hash, op.results); } catch {} resolve({ type: TempleDAppMessageType.OperationResponse, opHash: op.hash }); } catch (err: any) { if (err instanceof TezosOperationError) { err.message = TempleDAppErrorType.TezosOperation; reject(err); } else { throw err; } } } else { decline(); } return { type: TempleMessageType.DAppOpsConfirmationResponse }; } return; } }); }); } export async function requestSign(origin: string, req: TempleDAppSignRequest): Promise<TempleDAppSignResponse> { if (req?.payload?.startsWith('0x')) { req = { ...req, payload: req.payload.substring(2) }; } if (![isAddressValid(req?.sourcePkh), HEX_PATTERN.test(req?.payload)].every(Boolean)) { throw new Error(TempleDAppErrorType.InvalidParams); } const dApp = await getDApp(origin); if (!dApp) { throw new Error(TempleDAppErrorType.NotGranted); } if (req.sourcePkh !== dApp.pkh) { throw new Error(TempleDAppErrorType.NotFound); } return new Promise(async (resolve, reject) => { const id = nanoid(); const networkRpc = await getNetworkRPC(dApp.network); let preview: any; try { if (req.payload.match(TEZ_MSG_SIGN_PATTERN)) { preview = emitMicheline(valueDecoder(Uint8ArrayConsumer.fromHexString(req.payload.slice(2))), { indent: ' ', newline: '\n' }).slice(1, -1); } else { const parsed = await localForger.parse(req.payload); if (parsed.contents.length > 0) { preview = parsed; } } } catch { preview = null; } await requestConfirm({ id, payload: { type: 'sign', origin, networkRpc, appMeta: dApp.appMeta, sourcePkh: req.sourcePkh, payload: req.payload, preview }, onDecline: () => { reject(new Error(TempleDAppErrorType.NotGranted)); }, handleIntercomRequest: async (confirmReq, decline) => { if (confirmReq?.type === TempleMessageType.DAppSignConfirmationRequest && confirmReq?.id === id) { if (confirmReq.confirmed) { const { prefixSig: signature } = await withUnlocked(({ vault }) => vault.sign(dApp.pkh, req.payload)); resolve({ type: TempleDAppMessageType.SignResponse, signature }); } else { decline(); } return { type: TempleMessageType.DAppSignConfirmationResponse }; } return; } }); }); } export async function requestBroadcast( origin: string, req: TempleDAppBroadcastRequest ): Promise<TempleDAppBroadcastResponse> { if (![req?.signedOpBytes?.length > 0].every(Boolean)) { throw new Error(TempleDAppErrorType.InvalidParams); } const dApp = await getDApp(origin); if (!dApp) { throw new Error(TempleDAppErrorType.NotGranted); } try { const rpc = new RpcClient(await getNetworkRPC(dApp.network)); const opHash = await rpc.injectOperation(req.signedOpBytes); return { type: TempleDAppMessageType.BroadcastResponse, opHash }; } catch (err: any) { throw err instanceof TezosOperationError ? (() => { err.message = TempleDAppErrorType.TezosOperation; return err; })() : new Error('Failed to broadcast'); } } export async function getAllDApps() { const dAppsSessions: TempleDAppSessions = (await browser.storage.local.get([STORAGE_KEY]))[STORAGE_KEY] || {}; return dAppsSessions; } export async function getDApp(origin: string): Promise<TempleDAppSession | undefined> { return (await getAllDApps())[origin]; } export async function setDApp(origin: string, permissions: TempleDAppSession) { const current = await getAllDApps(); const newDApps = { ...current, [origin]: permissions }; await setDApps(newDApps); return newDApps; } export async function removeDApp(origin: string) { const { [origin]: permissionsToRemove, ...restDApps } = await getAllDApps(); await setDApps(restDApps); await Beacon.removeDAppPublicKey(origin); return restDApps; } export function cleanDApps() { return setDApps({}); } function setDApps(newDApps: TempleDAppSessions) { return browser.storage.local.set({ [STORAGE_KEY]: newDApps }); } type RequestConfirmParams = { id: string; payload: TempleDAppPayload; onDecline: () => void; handleIntercomRequest: (req: TempleRequest, decline: () => void) => Promise<any>; }; async function requestConfirm({ id, payload, onDecline, handleIntercomRequest }: RequestConfirmParams) { let closing = false; const close = async () => { if (closing) return; closing = true; try { stopTimeout(); stopRequestListening(); stopWinRemovedListening(); await closeWindow(); } catch (_err) {} }; const declineAndClose = () => { onDecline(); close(); }; let knownPort: Runtime.Port | undefined; const stopRequestListening = intercom.onRequest(async (req: TempleRequest, port) => { if (req?.type === TempleMessageType.DAppGetPayloadRequest && req.id === id) { knownPort = port; if (payload.type === 'confirm_operations') { const dryrunResult = await dryRunOpParams({ opParams: payload.opParams, networkRpc: payload.networkRpc, sourcePkh: payload.sourcePkh, sourcePublicKey: payload.sourcePublicKey }); if (dryrunResult) { payload = { ...payload, ...dryrunResult }; } } return { type: TempleMessageType.DAppGetPayloadResponse, payload }; } else { if (knownPort !== port) return; const result = await handleIntercomRequest(req, onDecline); if (result) { close(); return result; } } }); const isWin = (await browser.runtime.getPlatformInfo()).os === 'win'; let left = 0; let top = 0; try { const lastFocused = await browser.windows.getLastFocused(); // Position window in top right corner of lastFocused window. top = Math.round(lastFocused.top! + lastFocused.height! / 2 - CONFIRM_WINDOW_HEIGHT / 2); left = Math.round(lastFocused.left! + lastFocused.width! / 2 - CONFIRM_WINDOW_WIDTH / 2); } catch { // The following properties are more than likely 0, due to being // opened from the background chrome process for the extension that // has no physical dimensions const { screenX, screenY, outerWidth, outerHeight } = window; top = Math.round(screenY + outerHeight / 2 - CONFIRM_WINDOW_HEIGHT / 2); left = Math.round(screenX + outerWidth / 2 - CONFIRM_WINDOW_WIDTH / 2); } const confirmWin = await browser.windows.create({ type: 'popup', url: browser.runtime.getURL(`confirm.html#?id=${id}`), width: isWin ? CONFIRM_WINDOW_WIDTH + 16 : CONFIRM_WINDOW_WIDTH, height: isWin ? CONFIRM_WINDOW_HEIGHT + 17 : CONFIRM_WINDOW_HEIGHT, top: Math.max(top, 20), left: Math.max(left, 20) }); // Firefox currently ignores left/top for create, but it works for update if (confirmWin.id && confirmWin.left !== left && confirmWin.state !== 'fullscreen') { await browser.windows.update(confirmWin.id, { left, top }); } const closeWindow = async () => { if (confirmWin.id) { const win = await browser.windows.get(confirmWin.id); if (win.id) { await browser.windows.remove(win.id); } } }; const handleWinRemoved = (winId: number) => { if (winId === confirmWin?.id) { declineAndClose(); } }; browser.windows.onRemoved.addListener(handleWinRemoved); const stopWinRemovedListening = () => browser.windows.onRemoved.removeListener(handleWinRemoved); // Decline after timeout const t = setTimeout(declineAndClose, AUTODECLINE_AFTER); const stopTimeout = () => clearTimeout(t); } export async function getNetworkRPC(net: TempleDAppNetwork) { const targetRpc = typeof net === 'string' ? NETWORKS.find(n => n.id === net)!.rpcBaseURL : removeLastSlash(net.rpc); if (typeof net === 'string') { try { const current = await getCurrentTempleNetwork(); const [currentChainId, targetChainId] = await Promise.all([ loadChainId(current.rpcBaseURL), loadChainId(targetRpc).catch(() => null) ]); return targetChainId === null || currentChainId === targetChainId ? current.rpcBaseURL : targetRpc; } catch { return targetRpc; } } else { return targetRpc; } } async function getCurrentTempleNetwork() { const { network_id: networkId, custom_networks_snapshot: customNetworksSnapshot } = await browser.storage.local.get([ 'network_id', 'custom_networks_snapshot' ]); return [...NETWORKS, ...(customNetworksSnapshot ?? [])].find(n => n.id === networkId) ?? NETWORKS[0]; } function isAllowedNetwork(net: TempleDAppNetwork) { return typeof net === 'string' ? NETWORKS.some(n => !n.disabled && n.id === net) : Boolean(net?.rpc); } function isNetworkEquals(fNet: TempleDAppNetwork, sNet: TempleDAppNetwork) { return typeof fNet !== 'string' && typeof sNet !== 'string' ? removeLastSlash(fNet.rpc) === removeLastSlash(sNet.rpc) : fNet === sNet; } function removeLastSlash(str: string) { return str.endsWith('/') ? str.slice(0, -1) : str; }
the_stack
import * as picomatch from 'picomatch'; import * as vscode from 'vscode'; import * as nls from 'vscode-nls'; import { CommandManager } from '../commandManager'; import { MarkdownEngine } from '../markdownEngine'; import { MdTableOfContentsProvider } from '../tableOfContents'; import { MdTableOfContentsWatcher } from '../test/tableOfContentsWatcher'; import { Delayer } from '../util/async'; import { noopToken } from '../util/cancellation'; import { Disposable } from '../util/dispose'; import { isMarkdownFile } from '../util/file'; import { Limiter } from '../util/limiter'; import { ResourceMap } from '../util/resourceMap'; import { MdWorkspaceContents, SkinnyTextDocument } from '../workspaceContents'; import { InternalHref, LinkDefinitionSet, MdLink, MdLinkProvider, MdLinkSource } from './documentLinkProvider'; import { MdReferencesProvider, tryFindMdDocumentForLink } from './references'; const localize = nls.loadMessageBundle(); export interface DiagnosticConfiguration { /** * Fired when the configuration changes. */ readonly onDidChange: vscode.Event<void>; getOptions(resource: vscode.Uri): DiagnosticOptions; } export enum DiagnosticLevel { ignore = 'ignore', warning = 'warning', error = 'error', } export interface DiagnosticOptions { readonly enabled: boolean; readonly validateReferences: DiagnosticLevel | undefined; readonly validateFragmentLinks: DiagnosticLevel | undefined; readonly validateFileLinks: DiagnosticLevel | undefined; readonly validateMarkdownFileLinkFragments: DiagnosticLevel | undefined; readonly ignoreLinks: readonly string[]; } function toSeverity(level: DiagnosticLevel | undefined): vscode.DiagnosticSeverity | undefined { switch (level) { case DiagnosticLevel.error: return vscode.DiagnosticSeverity.Error; case DiagnosticLevel.warning: return vscode.DiagnosticSeverity.Warning; case DiagnosticLevel.ignore: return undefined; case undefined: return undefined; } } class VSCodeDiagnosticConfiguration extends Disposable implements DiagnosticConfiguration { private readonly _onDidChange = this._register(new vscode.EventEmitter<void>()); public readonly onDidChange = this._onDidChange.event; constructor() { super(); this._register(vscode.workspace.onDidChangeConfiguration(e => { if ( e.affectsConfiguration('markdown.experimental.validate.enabled') || e.affectsConfiguration('markdown.experimental.validate.referenceLinks.enabled') || e.affectsConfiguration('markdown.experimental.validate.fragmentLinks.enabled') || e.affectsConfiguration('markdown.experimental.validate.fileLinks.enabled') || e.affectsConfiguration('markdown.experimental.validate.fileLinks.markdownFragmentLinks') || e.affectsConfiguration('markdown.experimental.validate.ignoreLinks') ) { this._onDidChange.fire(); } })); } public getOptions(resource: vscode.Uri): DiagnosticOptions { const config = vscode.workspace.getConfiguration('markdown', resource); const validateFragmentLinks = config.get<DiagnosticLevel>('experimental.validate.fragmentLinks.enabled'); return { enabled: config.get<boolean>('experimental.validate.enabled', false), validateReferences: config.get<DiagnosticLevel>('experimental.validate.referenceLinks.enabled'), validateFragmentLinks, validateFileLinks: config.get<DiagnosticLevel>('experimental.validate.fileLinks.enabled'), validateMarkdownFileLinkFragments: config.get<DiagnosticLevel | undefined>('markdown.experimental.validate.fileLinks.markdownFragmentLinks', validateFragmentLinks), ignoreLinks: config.get('experimental.validate.ignoreLinks', []), }; } } class InflightDiagnosticRequests { private readonly inFlightRequests = new ResourceMap<{ readonly cts: vscode.CancellationTokenSource }>(); public async trigger(resource: vscode.Uri, compute: (token: vscode.CancellationToken) => Promise<void>): Promise<void> { this.cancel(resource); const cts = new vscode.CancellationTokenSource(); const entry = { cts }; this.inFlightRequests.set(resource, entry); try { return await compute(cts.token); } finally { if (this.inFlightRequests.get(resource) === entry) { this.inFlightRequests.delete(resource); } cts.dispose(); } } public cancel(resource: vscode.Uri) { const existing = this.inFlightRequests.get(resource); if (existing) { existing.cts.cancel(); this.inFlightRequests.delete(resource); } } public dispose() { this.clear(); } public clear() { for (const { cts } of this.inFlightRequests.values()) { cts.dispose(); } this.inFlightRequests.clear(); } } class LinkWatcher extends Disposable { private readonly _onDidChangeLinkedToFile = this._register(new vscode.EventEmitter<Iterable<vscode.Uri>>); /** * Event fired with a list of document uri when one of the links in the document changes */ public readonly onDidChangeLinkedToFile = this._onDidChangeLinkedToFile.event; private readonly _watchers = new ResourceMap<{ /** * Watcher for this link path */ readonly watcher: vscode.Disposable; /** * List of documents that reference the link */ readonly documents: ResourceMap</* document resource*/ vscode.Uri>; }>(); override dispose() { super.dispose(); for (const entry of this._watchers.values()) { entry.watcher.dispose(); } this._watchers.clear(); } /** * Set the known links in a markdown document, adding and removing file watchers as needed */ updateLinksForDocument(document: vscode.Uri, links: readonly MdLink[]) { const linkedToResource = new Set<vscode.Uri>( links .filter(link => link.href.kind === 'internal') .map(link => (link.href as InternalHref).path)); // First decrement watcher counter for previous document state for (const entry of this._watchers.values()) { entry.documents.delete(document); } // Then create/update watchers for new document state for (const path of linkedToResource) { let entry = this._watchers.get(path); if (!entry) { entry = { watcher: this.startWatching(path), documents: new ResourceMap(), }; this._watchers.set(path, entry); } entry.documents.set(document, document); } // Finally clean up watchers for links that are no longer are referenced anywhere for (const [key, value] of this._watchers) { if (value.documents.size === 0) { value.watcher.dispose(); this._watchers.delete(key); } } } deleteDocument(resource: vscode.Uri) { this.updateLinksForDocument(resource, []); } private startWatching(path: vscode.Uri): vscode.Disposable { const watcher = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(path, '*'), false, true, false); const handler = (resource: vscode.Uri) => this.onLinkedResourceChanged(resource); return vscode.Disposable.from( watcher, watcher.onDidDelete(handler), watcher.onDidCreate(handler), ); } private onLinkedResourceChanged(resource: vscode.Uri) { const entry = this._watchers.get(resource); if (entry) { this._onDidChangeLinkedToFile.fire(entry.documents.values()); } } } class LinkDoesNotExistDiagnostic extends vscode.Diagnostic { public readonly link: string; constructor(range: vscode.Range, message: string, severity: vscode.DiagnosticSeverity, link: string) { super(range, message, severity); this.link = link; } } export abstract class DiagnosticReporter extends Disposable { private readonly pending = new Set<Promise<any>>(); public clear(): void { this.pending.clear(); } public abstract set(uri: vscode.Uri, diagnostics: readonly vscode.Diagnostic[]): void; public abstract delete(uri: vscode.Uri): void; public addWorkItem(promise: Promise<any>): Promise<any> { this.pending.add(promise); promise.finally(() => this.pending.delete(promise)); return promise; } public async waitPendingWork(): Promise<void> { await Promise.all([...this.pending.values()]); } } export class DiagnosticCollectionReporter extends DiagnosticReporter { private readonly collection: vscode.DiagnosticCollection; constructor() { super(); this.collection = this._register(vscode.languages.createDiagnosticCollection('markdown')); } public override clear(): void { super.clear(); this.collection.clear(); } public set(uri: vscode.Uri, diagnostics: readonly vscode.Diagnostic[]): void { const tabs = this.getAllTabResources(); this.collection.set(uri, tabs.has(uri) ? diagnostics : []); } public delete(uri: vscode.Uri): void { this.collection.delete(uri); } private getAllTabResources(): ResourceMap<void> { const openedTabDocs = new ResourceMap<void>(); for (const group of vscode.window.tabGroups.all) { for (const tab of group.tabs) { if (tab.input instanceof vscode.TabInputText) { openedTabDocs.set(tab.input.uri); } } } return openedTabDocs; } } export class DiagnosticManager extends Disposable { private readonly diagnosticDelayer: Delayer<void>; private readonly pendingDiagnostics = new Set<vscode.Uri>(); private readonly inFlightDiagnostics = this._register(new InflightDiagnosticRequests()); private readonly linkWatcher = this._register(new LinkWatcher()); private readonly tableOfContentsWatcher: MdTableOfContentsWatcher; public readonly ready: Promise<void>; constructor( engine: MarkdownEngine, private readonly workspaceContents: MdWorkspaceContents, private readonly computer: DiagnosticComputer, private readonly configuration: DiagnosticConfiguration, private readonly reporter: DiagnosticReporter, private readonly referencesProvider: MdReferencesProvider, delay = 300, ) { super(); this.diagnosticDelayer = this._register(new Delayer(delay)); this._register(this.configuration.onDidChange(() => { this.rebuild(); })); this._register(workspaceContents.onDidCreateMarkdownDocument(doc => { this.triggerDiagnostics(doc.uri); })); this._register(workspaceContents.onDidChangeMarkdownDocument(doc => { this.triggerDiagnostics(doc.uri); })); this._register(vscode.workspace.onDidCloseTextDocument(({ uri }) => { this.pendingDiagnostics.delete(uri); this.inFlightDiagnostics.cancel(uri); this.linkWatcher.deleteDocument(uri); this.reporter.delete(uri); })); this._register(this.linkWatcher.onDidChangeLinkedToFile(changedDocuments => { for (const resource of changedDocuments) { const doc = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === resource.toString()); if (doc && isMarkdownFile(doc)) { this.triggerDiagnostics(doc.uri); } } })); this.tableOfContentsWatcher = this._register(new MdTableOfContentsWatcher(engine, workspaceContents)); this._register(this.tableOfContentsWatcher.onTocChanged(async e => { // When the toc of a document changes, revalidate every file that linked to it too const triggered = new ResourceMap<void>(); for (const ref of await this.referencesProvider.getAllReferencesToFile(e.uri, noopToken)) { const file = ref.location.uri; if (!triggered.has(file)) { this.triggerDiagnostics(file); triggered.set(file); } } })); this.ready = this.rebuild(); } public override dispose() { super.dispose(); this.pendingDiagnostics.clear(); } private async recomputeDiagnosticState(doc: SkinnyTextDocument, token: vscode.CancellationToken): Promise<{ diagnostics: readonly vscode.Diagnostic[]; links: readonly MdLink[]; config: DiagnosticOptions }> { const config = this.configuration.getOptions(doc.uri); if (!config.enabled) { return { diagnostics: [], links: [], config }; } return { ...await this.computer.getDiagnostics(doc, config, token), config }; } private async recomputePendingDiagnostics(): Promise<void> { const pending = [...this.pendingDiagnostics]; this.pendingDiagnostics.clear(); await Promise.all(pending.map(async resource => { const doc = await this.workspaceContents.getMarkdownDocument(resource); if (doc) { await this.inFlightDiagnostics.trigger(doc.uri, async (token) => { const state = await this.recomputeDiagnosticState(doc, token); this.linkWatcher.updateLinksForDocument(doc.uri, state.config.enabled && state.config.validateFileLinks ? state.links : []); this.reporter.set(doc.uri, state.diagnostics); }); } })); } private rebuild(): Promise<void> { this.reporter.clear(); this.pendingDiagnostics.clear(); this.inFlightDiagnostics.clear(); return this.reporter.addWorkItem( (async () => { const allDocs = await this.workspaceContents.getAllMarkdownDocuments(); await Promise.all(Array.from(allDocs, doc => this.triggerDiagnostics(doc.uri))); })() ); } private async triggerDiagnostics(uri: vscode.Uri): Promise<void> { this.inFlightDiagnostics.cancel(uri); this.pendingDiagnostics.add(uri); return this.reporter.addWorkItem( this.diagnosticDelayer.trigger(() => this.recomputePendingDiagnostics()) ); } } /** * Map of file paths to markdown links to that file. */ class FileLinkMap { private readonly _filesToLinksMap = new ResourceMap<{ readonly outgoingLinks: Array<{ readonly source: MdLinkSource; readonly fragment: string; }>; }>(); constructor(links: Iterable<MdLink>) { for (const link of links) { if (link.href.kind !== 'internal') { continue; } const existingFileEntry = this._filesToLinksMap.get(link.href.path); const linkData = { source: link.source, fragment: link.href.fragment }; if (existingFileEntry) { existingFileEntry.outgoingLinks.push(linkData); } else { this._filesToLinksMap.set(link.href.path, { outgoingLinks: [linkData] }); } } } public get size(): number { return this._filesToLinksMap.size; } public entries() { return this._filesToLinksMap.entries(); } } export class DiagnosticComputer { constructor( private readonly workspaceContents: MdWorkspaceContents, private readonly linkProvider: MdLinkProvider, private readonly tocProvider: MdTableOfContentsProvider, ) { } public async getDiagnostics(doc: SkinnyTextDocument, options: DiagnosticOptions, token: vscode.CancellationToken): Promise<{ readonly diagnostics: vscode.Diagnostic[]; readonly links: readonly MdLink[] }> { const { links, definitions } = await this.linkProvider.getLinks(doc); if (token.isCancellationRequested || !options.enabled) { return { links, diagnostics: [] }; } return { links, diagnostics: (await Promise.all([ this.validateFileLinks(options, links, token), Array.from(this.validateReferenceLinks(options, links, definitions)), this.validateFragmentLinks(doc, options, links, token), ])).flat() }; } private async validateFragmentLinks(doc: SkinnyTextDocument, options: DiagnosticOptions, links: readonly MdLink[], token: vscode.CancellationToken): Promise<vscode.Diagnostic[]> { const severity = toSeverity(options.validateFragmentLinks); if (typeof severity === 'undefined') { return []; } const toc = await this.tocProvider.get(doc.uri); if (token.isCancellationRequested) { return []; } const diagnostics: vscode.Diagnostic[] = []; for (const link of links) { if (link.href.kind === 'internal' && link.source.text.startsWith('#') && link.href.path.toString() === doc.uri.toString() && link.href.fragment && !toc.lookup(link.href.fragment) ) { if (!this.isIgnoredLink(options, link.source.text)) { diagnostics.push(new LinkDoesNotExistDiagnostic( link.source.hrefRange, localize('invalidHeaderLink', 'No header found: \'{0}\'', link.href.fragment), severity, link.source.text)); } } } return diagnostics; } private *validateReferenceLinks(options: DiagnosticOptions, links: readonly MdLink[], definitions: LinkDefinitionSet): Iterable<vscode.Diagnostic> { const severity = toSeverity(options.validateReferences); if (typeof severity === 'undefined') { return []; } for (const link of links) { if (link.href.kind === 'reference' && !definitions.lookup(link.href.ref)) { yield new vscode.Diagnostic( link.source.hrefRange, localize('invalidReferenceLink', 'No link definition found: \'{0}\'', link.href.ref), severity); } } } private async validateFileLinks(options: DiagnosticOptions, links: readonly MdLink[], token: vscode.CancellationToken): Promise<vscode.Diagnostic[]> { const pathErrorSeverity = toSeverity(options.validateFileLinks); if (typeof pathErrorSeverity === 'undefined') { return []; } const fragmentErrorSeverity = toSeverity(typeof options.validateMarkdownFileLinkFragments === 'undefined' ? options.validateFragmentLinks : options.validateMarkdownFileLinkFragments); // We've already validated our own fragment links in `validateOwnHeaderLinks` const linkSet = new FileLinkMap(links.filter(link => !link.source.text.startsWith('#'))); if (linkSet.size === 0) { return []; } const limiter = new Limiter(10); const diagnostics: vscode.Diagnostic[] = []; await Promise.all( Array.from(linkSet.entries()).map(([path, { outgoingLinks: links }]) => { return limiter.queue(async () => { if (token.isCancellationRequested) { return; } const hrefDoc = await tryFindMdDocumentForLink({ kind: 'internal', path: path, fragment: '' }, this.workspaceContents); if (!hrefDoc && !await this.workspaceContents.pathExists(path)) { const msg = localize('invalidPathLink', 'File does not exist at path: {0}', path.fsPath); for (const link of links) { if (!this.isIgnoredLink(options, link.source.pathText)) { diagnostics.push(new LinkDoesNotExistDiagnostic(link.source.hrefRange, msg, pathErrorSeverity, link.source.pathText)); } } } else if (hrefDoc && typeof fragmentErrorSeverity !== 'undefined') { // Validate each of the links to headers in the file const fragmentLinks = links.filter(x => x.fragment); if (fragmentLinks.length) { const toc = await this.tocProvider.get(hrefDoc.uri); for (const link of fragmentLinks) { if (!toc.lookup(link.fragment) && !this.isIgnoredLink(options, link.source.pathText) && !this.isIgnoredLink(options, link.source.text)) { const msg = localize('invalidLinkToHeaderInOtherFile', 'Header does not exist in file: {0}', link.fragment); const range = link.source.fragmentRange?.with({ start: link.source.fragmentRange.start.translate(0, -1) }) ?? link.source.hrefRange; diagnostics.push(new LinkDoesNotExistDiagnostic(range, msg, fragmentErrorSeverity, link.source.text)); } } } } }); })); return diagnostics; } private isIgnoredLink(options: DiagnosticOptions, link: string): boolean { return options.ignoreLinks.some(glob => picomatch.isMatch(link, glob)); } } class AddToIgnoreLinksQuickFixProvider implements vscode.CodeActionProvider { private static readonly _addToIgnoreLinksCommandId = '_markdown.addToIgnoreLinks'; private static readonly metadata: vscode.CodeActionProviderMetadata = { providedCodeActionKinds: [ vscode.CodeActionKind.QuickFix ], }; public static register(selector: vscode.DocumentSelector, commandManager: CommandManager): vscode.Disposable { const reg = vscode.languages.registerCodeActionsProvider(selector, new AddToIgnoreLinksQuickFixProvider(), AddToIgnoreLinksQuickFixProvider.metadata); const commandReg = commandManager.register({ id: AddToIgnoreLinksQuickFixProvider._addToIgnoreLinksCommandId, execute(resource: vscode.Uri, path: string) { const settingId = 'experimental.validate.ignoreLinks'; const config = vscode.workspace.getConfiguration('markdown', resource); const paths = new Set(config.get<string[]>(settingId, [])); paths.add(path); config.update(settingId, [...paths], vscode.ConfigurationTarget.WorkspaceFolder); } }); return vscode.Disposable.from(reg, commandReg); } provideCodeActions(document: vscode.TextDocument, _range: vscode.Range | vscode.Selection, context: vscode.CodeActionContext, _token: vscode.CancellationToken): vscode.ProviderResult<(vscode.CodeAction | vscode.Command)[]> { const fixes: vscode.CodeAction[] = []; for (const diagnostic of context.diagnostics) { if (diagnostic instanceof LinkDoesNotExistDiagnostic) { const fix = new vscode.CodeAction( localize('ignoreLinksQuickFix.title', "Exclude '{0}' from link validation.", diagnostic.link), vscode.CodeActionKind.QuickFix); fix.command = { command: AddToIgnoreLinksQuickFixProvider._addToIgnoreLinksCommandId, title: '', arguments: [document.uri, diagnostic.link] }; fixes.push(fix); } } return fixes; } } export function registerDiagnosticSupport( selector: vscode.DocumentSelector, engine: MarkdownEngine, workspaceContents: MdWorkspaceContents, linkProvider: MdLinkProvider, commandManager: CommandManager, referenceProvider: MdReferencesProvider, tocProvider: MdTableOfContentsProvider, ): vscode.Disposable { const configuration = new VSCodeDiagnosticConfiguration(); const manager = new DiagnosticManager( engine, workspaceContents, new DiagnosticComputer(workspaceContents, linkProvider, tocProvider), configuration, new DiagnosticCollectionReporter(), referenceProvider); return vscode.Disposable.from( configuration, manager, AddToIgnoreLinksQuickFixProvider.register(selector, commandManager)); }
the_stack
import React, { FormEvent, ComponentType, Component } from 'react'; import { serializeForm, submitForm, instanceOfValueFormField, getFieldValueFromModel, SitecoreForm, FormField, FormTracker, FormFetcher, TrackerFetcher, } from '@sitecore-jss/sitecore-jss-forms'; import FieldFactory from '../field-factory'; import { FieldWithValueProps, LabelProps } from '../FieldProps'; import DefaultFieldFactory from '../default-field-factory'; import { DefaultError } from './default-error'; export interface ErrorComponentProps { form: SitecoreForm; formErrors: string[]; fieldErrors: Array<{ fieldName: string; state: FieldState }>; } export interface FormProps { form: SitecoreForm; className?: string; fieldFactory?: FieldFactory; sitecoreApiHost: string; sitecoreApiKey: string; onRedirect?: (url: string) => void; errorComponent?: ComponentType<ErrorComponentProps>; fieldWrapperComponent?: ComponentType<FieldWithValueProps>; /** Optionally override the label component for any field components that render a label */ labelComponent?: ComponentType<LabelProps>; /** Optionally override the field validation errors display component for any field components that render validation errors */ fieldValidationErrorsComponent?: ComponentType<LabelProps>; /** Fetch function used when submitting the form (defaults to using `fetch`) */ formFetcher?: FormFetcher; /** Fetch function used when posting form field tracking data (defaults to using `fetch`) */ trackerFetcher?: TrackerFetcher; } export interface FieldState { value?: string | string[] | File[] | boolean; isValid: boolean; errors: string[]; } export interface FormState { errors: string[]; nextForm: SitecoreForm | null; submitButton: string | null; } export interface FieldStateCollection { [key: string]: FieldState; } export class Form extends Component<FormProps, FormState & FieldStateCollection> { private _tracker: FormTracker; constructor(props: FormProps) { super(props); this.state = ({ errors: [], // in a multistep form the server can reset the form schema // to display further steps; this state property overrides // the form passed in from props if present nextForm: null, submitButton: null, } as unknown) as FieldStateCollection & FormState; this.createFieldComponent = this.createFieldComponent.bind(this); this.getCurrentFieldState = this.getCurrentFieldState.bind(this); this.collectCurrentFieldValues = this.collectCurrentFieldValues.bind(this); this._tracker = new FormTracker({ endpoint: `${this.props.sitecoreApiHost}/api/jss/fieldtracking/register?sc_apikey=${this.props.sitecoreApiKey}`, fetcher: this.props.trackerFetcher, }); } render() { const form = this.state.nextForm || this.props.form; if (!form) { return <div>No form data was provided. Need to set a datasource?</div>; } if (!form.metadata) { return <div>Form data invalid. Forget to set the rendering contents resolver?</div>; } const action = `${this.props.sitecoreApiHost}/api/jss/formbuilder?fxb.FormItemId=${form.metadata.itemId}&fxb.HtmlPrefix=${form.htmlPrefix}&sc_apikey=${this.props.sitecoreApiKey}&sc_itemid=${form.contextItemId}`; this._tracker.setFormData( form.formItemId.value, form.formSessionId.value, form.metadata.isTrackingEnabled ); const fieldComponents = form.fields.map(this.createFieldComponent); const ErrorComponent = this.props.errorComponent || DefaultError; const fieldErrors = this.collectCurrentFieldValues().filter((field) => !field.state.isValid); return ( <form className={this.props.className} action={action} method="POST" onSubmit={this.onSubmit.bind(this)} > <ErrorComponent form={form} formErrors={this.state.errors} fieldErrors={fieldErrors} /> {fieldComponents} </form> ); } /** * Creates a field component to render a field based on the form schema data * @param {FormField} field * @returns {React.ReactNode} field component */ createFieldComponent(field: FormField): React.ReactNode { const props = { field, key: field.model.itemId, onChange: this.onFieldChange.bind(this), onButtonClick: this.onButtonClick.bind(this), fieldFactory: this.createFieldComponent, fieldValidationErrorsComponent: this.props.fieldValidationErrorsComponent, labelComponent: this.props.labelComponent, tracker: this._tracker, ...this.getCurrentFieldState(field), } as FieldWithValueProps; const component = (this.props.fieldFactory || DefaultFieldFactory).get(field, props); if (this.props.fieldWrapperComponent) { const Wrapper = this.props.fieldWrapperComponent; return <Wrapper {...props}>{component}</Wrapper>; } return component; } /** * Acquires the current form field state for a single field. * This state can come from two possible sources: * - The form schema/current data (default values, previously saved steps in multistep) * - This component's state (the mutated state of the field after user changes) * The field state includes both current value as well as current validity. * @param {FormField} field * @returns {Object | null} field state */ getCurrentFieldState(field: FormField) { // non-valued fields, i.e. text, section, do not have a value or validity state if (!instanceOfValueFormField(field)) { return null; } const fieldName = field.valueField.name || null; if (!fieldName) { return null; } const fieldState = this.state[fieldName]; // field has a value in react state i.e. due to user change if (fieldState) { const result: FieldState = { isValid: fieldState.isValid, errors: fieldState.errors || [], }; if (typeof fieldState.value !== 'undefined') { // field state from changed field value (in this.state) result.value = fieldState.value; } else { result.value = getFieldValueFromModel(field); } return result; } // default state from form API model return { isValid: true, errors: [], value: getFieldValueFromModel(field), }; } /** * Handler triggered by child components that informs us which button triggered a submit. * This is important for multistep forms to disambiguate between back and next/submit buttons. * @param {string} buttonName */ onButtonClick(buttonName: string) { this.setState({ submitButton: buttonName }); } /** * Handler triggered by child components that updates a given field's current value * (which we then push back down to the child via prop) * @param {string} key Field's name attribute * @param {string | string[] | File[]} value New field value * @param {boolean} isValid Whether the field is valid or not * @param {string[]} errors Validation error message(s) if field is invalid */ onFieldChange( key: string, value: string | string[] | File[], isValid: boolean, errors: string[] ) { this.setState({ [key]: { value, isValid, errors }, }); } /** * Handler triggered when the form is submitted. May transition its state between * steps in a multistep form or handle a final submit. * @param {FormEvent} e */ onSubmit(e: FormEvent) { e.preventDefault(); const form = this.state.nextForm || this.props.form; const fieldValues: { [key: string]: string | string[] | boolean | File[] } = {}; const currentFieldValues = this.collectCurrentFieldValues(); currentFieldValues.forEach((field) => { if (typeof field.state.value !== 'undefined') { fieldValues[field.fieldName] = field.state.value; } }); // NOTE: we're not pre-validating the submit on the client because // Sitecore won't be able to track validation errors in xConnect // serialize the form data that we got from the server // (hidden fields with constant values, unchanged default field values, etc) const formData = serializeForm(form, { submitButtonName: this.state.submitButton }); // merge in user-updated field values formData.mergeOverwritingExisting(fieldValues); const submitUrl = (e.target as HTMLFormElement).action; if (!submitUrl) { throw new Error('Submit URL was not defined. Ensure the form has an action attribute.'); } submitForm(formData, submitUrl, { fetcher: this.props.formFetcher }) .then((result) => { if (result.success && result.redirectUrl) { // Process redirect-on-success action. if (this.props.onRedirect) { this.props.onRedirect(result.redirectUrl); } else { window.location.href = result.redirectUrl; } } if (result.validationErrors) { const stateUpdate: FieldStateCollection = {}; Object.keys(result.validationErrors).forEach((fieldKey) => { stateUpdate[fieldKey] = { value: (this.state[fieldKey] || {}).value, isValid: false, errors: result.validationErrors[fieldKey], }; }); this.setState(stateUpdate); } if (result.nextForm) { this.setState({ nextForm: result.nextForm }); } if (result.success) { this.resetFieldsState(); } if (result.errors && result.errors.length > 0) { throw result.errors; } this.setState({ errors: [] }); }) .catch((error: Error | string[] | string) => { if (Array.isArray(error)) { this.setState({ errors: error }); } else if (typeof error === 'string') { console.log('Form submit error', error); this.setState({ errors: [error] }); } else { console.log('Form submit error', error); this.setState({ errors: [error.message] }); } }); } collectCurrentFieldValues() { return Object.keys(this.state) .filter( (fieldName) => this.state[fieldName] && typeof this.state[fieldName].isValid !== 'undefined' ) .map((fieldName) => ({ fieldName: fieldName, state: this.state[fieldName] as FieldState })); } /** * Removes the current fields' mutated state from this.state, * which prevents validation issues and mutable field state from following us * across steps in a multistep form. */ resetFieldsState() { const keys = Object.keys(this.state).filter( (key) => key !== 'nextForm' && key !== 'errors' && key !== 'submitButton' ); const stateReset = keys.reduce((acc, v) => ({ ...acc, [v]: undefined }), {}); this.setState({ ...stateReset, errors: [] }); } }
the_stack
/// <reference path="AotProfilerSupport.ts"/> /// <reference path="HotReloadSupport.ts"/> /// <reference path="LogProfilerSupport.ts"/> /// <reference path="UnoConfig.ts"/> namespace Uno.WebAssembly.Bootstrap { export class Bootstrapper { public disableDotnet6Compatibility: boolean; public configSrc: string; public onConfigLoaded: Function; public onAbort: Function; public onDotnetReady: Function; private _context?: DotnetPublicAPI; private _monoConfig: MonoConfig; private _unoConfig: Uno.WebAssembly.Bootstrap.UnoConfig; private _hotReloadSupport?: HotReloadSupport; private _logProfiler?: LogProfilerSupport; private _aotProfiler?: AotProfilerSupport; private _webAppBasePath: string; private _appBase: string; private body: HTMLElement; private loader: HTMLElement; private progress: HTMLProgressElement; private _isUsingCommonJS: boolean; private _currentBrowserIsChrome: boolean; private _hasReferencedPdbs: boolean; static ENVIRONMENT_IS_WEB: boolean; static ENVIRONMENT_IS_WORKER: boolean; static ENVIRONMENT_IS_NODE: boolean; static ENVIRONMENT_IS_SHELL: boolean; constructor(unoConfig: Uno.WebAssembly.Bootstrap.UnoConfig) { this._unoConfig = unoConfig; this._webAppBasePath = this._unoConfig.environmentVariables["UNO_BOOTSTRAP_WEBAPP_BASE_PATH"]; this._appBase = this._unoConfig.environmentVariables["UNO_BOOTSTRAP_APP_BASE"]; this.disableDotnet6Compatibility = false; this.configSrc = `${this._webAppBasePath}${this._appBase}/mono-config.json`; this.onConfigLoaded = () => this.configLoaded(); this.onDotnetReady = () => this.RuntimeReady(); this.onAbort = () => this.runtimeAbort(); } public static async bootstrap(): Promise<void> { try { // Extract of https://github.com/emscripten-core/emscripten/blob/2.0.23/src/shell.js#L99-L104 Bootstrapper.ENVIRONMENT_IS_WEB = typeof window === 'object'; Bootstrapper.ENVIRONMENT_IS_WORKER = typeof (<any>globalThis).importScripts === 'function'; // N.b. Electron.js environment is simultaneously a NODE-environment, but // also a web environment. Bootstrapper.ENVIRONMENT_IS_NODE = typeof (<any>globalThis).process === 'object' && typeof (<any>globalThis).process.versions === 'object' && typeof (<any>globalThis).process.versions.node === 'string'; Bootstrapper.ENVIRONMENT_IS_SHELL = !Bootstrapper.ENVIRONMENT_IS_WEB && !Bootstrapper.ENVIRONMENT_IS_NODE && !Bootstrapper.ENVIRONMENT_IS_WORKER; let runtime: Bootstrapper = null; let DOMContentLoaded = false; if (typeof window === 'object' /* ENVIRONMENT_IS_WEB */) { globalThis.document.addEventListener("DOMContentLoaded", () => { DOMContentLoaded = true; runtime?.preInit(); }); } //@ts-ignore var config = await eval("import('./uno-config.js')"); runtime = new Bootstrapper(config.config); if (DOMContentLoaded) { runtime.preInit(); } //@ts-ignore var m = await eval("import(`./dotnet.js`)"); const { MONO, BINDING } = await m.default( (context: DotnetPublicAPI) => { runtime.configure(context); return runtime.asDotnetConfig(); } ); } catch (e) { throw `.NET runtime initialization failed (${e})` } } public asDotnetConfig(): DotnetModuleConfig { return <DotnetModuleConfig>{ disableDotnet6Compatibility: this.disableDotnet6Compatibility, configSrc: this.configSrc, baseUrl: this._unoConfig.uno_app_base + "/", mainScriptPath: "dotnet.js", onConfigLoaded: this.onConfigLoaded, onDotnetReady: this.onDotnetReady, onAbort: this.onAbort, exports: ["IDBFS", "FS"] }; } public configure(context: DotnetPublicAPI) { this._context = context; this._context.Module.ENVIRONMENT_IS_WEB = Bootstrapper.ENVIRONMENT_IS_WEB; this._context.Module.ENVIRONMENT_IS_NODE = Bootstrapper.ENVIRONMENT_IS_NODE; this.setupRequire(); this.setupEmscriptenPreRun(); this.setupHotReload(); } private setupHotReload() { if (this._context.Module.ENVIRONMENT_IS_WEB && this.hasDebuggingEnabled()) { this._hotReloadSupport = new HotReloadSupport(this._context); } } private setupEmscriptenPreRun() { if (!this._context.Module.preRun) { this._context.Module.preRun = []; } else if (typeof this._context.Module.preInit === "function") { this._context.Module.preRun = []; } this._context.Module.preRun.push(() => this.wasmRuntimePreRun()); } /** * Setup the global require.js library * * This setup is needed as .NET 7 sets up its own require function * if none is present, and the bootstrapper uses a global require.js. * */ private setupRequire() { const anyModule = <any>this._context.Module; anyModule.imports = anyModule.imports || {}; anyModule.imports.require = (<any>globalThis).require; } private wasmRuntimePreRun() { if (this._unoConfig.environmentVariables) { for (let key in this._unoConfig.environmentVariables) { if (this._unoConfig.environmentVariables.hasOwnProperty(key)) { if (this._monoConfig.enable_debugging) console.log(`Setting ${key}=${this._unoConfig.environmentVariables[key]}`); this._monoConfig.environment_variables[key] = this._unoConfig.environmentVariables[key]; } } } if (LogProfilerSupport.initializeLogProfiler(this._unoConfig)) { this._logProfiler = new LogProfilerSupport(this._context, this._unoConfig); } } private RuntimeReady() { MonoRuntimeCompatibility.initialize(); this.configureGlobal(); this.initializeRequire(); this._aotProfiler = AotProfilerSupport.initialize(this._context, this._unoConfig); this._logProfiler?.postInitializeLogProfiler(); } private configureGlobal() { var thatGlobal = (<any>globalThis); thatGlobal.config = this._unoConfig; thatGlobal.MonoRuntime = MonoRuntimeCompatibility; // global exports from emscripten that are not exposed // as .NET is initialized in a module // List of possible exports: https://github.com/emscripten-core/emscripten/blob/c834ef7d69ccb4100239eeba0b0f6573fed063bc/src/modules.js#L391 // Needs to be aligned with exports in https://github.com/unoplatform/Uno.DotnetRuntime.WebAssembly/blob/f7294fe410705bc220e63fc51d44bdffe4093a5d/patches/fix-additional-emscripten-exports.patch#L19 // And in the packager's list of exports. thatGlobal.lengthBytesUTF8 = (<any>this._context.Module).lengthBytesUTF8; thatGlobal.stringToUTF8 = (<any>this._context.Module).stringToUTF8; thatGlobal.UTF8ToString = (<any>this._context.Module).UTF8ToString; thatGlobal.UTF8ArrayToString = (<any>this._context.Module).UTF8ArrayToString; } // This is called during emscripten `preInit` event, after we fetched config. private configLoaded() { this._monoConfig = this._context.MONO.config as MonoConfig; if (this._unoConfig.generate_aot_profile) { this._monoConfig.aot_profiler_options = <AOTProfilerOptions>{ write_at: "Uno.AotProfilerSupport::StopProfile", send_to: "Uno.AotProfilerSupport::DumpAotProfileData" }; } if (this._monoConfig != null) { this._monoConfig.fetch_file_cb = (asset: string) => this.fetchFile(asset); } else { throw `Invalid .NET onfiguration`; } } private runtimeAbort() { // set_exit_code(1, error); } public preInit() { this.body = document.getElementById("uno-body"); this.initProgress(); } private async mainInit(): Promise<void> { try { this.attachDebuggerHotkey(); this.timezoneSetup(); if (this._hotReloadSupport) { await this._hotReloadSupport.initializeHotReload(); } this._context.MONO.mono_run_main(this._unoConfig.uno_main, []); this.initializePWA(); } catch (e) { console.error(e); } this.cleanupInit(); } private timezoneSetup() { var timeZoneSetupMethod = this._context.BINDING.bind_static_method("[Uno.Wasm.TimezoneData] Uno.Wasm.TimezoneData.TimezoneHelper:Setup"); if (timeZoneSetupMethod) { timeZoneSetupMethod(Intl.DateTimeFormat().resolvedOptions().timeZone); } } private cleanupInit() { // Remove loader node, not needed anymore if (this.loader && this.loader.parentNode) { this.loader.parentNode.removeChild(this.loader); } } private initProgress() { this.loader = this.body.querySelector(".uno-loader"); if (this.loader) { const totalBytesToDownload = this._unoConfig.mono_wasm_runtime_size + this._unoConfig.total_assemblies_size; const progress = this.loader.querySelector("progress"); progress.max = totalBytesToDownload; (<any>progress).value = ""; // indeterminate this.progress = progress; } const configLoader = () => { if (manifest && manifest.lightThemeBackgroundColor) { this.loader.style.setProperty("--light-theme-bg-color", manifest.lightThemeBackgroundColor); } if (manifest && manifest.darkThemeBackgroundColor) { this.loader.style.setProperty("--dark-theme-bg-color", manifest.darkThemeBackgroundColor); } if (manifest && manifest.splashScreenColor && manifest.splashScreenColor != "transparent") { this.loader.style.setProperty("background-color", manifest.splashScreenColor); } if (manifest && manifest.accentColor) { this.loader.style.setProperty("--accent-color", manifest.accentColor); } const img = this.loader.querySelector("img"); if (manifest && manifest.splashScreenImage) { if (!manifest.splashScreenImage.match(/^(http(s)?:\/\/.)/g)) { // Local images need to be prefixed with the app based path manifest.splashScreenImage = `${this._unoConfig.uno_app_base}/${manifest.splashScreenImage}`; } img.setAttribute("src", manifest.splashScreenImage); } else { img.setAttribute("src", "https://nv-assets.azurewebsites.net/logos/uno-splashscreen-light.png"); } }; let manifest = (<any>window)["UnoAppManifest"]; if (manifest) { configLoader(); } else { for (var i = 0; i < this._unoConfig.uno_dependencies.length; i++) { if (this._unoConfig.uno_dependencies[i].endsWith('AppManifest') || this._unoConfig.uno_dependencies[i].endsWith('AppManifest.js')) { require([this._unoConfig.uno_dependencies[i]], function () { manifest = (<any>window)["UnoAppManifest"]; configLoader(); }); break; } } } } private reportProgressWasmLoading(loaded: number) { if (this.progress) { this.progress.value = loaded; } } private reportAssemblyLoading(adding: number) { if (this.progress) { this.progress.value += adding; } } private raiseLoadingError(err: any) { this.loader.setAttribute("loading-alert", "error"); const alert = this.loader.querySelector(".alert"); let title = alert.getAttribute("title"); if (title) { title += `\n${err}`; } else { title = `${err}`; } alert.setAttribute("title", title); } private raiseLoadingWarning(msg: string) { if (this.loader.getAttribute("loading-alert") !== "error") { this.loader.setAttribute("loading-alert", "warning"); } const alert = this.loader.querySelector(".alert"); let title = alert.getAttribute("title"); if (title) { title += `\n${msg}`; } else { title = `${msg}`; } alert.setAttribute("title", title); } private getFetchInit(url: string): RequestInit { const fileName = url.substring(url.lastIndexOf("/") + 1); const init: RequestInit = { credentials: "omit" }; if (this._unoConfig.files_integrity.hasOwnProperty(fileName)) { init.integrity = this._unoConfig.files_integrity[fileName]; } return init; } private fetchWithProgress(url: string, progressCallback: Function) { if (!this.loader) { // No active loader, simply use the fetch API directly... return fetch(url, this.getFetchInit(url)); } return fetch(url, this.getFetchInit(url)) .then(response => { if (!response.ok) { throw Error(`${response.status} ${response.statusText}`); } try { let loaded = 0; // Wrap original stream with another one, while reporting progress. const stream = new ReadableStream({ start(ctl) { const reader = response.body.getReader(); read(); function read() { reader.read() .then( ({ done, value }) => { if (done) { ctl.close(); return; } loaded += value.byteLength; progressCallback(loaded, value.byteLength); ctl.enqueue(value); read(); }) .catch(error => { console.error(error); ctl.error(error); }); } } }); // We copy the previous response to keep original headers. // Not only the WebAssembly will require the right content-type, // but we also need it for streaming optimizations: // https://bugs.chromium.org/p/chromium/issues/detail?id=719172#c28 return new Response(stream, response); } catch (ex) { // ReadableStream may not be supported (Edge as of 42.17134.1.0) return response; } }) .catch(err => this.raiseLoadingError(err)); } private fetchFile(asset: string) { if (asset.lastIndexOf(".dll") !== -1) { asset = asset.replace(".dll", `.${this._unoConfig.assemblyFileExtension}`); } if (asset.startsWith("icudt") && asset.endsWith(".dat")) { asset = `${this._unoConfig.uno_app_base}/${asset}`; } asset = asset.replace("/managed/", `/${this._unoConfig.uno_remote_managedpath}/`); if (this._context.Module.ENVIRONMENT_IS_NODE) { var fs = require('fs'); console.log('Loading... ' + asset); var binary = fs.readFileSync(asset); var resolve_func2 = function (resolve: any, reject: any) { resolve(new Uint8Array(binary)); }; var resolve_func1 = function (resolve: any, reject: any) { var response = { ok: true, url: asset, arrayBuffer: function () { return new Promise(resolve_func2); } }; resolve(response); }; return new Promise(resolve_func1); } else { if (!this._unoConfig.enable_debugging) { // Assembly fetch streaming is disabled during debug, it seems to // interfere with the ability for mono or the chrome debugger to // initialize the debugging session properly. Streaming in debug is // not particularly interesting, so we can skip it. const assemblyName = asset.substring(asset.lastIndexOf("/") + 1); if (this._unoConfig.assemblies_with_size.hasOwnProperty(assemblyName)) { return this .fetchWithProgress(asset, (loaded: any, adding: any) => this.reportAssemblyLoading(adding)); } } return fetch(asset); } } private isElectron() { return navigator.userAgent.indexOf('Electron') !== -1; } private initializeRequire() { // Uno.Wasm.Bootstrap is using "requirejs" by default, which is an AMD implementation // But when run with NodeJS or Electron, it's using CommonJS instead of AMD this._isUsingCommonJS = this._unoConfig.uno_shell_mode !== "BrowserEmbedded" && (this._context.Module.ENVIRONMENT_IS_NODE || this.isElectron()); if (this._unoConfig.enable_debugging) console.log("Done loading the BCL"); if (this._unoConfig.uno_dependencies && this._unoConfig.uno_dependencies.length !== 0) { let pending = this._unoConfig.uno_dependencies.length; const checkDone = (dependency: string) => { --pending; if (this._unoConfig.enable_debugging) console.log(`Loaded dependency (${dependency}) - remains ${pending} other(s).`); if (pending === 0) { this.mainInit(); } }; this._unoConfig.uno_dependencies.forEach((dependency) => { if (this._unoConfig.enable_debugging) console.log(`Loading dependency (${dependency})`); let processDependency = (instance: any) => { // If the module is built on emscripten, intercept its loading. if (instance && instance.HEAP8 !== undefined) { const existingInitializer = instance.onRuntimeInitialized; if (this._unoConfig.enable_debugging) console.log(`Waiting for dependency (${dependency}) initialization`); instance.onRuntimeInitialized = () => { checkDone(dependency); if (existingInitializer) existingInitializer(); }; } else { checkDone(dependency); } }; this.require([dependency], processDependency); }); } else { this.mainInit(); } } private require(modules: string[], callback: Function) { if (this._isUsingCommonJS) { modules.forEach(id => { // Emulate asynchronous process of AMD setTimeout(() => { const d = require('./' + id); callback(d); }, 0); }); } else { if (typeof require === undefined) { throw `Require.js has not been loaded yet. If you have customized your index.html file, make sure that <script src="./require.js"></script> does not contain the defer directive.`; } require(modules, callback); } } private hasDebuggingEnabled() { return this._hasReferencedPdbs && this._currentBrowserIsChrome; } private attachDebuggerHotkey() { if (this._context.Module.ENVIRONMENT_IS_WEB) { let loadAssemblyUrls = this._monoConfig.assets.map(a => a.name); // // Imported from https://github.com/aspnet/Blazor/tree/release/0.7.0 // // History: // 2019-01-14: Adjustments to make the debugger helper compatible with Uno.Bootstrap. // this._currentBrowserIsChrome = (<any>window).chrome && navigator.userAgent.indexOf("Edge") < 0; // Edge pretends to be Chrome this._hasReferencedPdbs = loadAssemblyUrls .some(function (url) { return /\.pdb$/.test(url); }); // Use the combination shift+alt+D because it isn't used by the major browsers // for anything else by default const altKeyName = navigator.platform.match(/^Mac/i) ? "Cmd" : "Alt"; if (this.hasDebuggingEnabled()) { console.info(`Debugging hotkey: Shift+${altKeyName}+D (when application has focus)`); } // Even if debugging isn't enabled, we register the hotkey so we can report why it's not enabled document.addEventListener("keydown", (evt) => { if (evt.shiftKey && (evt.metaKey || evt.altKey) && evt.code === "KeyD") { if (!this._hasReferencedPdbs) { console.error("Cannot start debugging, because the application was not compiled with debugging enabled."); } else if (!this._currentBrowserIsChrome) { console.error("Currently, only Chrome is supported for debugging."); } else { this.launchDebugger(); } } }); } } private launchDebugger() { // // Imported from https://github.com/aspnet/Blazor/tree/release/0.7.0 // // History: // 2019-01-14: Adjustments to make the debugger helper compatible with Uno.Bootstrap. // // The noopener flag is essential, because otherwise Chrome tracks the association with the // parent tab, and then when the parent tab pauses in the debugger, the child tab does so // too (even if it's since navigated to a different page). This means that the debugger // itself freezes, and not just the page being debugged. // // We have to construct a link element and simulate a click on it, because the more obvious // window.open(..., 'noopener') always opens a new window instead of a new tab. const link = document.createElement("a"); link.href = `_framework/debug?url=${encodeURIComponent(location.href)}`; link.target = "_blank"; link.rel = "noopener noreferrer"; link.click(); } private initializePWA() { if (typeof window === 'object' /* ENVIRONMENT_IS_WEB */) { if (this._unoConfig.enable_pwa && 'serviceWorker' in navigator) { if (navigator.serviceWorker.controller) { console.debug("Active service worker found, skipping register"); } else { const _webAppBasePath = this._unoConfig.environmentVariables["UNO_BOOTSTRAP_WEBAPP_BASE_PATH"]; console.debug(`Registering service worker for ${_webAppBasePath}`); navigator.serviceWorker .register( `${_webAppBasePath}service-worker.js`, { scope: _webAppBasePath }) .then(function () { console.debug('Service Worker Registered'); }); } } } } } }
the_stack
import {ShaderMaterial} from 'three/src/materials/ShaderMaterial'; import {Vector2} from 'three/src/math/Vector2'; import {LineType} from '../utils/LineType'; import {ShaderConfig} from '../configs/ShaderConfig'; import {VariableConfig} from '../configs/VariableConfig'; import {CodeBuilder} from '../utils/CodeBuilder'; import {BaseGlNodeType} from '../../_Base'; import {GlobalsGeometryHandler} from '../globals/Geometry'; import {TypedAssembler} from '../../../utils/shaders/BaseAssembler'; import {ShaderName} from '../../../utils/shaders/ShaderName'; import {OutputGlNode} from '../../Output'; // import {ParamType} from '../../../../poly/ParamType'; import {GlConnectionPoint, GlConnectionPointType} from '../../../utils/io/connections/Gl'; import {GlobalsGlNode} from '../../Globals'; import {AttributeGlNode} from '../../Attribute'; import {AssemblerControllerNode} from '../Controller'; import {GlobalsBaseController} from '../globals/_Base'; import {CustomMaterialName} from './materials/_BaseMaterial'; import {ShadersCollectionController} from '../utils/ShadersCollectionController'; import {IUniforms} from '../../../../../core/geometry/Material'; import {ParamGlNode} from '../../Param'; import {NodeContext} from '../../../../poly/NodeContext'; import {ShaderChunk} from 'three/src/renderers/shaders/ShaderChunk'; import {TypedNodeTraverser} from '../../../utils/shaders/NodeTraverser'; import {GlNodeFinder} from '../utils/NodeFinder'; import {VaryingWriteGlNode} from '../../VaryingWrite'; type StringArrayByShaderName = Map<ShaderName, string[]>; interface ITemplateShader { vertexShader?: string; fragmentShader?: string; uniforms?: IUniforms; } const INSERT_DEFINE_AFTER_MAP: Map<ShaderName, string> = new Map([ [ShaderName.VERTEX, '#include <common>'], [ShaderName.FRAGMENT, '#include <common>'], ]); const INSERT_BODY_AFTER_MAP: Map<ShaderName, string> = new Map([ [ShaderName.VERTEX, '#include <color_vertex>'], [ShaderName.FRAGMENT, 'vec4 diffuseColor = vec4( diffuse, opacity );'], ]); const LINES_TO_REMOVE_MAP: Map<ShaderName, string[]> = new Map([ [ShaderName.VERTEX, ['#include <begin_vertex>', '#include <beginnormal_vertex>']], [ShaderName.FRAGMENT, []], ]); const SPACED_LINES = 3; export class BaseGlShaderAssembler extends TypedAssembler<NodeContext.GL> { protected _shaders_by_name: Map<ShaderName, string> = new Map(); protected _lines: StringArrayByShaderName = new Map(); protected _code_builder: CodeBuilder | undefined; private _param_config_owner: CodeBuilder | undefined; protected _root_nodes: BaseGlNodeType[] = []; protected _leaf_nodes: BaseGlNodeType[] = []; protected _material: ShaderMaterial | undefined; private _shader_configs: ShaderConfig[] | undefined; private _variable_configs: VariableConfig[] | undefined; private _uniforms_time_dependent: boolean = false; private _uniforms_resolution_dependent: boolean = false; constructor(protected _gl_parent_node: AssemblerControllerNode) { super(); } protected _overriden_gl_parent_node: AssemblerControllerNode | undefined; setGlParentNode(gl_parent_node: AssemblerControllerNode) { this._overriden_gl_parent_node = gl_parent_node; } currentGlParentNode() { return this._overriden_gl_parent_node || this._gl_parent_node; } compile() {} // private get material() { // return (this._material = this._material || this._createMaterial()); // } // async get_material(/*master_assembler?: BaseGlShaderAssembler*/) { // this._material = this._material || this._createMaterial(); // await this._update_material(/*master_assembler*/); // return this._material; // } protected _template_shader_for_shader_name(shader_name: ShaderName): string | undefined { switch (shader_name) { case ShaderName.VERTEX: return this.templateShader()?.vertexShader; case ShaderName.FRAGMENT: return this.templateShader()?.fragmentShader; } } get globals_handler(): GlobalsBaseController | undefined { return this.currentGlParentNode().assemblerController?.globals_handler; } compileAllowed(): boolean { return this.currentGlParentNode().assemblerController?.globals_handler != null; } shaders_by_name() { return this._shaders_by_name; } // protected createMaterial(): ShaderMaterial | undefined { // return undefined; // } protected _build_lines() { for (let shader_name of this.shaderNames()) { const template = this._template_shader_for_shader_name(shader_name); if (template) { this._replace_template(template, shader_name); } } } // protected _build_lines_for_shader_name(shader_name: ShaderName){ // const template = this._template_shader() // this._replace_template(template[`${shader_name}Shader`], shader_name) // } set_root_nodes(root_nodes: BaseGlNodeType[]) { this._root_nodes = root_nodes; } protected templateShader(): ITemplateShader | undefined { return undefined; } protected addUniforms(current_uniforms: IUniforms) { for (let param_config of this.param_configs()) { current_uniforms[param_config.uniform_name] = param_config.uniform; } if (this.uniformsTimeDependent()) { current_uniforms['time'] = { // type: '1f', value: this.currentGlParentNode().scene().time(), }; } if (this.uniforms_resolution_dependent()) { current_uniforms['resolution'] = { value: new Vector2(1000, 1000), }; } } // // // ROOT NODES AND SHADER NAMES // // root_nodes_by_shader_name(shader_name: ShaderName): BaseGlNodeType[] { // return this._root_nodes const list = []; for (let node of this._root_nodes) { switch (node.type()) { case OutputGlNode.type(): { list.push(node); break; } case ParamGlNode.type(): { list.push(node); break; } case AttributeGlNode.type(): { // TODO: typescript - gl - why is there a texture allocation controller in the base assembler? // const attrib_name = (node as AttributeGlNode).attribute_name; // const variable = this._texture_allocations_controller.variable(attrib_name); // if (variable) { // const allocation_shader_name = variable.allocation().shader_name(); // if (allocation_shader_name == shader_name) { // list.push(node); // } // } // break; } case VaryingWriteGlNode.type(): { list.push(node); break; } } } return list; } leaf_nodes_by_shader_name(shader_name: ShaderName): BaseGlNodeType[] { const list = []; for (let node of this._leaf_nodes) { switch (node.type()) { case GlobalsGlNode.type(): { list.push(node); break; } case AttributeGlNode.type(): { // TODO: typescript - gl - why is there a texture allocation controller in the base assembler? AND especially since there is no way to assign it? // const attrib_name: string = (node as AttributeGlNode).attribute_name; // const variable = this._texture_allocations_controller.variable(attrib_name); // if (variable) { // const allocation_shader_name = variable.allocation().shader_name(); // if (allocation_shader_name == shader_name) { // list.push(node); // } // } // break; } } } return list; } set_node_lines_globals(globals_node: GlobalsGlNode, shaders_collection_controller: ShadersCollectionController) {} set_node_lines_output(output_node: OutputGlNode, shaders_collection_controller: ShadersCollectionController) {} set_node_lines_attribute( attribute_node: AttributeGlNode, shaders_collection_controller: ShadersCollectionController ) {} // // // CHILDREN NODES PARAMS // // codeBuilder() { return (this._code_builder = this._code_builder || this._create_code_builder()); } protected _resetCodeBuilder() { this._code_builder = undefined; } private _create_code_builder() { const node_traverser = new TypedNodeTraverser<NodeContext.GL>( this.currentGlParentNode(), this.shaderNames(), (root_node, shader_name) => { return this.input_names_for_shader_name(root_node, shader_name); } ); return new CodeBuilder( node_traverser, (shader_name) => { return this.root_nodes_by_shader_name(shader_name); }, this ); } build_code_from_nodes(root_nodes: BaseGlNodeType[]) { const param_nodes = GlNodeFinder.findParamGeneratingNodes(this.currentGlParentNode()); this.codeBuilder().buildFromNodes(root_nodes, param_nodes); } allow_new_param_configs() { this.codeBuilder().allow_new_param_configs(); } disallow_new_param_configs() { this.codeBuilder().disallow_new_param_configs(); } builder_param_configs() { return this.codeBuilder().param_configs(); } builder_lines(shader_name: ShaderName, line_type: LineType) { return this.codeBuilder().lines(shader_name, line_type); } all_builder_lines() { return this.codeBuilder().all_lines(); } param_configs() { const code_builder = this._param_config_owner || this.codeBuilder(); return code_builder.param_configs(); } set_param_configs_owner(param_config_owner: CodeBuilder) { this._param_config_owner = param_config_owner; if (this._param_config_owner) { this.codeBuilder().disallow_new_param_configs(); } else { this.codeBuilder().allow_new_param_configs(); } } // // // CHILDREN NODES PARAMS // // static output_input_connection_points(): GlConnectionPoint<GlConnectionPointType>[] { return [ new GlConnectionPoint('position', GlConnectionPointType.VEC3), new GlConnectionPoint('normal', GlConnectionPointType.VEC3), new GlConnectionPoint('color', GlConnectionPointType.VEC3), new GlConnectionPoint('alpha', GlConnectionPointType.FLOAT), new GlConnectionPoint('uv', GlConnectionPointType.VEC2), ]; } add_output_inputs(output_child: OutputGlNode) { output_child.io.inputs.setNamedInputConnectionPoints(BaseGlShaderAssembler.output_input_connection_points()); } static create_globals_node_output_connections() { // TODO: move this in material only, to use the enum GlobalsOutput return [ new GlConnectionPoint('position', GlConnectionPointType.VEC3), new GlConnectionPoint('normal', GlConnectionPointType.VEC3), new GlConnectionPoint('color', GlConnectionPointType.VEC3), new GlConnectionPoint('uv', GlConnectionPointType.VEC2), new GlConnectionPoint('mvPosition', GlConnectionPointType.VEC4), // Maybe I should not add worldPosition, worldNormal, I just now // as those could add computation overhead when always present in the shader. // But hopefully in the soon future, they will only be added when the code builder // adds lines based on connections, as opposed to the whole node new GlConnectionPoint('worldPosition', GlConnectionPointType.VEC4), // vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); new GlConnectionPoint('worldNormal', GlConnectionPointType.VEC3), // vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal ); // new GlConnectionPoint('I', GlConnectionPointType.VEC3), // vec3 I = worldPosition.xyz - cameraPosition; new GlConnectionPoint('gl_Position', GlConnectionPointType.VEC4), new GlConnectionPoint('gl_FragCoord', GlConnectionPointType.VEC4), new GlConnectionPoint('cameraPosition', GlConnectionPointType.VEC3), new GlConnectionPoint('resolution', GlConnectionPointType.VEC2), new GlConnectionPoint('time', GlConnectionPointType.FLOAT), ]; } create_globals_node_output_connections() { return BaseGlShaderAssembler.create_globals_node_output_connections(); } add_globals_outputs(globals_node: GlobalsGlNode) { globals_node.io.outputs.setNamedOutputConnectionPoints(this.create_globals_node_output_connections()); } allow_attribute_exports() { return false; } // // // CONFIGS // // reset_configs() { this._reset_shader_configs(); this._reset_variable_configs(); this._resetUniformsTimeDependency(); this._reset_uniforms_resolution_dependency(); } shaderConfigs() { return (this._shader_configs = this._shader_configs || this.create_shader_configs()); } set_shader_configs(shader_configs: ShaderConfig[]) { this._shader_configs = shader_configs; } shaderNames(): ShaderName[] { return this.shaderConfigs()?.map((sc) => sc.name()) || []; } protected _reset_shader_configs() { this._shader_configs = undefined; } create_shader_configs(): ShaderConfig[] { return [ new ShaderConfig(ShaderName.VERTEX, ['position', 'normal', 'uv', VaryingWriteGlNode.INPUT_NAME], []), new ShaderConfig(ShaderName.FRAGMENT, ['color', 'alpha'], [ShaderName.VERTEX]), ]; } shader_config(name: string): ShaderConfig | undefined { return this.shaderConfigs()?.filter((sc) => { return sc.name() == name; })[0]; } variable_configs() { return (this._variable_configs = this._variable_configs || this.create_variable_configs()); } set_variable_configs(variable_configs: VariableConfig[]) { this._variable_configs = variable_configs; } variable_config(name: string) { return this.variable_configs().filter((vc) => { return vc.name() == name; })[0]; } static create_variable_configs() { return [ new VariableConfig('position', { default_from_attribute: true, // default: this.globals_handler().variable_config_default('position'), // required_definitions: this.globals_handler().variable_config_required_definitions('position'), prefix: 'vec3 transformed = ', }), new VariableConfig('normal', { default_from_attribute: true, prefix: 'vec3 objectNormal = ', postLines: ['#ifdef USE_TANGENT', ' vec3 objectTangent = vec3( tangent.xyz );', '#endif'], }), new VariableConfig('color', { prefix: 'diffuseColor.xyz = ', }), new VariableConfig('alpha', { prefix: 'diffuseColor.a = ', }), new VariableConfig('uv', { // default_from_attribute: true, prefix: 'vUv = ', if: GlobalsGeometryHandler.IF_RULE.uv, }), ]; } create_variable_configs(): VariableConfig[] { return BaseGlShaderAssembler.create_variable_configs(); } protected _reset_variable_configs() { this._variable_configs = undefined; this.variable_configs(); } input_names_for_shader_name(root_node: BaseGlNodeType, shader_name: ShaderName) { return this.shader_config(shader_name)?.input_names() || []; } // time dependency protected _resetUniformsTimeDependency() { this._uniforms_time_dependent = false; } setUniformsTimeDependent() { this._uniforms_time_dependent = true; } uniformsTimeDependent(): boolean { return this._uniforms_time_dependent; } // resolution dependency protected _reset_uniforms_resolution_dependency() { this._uniforms_resolution_dependent = false; } set_uniforms_resolution_dependent() { this._uniforms_resolution_dependent = true; } uniforms_resolution_dependent(): boolean { return this._uniforms_resolution_dependent; } // // // TEMPLATE HOOKS // // protected insert_define_after(shader_name: ShaderName): string | undefined { return INSERT_DEFINE_AFTER_MAP.get(shader_name); } protected insert_body_after(shader_name: ShaderName): string | undefined { return INSERT_BODY_AFTER_MAP.get(shader_name); } protected lines_to_remove(shader_name: ShaderName): string[] | undefined { return LINES_TO_REMOVE_MAP.get(shader_name); } // // // TEMPLATE CODE REPLACEMENT // // private _replace_template(template: string, shader_name: ShaderName) { const function_declaration = this.builder_lines(shader_name, LineType.FUNCTION_DECLARATION); const define = this.builder_lines(shader_name, LineType.DEFINE); // let all_define = function_declaration.concat(define); const body = this.builder_lines(shader_name, LineType.BODY); let template_lines = template.split('\n'); // const scene = this.currentGlParentNode().scene; const new_lines = [ // `#define FPS ${ThreeToGl.float(scene.time_controller.fps)}`, // `#define TIME_INCREMENT (1.0/${ThreeToGl.float(scene.time_controller.fps)})`, // `#define FRAME_RANGE_START ${ThreeToGl.float(scene.time_controller.frame_range[0])}`, // `#define FRAME_RANGE_END ${ThreeToGl.float(scene.time_controller.frame_range[1])}`, ]; const line_before_define = this.insert_define_after(shader_name); const line_before_body = this.insert_body_after(shader_name); const lines_to_remove = this.lines_to_remove(shader_name); let line_before_define_found = false; let line_before_body_found = false; for (let template_line of template_lines) { if (line_before_define_found == true) { if (function_declaration) { this._insert_lines(new_lines, function_declaration); } if (define) { this._insert_lines(new_lines, define); } line_before_define_found = false; } if (line_before_body_found == true) { // this._insert_default_body_declarations(new_lines, shader_name) if (body) { this._insert_lines(new_lines, body); } line_before_body_found = false; } let line_remove_required = false; if (lines_to_remove) { for (let line_to_remove of lines_to_remove) { if (template_line.indexOf(line_to_remove) >= 0) { line_remove_required = true; } } } if (!line_remove_required) { new_lines.push(template_line); } else { new_lines.push('// removed:'); new_lines.push(`//${template_line}`); } if (line_before_define && template_line.indexOf(line_before_define) >= 0) { line_before_define_found = true; } if (line_before_body && template_line.indexOf(line_before_body) >= 0) { line_before_body_found = true; } // if(template_line.indexOf('// INSERT DEFINE') >= 0){ // } else { // if(template_line.indexOf('// INSERT BODY') >= 0){ // if(body.length > 0){ // lodash_times(3, ()=>new_lines.push(' ')) // body.forEach(body_line=>{ // new_lines.push(body_line) // }) // lodash_times(3, ()=>new_lines.push(' ')) // } // } else { // if(template_line.indexOf('// TO REMOVE') < 0){ // new_lines.push(template_line) // } // } // } } this._lines.set(shader_name, new_lines); } // protected _insert_default_body_declarations(new_lines, shader_name){ // new_lines.push('float POLY_roughness = 1.0;') // } private _insert_lines(new_lines: string[], lines_to_add: string[]) { if (lines_to_add.length > 0) { for (let i = 0; i < SPACED_LINES; i++) { new_lines.push(''); } for (let line_to_add of lines_to_add) { new_lines.push(line_to_add); } for (let i = 0; i < SPACED_LINES; i++) { new_lines.push(''); } } } _addFilterFragmentShaderCallback(callbackName: string, callback: (s: string) => string) {} _removeFilterFragmentShaderCallback(callbackName: string) {} getCustomMaterials(): Map<CustomMaterialName, ShaderMaterial> { return new Map<CustomMaterialName, ShaderMaterial>(); } static expandShader(shader_string: string) { function parseIncludes(string: string) { var pattern = /^[ \t]*#include +<([\w\d./]+)>/gm; function replace(match: string, include: string): string { var replace = ShaderChunk[include]; if (replace === undefined) { throw new Error('Can not resolve #include <' + include + '>'); } return parseIncludes(replace); } return string.replace(pattern, replace); } return parseIncludes(shader_string); } // // // GLTF EXPORT // // // static convert_material_to_gltf_supported(material: ShaderMaterial): Material{ // const gltf_constructor = this.isPhysical() ? MeshPhysicalMaterial : MeshStandardMaterial // const options = {} // this._match_uniform('color', options, material, 'diffuse') // this._match_uniform('map', options, material) // this._match_uniform('envMap', options, material) // this._match_uniform('envMapIntensity', options, material) // this._match_uniform('metalness', options, material) // this._match_uniform('roughness', options, material) // const gltf_material = new gltf_constructor(options) // return gltf_material // } // static _match_uniform(name: string, options: object, material: ShaderMaterial, uniform_name?: string) { // uniform_name = uniform_name || name; // options[name] = material.uniforms[uniform_name].value; // } }
the_stack
import { AfterContentChecked, AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, Directive, ElementRef, EventEmitter, Inject, Input, NgZone, OnDestroy, Output, PLATFORM_ID, QueryList, TemplateRef, ViewEncapsulation, AfterViewInit } from '@angular/core'; import {isPlatformBrowser} from '@angular/common'; import {NgbCarouselConfig} from './carousel-config'; import {BehaviorSubject, combineLatest, NEVER, Observable, Subject, timer, zip} from 'rxjs'; import {distinctUntilChanged, map, startWith, switchMap, take, takeUntil} from 'rxjs/operators'; import {ngbCompleteTransition, ngbRunTransition, NgbTransitionOptions} from '../util/transition/ngbTransition'; import { ngbCarouselTransitionIn, ngbCarouselTransitionOut, NgbSlideEventDirection, NgbCarouselCtx } from './carousel-transition'; let nextId = 0; /** * A directive that wraps the individual carousel slide. */ @Directive({selector: 'ng-template[ngbSlide]'}) export class NgbSlide { /** * Slide id that must be unique for the entire document. * * If not provided, will be generated in the `ngb-slide-xx` format. */ @Input() id = `ngb-slide-${nextId++}`; /** * An event emitted when the slide transition is finished * * @since 8.0.0 */ @Output() slid = new EventEmitter<NgbSingleSlideEvent>(); constructor(public tplRef: TemplateRef<any>) {} } /** * Carousel is a component to easily create and control slideshows. * * Allows to set intervals, change the way user interacts with the slides and provides a programmatic API. */ @Component({ selector: 'ngb-carousel', exportAs: 'ngbCarousel', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, host: { 'class': 'carousel slide', '[style.display]': '"block"', 'tabIndex': '0', '(keydown.arrowLeft)': 'keyboard && arrowLeft()', '(keydown.arrowRight)': 'keyboard && arrowRight()', '(mouseenter)': 'mouseHover = true', '(mouseleave)': 'mouseHover = false', '(focusin)': 'focused = true', '(focusout)': 'focused = false', '[attr.aria-activedescendant]': `'slide-' + activeId` }, template: ` <ol class="carousel-indicators" [class.sr-only]="!showNavigationIndicators" role="tablist"> <li *ngFor="let slide of slides" [class.active]="slide.id === activeId" role="tab" [attr.aria-labelledby]="'slide-' + slide.id" [attr.aria-controls]="'slide-' + slide.id" [attr.aria-selected]="slide.id === activeId" (click)="focus();select(slide.id, NgbSlideEventSource.INDICATOR);"></li> </ol> <div class="carousel-inner"> <div *ngFor="let slide of slides; index as i; count as c" class="carousel-item" [id]="'slide-' + slide.id" role="tabpanel"> <span class="sr-only" i18n="Currently selected slide number read by screen reader@@ngb.carousel.slide-number"> Slide {{i + 1}} of {{c}} </span> <ng-template [ngTemplateOutlet]="slide.tplRef"></ng-template> </div> </div> <a class="carousel-control-prev" role="button" (click)="arrowLeft()" *ngIf="showNavigationArrows"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only" i18n="@@ngb.carousel.previous">Previous</span> </a> <a class="carousel-control-next" role="button" (click)="arrowRight()" *ngIf="showNavigationArrows"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only" i18n="@@ngb.carousel.next">Next</span> </a> ` }) export class NgbCarousel implements AfterContentChecked, AfterContentInit, AfterViewInit, OnDestroy { @ContentChildren(NgbSlide) slides: QueryList<NgbSlide>; public NgbSlideEventSource = NgbSlideEventSource; private _destroy$ = new Subject<void>(); private _interval$ = new BehaviorSubject(0); private _mouseHover$ = new BehaviorSubject(false); private _focused$ = new BehaviorSubject(false); private _pauseOnHover$ = new BehaviorSubject(false); private _pauseOnFocus$ = new BehaviorSubject(false); private _pause$ = new BehaviorSubject(false); private _wrap$ = new BehaviorSubject(false); /** * A flag to enable/disable the animations. * * @since 8.0.0 */ @Input() animation: boolean; /** * The slide id that should be displayed **initially**. * * For subsequent interactions use methods `select()`, `next()`, etc. and the `(slide)` output. */ @Input() activeId: string; /** * Time in milliseconds before the next slide is shown. */ @Input() set interval(value: number) { this._interval$.next(value); } get interval() { return this._interval$.value; } /** * If `true`, will 'wrap' the carousel by switching from the last slide back to the first. */ @Input() set wrap(value: boolean) { this._wrap$.next(value); } get wrap() { return this._wrap$.value; } /** * If `true`, allows to interact with carousel using keyboard 'arrow left' and 'arrow right'. */ @Input() keyboard: boolean; /** * If `true`, will pause slide switching when mouse cursor hovers the slide. * * @since 2.2.0 */ @Input() set pauseOnHover(value: boolean) { this._pauseOnHover$.next(value); } get pauseOnHover() { return this._pauseOnHover$.value; } /** * If `true`, will pause slide switching when the focus is inside the carousel. */ @Input() set pauseOnFocus(value: boolean) { this._pauseOnFocus$.next(value); } get pauseOnFocus() { return this._pauseOnFocus$.value; } /** * If `true`, 'previous' and 'next' navigation arrows will be visible on the slide. * * @since 2.2.0 */ @Input() showNavigationArrows: boolean; /** * If `true`, navigation indicators at the bottom of the slide will be visible. * * @since 2.2.0 */ @Input() showNavigationIndicators: boolean; /** * An event emitted just before the slide transition starts. * * See [`NgbSlideEvent`](#/components/carousel/api#NgbSlideEvent) for payload details. */ @Output() slide = new EventEmitter<NgbSlideEvent>(); /** * An event emitted right after the slide transition is completed. * * See [`NgbSlideEvent`](#/components/carousel/api#NgbSlideEvent) for payload details. * * @since 8.0.0 */ @Output() slid = new EventEmitter<NgbSlideEvent>(); /* * Keep the ids of the panels currently transitionning * in order to allow only the transition revertion */ private _transitionIds: [string, string] | null = null; set mouseHover(value: boolean) { this._mouseHover$.next(value); } get mouseHover() { return this._mouseHover$.value; } set focused(value: boolean) { this._focused$.next(value); } get focused() { return this._focused$.value; } constructor( config: NgbCarouselConfig, @Inject(PLATFORM_ID) private _platformId, private _ngZone: NgZone, private _cd: ChangeDetectorRef, private _container: ElementRef) { this.animation = config.animation; this.interval = config.interval; this.wrap = config.wrap; this.keyboard = config.keyboard; this.pauseOnHover = config.pauseOnHover; this.pauseOnFocus = config.pauseOnFocus; this.showNavigationArrows = config.showNavigationArrows; this.showNavigationIndicators = config.showNavigationIndicators; } arrowLeft() { this.focus(); this.prev(NgbSlideEventSource.ARROW_LEFT); } arrowRight() { this.focus(); this.next(NgbSlideEventSource.ARROW_RIGHT); } ngAfterContentInit() { // setInterval() doesn't play well with SSR and protractor, // so we should run it in the browser and outside Angular if (isPlatformBrowser(this._platformId)) { this._ngZone.runOutsideAngular(() => { const hasNextSlide$ = combineLatest([ this.slide.pipe(map(slideEvent => slideEvent.current), startWith(this.activeId)), this._wrap$, this.slides.changes.pipe(startWith(null)) ]) .pipe( map(([currentSlideId, wrap]) => { const slideArr = this.slides.toArray(); const currentSlideIdx = this._getSlideIdxById(currentSlideId); return wrap ? slideArr.length > 1 : currentSlideIdx < slideArr.length - 1; }), distinctUntilChanged()); combineLatest([ this._pause$, this._pauseOnHover$, this._mouseHover$, this._pauseOnFocus$, this._focused$, this._interval$, hasNextSlide$ ]) .pipe( map(([pause, pauseOnHover, mouseHover, pauseOnFocus, focused, interval, hasNextSlide]: [boolean, boolean, boolean, boolean, boolean, number, boolean]) => ((pause || (pauseOnHover && mouseHover) || (pauseOnFocus && focused) || !hasNextSlide) ? 0 : interval)), distinctUntilChanged(), switchMap(interval => interval > 0 ? timer(interval, interval) : NEVER), takeUntil(this._destroy$)) .subscribe(() => this._ngZone.run(() => this.next(NgbSlideEventSource.TIMER))); }); } this.slides.changes.pipe(takeUntil(this._destroy$)).subscribe(() => { this._transitionIds ?.forEach(id => ngbCompleteTransition(this._getSlideElement(id))); this._transitionIds = null; this._cd.markForCheck(); // The following code need to be done asynchronously, after the dom becomes stable, // otherwise all changes will be undone. this._ngZone.onStable.pipe(take(1)).subscribe(() => { for (const { id } of this.slides) { const element = this._getSlideElement(id); if (id === this.activeId) { element.classList.add('active'); } else { element.classList.remove('active'); } } }); }); } ngAfterContentChecked() { let activeSlide = this._getSlideById(this.activeId); this.activeId = activeSlide ? activeSlide.id : (this.slides.length ? this.slides.first.id : ''); } ngAfterViewInit() { // Initialize the 'active' class (not managed by the template) if (this.activeId) { const element = this._getSlideElement(this.activeId); if (element) { element.classList.add('active'); } } } ngOnDestroy() { this._destroy$.next(); } /** * Navigates to a slide with the specified identifier. */ select(slideId: string, source?: NgbSlideEventSource) { this._cycleToSelected(slideId, this._getSlideEventDirection(this.activeId, slideId), source); } /** * Navigates to the previous slide. */ prev(source?: NgbSlideEventSource) { this._cycleToSelected(this._getPrevSlide(this.activeId), NgbSlideEventDirection.RIGHT, source); } /** * Navigates to the next slide. */ next(source?: NgbSlideEventSource) { this._cycleToSelected(this._getNextSlide(this.activeId), NgbSlideEventDirection.LEFT, source); } /** * Pauses cycling through the slides. */ pause() { this._pause$.next(true); } /** * Restarts cycling through the slides from left to right. */ cycle() { this._pause$.next(false); } /** * Set the focus on the carousel. */ focus() { this._container.nativeElement.focus(); } private _cycleToSelected(slideIdx: string, direction: NgbSlideEventDirection, source?: NgbSlideEventSource) { const transitionIds = this._transitionIds; if (transitionIds && (transitionIds[0] !== slideIdx || transitionIds[1] !== this.activeId)) { // Revert prevented return; } let selectedSlide = this._getSlideById(slideIdx); if (selectedSlide && selectedSlide.id !== this.activeId) { this._transitionIds = [this.activeId, slideIdx]; this.slide.emit( {prev: this.activeId, current: selectedSlide.id, direction: direction, paused: this._pause$.value, source}); const options: NgbTransitionOptions<NgbCarouselCtx> = { animation: this.animation, runningTransition: 'stop', context: {direction}, }; const transitions: Array<Observable<any>> = []; const activeSlide = this._getSlideById(this.activeId); if (activeSlide) { const activeSlideTransition = ngbRunTransition(this._ngZone, this._getSlideElement(activeSlide.id), ngbCarouselTransitionOut, options); activeSlideTransition.subscribe(() => { activeSlide.slid.emit({isShown: false, direction, source}); }); transitions.push(activeSlideTransition); } const previousId = this.activeId; this.activeId = selectedSlide.id; const nextSlide = this._getSlideById(this.activeId); const transition = ngbRunTransition(this._ngZone, this._getSlideElement(selectedSlide.id), ngbCarouselTransitionIn, options); transition.subscribe(() => { nextSlide ?.slid.emit({isShown: true, direction, source}); }); transitions.push(transition); zip(...transitions).pipe(take(1)).subscribe(() => { this._transitionIds = null; this.slid.emit( {prev: previousId, current: selectedSlide !.id, direction: direction, paused: this._pause$.value, source}); }); } // we get here after the interval fires or any external API call like next(), prev() or select() this._cd.markForCheck(); } private _getSlideEventDirection(currentActiveSlideId: string, nextActiveSlideId: string): NgbSlideEventDirection { const currentActiveSlideIdx = this._getSlideIdxById(currentActiveSlideId); const nextActiveSlideIdx = this._getSlideIdxById(nextActiveSlideId); return currentActiveSlideIdx > nextActiveSlideIdx ? NgbSlideEventDirection.RIGHT : NgbSlideEventDirection.LEFT; } private _getSlideById(slideId: string): NgbSlide | null { return this.slides.find(slide => slide.id === slideId) || null; } private _getSlideIdxById(slideId: string): number { const slide = this._getSlideById(slideId); return slide != null ? this.slides.toArray().indexOf(slide) : -1; } private _getNextSlide(currentSlideId: string): string { const slideArr = this.slides.toArray(); const currentSlideIdx = this._getSlideIdxById(currentSlideId); const isLastSlide = currentSlideIdx === slideArr.length - 1; return isLastSlide ? (this.wrap ? slideArr[0].id : slideArr[slideArr.length - 1].id) : slideArr[currentSlideIdx + 1].id; } private _getPrevSlide(currentSlideId: string): string { const slideArr = this.slides.toArray(); const currentSlideIdx = this._getSlideIdxById(currentSlideId); const isFirstSlide = currentSlideIdx === 0; return isFirstSlide ? (this.wrap ? slideArr[slideArr.length - 1].id : slideArr[0].id) : slideArr[currentSlideIdx - 1].id; } private _getSlideElement(slideId: string): HTMLElement { return this._container.nativeElement.querySelector(`#slide-${slideId}`); } } /** * A slide change event emitted right after the slide transition is completed. */ export interface NgbSlideEvent { /** * The previous slide id. */ prev: string; /** * The current slide id. */ current: string; /** * The slide event direction. * * Possible values are `'left' | 'right'`. */ direction: NgbSlideEventDirection; /** * Whether the pause() method was called (and no cycle() call was done afterwards). * * @since 5.1.0 */ paused: boolean; /** * Source triggering the slide change event. * * Possible values are `'timer' | 'arrowLeft' | 'arrowRight' | 'indicator'` * * @since 5.1.0 */ source?: NgbSlideEventSource; } /** * A slide change event emitted right after the slide transition is completed. * * @since 8.0.0 */ export interface NgbSingleSlideEvent { /** * true if the slide is shown, false otherwise */ isShown: boolean; /** * The slide event direction. * * Possible values are `'left' | 'right'`. */ direction: NgbSlideEventDirection; /** * Source triggering the slide change event. * * Possible values are `'timer' | 'arrowLeft' | 'arrowRight' | 'indicator'` * */ source?: NgbSlideEventSource; } export enum NgbSlideEventSource { TIMER = 'timer', ARROW_LEFT = 'arrowLeft', ARROW_RIGHT = 'arrowRight', INDICATOR = 'indicator' } export const NGB_CAROUSEL_DIRECTIVES = [NgbCarousel, NgbSlide];
the_stack
import * as React from 'react'; import DatePicker from 'react-datepicker' import { PushshiftAPI, SearchSettings, SearchType } from './api' import { GithubLink } from './github-link' import "react-datepicker/dist/react-datepicker.css"; import { RandomLink } from './random-link'; interface AppState extends SearchSettings { error: string, errorTime: Date, searching: boolean, comments: Array<any>, posts: Array<any>, moreing: boolean, lastUrl: string, } /** Main class for Reddit Search */ export class App extends React.Component<{}, AppState> { lastSearch: SearchSettings; api: PushshiftAPI; updatedHash: boolean; constructor(props) { super(props); this.state = { author: "", subreddit: "", searchFor: SearchType.Comments, resultSize: 100, filter: "", after: null, before: null, query: "", error: null, errorTime: null, searching: false, comments: null, posts: null, moreing: false, lastUrl: "", }; this.api = new PushshiftAPI(); this.updatedHash = false; } loadLocationHash(shouldSearch: boolean = false) { let params = hash_accessor.load(); if (params.after) { params.after = new Date(params.after); } if (params.before) { params.before = new Date(params.before); } if (shouldSearch) { this.setState(params, this.doSearch); } else { this.setState(params); } } componentDidMount() { // Add hash change event listener window.addEventListener("hashchange", e => { if (this.updatedHash) { this.updatedHash = false; return; } console.log("location.hash changed. loading new params"); this.loadLocationHash(); }); // Check for location hash. Use it if found if (window.location.hash) { this.loadLocationHash(true); console.log("Loaded params from location.hash"); return; } // Load stored form data if exists let formDataJson = localStorage.getItem("search-form"); if (formDataJson !== null) { let formData: SearchSettings = JSON.parse(formDataJson); // Reconstruct `Date`s if (formData.after) { formData.after = new Date(formData.after); } if (formData.before) { formData.before = new Date(formData.before); } this.setState(formData); console.log("Loaded params from local storage"); } } componentDidUpdate() { let toSave: SearchSettings = { author: this.state.author, subreddit: this.state.subreddit, searchFor: this.state.searchFor, resultSize: this.state.resultSize, filter: this.state.filter, after: this.state.after, before: this.state.before, query: this.state.query, }; localStorage.setItem("search-form", JSON.stringify(toSave)); } setError = (error: string) => { this.setState({ error: error, errorTime: new Date() }); } handleAuthorChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ author: e.target.value }); } handleSubredditChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ subreddit: e.target.value }); } handleSearchTypeChange = (e: React.ChangeEvent<HTMLSelectElement>) => { if (e.target.value === "Comments") { this.setState({ searchFor: SearchType.Comments }); } else if (e.target.value === "Posts") { this.setState({ searchFor: SearchType.Posts }); } else { this.setError(e.target.value + " is not a valid search type"); } } handleResultSizeChange = (e: React.ChangeEvent<HTMLInputElement>) => { let count: number = parseInt(e.target.value); if (!count) { return; } this.setState({ resultSize: count }); } handleFilterChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ filter: e.target.value }); } handleAfterDateChange = (date: Date) => { this.setState({ after: date }); } handleBeforeDateChange = (date: Date) => { this.setState({ before: date }); } handleQueryChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ query: e.target.value }); } doSearch = async () => { this.setState({ error: null, comments: null, posts: null, searching: true }); this.lastSearch = { ...this.state }; // Update location.hash let toSave = { author: this.state.author, subreddit: this.state.subreddit, searchFor: this.state.searchFor, resultSize: this.state.resultSize, filter: this.state.filter, after: this.state.after, before: this.state.before, query: this.state.query, }; this.updatedHash = true; hash_accessor.save(toSave); // Search try { let url = this.api.get_url(this.lastSearch); this.setState({ lastUrl: url }); let data = await this.api.query(url); // Update state with results if (this.lastSearch.searchFor == SearchType.Comments) { this.setState({ comments: data.data, searching: false }); } else if (this.lastSearch.searchFor == SearchType.Posts) { this.setState({ posts: data.data, searching: false }); } } catch (err) { this.setState({ searching: false }); this.setError(String(err)); } } /** Handle the main form being submitted */ searchSubmit = async (e) => { // Update state e.preventDefault(); this.doSearch(); } /** Handle the more button being clicked. */ handleMoreClick = async (e) => { this.setState({ error: null, moreing: true }); if (this.state.comments && this.state.comments.length > 0) { this.lastSearch.before = new Date(this.state.comments[this.state.comments.length - 1].created_utc * 1000); } else if (this.state.posts && this.state.posts.length > 0) { this.lastSearch.before = new Date(this.state.posts[this.state.posts.length - 1].created_utc * 1000); } let url = this.api.get_url(this.lastSearch); let data = await this.api.query(url); if (this.lastSearch.searchFor == SearchType.Comments && data.data) { this.setState({ comments: this.state.comments.concat(data.data), moreing: false }); } else if (this.lastSearch.searchFor == SearchType.Posts && data.data) { this.setState({ posts: this.state.posts.concat(data.data), moreing: false }); } else { this.setState({ moreing: false }); } } /** Render the app * @return {React.ReactNode} The react node for the app */ render(): React.ReactNode { // Not tidy at all but it's a one page app so WONTFIX let moreButton = <button type="button" onClick={this.handleMoreClick} className="bg-red-900 hover:bg-red-800 font-bold py-2 mb-1">{this.state.moreing ? "Moreing..." : "More"}</button>; let linkClass = "text-blue-400 hover:text-blue-600"; let content; let resultCount; let inner; if (this.state.comments) { resultCount = this.state.comments.length; // Render comments inner = this.state.comments.map((comment) => { if (!comment) { return; } let permalink; if (comment.permalink) { permalink = comment.permalink; } else { permalink = `/comments/${comment.link_id.split('_')[1]}/_/${comment.id}/` } return <div className="bg-gray-900 px-1 mb-1" key={comment.id}> <div className="flex"> <a href={`https://reddit.com/r/${comment.subreddit}`}> <div className="text-sm text-red-500">/r/{comment.subreddit}</div> </a> <a href={`https://reddit.com/u/${comment.author}`}> <div className="text-sm text-red-500 ml-2">/u/{comment.author}</div> </a> <div className="text-sm text-red-500 ml-auto">{new Date(comment.created_utc * 1000).toLocaleString()}</div> </div> <a href={`https://reddit.com${permalink}?context=999`}> <div className="whitespace-pre-wrap">{comment.body}</div> </a> </div> }); } else if (this.state.posts && this.state.posts.length > 0) { resultCount = this.state.posts.length; // Render posts inner = this.state.posts.map((post) => { if (!post) { return; } let thumbnailUrl; if (post.thumbnail.startsWith('http')) { thumbnailUrl = post.thumbnail; } else if (post.url.split('.').pop() === 'png' || post.url.split('.').pop() === 'jpg') { thumbnailUrl = post.url; } let body; if (post.selftext && post.selftext.length !== 0) { body = <div className="whitespace-pre-wrap">{post.selftext}</div> } else { body = <a href={post.url}> <div>{post.url}</div> </a> } return <div className="bg-gray-900 px-1 mb-1" key={post.id}> <div className="flex"> <a href={`https://reddit.com/r/${post.subreddit}`}> <div className="text-sm text-red-500">/r/{post.subreddit}</div> </a> <a href={`https://reddit.com/u/${post.author}`}> <div className="text-sm text-red-500 ml-2">/u/{post.author}</div> </a> <div className="text-sm text-red-500 ml-auto">{new Date(post.created_utc * 1000).toLocaleString()}</div> </div> <div className="flex"> <div className="mr-1 mb-1 w-32 h-32 overflow-hidden flex-shrink-0"> <img className="w-full h-full object-cover" src={thumbnailUrl} /> </div> <div> <a href={`https://reddit.com/${post.id}`}> <div className="font-bold">{post.title}</div> </a> {body} </div> </div> </div> }); } if (this.state.comments || this.state.posts) { content = <div className="flex flex-col px-auto max-w-5xl mx-auto"> <div className="mx-auto mb-1">{resultCount} results - <a className={linkClass} href={this.state.lastUrl}>Generated API URL</a></div> {inner} {moreButton} </div> } else if (this.state.lastUrl) { content = <div className="flex flex-col px-auto max-w-5xl mx-auto"> <div className="mx-auto mb-1"><a className={linkClass} href={this.state.lastUrl}>Generated API URL</a></div> </div> } else { content = <div className="text-center px-4 max-w-5xl mx-auto"> <p>Search reddit using the <a className={linkClass} href="https://pushshift.io/">pushshift.io API</a>. For more advanced searches you can directly query the API <a className={linkClass} href="https://api.pushshift.io/reddit/comment/search?distinguished=admin&q=howdy&subreddit=!ModSupport">fairly easily</a>.</p> <p>The 'More' button works by changing the 'before' value to the time of the last post in the results. <em>This means that entries might be missed if they were posted at the same time.</em></p> </div > } // Combine everything and return return ( <> <GithubLink /> <form onSubmit={this.searchSubmit} className="flex flex-col mx-auto max-w-3xl pb-1 mb-3"> {/* Author and Subreddit */} <div className="sm:flex"> <div className="sm:w-1/2"> <label className="block text-xs uppercase font-bold">Author</label> <input onChange={this.handleAuthorChange} value={this.state.author} className="text-gray-900 bg-gray-300 focus:bg-gray-100 w-full py-2 px-1" /> </div> <div className="sm:w-1/2 sm:ml-1"> <label className="block text-xs uppercase font-bold">Subreddit</label> <input onChange={this.handleSubredditChange} value={this.state.subreddit} className="text-gray-900 bg-gray-300 focus:bg-gray-100 w-full py-2 px-1" /> </div> </div> {/* Type, Count and Score Filter */} <div className="sm:flex"> <div className="sm:w-1/3"> <label className="block text-xs uppercase font-bold">Search for</label> <div className="relative"> <select onChange={this.handleSearchTypeChange} value={this.state.searchFor === SearchType.Comments ? "Comments" : "Posts"} className="text-gray-900 bg-gray-300 focus:bg-gray-100 w-full py-2 px-1 appearance-none"> <option>Comments</option> <option>Posts</option> </select> <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /></svg> </div> </div> </div> <div className="sm:w-1/3 sm:ml-1"> <label className="block text-xs uppercase font-bold">Num. Returned</label> <input onInput={this.handleResultSizeChange} className="text-gray-900 bg-gray-300 focus:bg-gray-100 w-full py-2 px-1" type="number" min="25" step="25" value={this.state.resultSize} onChange={e => { }} /> </div> <div className="sm:w-1/3 sm:ml-1"> <label className="block text-xs uppercase font-bold">Score Filter</label> <input onChange={this.handleFilterChange} value={this.state.filter} className="text-gray-900 bg-gray-300 focus:bg-gray-100 w-full py-2 px-1" placeholder="e.g. >10 <100 >100,<900" /> </div> </div> {/* Time Range */} <div className="sm:flex"> <div className="sm:w-1/2"> <label className="block text-xs uppercase font-bold">After</label> <DatePicker showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy h:mm aa" className="text-gray-900 bg-gray-300 focus:bg-gray-100 py-2 px-1" onChange={this.handleAfterDateChange} selected={this.state.after} /> </div> <div className="sm:w-1/2 sm:ml-1"> <label className="block text-xs uppercase font-bold">Before</label> <DatePicker showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy h:mm aa" className="text-gray-900 bg-gray-300 focus:bg-gray-100 py-2 px-1" onChange={this.handleBeforeDateChange} selected={this.state.before} /> </div> </div> {/* Search Term */} <div> <label className="block text-xs uppercase font-bold">Search Term</label> <input onChange={this.handleQueryChange} value={this.state.query} className="text-gray-900 bg-gray-300 focus:bg-gray-100 w-full py-2 px-1" /> </div> {/* Submit Button and Error text */} <button type="submit" className="bg-red-900 hover:bg-red-800 font-bold mt-4 py-2">{this.state.searching ? "Searching..." : "Search"}</button> {this.state.error && <> <p className="text-red-200 text-center">{this.state.errorTime.toLocaleTimeString()} Error: {this.state.error}</p> </> } </form> {content} <div className="pb-2 pt-4 text-center"><RandomLink /></div> </> ); } } // https://gist.github.com/jokester/4a543ea76dbc5ae1bf05 var hash_accessor = (function (window) { return { load: function () { try { // strip ^# var json_str_escaped = window.location.hash.slice(1); // unescape var json_str = decodeURIComponent(json_str_escaped); return JSON.parse(json_str); } catch (e) { return {}; } }, save: function (obj) { // use replace so that previous url does not go into history window.location.replace('#' + JSON.stringify(obj, (key, value) => { if (value) return value; })); } }; })(window);
the_stack
// Hasta ahora hemos visto la base de Typescript sobre la que se sustenta // todo el chequeo de tipos. Pero la verdadera potencia llega con los tipos // avanzado. // *** ALIAS *************** // Un alias no es más que un nuevo nombre para un tipo, sea cual sea, // tipos primitivos, interfaces, funciones, uniones, etc: // Es muy util para REUSAR tipos cuya definición es más compleja o verbosa // de forma fácil y eficiente, abstrayéndola a un nombre simple, sin tener // que repetirla una y otra vez. // -- Caso Base -- type Message = string | number; type FunctionVoid = () => void; type Whatever<T> = { value: T; } // Muy util para abstraernos de definiciones complejas. No crea nuevos // tipos, solo nuevos nombres para referirse a ellos. type ReducerFunction<S> = (previousState: S, update: Partial<S>) => S; // *** INTERSECCIÓN *************** // Con la intersección podemos combinar múltiples tipos en uno solo. Sería // equivalente al operador AND lógico pero con tipos. // Es muy util para hacer composiciones: // -- Caso Base -- type Merged = { a: string } & { b: string }; const ab: Merged = { a: "A", b: "B" }; // Podría haber colisión, en tal caso, el tipado será never: type MergedCollision = { a: string } & { a: number }; // a: never const abc: MergedCollision = { a: 1 }; // Ni number ni string // -- Caso Práctico -- const compose = <A, B>(a: A, b: B): A & B => ({ ...a, ...b }); const cat = compose({ type: "feline" }, { skill: "hunting" }); const pigeon = compose({ wings: true }, { type: "bird" }); console.log(cat.type); console.log(pigeon.skill); // TS error: Property 'skill' is missing. // *** UNIÓN *************** // Siguiendo la analogía anterior, la unión de tipos sería entendida como // el operador OR. La unión de tipos es muy util para indicar que una // determinada entidad podrá ser de un tipo u otro, ámbos válidos. // -- Caso Base -- type A = "a" | "A" | "á" | "à"; type B = "b" | "B"; type AB = A | B; // "a" | "A" | "á" | "à" | "b" | "B" // -- Caso Práctico -- // Por ejemplo, sin unión, tendriamos que recurrir al any para admitir // argumentos de tipo string o númerico: const saySomething = (message: any) => console.log(message); // Pero con la unión, restringimos el argumento a los tipos deseados: const saySomethingTyped = (message: string | number) => console.log(message); saySomethingTyped(true); // TS error: Argument of type 'true' is not assignable // *** GUARDAS *************** // La situación anterior, sin embargo, puede llevarnos a un escenario donde // tengamos que comprobar de que tipo concreto es un determinado argumento // recibido, de entre todos los posibles tipos de su unión. // Por tanto, las guardas surgen ante la necesidad de tener que desambiguar // uniones. // Imaginemos la siguiente situacion, 2 interfaces y una función que // devuelve uno u otro de forma aleatoria: const randomBool = (): boolean => Boolean(Math.round(Math.random())); interface Human { sleep: () => void; } interface Man extends Human { moustache: boolean; } interface Woman extends Human { longHair: boolean; } const randomMan = (): Man => ({ moustache: randomBool(), sleep: () => console.log("Man is zzz"), }); const randomWoman = (): Woman => ({ longHair: randomBool(), sleep: () => console.log("Woman is zzz"), }); const getRandomPerson = (): Man | Woman => randomBool() ? randomMan() : randomWoman(); // ¿Cómo se que tengo un hombre o una mujer devueltos? const person = getRandomPerson(); if (person.moustache) { } // TS error: Property 'moustache' does not exist on type 'Woman' if (person.longHair) { } // TS error: Property 'longHair' does not exist on type 'Man' // [!] El acceso a estas propiedades causa un error porque tenemos // que DESAMBIGUAR el tipo. Para ello recurrimos a las GUARDAS. // Podemos construirlas de distintas maneras: // -- Guardas Definidas por el Usuario // Estas guardas se usan cuando queremos desambiguar objetos. // Una forma podría ser aplicando "duck typing" mediante el operador // "in" para comprobar de forma segura que una propiedad existe // en un objeto: if ("moustache" in person) { console.log("Man with moustache:", person["moustache"]); } else if ("longHair" in person) { console.log("Woman with long hair:", person["longHair"]); } // Otra forma más habitual para hacer el "duck typing" consiste en // hacer uso de la aseveración de tipos para discriminar entre // uno u otro: if ((person as Man).moustache !== undefined) { console.log("Man with moustache:", (person as Man).moustache); } else if ((<Woman>person).longHair !== undefined) { console.log("Woman with long hair:", (<Woman>person).longHair); } // Hasta aqui bien, pero hemos tenido que 'engañar' a intellisense // para que funcione correctamente. // Una forma más eficiente para este tipo de guardas sería haciendo // uso de de una funcion especial de chequeo que devuelve un // "type predicate": const isMan = (whoever: any): whoever is Man => (<Man>whoever).moustache !== undefined; if (isMan(person)) { console.log("Man with moustache:", person.moustache); } else { console.log("Woman with long hair:", person.longHair); } // -- Guardas con "typeof" // Cuando queremos desambiguar tipos primitivos, podemos recurrir // al operador "typeof": const giveMeSomething = (): number | string => randomBool() ? 13 : "trece"; const something = giveMeSomething(); if (typeof something === "number") { } // -- Guardas con "instanceof" // Cuando queremos desambiguar clases, es habitual recurrir // al operador "instanceof": class Bool { value: boolean }; const giveMeSomeClass = (): Bool | String => randomBool() ? { value: true } : "trece"; const someClass = giveMeSomeClass(); if (someClass instanceof Bool) console.log("Is Bool"); else console.log("Is String"); // *** STRING & NUMERIC LITERALS *************** // Muy útil para hacer que un tipo solo pueda tomar determinados // valores literales, es decir, limitar el conjunto de posibles valores // a un subconjunto finito. Se emplea habitualmente junto con la unión: // -- Caso Práctico -- type LabourDay = "monday" | "tuesday" | "wednesday" | "thursday" | "friday"; const day: LabourDay = "sunday"; // TS error: '"sunday"' is not assignable to type 'LabourDay' // También es aplicable a números literales: const throwDice = (): 1 | 2 | 3 | 4 | 5 | 6 => { return 6; // Dado trucado MUAHAHAHAHA. } // *** KEYOF *************** // Operador muy util para extraer las propiedades de un interfaz como // posibles literales de un tipo concreto: // -- Caso Base -- interface Week { monday: string; tuesday: string; wednesday: string; thursday: string; friday: string; saturday: string; sunday: string; } type Day = keyof Week; // -- Caso Práctico -- const showProps = <T>(obj: T, ...keys: (keyof T)[]): void => { keys.forEach(key => console.log(obj[key])); }; const dev = { type: "frontend", languages: ["js", "css", "html"], senior: true, }; showProps(dev, "type", "languages"); // Check intellisense!; // *** TIPOS MAPEADOS (MAPPED TYPES) *************** // Nos permiten crear nuevos alias a partir de las propiedades de otro alias. // -- Caso Práctico -- interface ProductItem { name: string; price: number; } // Index type => Acceder al tipo de una propiedad en un interface: type ProductName = ProductItem["name"]; // El objeto resultante tendrá todas las propiedades de Obj // y valores funciones transformadoras type Evolver<Obj> = { [Key in keyof Obj]?: (arg: Obj[Key]) => Obj[Key]; } // Función que devolverá una nueva copia del objeto aplicando // las transformaciones en las propiedades const evolve = <Obj extends object>(transformations: Evolver<Obj>, obj: Obj): Obj => { return Object.keys(obj).reduce<Obj>((result, key) => { result[key] = key in transformations ? transformations[key](obj[key]) : obj[key]; return result; }, {} as Obj); } const product: ProductItem = { name: " macbook Pro 16\" ", price: 2638, }; // Transformaciones: const formatString = (str: string) => ( str = str.trim(), str[0].toUpperCase() + str.substr(0) ) const applyIVA = (price: number): number => price * 1.21; // Aplicación const updatedProduct = evolve({ name: formatString, price: applyIVA }, product); console.log(updatedProduct); // *** TIPOS CONDICIONALES *************** // Permite mapear a diferentes tipos comprobando el valor de otro. // En la practica es equivalente a poder usar ternarios para tipos. // -- Caso Práctico -- type DarkColors = "black" | "grey"; type LightColors = "white" | "yellow" | "pink"; type Status = "sad" | "happy"; type Palette<P extends Status> = P extends "sad" ? DarkColors : LightColors; const palette: Palette<"sad"> = "black"; // Only black or grey allowed. // *** RECURSIVIDAD *************** // -- Recursividad en Interfaces -- // Podemos plantearnos el tipado de una estructura en árbol del siguiente // modo: interface TreeNode<T> { value: T; children?: Array<TreeNode<T>>; // Colección opcional de más nodos (hijos) } const myTree: TreeNode<number> = { value: 1, children: [{ value: 2 }, { value: 3, children: [{ value: 4 }] }], }; // -- Recursividad en Alias con Interfaces -- // Aunque aplicando la recursividad en interfaces si que podíamos hacer // cosas muy interesantes como esta: type IterableList<T> = T & { next: IterableList<T> }; interface Student { name: string; } let classList: IterableList<Student>; classList.name; classList.next.name; classList.next.next.name; // -- Recursividad en Alias -- // * Antes de la versión 3.7 de TS no se podía hacer recursividad // en la declaración de los Alias. Es decir, que la declaración del // alias se refiera a sí misma. De lo contrario nos daría un error // de referencia circular. // Por ejemplo, si queremos tipar nuestro árbol como: type TreeNodeError<T> = T | Array<TreeNodeError<T>>; // TS Error Circular Reference // Obtenemos un error de referencia circular. // Para burlar esta limitación podemos usar una técnica conocida como // "middleman", con la que desdoblamos la parte recursiva y la extraemos: interface TreeChildren<T> extends Array<TreeNodeMM<T>> { } // Middleman. type TreeNodeMM<T> = T | TreeChildren<T>; const myTreeMM: TreeNodeMM<string> = ["hello", [["world"], "!"]]; // * A partir de la version 3.7 de TS ya si está soportada totalmente // la recursión con Alias. Esto abre un abanico de nuevas posibilidades. type TreeNodeR<T> = T | Array<TreeNodeR<T>>; const myTreeRecursive: TreeNodeR<boolean> = [true, [false, true, [false]]];
the_stack
import * as util from '../util'; import * as concat3d_util from './concat3d_util'; import * as copy2d_util from './copy2d_util'; import {Array1D, Array2D, Array3D, Array4D, NDArray, Scalar} from './ndarray'; export type ScopeResult = NDArray[]|NDArray|void; export abstract class NDArrayMath { private ndarrayScopes: NDArray[][] = []; private activeScope: NDArray[]; private ndarraysToKeep: NDArray[][] = []; private activeScopeNDArraysToKeep: NDArray[] = []; private debugMode = false; /** * @param safeMode In safe mode, you must use math operations inside * a math.scope() which will automatically clean up intermediate NDArrays. */ constructor(private safeMode: boolean) {} /** * Create a new math scope. Put chained math operations inside a scope * function closure so that the library automatically cleans up NDArrays * from intermediate math operations. You must create a scope in safe mode * to call math operations. If a result is returned from the scope, it will * also be tracked, which means there must be yet another wrapping scope. * @param scopeFn The function to execute with chained math operations. */ scope<T extends ScopeResult>( scopeFn: (keep: <T1 extends NDArray>(ndarray: T1) => T1, track: <T2 extends NDArray>(ndarray: T2) => T2) => T) { this.startScope(); const keepFn = <T extends NDArray>(ndarray: T): T => this.keep(ndarray); const trackFn = <T extends NDArray>(ndarray: T): T => this.track(ndarray); const result = scopeFn(keepFn, trackFn); this.endScope(result); return result; } /** * In debug mode, the output of every math call will be downloaded to the CPU * and checked for NaNs. This significantly impacts performance. */ enableDebugMode() { this.debugMode = true; console.warn('Debugging mode is ON. The output of every math call will ' + 'be downloaded to CPU and checked for NaNs. ' + 'This significantly impacts performance.'); } /** * Start a scope. Use this with endScope() to achieve the same functionality * as scope() without the need for a function closure. */ startScope() { const newScope: NDArray[] = []; this.ndarrayScopes.push(newScope); this.activeScope = newScope; const newNDArraysToKeep: NDArray[] = []; this.ndarraysToKeep.push(newNDArraysToKeep); this.activeScopeNDArraysToKeep = newNDArraysToKeep; } /** * End a scope. Use this with startScope() to achieve the same functionality * as scope() without the need for a function closure. */ endScope(result: ScopeResult) { let arraysToKeep = this.activeScopeNDArraysToKeep; if (result != null) { arraysToKeep = arraysToKeep.concat(result as NDArray|NDArray[]); } // Dispose the current scope. for (let i = 0; i < this.activeScope.length; i++) { const ndarray = this.activeScope[i]; if (this.isNDArrayDataInList(ndarray, arraysToKeep)) { continue; } ndarray.dispose(); } // Pop the current scope. this.ndarrayScopes.pop(); this.activeScope = this.ndarrayScopes.length === 0 ? null! : this.ndarrayScopes[this.ndarrayScopes.length - 1]; // Track the current result in the parent scope. if (result instanceof NDArray && !this.isNDArrayDataInList(result, this.activeScopeNDArraysToKeep)) { this.track(result); } else if (Array.isArray(result)) { result.forEach(r => { if (r instanceof NDArray && !this.isNDArrayDataInList(r, this.activeScopeNDArraysToKeep)) { this.track(r); } }); } this.ndarraysToKeep.pop(); this.activeScopeNDArraysToKeep = this.ndarraysToKeep.length === 0 ? null! : this.ndarraysToKeep[this.ndarraysToKeep.length - 1]; } private isNDArrayDataInList(ndarray: NDArray, ndarrayList: NDArray[]) { for (let i = 0; i < ndarrayList.length; i++) { if (ndarrayList[i].getData() === ndarray.getData()) { return true; } } return false; } /** * Keeps an NDArray in the current scope from being disposed automatically. * @param result The NDArray to keep from being disposed. */ keep<T extends NDArray>(result: T): T { if (this.activeScope == null) { if (this.safeMode) { throw new Error( 'You are using math in safe mode. Enclose all ' + 'math.method() calls inside a scope: ' + 'math.scope(() => {math.method();...}) to avoid memory ' + 'leaks.'); } return result; } this.activeScopeNDArraysToKeep.push(result); return result; } private checkForNaN(arr: NDArray): void { const vals = arr.getValues(); for (let i = 0; i < vals.length; i++) { if (isNaN(vals[i])) { throw Error('The result NDArray of the last math call has NaNs.'); } } } /** * Tracks an NDArray in the current scope to be automatically cleaned up when * the current scope ends, and returns the value. * @param result The NDArray to track in the current scope. */ track<T extends NDArray>(result: T): T { if (this.debugMode) { this.checkForNaN(result); } if (this.activeScope == null) { if (this.safeMode) { throw new Error( 'You are using math in safe mode. Enclose all ' + 'math.method() calls inside a scope: ' + 'math.scope(() => {math.method();...}) to avoid memory ' + 'leaks.'); } return result; } this.activeScope.push(result); return result; } /** * Computes the dot product of two matrices, A * B. These must be matrices, * use matrixTimesVector and vectorTimesMatrix, dotProduct, and outerProduct * in other cases. * @param a First matrix in dot product operation. * @param b Second matrix in dot product operation. * @param aOrientation The MatrixOrientation of A. If using TRANSPOSED, will * compute A^T * B. * @param bOrientation The MatrixOrientation of B. If using TRANSPOSED, will * compute A * B^T. */ matMul( a: Array2D, b: Array2D, aOrientation = MatrixOrientation.REGULAR, bOrientation = MatrixOrientation.REGULAR): Array2D { const innerShapeA = (aOrientation === MatrixOrientation.REGULAR) ? a.shape[1] : a.shape[0]; const innerShapeB = (bOrientation === MatrixOrientation.REGULAR) ? b.shape[0] : b.shape[1]; util.assert( a.rank === 2 && b.rank === 2, `Error in matMul: inputs must be rank 2, got ranks ${a.rank}` + `and ${b.rank}.`); util.assert( innerShapeA === innerShapeB, `Error in matMul: inner shapes (${innerShapeA}) and (` + `${innerShapeB}) of NDArrays with shapes ${a.shape} and ` + `${b.shape} and orientations ${MatrixOrientation[aOrientation]}` + ` and ${MatrixOrientation[bOrientation]} must match.`); return this.track(this.matMulInternal(a, b, aOrientation, bOrientation)); } protected abstract matMulInternal( a: Array2D, b: Array2D, aOrientation: MatrixOrientation, bOrientation: MatrixOrientation): Array2D; /** * Computes the dot product of a vector and a matrix, v * B. * @param v The vector in dot product operation. * @param matrix The matrix in dot product operation. */ vectorTimesMatrix(v: Array1D, matrix: Array2D): Array1D { util.assert( v.rank === 1, `Error in vectorTimesMatrix: first input must be rank 1, but got ` + `rank ${v.rank}.`); util.assert( matrix.rank === 2, `Error in vectorTimesMatrix: second input must be rank 2, but got ` + `rank ${matrix.rank}.`); util.assert( v.size === matrix.shape[0], `Error in vectorTimesMatrix: size of first rank 1 input (${v.size}) ` + `must match inner dimension of second rank 2 input, but got ` + `rank ${matrix.rank}.`); return this.matMul(v.as2D(1, v.size), matrix).as1D(); } /** * Computes the dot product of a matrix and vector, A * v. * @param matrix The matrix in dot product operation. * @param v The vector in dot product operation. */ matrixTimesVector(matrix: Array2D, v: Array1D): Array1D { util.assert( v.rank === 1, `Error in vectorTimesMatrix: second input must rank 1, but got ` + `rank ${v.rank}.`); util.assert( matrix.rank === 2, `Error in vectorTimesMatrix: first input must be a rank 2, but got ` + `rank ${matrix.rank}.`); util.assert( v.size === matrix.shape[1], `Error in vectorTimesMatrix: size of first rank 1 input ${v.size} ` + `must match inner dimension of second rank 2 input, but got ` + `shape ${matrix.shape}.`); return this.matMul(matrix, v.as2D(v.size, 1)).as1D(); } /** * Computes the dot product of two vectors, v1 * v2. * @param v1 The first vector in the dot product operation. * @param v2 The second vector in the dot product operation. */ dotProduct(v1: Array1D, v2: Array1D): Scalar { util.assert( v1.rank === 1 && v2.rank === 1, `Error in dotProduct: inputs must be rank 1, but got ranks ` + `${v1.rank} and ${v2.rank}.`); util.assert( v1.size === v2.size, `Error in dotProduct: size of inputs (${v1.size}) and (` + `${v2.size}) must match.`); return this.matMul(v1.as2D(1, v1.size), v2.as2D(v2.size, 1)).asScalar(); } /** * Computes the outer product of two vectors, v1 and v2. * @param v1 The first vector in the outer product operation. * @param v2 The second vector in the dot product operation. */ outerProduct(v1: Array1D, v2: Array1D): Array2D { util.assert( v1.rank === 1 && v2.rank === 1, `Error in outerProduct: inputs must be rank 1, but got ranks ` + `${v1.rank} and ${v2.rank}.`); return this.matMul(v1.as2D(v1.size, 1), v2.as2D(1, v2.size)); } /////////////// // Shape ops // /////////////// /** * Clones an NDArray of any shape. * @param ndarray The NDArray to clone. */ clone<T extends NDArray>(ndarray: T): T { return this.track(this.cloneInternal(ndarray)); } protected abstract cloneInternal<T extends NDArray>(ndarray: T): T; /** * Reshapes an NDArray to a new shape. The size of the input NDArray must * match the size of the requested shape. * @param ndarray The input NDArray. * @param newShape The new shape to reshape the NDArray to. Must be the same * size as the NDArray. */ reshape<T1 extends NDArray, T2 extends NDArray>( ndarray: T1, newShape: number[]): T2 { util.assert( ndarray.size === util.sizeFromShape(newShape), `Error in reshape: old size ${ndarray.size} must match new size ` + `${util.sizeFromShape(newShape)}.`); return this.track(this.reshapeInternal<T1, T2>(ndarray, newShape)); } protected abstract reshapeInternal<T1 extends NDArray, T2 extends NDArray>( ndarray: T1, newShape: number[]): T2; /** * Extracts a slice from a matrix. The operation extraces a slice from input * that starts at coordinates `begin` and is of size `size`. * @param input The input matrix to slice from. * @param begin The 2D coordinates in the input matrix to start the slice * from. * @param size The sice of the 2D window to slice. */ slice2D(input: Array2D, begin: [number, number], size: [number, number]): Array2D { util.assert( begin[0] + size[0] <= input.shape[0] && begin[1] + size[1] <= input.shape[1], `Error in slice2D: requested start position ${begin} and size ` + `${size} would overflow input of shape ${input.shape}.`); return this.track(this.slice2DInternal(input, begin, size)); } protected abstract slice2DInternal( input: Array2D, begin: [number, number], size: [number, number]): Array2D; /** * Copies a window from the `source` matrix starting at `sourceBegin` and is * of size `sourceSize` to a window in the `dest` matrix starting at * `destBegin` and is of size `destSize`/ * @param source The source matrix to copy from. * @param sourceBegin The coordinates to start the copy from. * @param sourceSize The size of the copy window. * @param dest The destination matrix to copy to. * @param destBegin The coordinates in `dest` to copy to. * @param destSize The size of the destination window. */ copy2D( source: Array2D, sourceBegin: [number, number], sourceSize: [number, number], dest: Array2D, destBegin: [number, number], destSize: [number, number]) { util.assert( sourceBegin[0] + sourceSize[0] <= source.shape[0] && sourceBegin[1] + sourceSize[1] <= source.shape[1], `Error in copy2D: requested source start position ${sourceBegin} ` + `and source size ${sourceSize} would overflow source NDArray` + `of shape ${source.shape}.`); util.assert( destBegin[0] + destSize[0] <= dest.shape[0] && destBegin[1] + destSize[1] <= dest.shape[1], `Error in copy2D: requested dest start position ${destBegin} ` + `and source size ${destSize} would overflow dest NDArray of` + `shape ${dest.shape}.`); copy2d_util.validateShapes(sourceSize, destSize); return this.copy2DInternal( source, sourceBegin, sourceSize, dest, destBegin, destSize); } protected abstract copy2DInternal( source: Array2D, sourceBegin: [number, number], sourceSize: [number, number], dest: Array2D, destBegin: [number, number], destSize: [number, number]): void; /** * Concatenates two 3D ndarrays along a given axis. * * For example, if: * A: shape(2, 1, 3) = | r1, g1, b1 | * | r2, g2, b2 | * * B: shape(2, 1, 3) = | r3, g3, b3 | * | r4, g4, b4 | * * C = concat3D(A, B, axis) * * if axis = 0: * C: shape(4, 1, 3) = | r1, g1, b1 | * | r2, g2, b2 | * | r3, g3, b3 | * | r4, g4, b4 | * * if axis = 1: * C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 | * | r2, g2, b2, r4, g4, b4 | * * if axis = 2: * C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 | * | r2, g2, b2, r4, g4, b4 | * * @param ndarray1 The first array to concat. * @param ndarray2 The second array to conat. * @param axis The axis to concate along. */ concat3D(ndarray1: Array3D, ndarray2: Array3D, axis: number): Array3D { concat3d_util.assertConcat3DShapesMatch( ndarray1.shape, ndarray2.shape, axis, 'Error in concat3d: '); return this.track(this.concat3DInternal(ndarray1, ndarray2, axis)); } protected abstract concat3DInternal( ndarray1: Array3D, ndarray2: Array3D, axis: number): Array3D; /////////////////// // Reduction ops // /////////////////// /** * Computes the the log(sum(e ^ x)) for each x in the input ndarray. * @param ndarray The input NDArray to compute the logSumExp over. */ logSumExp(ndarray: NDArray): Scalar { return this.track(this.logSumExpInternal(ndarray)); } protected abstract logSumExpInternal(ndarray: NDArray): Scalar; /** * Computes the sum of all the entries in the input NDArray. * @param ndarray The input NDArray to compute the sum over. */ sum(ndarray: NDArray): Scalar { return this.track(this.sumInternal(ndarray)); } protected abstract sumInternal(ndarray: NDArray): Scalar; /** * Computes the flattened index of the minimum element in the ndarray. * @param ndarray The input NDArray. */ argMin(ndarray: NDArray): Scalar { return this.track(this.argMinInternal(ndarray)); } protected abstract argMinInternal(ndarray: NDArray): Scalar; /** * Computes the flattened index of the maximum element in the ndarray. * @param ndarray The input NDArray. */ argMax(ndarray: NDArray): Scalar { return this.track(this.argMaxInternal(ndarray)); } protected abstract argMaxInternal(ndarray: NDArray): Scalar; /** * Returns a 1 if the argMax of x1 and x2 are the same, otherwise 0. * @param x1 The first input NDArray. * @param x2 The second input NDArray. */ argMaxEquals(x1: NDArray, x2: NDArray): Scalar { util.assertShapesMatch(x1.shape, x2.shape, 'Error in argMaxEquals: '); return this.track(this.argMaxEqualsInternal(x1, x2)); } protected abstract argMaxEqualsInternal(x1: NDArray, x2: NDArray): Scalar; /** * Computes the top K values and flattened indices. * @param ndarray The input NDArray. * @param k How many top values to compute. */ topK(ndarray: NDArray, k: number): {values: Array1D, indices: Array1D} { util.assert( k <= ndarray.size, `Error in topK: k value (${k}) must be less than size of input ` + `ndarray, got shape ${ndarray.shape}.`); const result = this.topKInternal(ndarray, k); this.track(result.values); this.track(result.indices); return result; } protected abstract topKInternal(ndarray: NDArray, k: number): {values: Array1D, indices: Array1D}; /** * Computes the minimum value from the input. * @param ndarray The input NDArray. */ min(ndarray: NDArray): Scalar { return this.track(this.minInternal(ndarray)); } protected abstract minInternal(ndarray: NDArray): Scalar; /** * Computes the maximum value from the input. * @param ndarray The input NDArray. */ max(ndarray: NDArray): Scalar { return this.track(this.maxInternal(ndarray)); } protected abstract maxInternal(ndarray: NDArray): Scalar; /** * Computes the softmax normalized vector from the input vector. * @param x The input vector. */ softmax(x: Array1D): Array1D { return this.scope(() => { // Do it in log space for numerical stability. // exp(X - logSumExp(X)) const lse = this.logSumExp(x); const logResult = this.arrayMinusScalar(x, lse); return this.exp(logResult); }); } ////////////////////// // Element-wise ops // ////////////////////// /** * Switches dimensions of the input NDArray. * @param a The input NDArray. * @param newDim The new indices that define which shapes values to switch. */ switchDim<T extends NDArray>(a: T, newDim: number[]): T { util.assert( a.rank === newDim.length, `Error in switchDim: length of input shape ${a.shape} ` + `must match size of newDim array ${newDim}.`); return this.track(this.switchDimInternal(a, newDim)); } protected abstract switchDimInternal<T extends NDArray>( a: T, newDim: number[]): T; /** * Computes a scalar plus NDArray, c + A. * @param c The scalar c in c + A. * @param a The NDArray A in c + A. */ scalarPlusArray<T extends NDArray>(c: Scalar, a: T): T { util.assert( c.size === 1, `Error in scalarPlusArray: first argument must be rank 0, but got ` + `rank ${c.rank}.`); return this.add(c, a) as T; } /** * Computes a scalar minus NDArray, c - A. * @param c The scalar c in c - A. * @param a The NDArray A in c - A. */ scalarMinusArray<T extends NDArray>(c: Scalar, a: T): T { util.assert( c.size === 1, `Error in scalarMinusArray: first argument must be rank 0, but got ` + `rank ${c.rank}.`); return this.sub(c, a) as T; } /** * Computes A - c. A is NDArray, c is Scalar. * @param a The NDArray A in A - c. * @param c The Scalar c in A - c. */ arrayMinusScalar<T extends NDArray>(a: T, c: Scalar): T { util.assert( c.size === 1, `Error in arrayMinusScalar: second argument must be rank 0, but ` + `got rank ${c.rank}.`); return this.sub(a, c) as T; } /** * Computes -1 * A element-wise. * @param a The input array. */ neg<T extends NDArray>(a: T): T { return this.track(this.negInternal(a)); } protected abstract negInternal<T extends NDArray>(a: T): T; /** * Adds two NDArrays element-wise, A + B. Supports broadcasting. * For a stricter version without broadcasting use math.addStrict(). * * @param a The first NDArray to add element-wise. * @param b The second NDArray to add element-wise. */ add(a: NDArray, b: NDArray): NDArray { util.assertAndGetBroadcastedShape(a.shape, b.shape); return this.track(this.addInternal(a, b)); } protected abstract addInternal(a: NDArray, b: NDArray): NDArray; /** * Adds two NDArrays element-wise, A + B. Inputs must * be the same shape. For broadcasting support, use math.add() instead. * * @param a The first NDArray to multiply element-wise. * @param b The second NDArray to multiply element-wise. */ addStrict<T extends NDArray>(a: T, b: T): T { util.assertShapesMatch(a.shape, b.shape, 'Error in addStrict: '); return this.add(a, b) as T; } /** * Subtracts two NDArrays element-wise, A - B. Supports broadcasting. * For a stricter version without broadcasting use math.subStrict(). * * @param a The first NDArray to subtract element-wise. * @param b The second NDArray to subtract element-wise. */ sub(a: NDArray, b: NDArray): NDArray { util.assertAndGetBroadcastedShape(a.shape, b.shape); return this.track(this.subInternal(a, b)); } protected abstract subInternal(a: NDArray, b: NDArray): NDArray; /** * Subtracts two NDArrays element-wise, A - B. Inputs must * be the same shape. For broadcasting support, use math.sub() instead. * * @param a The first NDArray to multiply element-wise. * @param b The second NDArray to multiply element-wise. */ subStrict<T extends NDArray>(a: T, b: T): T { util.assertShapesMatch(a.shape, b.shape, 'Error in subStrict: '); return this.sub(a, b) as T; } /** * Multiplies two NDArrays element-wise, A * B. Supports broadcasting. * For a stricter version without broadcasting use math.multiplyStrict(). * * @param a The first NDArray to multiply element-wise. * @param b The second NDArray to multiply element-wise. */ multiply(a: NDArray, b: NDArray): NDArray { util.assertAndGetBroadcastedShape(a.shape, b.shape); return this.track(this.multiplyInternal(a, b)); } protected abstract multiplyInternal<T extends NDArray>(a: T, b: T): T; /** * @deprecated Use math.multiplyStrict() instead. */ elementWiseMul<T extends NDArray>(a: T, b: T): T { return this.multiplyStrict(a, b); } /** * Multiplies two NDArrays element-wise, A * B. Inputs must * be the same shape. For broadcasting support, use math.multiply() instead. * * @param a The first NDArray to multiply element-wise. * @param b The second NDArray to multiply element-wise. */ multiplyStrict<T extends NDArray>(a: T, b: T): T { util.assertShapesMatch(a.shape, b.shape, 'Error in multiplyStrict: '); return this.multiply(a, b) as T; } /** * Divides two NDArrays element-wise, A / B. Supports broadcasting. * For a stricter version without broadcasting use math.divideStrict(). * * @param a The first NDArray to divide element-wise. * @param b The second NDArray to divide element-wise. */ divide(a: NDArray, b: NDArray): NDArray { util.assertAndGetBroadcastedShape(a.shape, b.shape); return this.track(this.divideInternal(a, b)); } protected abstract divideInternal(a: NDArray, b: NDArray): NDArray; /** * Divides two NDArrays element-wise, A / B. Inputs must * be the same shape. For broadcasting support, use math.divide() instead. * * @param a The first NDArray to multiply element-wise. * @param b The second NDArray to multiply element-wise. */ divideStrict<T extends NDArray>(a: T, b: T): T { util.assertShapesMatch(a.shape, b.shape, 'Error in divideStrict: '); return this.divide(a, b) as T; } /** * Computes a scalar divided by an NDArray, broadcasted over the NDArray, c / * A. * @param c The scalar value in c / A. * @param a The NDArray value in c / A. */ scalarDividedByArray<T extends NDArray>(c: Scalar, a: T): T { util.assert( c.size === 1, `Error in scalarDividedByArray: first argument must be rank 0, but ` + `got NDArray of rank ${c.rank}.`); return this.divide(c, a) as T; } /** * Computes an NDArray divided by a scalar, broadcasted over the NDArray, A / * c. * @param a The NDArray value in A / c. * @param c The scalar value in A / c. */ arrayDividedByScalar<T extends NDArray>(a: T, c: Scalar): T { util.assert( c.size === 1, `Error in arrayDividedByScalar: second argument must be rank 0, ` + `but got NDArray of rank ${c.rank}.`); return this.divide(a, c) as T; } /** * Computes exponential of the input NDArray element-wise. y = e ^ x * @param ndarray The input NDArray. */ exp<T extends NDArray>(ndarray: T): T { return this.track(this.expInternal(ndarray)); } protected abstract expInternal<T extends NDArray>(ndarray: T): T; /** * Computes natural logarithm of the input NDArray element-wise. y = ln(x) * @param ndarray The input NDArray. */ log<T extends NDArray>(ndarray: T): T { return this.track(this.logInternal(ndarray)); } protected abstract logInternal<T extends NDArray>(ndarray: T): T; /** * Computes rectified linear element-wise, max(x, 0). * @param ndarray The input NDArray. */ relu<T extends NDArray>(ndarray: T): T { return this.track(this.reluInternal(ndarray)); } protected abstract reluInternal<T extends NDArray>(ndarray: T): T; /** * Computes sigmoid element-wise, y = 1 / (1 + exp(-x)). * @param ndarray The input NDArray. */ sigmoid<T extends NDArray>(ndarray: T): T { return this.track(this.sigmoidInternal(ndarray)); } protected abstract sigmoidInternal<T extends NDArray>(ndarray: T): T; /** * Computes hyperbolic tangent of the input NDArray element-wise. * @param ndarray The input NDArray. */ tanh<T extends NDArray>(ndarray: T): T { return this.track(this.tanhInternal(ndarray)); } protected abstract tanhInternal<T extends NDArray>(ndarray: T): T; /** * Computes sin of the input NDArray element-wise, y = sin(x). * @param ndarray The input NDArray. */ sin<T extends NDArray>(ndarray: T): T { return this.track(this.sinInternal(ndarray)); } protected abstract sinInternal<T extends NDArray>(ndarray: T): T; /** * Computes step of the input NDArray element-wise, y = 1 if x > 0 | 0 if x <= * 0 * @param ndarray The input NDArray. */ step<T extends NDArray>(ndarray: T): T { return this.track(this.stepInternal(ndarray)); } protected abstract stepInternal<T extends NDArray>(ndarray: T): T; /** * Computes a scaled array add operation, c1 * A + c2 * B. * @param c1 The first scalar in the scaled array add computation. * @param a The first NDArray in the scaled array add computation. * @param c2 The second scalar in the scaled array add computation. * @param cb The second NDArray in the scaled array add computation. */ scaledArrayAdd<T extends NDArray>(c1: Scalar, a: T, c2: Scalar, b: T): T { util.assert( c1.size === 1, `Error in scaledArrayAdd: first argument must rank 0, but got ` + ` rank ${c1.rank}.`); util.assert( c2.size === 1, `Error in scaledArrayAdd: third argument must be rank 0, but got ` + `NDArray of rank ${c2.rank}.`); util.assertShapesMatch(a.shape, b.shape, 'Error in scaledArrayAdd: '); return this.track(this.scaledArrayAddInternal(c1, a, c2, b)); } protected abstract scaledArrayAddInternal<T extends NDArray>( c1: Scalar, a: T, c2: Scalar, b: T): T; /** * Computes a scalar times array operation broadcasted over the NDArray, c * * A. * @param c The scalar in the operation. * @param A the NDArray in the operation that will be broadcasted over. */ scalarTimesArray<T extends NDArray>(c: Scalar, a: T): T { util.assert( c.size === 1, `Error in arrayDividedByScalar: first argument must be rank 0, but ` + `got rank ${c.rank}.`); return this.multiply(c, a) as T; } /** * @deprecated Use math.multiply() instead. */ elementWiseMulBroadcast(a: Array2D, b: Array2D): Array2D { util.assert( a.rank === 2, `Error in elementWiseMulBroadcast: first argument must be ` + `rank 2, but got rank ${a.rank}.`); util.assert( b.rank === 2, `Error in elementWiseMulBroadcast: second argument must be ` + `rank 2, but got rank ${b.rank}.`); return this.multiply(a, b) as Array2D; } ///////////////////// // Convolution ops // ///////////////////// /** * Computes a 2D convolution over the input x. * @param x The input image, must be rank 3, of shape [rows, cols, depth1]. * @param weights The weights NDArray, must be rank 4, of shape [f, f, depth1, * depth2]. * @param biases Optional biases NDArray, must be rank 1 of shape [depth2]. * @param stride The stride of the convolution. * @param zeroPad The zero padding of each side of the input NDArray. Will pad * equally on all sides. */ conv2d( x: Array3D, weights: Array4D, biases: Array1D|null, stride: number, zeroPad: number): Array3D { util.assert( x.rank === 3, `Error in conv2d: x must be rank 3, but got rank ${x.rank}.`); util.assert( weights.rank === 4, `Error in conv2d: weights must be rank 4, but got rank ` + `${weights.rank}.`); if (biases != null) { util.assert( biases.rank === 1, `Error in conv2d: biases must be rank 1, but got rank ` + `${biases.rank}.`); } util.assert( x.shape[2] === weights.shape[2], `Error in conv2d: depth of input (${x.shape[2]}) must match ` + `input depth for weights ${weights.shape[2]}.`); return this.track(this.conv2dInternal(x, weights, biases, stride, zeroPad)); } protected abstract conv2dInternal( x: Array3D, weights: Array4D, biases: Array1D|null, stride: number, zeroPad: number): Array3D; /** * Computes the backprop of a 2D convolution. * @param x The input image, must be rank 3, of shape [xrows, xcols, depth1]. * @param dy The dy image, must be rank 3, of shape [yrows, ycols, depth2]. * @param weights The weights NDArray, must be rank 4, of shape [f, f, depth1, * depth2]. * @param stride The stride of the original convolution. * @param pad The padding of the original convolution. */ conv2dBackProp( x: Array3D, dy: Array3D, weights: Array4D, stride: number, pad: number): {dx: Array3D, dw: Array4D, db: Array1D} { util.assert( x.rank === 3, `Error in conv2dBackProp: x must be rank 3, but got shape ` + `${x.shape}.`); util.assert( dy.rank === 3, `Error in conv2dBackProp: dy must be rank 3, but got shape ` + `${dy.shape}.`); util.assert( weights.rank === 4, `Error in conv2dBackProp: weights must be rank 4, but got shape ` + `${weights.shape}.`); util.assert( x.shape[2] === weights.shape[2], `Error in conv2dBackProp: depth of x ${x.shape[2]}) must ` + `match input depth for weights (${weights.shape[2]}.`); util.assert( dy.shape[2] === weights.shape[3], `Error in conv2dBackProp: depth of dy (${dy.shape[2]}) must ` + `match output depth for weights (${weights.shape[3]}).`); const backpropResult = this.conv2dBackPropInternal(x, dy, weights, stride, pad); this.track(backpropResult.db); this.track(backpropResult.dw); this.track(backpropResult.dx); return backpropResult; } protected abstract conv2dBackPropInternal( x: Array3D, dy: Array3D, weights: Array4D, stride: number, pad: number): {dx: Array3D, dw: Array4D, db: Array1D}; /** * Computes the transposed 2D convolution of an image, also known as a * deconvolution. * @param x The input image, must be rank 3, of shape [xrows, xcols, depth1]. * @param weights The weights NDArray, must be rank 4, of shape [f, f, depth1, * depth2]. * @param biases Optional biases NDArray, must be rank 1 of shape [depth2]. * @param stride The stride of the convolution. * @param pad The padding of each side of the input NDArray. Will pad equally * on all sides. */ conv2dTranspose( x: Array3D, weights: Array4D, biases: Array1D|null, stride: number, pad: number): Array3D { util.assert( x.rank === 3, `Error in conv2dTranspose: x must be rank 3, but got rank ` + `${x.rank}.`); util.assert( weights.rank === 4, `Error in conv2dTranspose: weights must be rank 4, but got ` + `rank ${weights.rank}`); if (biases != null) { util.assert( biases.rank === 1, `Error in conv2dTranspose: biases must be rank 1, but got ' + 'rank ${biases.rank}.`); } util.assert( x.shape[2] === weights.shape[3], `Error in conv2dTranspose: depth of input (${x.shape[2]}) must ` + `match input depth for weights ${weights.shape[3]}.`); return this.track( this.conv2dTransposeInternal(x, weights, biases, stride, pad)); } protected abstract conv2dTransposeInternal( x: Array3D, weights: Array4D, biases: Array1D|null, stride: number, pad: number): Array3D; /** * Computes the 2D max pooling of an image. * @param x The input image, must be rank 3. * @param fSize The field size of the max pool. * @param stride The stride of the max pool. * @param pad The padding of each side of the input NDArray. Will pad equally * on all sides. */ maxPool(x: Array3D, fSize: number, stride: number, pad: number): Array3D { util.assert( x.rank === 3, 'Error in maxPool: x must be rank 3 but got rank ' + x.rank + '.'); return this.track(this.maxPoolInternal(x, fSize, stride, pad)); } protected abstract maxPoolInternal( x: Array3D, fSize: number, stride: number, pad: number): Array3D; /** * Computes the backprop of a max pool. * @param dy The dy error. * @param x The input image, must be rank 3. * @param fSize The field size of the max pool. * @param stride The stride of the max pool. * @param pad The padding of each side of the input NDArray. Will pad equally * on all sides. */ maxPoolBackprop( dy: Array3D, x: Array3D, fSize: number, stride: number, pad: number): Array3D { util.assert( dy.rank === 3, `Error in maxPoolBackprop: dy must be rank 3 but got rank ` + `${dy.rank}.`); util.assert( x.rank === 3, `Error in maxPoolBackprop: x must be rank 3 but got rank ` + `${x.rank}.`); return this.track(this.maxPoolBackpropInternal(dy, x, fSize, stride, pad)); } protected abstract maxPoolBackpropInternal( dy: Array3D, x: Array3D, fSize: number, stride: number, pad: number): Array3D; /** * Computes the 2D min pooling of an image. * @param x The input image, must be rank 3. * @param fSize The field size of the max pool. * @param stride The stride of the max pool. * @param pad The padding of each side of the input NDArray. Will pad equally * on all sides. */ minPool(x: Array3D, fSize: number, stride: number, pad: number): Array3D { util.assert( x.rank === 3, `Error in minPool: x must be rank 3 but got rank ${x.rank}.`); return this.track(this.minPoolInternal(x, fSize, stride, pad)); } protected abstract minPoolInternal( x: Array3D, fSize: number, stride: number, pad: number): Array3D; /** * Computes the 2D average pooling of an image. * @param x The input image, must be rank 3. * @param fSize The field size of the max pool. * @param stride The stride of the max pool. * @param pad The padding of each side of the input NDArray. Will pad equally * on all sides. */ avgPool(x: Array3D, fSize: number, stride: number, pad: number): Array3D { util.assert( x.rank === 3, `Error in avgPool: x must be rank 3 but got rank ${x.rank}.`); return this.track(this.avgPoolInternal(x, fSize, stride, pad)); } protected abstract avgPoolInternal( x: Array3D, fSize: number, stride: number, pad: number): Array3D; /* * Bilinear resize a 3D array per each channel to a new 2D shape. * @param x The input Array3D. * @param newShape2D The new shape to resize the Array3D to. Each channel is * resized individually. * @param alignCorners An optional bool. Defaults to False. If true, rescale * input by (new_height - 1) / (height - 1), which exactly aligns the 4 * corners of images and resized images. If false, rescale by new_height / * height. Treat similarly the width dimension. */ resizeBilinear3D( x: Array3D, newShape2D: [number, number], alignCorners = false): Array3D { util.assert( x.rank === 3, `Error in resizeBilinear3D: x must be rank 3 but got rank ${x.rank}.`); util.assert( newShape2D.length === 2, `Error in resizeBilinear3D: new shape must 2D, but got shape ` + `${newShape2D}.`); return this.track( this.resizeBilinear3DInternal(x, newShape2D, alignCorners)); } protected abstract resizeBilinear3DInternal( x: Array3D, newShape2D: [number, number], alignCorners: boolean): Array3D; /** * Batch normalization 3D. Mean, variance, scale, and offset can be of two * shapes: 1) The same shape as the input: an Array3D. 2) In the common case, * the depth dimension is the last dimension of x, so the values would be an * Array1D of shape [depth]. * @param x The input NDArray. * @param mean A mean NDArray. * @param variance A variance NDArray. * @param varianceEpsilon A small float number to avoid dividing by 0. * @param scale A scale NDArray. * @param offset An offset NDArray. */ batchNormalization3D( x: Array3D, mean: Array3D|Array1D, variance: Array3D|Array1D, varianceEpsilon = .001, scale?: Array3D|Array1D, offset?: Array3D|Array1D): Array3D { util.assert( x.rank === 3, `Error in batchNormalization3D: x must be rank 3 but got rank ` + `${x.rank}.`); util.assert( mean.rank === 3 || mean.rank === 1, `Error in batchNormalization3D: mean must be rank 3 or rank 1 but ` + `got rank ${mean.rank}.`); util.assert( variance.rank === 3 || variance.rank === 1, `Error in batchNormalization3D: variance must be rank 3 or rank 1 ` + `but got rank ${variance.rank}.`); if (scale != null) { util.assert( scale.rank === 3 || scale.rank === 1, `Error in batchNormalization3D: scale must be rank 3 or rank 1 ` + `but got rank ${scale!.rank}.`); } if (offset != null) { util.assert( offset.rank === 3 || offset.rank === 1, `Error in batchNormalization3D: offset must be rank 3 or rank 1 ` + `but got rank ${offset!.rank}.`); } return this.track(this.batchNormalization3DInternal( x, mean, variance, varianceEpsilon, scale, offset)); } protected abstract batchNormalization3DInternal( x: Array3D, mean: Array3D|Array1D, variance: Array3D|Array1D, varianceEpsilon: number, scale?: Array3D|Array1D, offset?: Array3D|Array1D): Array3D; } export enum MatrixOrientation { REGULAR, TRANSPOSED }
the_stack