text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as assert from 'assert'; import { Config } from '../config/config'; import { JumpKind } from '../models/jump-kind'; import { Jumper } from './../jumper'; import { ScenarioBuilder } from './scenarios/scenario.builder'; describe('Jumper', () => { let sut: Jumper; let scenario: ScenarioBuilder; before(() => { sut = new Jumper(); const config = new Config(); sut.refreshConfig(config); scenario = new ScenarioBuilder(); }); after(() => { scenario.restore(); }); afterEach(() => { scenario.reset(); }); describe('both jumpkinds', () => { // it('when we finish a jump we should be able to recall it', async () => { // // given // scenario.withLines('this absolutely match').withCommand('a'); // await sut.jump(JumpKind.Normal); // // when // await sut.jump(JumpKind.Normal); // }); [JumpKind.Normal, JumpKind.MultiChar].forEach(jumpKind => { it(`should not jump when there is no editor for ${jumpKind}`, async () => { // given scenario.withNoEditor(); try { // when await sut.jump(jumpKind, false); throw new Error('should have thrown exception'); } catch (error) { // then assert.equal(error.message, 'No active editor'); scenario.hasStatusBarMessages(); } }); it(`should not jump if input is empty for ${jumpKind}`, async () => { // given scenario.withEditor().withCommands(''); try { // when await sut.jump(jumpKind, false); throw new Error('should have thrown exception'); } catch (error) { // then assert.equal(error.message, 'Empty Value'); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Empty Value', ); } }); it(`should break if there is no visibleRanges for ${jumpKind}`, async () => { // given scenario.withNoVisibleRanges().withCommands('a'); try { // when await sut.jump(jumpKind, false); throw new Error('should have thrown exception'); } catch (error) { // then assert.equal(error.message, 'There are no visible ranges!'); scenario.hasStatusBarMessages('$(rocket) Type', '$(rocket) Canceled'); } }); it(`should break if there is one row which does not match the char for ${jumpKind}`, async () => { // given scenario.withLines('no matching characters').withCommands('a'); try { // when await sut.jump(jumpKind, false); throw new Error('should have thrown exception'); } catch (error) { // then assert.equal(error.message, 'No Matches'); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) No Matches', ); } }); it(`should jump directly if there is three row where matches only one for ${jumpKind}`, async () => { // given scenario .withLines('my first row', 'this absolutely match', 'class some') .withCommands('a'); // when const { placeholder } = await sut.jump(jumpKind, false); // then assert.deepEqual(placeholder, { childrens: [], index: 0, placeholder: 'a', line: 2, character: 5, }); scenario.hasStatusBarMessages('$(rocket) Type', '$(rocket) Jumped!'); }); }); }); describe(`${JumpKind.Normal} jumpkind`, () => { it('should not jump if there is three row where matches three but we type empty value', async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands('a', ''); try { // when await sut.jump(JumpKind.Normal, false); throw new Error('should have thrown exception'); } catch (error) { // then assert.equal(error.message, 'Empty Value'); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Jump To', '$(rocket) Empty Value', ); } }); it('should not jump if there is three row where matches three but we type a non matching placeholder', async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands('a', 'd'); try { // when await sut.jump(JumpKind.Normal, false); throw new Error('should have thrown exception'); } catch (error) { // then assert.equal(error.message, 'No Matches'); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Jump To', '$(rocket) No Matches', ); } }); it('should jump if there is three row where matches three and we match a placeholder', async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands('a', 'b'); // when const { placeholder } = await sut.jump(JumpKind.Normal, false); // then scenario.hasDimmedEditor(1); scenario.hasCreatedPlaceholders(3); assert.deepEqual(placeholder, { childrens: [], index: 1, placeholder: 'b', line: 3, character: 0, }); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Jump To', '$(rocket) Jumped!', ); }); it('should jump if there is more than available characters and we have to jump twice', async () => { // given scenario .withLines( 'a a a a a a a a a a a a a', 'a a a a a a a a a a a a a', 'a a a a a a a a a a a a a', 'a a a a a a a a a a a a a', 'a a a a a a a a a a a a a', ) .withCommands('a', 'b', 'f'); // when const { placeholder } = await sut.jump(JumpKind.Normal, false); // then scenario.hasDimmedEditor(2); scenario.hasCreatedPlaceholders(121); assert.deepEqual(placeholder, { childrens: [], index: 5, placeholder: 'f', line: 3, character: 10, }); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Jump To', '$(rocket) Jump To', '$(rocket) Jumped!', ); }); it('should jump if there is three row where matches three', async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands('a', 'b'); // when const { placeholder } = await sut.jump(JumpKind.Normal, false); // then scenario.hasDimmedEditor(1); scenario.hasCreatedPlaceholders(3); assert.deepEqual(placeholder, { childrens: [], index: 1, placeholder: 'b', line: 3, character: 0, }); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Jump To', '$(rocket) Jumped!', ); }); }); describe(`${JumpKind.MultiChar} jumpkind`, () => { it('should not jump if there is three row where matches three but we type empty value', async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands('a', ''); try { // when await sut.jump(JumpKind.MultiChar, false); throw new Error('should have thrown exception'); } catch (error) { // then assert.equal(error.message, 'Empty Value'); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Next char', '$(rocket) Empty Value', ); } }); it(` should jump directly to first placeholder when there is three row where matches three and we restrict to a valid next char`, async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands( 'a', // we try to match a 'b', // we try to match second char ); // when const { placeholder } = await sut.jump(JumpKind.MultiChar, false); // then scenario.hasDimmedEditor(1); scenario.hasCreatedPlaceholders(3); assert.deepEqual(placeholder, { childrens: [], index: 0, placeholder: 'a', line: 2, character: 5, }); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Next char', '$(rocket) Jumped!', ); }); it(` should preserve placeholders and jump to correct placeholder when there is three row where matches three but we restrict with a non-matching char until we press a valid next char `, async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands( 'a', // we try to match a 'z', // non matching restrict char 'f', // non matching restrict char 'l', // we try to match second char 'escape', // we escape 'c', // we try to jump to placeholder ); // when const { placeholder } = await sut.jump(JumpKind.MultiChar, false); // then scenario.hasDimmedEditor(5); scenario.hasCreatedPlaceholders(13); assert.deepEqual(placeholder, { childrens: [], index: 2, placeholder: 'c', line: 3, character: 13, }); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Next char', '$(rocket) Next char', '$(rocket) Next char', '$(rocket) Next char', '$(rocket) Jump To', '$(rocket) Jumped!', ); }); it(` shoud jump to matched placeholder directly even without escaping when there is three row where matches three but we restrict with a non-matching char but which matches a placeholder `, async () => { // given scenario .withLines( 'my first row', 'this absolutely match', 'also this is also matching', ) .withCommands( 'a', // we try to match a 'l', // we restrict with l 'c', // we jump to placeholder b ); // when const { placeholder } = await sut.jump(JumpKind.MultiChar, false); // then scenario.hasDimmedEditor(2); scenario.hasCreatedPlaceholders(5); assert.deepEqual(placeholder, { childrens: [], index: 2, placeholder: 'c', line: 3, character: 13, }); scenario.hasStatusBarMessages( '$(rocket) Type', '$(rocket) Next char', '$(rocket) Next char', '$(rocket) Jumped!', ); }); }); });
the_stack
import { StepFormDirective } from '../../../step-form/step-form'; import { Directive, OnInit } from '@angular/core'; import { ClusterPlan } from '../../../constants/wizard.constants'; import { StepMapping } from '../../../field-mapping/FieldMapping'; import AppServices from '../../../../../../../shared/service/appServices'; import { NodeSettingField, NodeSettingStepMapping } from './node-setting-step.fieldmapping'; import { Validators } from '@angular/forms'; import { ValidationService } from '../../../validation/validation.service'; @Directive() export abstract class NodeSettingStepDirective<NODEINSTANCE> extends StepFormDirective implements OnInit { nodeTypes: Array<NODEINSTANCE> = []; clusterNameInstruction: string; private clusterPlan: string; private stepMapping: StepMapping; protected abstract getKeyFromNodeInstance(nodeInstance: NODEINSTANCE): string; protected abstract getDisplayFromNodeInstance(nodeInstance: NODEINSTANCE): string; protected constructor(protected validationService: ValidationService) { super(); } ngOnInit() { super.ngOnInit(); AppServices.userDataFormService.buildForm(this.formGroup, this.wizardName, this.formName, this.supplyStepMapping()); this.htmlFieldLabels = AppServices.fieldMapUtilities.getFieldLabelMap(this.supplyStepMapping()); this.storeDefaultLabels(this.supplyStepMapping()); this.registerDefaultFileImportedHandler(this.eventFileImported, this.supplyStepMapping()); this.registerDefaultFileImportErrorHandler(this.eventFileImportError); this.subscribeToServices(); this.listenToEvents(); this.setClusterNameInstruction(); } // available to HTML as handler for clicking on a cluster plan cardClickDev() { this.setControlPlaneToDev(); this.triggerStepDescriptionChange(); } cardClickProd() { this.setControlPlaneToProd(); this.triggerStepDescriptionChange(); } get devInstanceTypeValue() { return this.getFieldValue(NodeSettingField.INSTANCE_TYPE_DEV); } get prodInstanceTypeValue() { return this.getFieldValue(NodeSettingField.INSTANCE_TYPE_PROD); } // Extending classes should override this method by calling it first and then adding whatever additional field mappings they need protected createStepMapping(): StepMapping { return this.createDefaultStepMapping(); } // Extending classes will likely override this method by calling it first and then adding whatever listeners they need protected listenToEvents() { this.registerOnValueChange(NodeSettingField.INSTANCE_TYPE_DEV, this.onDevInstanceTypeChange.bind(this)); this.registerOnValueChange(NodeSettingField.INSTANCE_TYPE_PROD, this.onProdInstanceTypeChange.bind(this)); this.registerStepDescriptionTriggers({ clusterTypeDescriptor: true }); } // Extending classes may override this method if they have service to subscribe to protected subscribeToServices() { } protected onDevInstanceTypeChange(devNodeType: string) { if (devNodeType) { this.setWorkerInstanceTypeIfNotSet(devNodeType); this.clearControlValue(NodeSettingField.INSTANCE_TYPE_PROD); } } protected onProdInstanceTypeChange(prodNodeType: string) { if (prodNodeType) { this.setWorkerInstanceTypeIfNotSet(prodNodeType); this.clearControlValue(NodeSettingField.INSTANCE_TYPE_DEV); } } private setWorkerInstanceTypeIfNotSet(nodeType: string) { if (!this.modeClusterStandalone && nodeType) { // The user has just selected a new instance type for the management cluster. // If the worker node type hasn't been set, default to the same node type const workerNodeInstanceTypeControl = this.getControl(NodeSettingField.WORKER_NODE_INSTANCE_TYPE); if (!workerNodeInstanceTypeControl.value) { workerNodeInstanceTypeControl.setValue(nodeType); workerNodeInstanceTypeControl.updateValueAndValidity(); } } } // Extending classes MAY need to override this method if they have additional changes dependent on cluster plan change to DEV protected setControlPlaneToDev() { this.clusterPlan = ClusterPlan.DEV; let valueToUse; if (this.nodeTypes.length === 1) { valueToUse = this.getKeyFromNodeInstance(this.nodeTypes[0]); } else { const existingValue = this.formGroup.get(NodeSettingField.INSTANCE_TYPE_DEV).value; valueToUse = this.getStoredValue(NodeSettingField.INSTANCE_TYPE_DEV, this.supplyStepMapping(), existingValue); } this.resurrectFieldWithStoredValue(NodeSettingField.INSTANCE_TYPE_DEV, this.supplyStepMapping(), [Validators.required], valueToUse, this.quietly); this.disarmField(NodeSettingField.INSTANCE_TYPE_PROD); } // Extending classes MAY need to override this method if they have additional changes dependent on cluster plan change to PROD protected setControlPlaneToProd() { this.clusterPlan = ClusterPlan.PROD; let valueToUse; if (this.nodeTypes.length === 1) { valueToUse = this.getKeyFromNodeInstance(this.nodeTypes[0]); } else { const existingValue = this.formGroup.get(NodeSettingField.INSTANCE_TYPE_PROD).value; valueToUse = this.getStoredValue(NodeSettingField.INSTANCE_TYPE_PROD, this.supplyStepMapping(), existingValue); } this.resurrectFieldWithStoredValue(NodeSettingField.INSTANCE_TYPE_PROD, this.supplyStepMapping(), [Validators.required], valueToUse, this.quietly); this.disarmField(NodeSettingField.INSTANCE_TYPE_DEV); } private createDefaultStepMapping(): StepMapping { const stepMapping = AppServices.fieldMapUtilities.cloneStepMapping(NodeSettingStepMapping); // if we're in standalone mode, deactivate the worker node instance field mapping (because it isn't used) const workerInstanceMapping = AppServices.fieldMapUtilities.getFieldMapping(NodeSettingField.WORKER_NODE_INSTANCE_TYPE, stepMapping); workerInstanceMapping.deactivated = AppServices.appDataService.isModeClusterStandalone(); // dynamically modify the cluster field mapping const clusterNameMapping = AppServices.fieldMapUtilities.getFieldMapping(NodeSettingField.CLUSTER_NAME, stepMapping); clusterNameMapping.label = this.createClusterNameLabel(); clusterNameMapping.required = this.isClusterNameRequired(); // add retriever/restorer for cluster plan entry const clusterPlanMapping = AppServices.fieldMapUtilities.getFieldMapping(NodeSettingField.CLUSTER_PLAN, stepMapping); clusterPlanMapping.restorer = this.setClusterPlan.bind(this); clusterPlanMapping.retriever = this.getClusterPlan.bind(this); return stepMapping; } protected chooseInitialClusterPlan() { // we first check if the cluster plan type was stored const storedClusterPlan = this.getStoredValue(NodeSettingField.CLUSTER_PLAN, this.supplyStepMapping()); if (storedClusterPlan === ClusterPlan.PROD) { this.cardClickProd(); } else if (storedClusterPlan === ClusterPlan.DEV) { this.cardClickDev(); } else { // there was no cluster plan type stored, but if there was an instance type for prod, we'll assume a PROD cluster plan const prodInstanceType = this.getStoredValue(NodeSettingField.INSTANCE_TYPE_PROD, this.supplyStepMapping()); prodInstanceType ? this.cardClickProd() : this.cardClickDev(); } } // This method may be USED by subclasses, but should not be overwritten; subclasses should overwrite createStepMapping() instead. protected supplyStepMapping(): StepMapping { if (!this.stepMapping) { this.stepMapping = this.createStepMapping(); } return this.stepMapping; } private createClusterNameLabel(): string { let clusterNameLabel = this.clusterTypeDescriptor.toUpperCase() + ' CLUSTER NAME'; if (!AppServices.appDataService.isClusterNameRequired()) { clusterNameLabel += ' (OPTIONAL)'; } return clusterNameLabel; } private setClusterNameInstruction() { if (AppServices.appDataService.isClusterNameRequired()) { this.clusterNameInstruction = 'Specify a name for the ' + this.clusterTypeDescriptor + ' cluster.'; } else { this.clusterNameInstruction = 'Optionally specify a name for the ' + this.clusterTypeDescriptor + ' cluster. ' + 'If left blank, the installer names the cluster automatically.'; } } // Extending classes may want to override this method protected isClusterNameRequired(): boolean { return AppServices.appDataService.isClusterNameRequired(); } dynamicDescription(): string { if (this.isClusterPlanProd) { return 'Production cluster selected: 3 node control plane'; } else if (this.isClusterPlanDev) { return 'Development cluster selected: 1 node control plane'; } return `Specify the resources backing the ${this.clusterTypeDescriptor} cluster`; } get isClusterPlanProd(): boolean { return this.clusterPlan === ClusterPlan.PROD; } get isClusterPlanDev(): boolean { return this.clusterPlan === ClusterPlan.DEV; } private setClusterPlan(newClusterPlan: string) { this.clusterPlan = newClusterPlan; } private getClusterPlan(): string { return this.clusterPlan; } // TODO: this method is for testing classes; find another way clearClusterPlan() { this.clusterPlan = ''; } // Extending classes should have no reason to override this method. protected storeUserData() { this.storeUserDataFromMapping(this.supplyStepMapping()); this.storeDisplayOrder(this.getFieldDisplayOrder()); } // Extending classes may want to change the display order of the fields protected getFieldDisplayOrder() { return this.defaultDisplayOrder(this.supplyStepMapping()); } protected onStepStarted() { this.chooseInitialClusterPlan(); } }
the_stack
import { compact } from 'lodash' import { ensureDir } from 'fs-extra' import { app, ipcMain, Menu, shell } from 'electron' import { autoUpdater } from 'electron-updater' import { getLogDirectoryPath } from '@lib/logger' import { state } from '@lib/state' import { Menu as ContextMenu, ProjectMenu, FrameworkMenu } from '@main/menu' import { ApplicationWindow } from '@main/application-window' import { ProjectIdentifier, IProject } from '@lib/frameworks/project' import { IRepository } from '@lib/frameworks/repository' import { IFramework } from '@lib/frameworks/framework' type ClickHandler = ( menuItem: Electron.MenuItem, browserWindow: Electron.BrowserWindow | undefined, event: Electron.KeyboardEvent ) => void enum ZoomDirection { Reset, In, Out, } class ApplicationMenu { protected template: Array<Electron.MenuItemConstructorOptions> = [] protected window: ApplicationWindow | null = null protected options: { project: IProject | null, repository: IRepository | null framework: IFramework | null, isCheckingForUpdate: boolean, isDownloadingUpdate: boolean, hasDownloadedUpdate: boolean } = { project: null, repository: null, framework: null, isCheckingForUpdate: false, isDownloadingUpdate: false, hasDownloadedUpdate: false } protected menus: { [key: string]: ContextMenu } = {} protected render (): void { this.template = [] const separator: Electron.MenuItemConstructorOptions = { type: 'separator' } const currentProject: ProjectIdentifier | null = state.getCurrentProject() const projects: Array<ProjectIdentifier> = state.getAvailableProjects() const isCheckingForUpdate = this.options.isCheckingForUpdate const isDownloadingUpdate = this.options.isDownloadingUpdate const hasDownloadedUpdate = this.options.hasDownloadedUpdate const updater = { label: isDownloadingUpdate ? 'Downloading Update' : (hasDownloadedUpdate ? 'Restart and Install Update' : 'Check for Updates…'), enabled: !isCheckingForUpdate && !isDownloadingUpdate && !__DEV__, click () { if (hasDownloadedUpdate) { autoUpdater.quitAndInstall() } autoUpdater.checkForUpdates() } } if (__DARWIN__) { this.addSection('Lode', new ContextMenu(this.window!.getWebContents()) .add({ label: 'About Lode', click: emit('show-about') }) .add(updater) .separator() .add({ label: 'Preferences…', accelerator: 'CmdOrCtrl+,', click: emit('show-preferences') }) .separator() .add({ role: 'services', submenu: [] }) .separator() .add({ role: 'hide' }) .add({ role: 'hideOthers' }) .add({ role: 'unhide' }) .separator() .add({ role: 'quit' }) ) } this.addSection('&File', new ContextMenu(this.window!.getWebContents()) .add({ label: __DARWIN__ ? 'New Project' : 'New project', accelerator: 'CmdOrCtrl+N', click: emit('project-add') }) .add({ label: __DARWIN__ ? 'Switch Project' : 'Switch project', enabled: projects && projects.length > 1, submenu: projects && projects.length > 1 ? projects.map(project => { return { label: project.name, type: 'checkbox', checked: !!currentProject && currentProject.id === project.id, click: emit('project-switch', project.id, (menuItem: Electron.MenuItem) => { // Don't toggle the item, unless it's the current project, // as the switch might still be cancelled by the user. If // switch project is confirmed, menu will be rebuilt anyway. menuItem.checked = !!currentProject && currentProject.id === project.id }) } }) : undefined }) .addIf(!__DARWIN__, separator) .addIf(!__DARWIN__, { label: 'Options…', accelerator: 'CmdOrCtrl+,', click: emit('show-preferences') }) .addIf(!__DARWIN__, separator) .addIf(!__DARWIN__, { role: 'quit', accelerator: 'Alt+F4' }) ) this.addSection('&Edit', new ContextMenu(this.window!.getWebContents()) .add({ role: 'undo', label: 'Undo' }) .add({ role: 'redo', label: 'Redo' }) .separator() .add({ role: 'cut', label: 'Cut' }) .add({ role: 'copy', label: 'Copy' }) .add({ role: 'paste', label: 'Paste' }) .add({ label: 'Select all', accelerator: 'CmdOrCtrl+A', click: emit('select-all') }) ) this.addSection('&View', new ContextMenu(this.window!.getWebContents()) .add({ label: __DARWIN__ ? 'Toggle Full Screen' : 'Toggle &full screen', role: 'togglefullscreen', accelerator: __DARWIN__ ? undefined : 'F11' }) .separator() .add({ label: __DARWIN__ ? 'Reset Zoom' : 'Reset zoom', accelerator: 'CmdOrCtrl+0', click: zoom(ZoomDirection.Reset) }) .add({ label: __DARWIN__ ? 'Zoom In' : 'Zoom in', accelerator: 'CmdOrCtrl+=', click: zoom(ZoomDirection.In) }) .add({ label: __DARWIN__ ? 'Zoom Out' : 'Zoom out', accelerator: 'CmdOrCtrl+-', click: zoom(ZoomDirection.Out) }) .separator() .add({ label: __DARWIN__ ? 'Toggle Developer Tools' : 'Toggle developer tools', accelerator: (() => { return __DARWIN__ ? 'Alt+Command+I' : 'Ctrl+Shift+I' })(), click (item: any, focusedWindow: Electron.BrowserWindow | undefined) { if (focusedWindow) { focusedWindow.webContents.toggleDevTools() } } }) ) this.addSection('&Project', new ProjectMenu( this.options.project, this.window!.getWebContents() )) this.addSection('F&ramework', new FrameworkMenu( this.options.repository, this.options.framework, this.window!.getWebContents() )) if (__DEV__) { this.addSection('&Development', new ContextMenu(this.window!.getWebContents()) .add({ label: '&Reload', accelerator: 'CmdOrCtrl+Shift+0', click (item: any, focusedWindow: Electron.BrowserWindow | undefined) { if (focusedWindow) { focusedWindow.reload() } }, visible: __DEV__ }) .separator() .add({ label: __DARWIN__ ? 'Log Project' : 'Log project', click: emit('log-project') }) .add({ label: __DARWIN__ ? 'Log Settings' : 'Log settings', click: emit('log-settings') }) .add({ label: __DARWIN__ ? 'Log Renderer State' : 'Log renderer state', click: emit('log-renderer-state') }) .separator() .add({ label: __DARWIN__ ? 'Show User Data Folder in Finder' : __WIN32__ ? 'Show user data folder in Explorer' : 'Show user data folder in your File Manager', click () { const path = app.getPath('userData') ensureDir(path) .then(() => { shell.openPath(path) }) .catch(error => { log.error('Failed to opened logs directory from menu.', error) }) } }) .separator() .add({ label: 'Crash main process', click () { throw new Error('Boomtown!') } }) .add({ label: 'Crash renderer process', click: emit('crash') }) ) } if (__DARWIN__) { this.template.push({ role: 'window', submenu: [ { role: 'minimize' }, { role: 'zoom' }, { role: 'close' }, separator, { role: 'front' } ] }) } const helpItems = [ { label: __DARWIN__ ? 'Report Issue' : 'Report issue', click () { shell.openExternal( 'https://github.com/lodeapp/lode/issues/new/choose' ).catch(err => log.error('Failed opening issue creation page', err)) } }, { label: __DARWIN__ ? 'Contact Support' : 'Contact support', click: emit('feedback') }, { label: __DARWIN__ ? 'Show Documentation' : 'Show documentation', click () { shell.openExternal( 'https://lode.run/documentation/' ).catch(err => log.error('Failed opening documentation page', err)) } }, separator, { label: 'Troubleshooting', submenu: [ { label: __DARWIN__ ? 'Show Logs in Finder' : __WIN32__ ? 'Show logs in Explorer' : 'Show logs in your File Manager', click () { const path = getLogDirectoryPath() ensureDir(path) .then(() => { shell.openPath(path) }) .catch(error => { log.error('Failed to opened logs directory from menu.', error) }) } }, { label: __DARWIN__ ? 'Reset Settings…' : 'Reset settings…', click: emit('settings-reset') } ] } ] if (__DARWIN__) { this.template.push({ role: 'help', submenu: helpItems }) } else { this.addSection('&Help', new ContextMenu(this.window!.getWebContents()) .add({ label: 'About Lode', click: emit('show-about') }) .add(updater) .separator() .addMultiple(helpItems) ) } Menu.setApplicationMenu(Menu.buildFromTemplate(this.template)) } protected addSection (label: string, menu: ContextMenu): void { this.menus[label] = menu this.template.push({ label, submenu: menu.getTemplate() }) } public build (window: ApplicationWindow | null): Promise<Array<Electron.MenuItemConstructorOptions>> { this.setWindow(window) const project = window ? window.getProject() : null return this.setOptions({ ...this.options, ...project ? project.getActive() : {}, project }) } public setWindow (window: ApplicationWindow | null): void { this.window = window } public setOptions (options: any): Promise<Array<Electron.MenuItemConstructorOptions>> { return new Promise((resolve, reject) => { this.options = { ...this.options, ...options } // Rebuild after options are updated. this.render() resolve(this.template) }) } public getTemplate (): Array<Electron.MenuItemConstructorOptions> { return this.template } public getSections (): Array<string> { return compact(this.template.map(item => { return item.label || '' })) } public getSection (label: string): ContextMenu { return this.menus[label] } } /** * Utility function returning a Click event handler which, when invoked, emits * the provided menu event over IPC. */ function emit (name: MenuEvent, properties?: any, callback?: Function): ClickHandler { return (menuItem, window, event) => { if (window) { window.webContents.send('menu-event', { name, properties }) } else { ipcMain.emit('menu-event', { name, properties }) } if (callback) { callback(menuItem, window, event) } } } /** The zoom steps that we support, these factors must sorted */ const ZoomInFactors = [1, 1.1, 1.25, 1.5, 1.75, 2] const ZoomOutFactors = ZoomInFactors.slice().reverse() /** * Returns the element in the array that's closest to the value parameter. Note * that this function will throw if passed an empty array. */ function findClosestValue (arr: Array<number>, value: number) { return arr.reduce((previous, current) => { return Math.abs(current - value) < Math.abs(previous - value) ? current : previous }) } /** * Figure out the next zoom level for the given direction and alert the renderer * about a change in zoom factor if necessary. */ function zoom (direction: ZoomDirection): ClickHandler { return (menuItem, window) => { if (!window) { return } const { webContents } = window if (direction === ZoomDirection.Reset) { webContents.setZoomFactor(1) webContents.send('zoom-factor-changed', 1) } else { const rawZoom: number = webContents.getZoomFactor() const zoomFactors = direction === ZoomDirection.In ? ZoomInFactors : ZoomOutFactors // So the values that we get from getZoomFactor are floating point // precision numbers from chromium that don't always round nicely so // we'll have to do a little trick to figure out which of our supported // zoom factors the value is referring to. const currentZoom = findClosestValue(zoomFactors, rawZoom) const nextZoomLevel = zoomFactors.find(f => direction === ZoomDirection.In ? f > currentZoom : f < currentZoom) // If we couldn't find a zoom level (likely due to manual manipulation // of the zoom factor in devtools) we'll just snap to the closest valid // factor we've got. const newZoom = nextZoomLevel === undefined ? currentZoom : nextZoomLevel webContents.setZoomFactor(newZoom) webContents.send('zoom-factor-changed', newZoom) } } } export const applicationMenu = new ApplicationMenu()
the_stack
// Some of the following code is similar to that of UZIP.js: // https://github.com/photopea/UZIP.js // However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. // Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint // is better for memory in most engines (I *think*). import wk from './node-worker'; // aliases for shorter compressed code (most minifers don't do this) const u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array; // fixed length extra bits const fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); // fixed distance extra bits // see fleb note const fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); // code length index map const clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); // get base, reverse index map from extra bits const freb = (eb: Uint8Array, start: number) => { const b = new u16(31); for (let i = 0; i < 31; ++i) { b[i] = start += 1 << eb[i - 1]; } // numbers here are at max 18 bits const r = new u32(b[30]); for (let i = 1; i < 30; ++i) { for (let j = b[i]; j < b[i + 1]; ++j) { r[j] = ((j - b[i]) << 5) | i; } } return [b, r] as const; } const [fl, revfl] = freb(fleb, 2); // we can ignore the fact that the other numbers are wrong; they never happen anyway fl[28] = 258, revfl[258] = 28; const [fd, revfd] = freb(fdeb, 0); // map of value to reverse (assuming 16 bits) const rev = new u16(32768); for (let i = 0; i < 32768; ++i) { // reverse table algorithm from SO let x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1); x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2); x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4); rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1; } // create huffman tree from u8 "map": index -> code length for code index // mb (max bits) must be at most 15 // TODO: optimize/split up? const hMap = ((cd: Uint8Array, mb: number, r: 0 | 1) => { const s = cd.length; // index let i = 0; // u16 "map": index -> # of codes with bit length = index const l = new u16(mb); // length of cd must be 288 (total # of codes) for (; i < s; ++i) { if (cd[i]) ++l[cd[i] - 1]; } // u16 "map": index -> minimum code for bit length = index const le = new u16(mb); for (i = 0; i < mb; ++i) { le[i] = (le[i - 1] + l[i - 1]) << 1; } let co: Uint16Array; if (r) { // u16 "map": index -> number of actual bits, symbol for code co = new u16(1 << mb); // bits to remove for reverser const rvb = 15 - mb; for (i = 0; i < s; ++i) { // ignore 0 lengths if (cd[i]) { // num encoding both symbol and bits read const sv = (i << 4) | cd[i]; // free bits const r = mb - cd[i]; // start value let v = le[cd[i] - 1]++ << r; // m is end value for (const m = v | ((1 << r) - 1); v <= m; ++v) { // every 16 bit value starting with the code yields the same result co[rev[v] >>> rvb] = sv; } } } } else { co = new u16(s); for (i = 0; i < s; ++i) { if (cd[i]) { co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]); } } } return co; }); // fixed length tree const flt = new u8(288); for (let i = 0; i < 144; ++i) flt[i] = 8; for (let i = 144; i < 256; ++i) flt[i] = 9; for (let i = 256; i < 280; ++i) flt[i] = 7; for (let i = 280; i < 288; ++i) flt[i] = 8; // fixed distance tree const fdt = new u8(32); for (let i = 0; i < 32; ++i) fdt[i] = 5; // fixed length map const flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); // fixed distance map const fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); // find max of array const max = (a: Uint8Array | number[]) => { let m = a[0]; for (let i = 1; i < a.length; ++i) { if (a[i] > m) m = a[i]; } return m; }; // read d, starting at bit p and mask with m const bits = (d: Uint8Array, p: number, m: number) => { const o = (p / 8) | 0; return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; } // read d, starting at bit p continuing for at least 16 bits const bits16 = (d: Uint8Array, p: number) => { const o = (p / 8) | 0; return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); } // get end of byte const shft = (p: number) => ((p + 7) / 8) | 0; // typed array slice - allows garbage collector to free original reference, // while being more compatible than .slice const slc = <T extends Uint8Array | Uint16Array | Uint32Array>(v: T, s: number, e?: number): T => { if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; // can't use .constructor in case user-supplied const n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s) as T; n.set(v.subarray(s, e)); return n; } // inflate state type InflateState = { // lmap l?: Uint16Array; // dmap d?: Uint16Array; // lbits m?: number; // dbits n?: number; // final f?: number; // pos p?: number; // byte b?: number; // lstchk i?: boolean; }; /** * Codes for errors generated within this library */ export const FlateErrorCode = { UnexpectedEOF: 0, InvalidBlockType: 1, InvalidLengthLiteral: 2, InvalidDistance: 3, StreamFinished: 4, NoStreamHandler: 5, InvalidHeader: 6, NoCallback: 7, InvalidUTF8: 8, ExtraFieldTooLong: 9, InvalidDate: 10, FilenameTooLong: 11, StreamFinishing: 12, InvalidZipData: 13, UnknownCompressionMethod: 14 } as const; // error codes const ec = [ 'unexpected EOF', 'invalid block type', 'invalid length/literal', 'invalid distance', 'stream finished', 'no stream handler', , // determined by compression function 'no callback', 'invalid UTF-8 data', 'extra field too long', 'date not in range 1980-2099', 'filename too long', 'stream finishing', 'invalid zip data' // determined by unknown compression method ]; /** * An error generated within this library */ export interface FlateError extends Error { /** * The code associated with this error */ code: number; }; const err = (ind: number, msg?: string | 0, nt?: 1) => { const e: Partial<FlateError> = new Error(msg || ec[ind]); e.code = ind; if (Error.captureStackTrace) Error.captureStackTrace(e, err); if (!nt) throw e; return e as FlateError; } // expands raw DEFLATE data const inflt = (dat: Uint8Array, buf?: Uint8Array, st?: InflateState) => { // source length const sl = dat.length; if (!sl || (st && st.f && !st.l)) return buf || new u8(0); // have to estimate size const noBuf = !buf || (st as unknown as boolean); // no state const noSt = !st || st.i; if (!st) st = {}; // Assumes roughly 33% compression ratio average if (!buf) buf = new u8(sl * 3); // ensure buffer can fit at least l elements const cbuf = (l: number) => { let bl = buf.length; // need to increase size to fit if (l > bl) { // Double or set to necessary, whichever is greater const nbuf = new u8(Math.max(bl * 2, l)); nbuf.set(buf); buf = nbuf; } }; // last chunk bitpos bytes let final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; // total bits const tbts = sl * 8; do { if (!lm) { // BFINAL - this is only 1 when last chunk is next final = bits(dat, pos, 1); // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman const type = bits(dat, pos + 1, 3); pos += 3; if (!type) { // go to end of byte boundary const s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; if (t > sl) { if (noSt) err(0); break; } // ensure size if (noBuf) cbuf(bt + l); // Copy over uncompressed data buf.set(dat.subarray(s, t), bt); // Get new bitpos, update byte count st.b = bt += l, st.p = pos = t * 8, st.f = final; continue; } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5; else if (type == 2) { // literal lengths const hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; const tl = hLit + bits(dat, pos + 5, 31) + 1; pos += 14; // length+distance tree const ldt = new u8(tl); // code length tree const clt = new u8(19); for (let i = 0; i < hcLen; ++i) { // use index map to get real code clt[clim[i]] = bits(dat, pos + i * 3, 7); } pos += hcLen * 3; // code lengths bits const clb = max(clt), clbmsk = (1 << clb) - 1; // code lengths map const clm = hMap(clt, clb, 1); for (let i = 0; i < tl;) { const r = clm[bits(dat, pos, clbmsk)]; // bits read pos += r & 15; // symbol const s = r >>> 4; // code length to copy if (s < 16) { ldt[i++] = s; } else { // copy count let c = 0, n = 0; if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3; else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7; while (n--) ldt[i++] = c; } } // length tree distance tree const lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); // max length bits lbt = max(lt) // max dist bits dbt = max(dt); lm = hMap(lt, lbt, 1); dm = hMap(dt, dbt, 1); } else err(1); if (pos > tbts) { if (noSt) err(0); break; } } // Make sure the buffer can hold this + the largest possible addition // Maximum chunk size (practically, theoretically infinite) is 2^17; if (noBuf) cbuf(bt + 131072); const lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; let lpos = pos; for (;; lpos = pos) { // bits read, code const c = lm[bits16(dat, pos) & lms], sym = c >>> 4; pos += c & 15; if (pos > tbts) { if (noSt) err(0); break; } if (!c) err(2); if (sym < 256) buf[bt++] = sym; else if (sym == 256) { lpos = pos, lm = null; break; } else { let add = sym - 254; // no extra bits needed if less if (sym > 264) { // index const i = sym - 257, b = fleb[i]; add = bits(dat, pos, (1 << b) - 1) + fl[i]; pos += b; } // dist const d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; if (!d) err(3); pos += d & 15; let dt = fd[dsym]; if (dsym > 3) { const b = fdeb[dsym]; dt += bits16(dat, pos) & ((1 << b) - 1), pos += b; } if (pos > tbts) { if (noSt) err(0); break; } if (noBuf) cbuf(bt + 131072); const end = bt + add; for (; bt < end; bt += 4) { buf[bt] = buf[bt - dt]; buf[bt + 1] = buf[bt + 1 - dt]; buf[bt + 2] = buf[bt + 2 - dt]; buf[bt + 3] = buf[bt + 3 - dt]; } bt = end; } } st.l = lm, st.p = lpos, st.b = bt, st.f = final; if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt; } while (!final) return bt == buf.length ? buf : slc(buf, 0, bt); } // starting at p, write the minimum number of bits that can hold v to d const wbits = (d: Uint8Array, p: number, v: number) => { v <<= p & 7; const o = (p / 8) | 0; d[o] |= v; d[o + 1] |= v >>> 8; } // starting at p, write the minimum number of bits (>8) that can hold v to d const wbits16 = (d: Uint8Array, p: number, v: number) => { v <<= p & 7; const o = (p / 8) | 0; d[o] |= v; d[o + 1] |= v >>> 8; d[o + 2] |= v >>> 16; } type HuffNode = { // symbol s: number; // frequency f: number; // left child l?: HuffNode; // right child r?: HuffNode; }; // creates code lengths from a frequency table const hTree = (d: Uint16Array, mb: number) => { // Need extra info to make a tree const t: HuffNode[] = []; for (let i = 0; i < d.length; ++i) { if (d[i]) t.push({ s: i, f: d[i] }); } const s = t.length; const t2 = t.slice(); if (!s) return [et, 0] as const; if (s == 1) { const v = new u8(t[0].s + 1); v[t[0].s] = 1; return [v, 1] as const; } t.sort((a, b) => a.f - b.f); // after i2 reaches last ind, will be stopped // freq must be greater than largest possible number of symbols t.push({ s: -1, f: 25001 }); let l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; t[0] = { s: -1, f: l.f + r.f, l, r }; // efficient algorithm from UZIP.js // i0 is lookbehind, i2 is lookahead - after processing two low-freq // symbols that combined have high freq, will start processing i2 (high-freq, // non-composite) symbols instead // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ while (i1 != s - 1) { l = t[t[i0].f < t[i2].f ? i0++ : i2++]; r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; t[i1++] = { s: -1, f: l.f + r.f, l, r }; } let maxSym = t2[0].s; for (let i = 1; i < s; ++i) { if (t2[i].s > maxSym) maxSym = t2[i].s; } // code lengths const tr = new u16(maxSym + 1); // max bits in tree let mbt = ln(t[i1 - 1], tr, 0); if (mbt > mb) { // more algorithms from UZIP.js // TODO: find out how this code works (debt) // ind debt let i = 0, dt = 0; // left cost const lft = mbt - mb, cst = 1 << lft; t2.sort((a, b) => tr[b.s] - tr[a.s] || a.f - b.f); for (; i < s; ++i) { const i2 = t2[i].s; if (tr[i2] > mb) { dt += cst - (1 << (mbt - tr[i2])); tr[i2] = mb; } else break; } dt >>>= lft; while (dt > 0) { const i2 = t2[i].s; if (tr[i2] < mb) dt -= 1 << (mb - tr[i2]++ - 1); else ++i; } for (; i >= 0 && dt; --i) { const i2 = t2[i].s; if (tr[i2] == mb) { --tr[i2]; ++dt; } } mbt = mb; } return [new u8(tr), mbt] as const; } // get the max length and assign length codes const ln = (n: HuffNode, l: Uint16Array, d: number): number => { return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : (l[n.s] = d); } // length codes generation const lc = (c: Uint8Array) => { let s = c.length; // Note that the semicolon was intentional while (s && !c[--s]); const cl = new u16(++s); // ind num streak let cli = 0, cln = c[0], cls = 1; const w = (v: number) => { cl[cli++] = v; } for (let i = 1; i <= s; ++i) { if (c[i] == cln && i != s) ++cls; else { if (!cln && cls > 2) { for (; cls > 138; cls -= 138) w(32754); if (cls > 2) { w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); cls = 0; } } else if (cls > 3) { w(cln), --cls; for (; cls > 6; cls -= 6) w(8304); if (cls > 2) w(((cls - 3) << 5) | 8208), cls = 0; } while (cls--) w(cln); cls = 1; cln = c[i]; } } return [cl.subarray(0, cli), s] as const; } // calculate the length of output from tree, code lengths const clen = (cf: Uint16Array, cl: Uint8Array) => { let l = 0; for (let i = 0; i < cl.length; ++i) l += cf[i] * cl[i]; return l; } // writes a fixed block // returns the new bit pos const wfblk = (out: Uint8Array, pos: number, dat: Uint8Array) => { // no need to write 00 as type: TypedArray defaults to 0 const s = dat.length; const o = shft(pos + 2); out[o] = s & 255; out[o + 1] = s >>> 8; out[o + 2] = out[o] ^ 255; out[o + 3] = out[o + 1] ^ 255; for (let i = 0; i < s; ++i) out[o + i + 4] = dat[i]; return (o + 4 + s) * 8; } // writes a block const wblk = (dat: Uint8Array, out: Uint8Array, final: number, syms: Uint32Array, lf: Uint16Array, df: Uint16Array, eb: number, li: number, bs: number, bl: number, p: number) => { wbits(out, p++, final); ++lf[256]; const [dlt, mlb] = hTree(lf, 15); const [ddt, mdb] = hTree(df, 15); const [lclt, nlc] = lc(dlt); const [lcdt, ndc] = lc(ddt); const lcfreq = new u16(19); for (let i = 0; i < lclt.length; ++i) lcfreq[lclt[i] & 31]++; for (let i = 0; i < lcdt.length; ++i) lcfreq[lcdt[i] & 31]++; const [lct, mlcb] = hTree(lcfreq, 7); let nlcc = 19; for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc); const flen = (bl + 5) << 3; const ftlen = clen(lf, flt) + clen(df, fdt) + eb; const dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); if (flen <= ftlen && flen <= dtlen) return wfblk(out, p, dat.subarray(bs, bs + bl)); let lm: Uint16Array, ll: Uint8Array, dm: Uint16Array, dl: Uint8Array; wbits(out, p, 1 + (dtlen < ftlen as unknown as number)), p += 2; if (dtlen < ftlen) { lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; const llm = hMap(lct, mlcb, 0); wbits(out, p, nlc - 257); wbits(out, p + 5, ndc - 1); wbits(out, p + 10, nlcc - 4); p += 14; for (let i = 0; i < nlcc; ++i) wbits(out, p + 3 * i, lct[clim[i]]); p += 3 * nlcc; const lcts = [lclt, lcdt]; for (let it = 0; it < 2; ++it) { const clct = lcts[it]; for (let i = 0; i < clct.length; ++i) { const len = clct[i] & 31; wbits(out, p, llm[len]), p += lct[len]; if (len > 15) wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12; } } } else { lm = flm, ll = flt, dm = fdm, dl = fdt; } for (let i = 0; i < li; ++i) { if (syms[i] > 255) { const len = (syms[i] >>> 18) & 31; wbits16(out, p, lm[len + 257]), p += ll[len + 257]; if (len > 7) wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len]; const dst = syms[i] & 31; wbits16(out, p, dm[dst]), p += dl[dst]; if (dst > 3) wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst]; } else { wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; } } wbits16(out, p, lm[256]); return p + ll[256]; } // deflate options (nice << 13) | chain const deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); // empty const et = /*#__PURE__*/new u8(0); // compresses data into a raw DEFLATE buffer const dflt = (dat: Uint8Array, lvl: number, plvl: number, pre: number, post: number, lst: 0 | 1) => { const s = dat.length; const o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); // writing to this writes to the output buffer const w = o.subarray(pre, o.length - post); let pos = 0; if (!lvl || s < 8) { for (let i = 0; i <= s; i += 65535) { // end const e = i + 65535; if (e < s) { // write full block pos = wfblk(w, pos, dat.subarray(i, e)); } else { // write final block w[i] = lst; pos = wfblk(w, pos, dat.subarray(i, s)); } } } else { const opt = deo[lvl - 1]; const n = opt >>> 13, c = opt & 8191; const msk = (1 << plvl) - 1; // prev 2-byte val map curr 2-byte val map const prev = new u16(32768), head = new u16(msk + 1); const bs1 = Math.ceil(plvl / 3), bs2 = 2 * bs1; const hsh = (i: number) => (dat[i] ^ (dat[i + 1] << bs1) ^ (dat[i + 2] << bs2)) & msk; // 24576 is an arbitrary number of maximum symbols per block // 424 buffer for last block const syms = new u32(25000); // length/literal freq distance freq const lf = new u16(288), df = new u16(32); // l/lcnt exbits index l/lind waitdx bitpos let lc = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; for (; i < s; ++i) { // hash value // deopt when i > s - 3 - at end, deopt acceptable const hv = hsh(i); // index mod 32768 previous index mod let imod = i & 32767, pimod = head[hv]; prev[imod] = pimod; head[hv] = imod; // We always should modify head and prev, but only add symbols if // this data is not yet processed ("wait" for wait index) if (wi <= i) { // bytes remaining const rem = s - i; if ((lc > 7000 || li > 24576) && rem > 423) { pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); li = lc = eb = 0, bs = i; for (let j = 0; j < 286; ++j) lf[j] = 0; for (let j = 0; j < 30; ++j) df[j] = 0; } // len dist chain let l = 2, d = 0, ch = c, dif = (imod - pimod) & 32767; if (rem > 2 && hv == hsh(i - dif)) { const maxn = Math.min(n, rem) - 1; const maxd = Math.min(32767, i); // max possible length // not capped at dif because decompressors implement "rolling" index population const ml = Math.min(258, rem); while (dif <= maxd && --ch && imod != pimod) { if (dat[i + l] == dat[i + l - dif]) { let nl = 0; for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl); if (nl > l) { l = nl, d = dif; // break out early when we reach "nice" (we are satisfied enough) if (nl > maxn) break; // now, find the rarest 2-byte sequence within this // length of literals and search for that instead. // Much faster than just using the start const mmd = Math.min(dif, nl - 2); let md = 0; for (let j = 0; j < mmd; ++j) { const ti = (i - dif + j + 32768) & 32767; const pti = prev[ti]; const cd = (ti - pti + 32768) & 32767; if (cd > md) md = cd, pimod = ti; } } } // check the previous match imod = pimod, pimod = prev[imod]; dif += (imod - pimod + 32768) & 32767; } } // d will be nonzero only when a match was found if (d) { // store both dist and len data in one Uint32 // Make sure this is recognized as a len/dist with 28th bit (2^28) syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; const lin = revfl[l] & 31, din = revfd[d] & 31; eb += fleb[lin] + fdeb[din]; ++lf[257 + lin]; ++df[din]; wi = i + l; ++lc; } else { syms[li++] = dat[i]; ++lf[dat[i]]; } } } pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); // this is the easiest way to avoid needing to maintain state if (!lst && pos & 7) pos = wfblk(w, pos + 1, et); } return slc(o, 0, pre + shft(pos) + post); } // crc check type CRCV = { p(d: Uint8Array): void; d(): number; }; // CRC32 table const crct = /*#__PURE__*/ (() => { const t = new Int32Array(256); for (let i = 0; i < 256; ++i) { let c = i, k = 9; while (--k) c = ((c & 1) && -306674912) ^ (c >>> 1); t[i] = c; } return t; })(); // CRC32 const crc = (): CRCV => { let c = -1; return { p(d) { // closures have awful performance let cr = c; for (let i = 0; i < d.length; ++i) cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); c = cr; }, d() { return ~c; } } } // Alder32 const adler = (): CRCV => { let a = 1, b = 0; return { p(d) { // closures have awful performance let n = a, m = b; const l = d.length | 0; for (let i = 0; i != l;) { const e = Math.min(i + 2655, l); for (; i < e; ++i) m += n += d[i]; n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); } a = n, b = m; }, d() { a %= 65521, b %= 65521; return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8); } } } /** * Options for compressing data into a DEFLATE format */ export interface DeflateOptions { /** * The level of compression to use, ranging from 0-9. * * 0 will store the data without compression. * 1 is fastest but compresses the worst, 9 is slowest but compresses the best. * The default level is 6. * * Typically, binary data benefits much more from higher values than text data. * In both cases, higher values usually take disproportionately longer than the reduction in final size that results. * * For example, a 1 MB text file could: * - become 1.01 MB with level 0 in 1ms * - become 400 kB with level 1 in 10ms * - become 320 kB with level 9 in 100ms */ level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; /** * The memory level to use, ranging from 0-12. Increasing this increases speed and compression ratio at the cost of memory. * * Note that this is exponential: while level 0 uses 4 kB, level 4 uses 64 kB, level 8 uses 1 MB, and level 12 uses 16 MB. * It is recommended not to lower the value below 4, since that tends to hurt performance. * In addition, values above 8 tend to help very little on most data and can even hurt performance. * * The default value is automatically determined based on the size of the input data. */ mem?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; }; /** * Options for compressing data into a GZIP format */ export interface GzipOptions extends DeflateOptions { /** * When the file was last modified. Defaults to the current time. * Set this to 0 to avoid revealing a modification date entirely. */ mtime?: Date | string | number; /** * The filename of the data. If the `gunzip` command is used to decompress the data, it will output a file * with this name instead of the name of the compressed file. */ filename?: string; } /** * Options for compressing data into a Zlib format */ export interface ZlibOptions extends DeflateOptions {} /** * Handler for data (de)compression streams * @param data The data output from the stream processor * @param final Whether this is the final block */ export type FlateStreamHandler = (data: Uint8Array, final: boolean) => void; /** * Handler for asynchronous data (de)compression streams * @param err Any error that occurred * @param data The data output from the stream processor * @param final Whether this is the final block */ export type AsyncFlateStreamHandler = (err: FlateError, data: Uint8Array, final: boolean) => void; /** * Callback for asynchronous (de)compression methods * @param err Any error that occurred * @param data The resulting data. Only present if `err` is null */ export type FlateCallback = (err: FlateError, data: Uint8Array) => void; // async callback-based compression interface AsyncOptions { /** * Whether or not to "consume" the source data. This will make the typed array/buffer you pass in * unusable but will increase performance and reduce memory usage. */ consume?: boolean; } /** * Options for compressing data asynchronously into a DEFLATE format */ export interface AsyncDeflateOptions extends DeflateOptions, AsyncOptions {} /** * Options for decompressing DEFLATE data asynchronously */ export interface AsyncInflateOptions extends AsyncOptions { /** * The original size of the data. Currently, the asynchronous API disallows * writing into a buffer you provide; the best you can do is provide the * size in bytes and be given back a new typed array. */ size?: number; } /** * Options for compressing data asynchronously into a GZIP format */ export interface AsyncGzipOptions extends GzipOptions, AsyncOptions {} /** * Options for decompressing GZIP data asynchronously */ export interface AsyncGunzipOptions extends AsyncOptions {} /** * Options for compressing data asynchronously into a Zlib format */ export interface AsyncZlibOptions extends ZlibOptions, AsyncOptions {} /** * Options for decompressing Zlib data asynchronously */ export interface AsyncUnzlibOptions extends AsyncInflateOptions {} /** * A terminable compression/decompression process */ export interface AsyncTerminable { /** * Terminates the worker thread immediately. The callback will not be called. */ (): void; } // deflate with opts const dopt = (dat: Uint8Array, opt: DeflateOptions, pre: number, post: number, st?: boolean) => dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st as unknown as 0 | 1); // Walmart object spread const mrg = <A, B>(a: A, b: B) => { const o = {} as Record<string, unknown>; for (const k in a) o[k] = a[k]; for (const k in b) o[k] = b[k]; return o as A & B; } // worker clone // This is possibly the craziest part of the entire codebase, despite how simple it may seem. // The only parameter to this function is a closure that returns an array of variables outside of the function scope. // We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. // We will return an object mapping of true variable name to value (basically, the current scope as a JS object). // The reason we can't just use the original variable names is minifiers mangling the toplevel scope. // This took me three weeks to figure out how to do. const wcln = (fn: () => unknown[], fnStr: string, td: Record<string, unknown>) => { const dt = fn(); const st = fn.toString(); const ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/ /g, '').split(','); for (let i = 0; i < dt.length; ++i) { let v = dt[i], k = ks[i]; if (typeof v == 'function') { fnStr += ';' + k + '='; const st = v.toString(); if (v.prototype) { // for global objects if (st.indexOf('[native code]') != -1) { const spInd = st.indexOf(' ', 8) + 1; fnStr += st.slice(spInd, st.indexOf('(', spInd)); } else { fnStr += st; for (const t in v.prototype) fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); } } else fnStr += st; } else td[k] = v; } return [fnStr, td] as const; } type CachedWorker = readonly [string, Record<string, unknown>]; const ch: CachedWorker[] = []; // clone bufs const cbfs = (v: Record<string, unknown>) => { const tl: ArrayBuffer[] = []; for (const k in v) { if (v[k] instanceof u8 || v[k] instanceof u16 || v[k] instanceof u32) tl.push((v[k] = new (v[k].constructor as typeof u8)(v[k] as Uint8Array)).buffer); } return tl; } // use a worker to execute code const wrkr = <T, R>(fns: (() => unknown[])[], init: (ev: MessageEvent<T>) => void, id: number, cb: (err: FlateError, msg: R) => void) => { if (!ch[id]) { let fnStr = '', td: Record<string, unknown> = {}, m = fns.length - 1; for (let i = 0; i < m; ++i) [fnStr, td] = wcln(fns[i], fnStr, td); ch[id] = wcln(fns[m], fnStr, td); } const td = mrg({}, ch[id][1]); return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); } // base async inflate fn const bInflt = () => [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; const bDflt = () => [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf] // gzip extra const gze = () => [gzh, gzhl, wbytes, crc, crct]; // gunzip extra const guze = () => [gzs, gzl]; // zlib extra const zle = () => [zlh, wbytes, adler]; // unzlib extra const zule = () => [zlv]; // post buf const pbf = (msg: Uint8Array) => (postMessage as Worker['postMessage'])(msg, [msg.buffer]); // get u8 const gu8 = (o?: AsyncInflateOptions) => o && o.size && new u8(o.size); // async helper const cbify = <T extends AsyncOptions>(dat: Uint8Array, opts: T, fns: (() => unknown[])[], init: (ev: MessageEvent<[Uint8Array, T]>) => void, id: number, cb: FlateCallback) => { const w = wrkr<[Uint8Array, T], Uint8Array>( fns, init, id, (err, dat) => { w.terminate(); cb(err, dat); } ); w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); return () => { w.terminate(); }; } type CmpDecmpStrm = Inflate | Deflate | Gzip | Gunzip | Zlib | Unzlib; // auto stream const astrm = (strm: CmpDecmpStrm) => { strm.ondata = (dat, final) => (postMessage as Worker['postMessage'])([dat, final], [dat.buffer]); return (ev: MessageEvent<[Uint8Array, boolean]>) => strm.push(ev.data[0], ev.data[1]); } type Astrm = { ondata: AsyncFlateStreamHandler; push: (d: Uint8Array, f?: boolean) => void; terminate: AsyncTerminable; }; // async stream attach const astrmify = <T>(fns: (() => unknown[])[], strm: Astrm, opts: T | 0, init: (ev: MessageEvent<T>) => void, id: number) => { let t: boolean; const w = wrkr<T, [Uint8Array, boolean]>( fns, init, id, (err, dat) => { if (err) w.terminate(), strm.ondata.call(strm, err); else { if (dat[1]) w.terminate(); strm.ondata.call(strm, err, dat[0], dat[1]); } } ) w.postMessage(opts); strm.push = (d, f) => { if (!strm.ondata) err(5); if (t) strm.ondata(err(4, 0, 1), null, !!f); w.postMessage([d, t = f], [d.buffer]); }; strm.terminate = () => { w.terminate(); }; } // read 2 bytes const b2 = (d: Uint8Array, b: number) => d[b] | (d[b + 1] << 8); // read 4 bytes const b4 = (d: Uint8Array, b: number) => (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; const b8 = (d: Uint8Array, b: number) => b4(d, b) + (b4(d, b + 4) * 4294967296); // write bytes const wbytes = (d: Uint8Array, b: number, v: number) => { for (; v; ++b) d[b] = v, v >>>= 8; } // gzip header const gzh = (c: Uint8Array, o: GzipOptions) => { const fn = o.filename; c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix if (o.mtime != 0) wbytes(c, 4, Math.floor((new Date(o.mtime as (string | number) || Date.now()) as unknown as number) / 1000)); if (fn) { c[3] = 8; for (let i = 0; i <= fn.length; ++i) c[i + 10] = fn.charCodeAt(i); } } // gzip footer: -8 to -4 = CRC, -4 to -0 is length // gzip start const gzs = (d: Uint8Array) => { if (d[0] != 31 || d[1] != 139 || d[2] != 8) err(6, 'invalid gzip data'); const flg = d[3]; let st = 10; if (flg & 4) st += d[10] | (d[11] << 8) + 2; for (let zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++] as unknown as number); return st + (flg & 2); } // gzip length const gzl = (d: Uint8Array) => { const l = d.length; return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0; } // gzip header length const gzhl = (o: GzipOptions) => 10 + ((o.filename && (o.filename.length + 1)) || 0); // zlib header const zlh = (c: Uint8Array, o: ZlibOptions) => { const lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1); } // zlib valid const zlv = (d: Uint8Array) => { if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) err(6, 'invalid zlib data'); if (d[1] & 32) err(6, 'invalid zlib data: preset dictionaries not supported'); } /** * Creates an asynchronous compression stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ function AsyncCmpStrm<T>(opts: T, cb?: AsyncFlateStreamHandler): T; /** * Creates an asynchronous compression stream * @param cb The callback to call whenever data is deflated */ function AsyncCmpStrm<T>(cb?: AsyncFlateStreamHandler): T; function AsyncCmpStrm<T>(opts?: T | AsyncFlateStreamHandler, cb?: AsyncFlateStreamHandler): T { if (!cb && typeof opts == 'function') cb = opts as AsyncFlateStreamHandler, opts = {} as T; this.ondata = cb as AsyncFlateStreamHandler; return opts as T; } // zlib footer: -4 to -0 is Adler32 /** * Streaming DEFLATE compression */ export class Deflate { /** * Creates a DEFLATE stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: DeflateOptions, cb?: FlateStreamHandler); constructor(cb?: FlateStreamHandler); constructor(opts?: DeflateOptions | FlateStreamHandler, cb?: FlateStreamHandler) { if (!cb && typeof opts == 'function') cb = opts as FlateStreamHandler, opts = {}; this.ondata = cb; this.o = (opts as DeflateOptions) || {}; } private o: DeflateOptions; private d: boolean; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; private p(c: Uint8Array, f: boolean) { this.ondata(dopt(c, this.o, 0, 0, !f), f); } /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { if (!this.ondata) err(5); if (this.d) err(4); this.d = final; this.p(chunk, final || false); } } /** * Asynchronous streaming DEFLATE compression */ export class AsyncDeflate { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous DEFLATE stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: DeflateOptions, cb?: AsyncFlateStreamHandler); /** * Creates an asynchronous DEFLATE stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); constructor(opts?: DeflateOptions | AsyncFlateStreamHandler, cb?: AsyncFlateStreamHandler) { astrmify([ bDflt, () => [astrm, Deflate] ], this as unknown as Astrm, AsyncCmpStrm.call(this, opts, cb), ev => { const strm = new Deflate(ev.data); onmessage = astrm(strm); }, 6); } /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ // @ts-ignore push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously compresses data with DEFLATE without any wrapper * @param data The data to compress * @param opts The compression options * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the compression */ export function deflate(data: Uint8Array, opts: AsyncDeflateOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously compresses data with DEFLATE without any wrapper * @param data The data to compress * @param cb The function to be called upon compression completion */ export function deflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; export function deflate(data: Uint8Array, opts: AsyncDeflateOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); return cbify(data, opts as AsyncDeflateOptions, [ bDflt, ], ev => pbf(deflateSync(ev.data[0], ev.data[1])), 0, cb); } /** * Compresses data with DEFLATE without any wrapper * @param data The data to compress * @param opts The compression options * @returns The deflated version of the data */ export function deflateSync(data: Uint8Array, opts?: DeflateOptions) { return dopt(data, opts || {}, 0, 0); } /** * Streaming DEFLATE decompression */ export class Inflate { /** * Creates an inflation stream * @param cb The callback to call whenever data is inflated */ constructor(cb?: FlateStreamHandler) { this.ondata = cb; } private s: InflateState = {}; private o: Uint8Array; private p = new u8(0); private d: boolean; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; private e(c: Uint8Array) { if (!this.ondata) err(5); if (this.d) err(4); const l = this.p.length; const n = new u8(l + c.length); n.set(this.p), n.set(c, l), this.p = n; } private c(final: boolean) { this.d = this.s.i = final || false; const bts = this.s.b; const dt = inflt(this.p, this.o, this.s); this.ondata(slc(dt, bts, this.s.b), this.d); this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; } /** * Pushes a chunk to be inflated * @param chunk The chunk to push * @param final Whether this is the final chunk */ push(chunk: Uint8Array, final?: boolean) { this.e(chunk), this.c(final); } } /** * Asynchronous streaming DEFLATE decompression */ export class AsyncInflate { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous inflation stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler) { this.ondata = cb; astrmify([ bInflt, () => [astrm, Inflate] ], this as unknown as Astrm, 0, () => { const strm = new Inflate(); onmessage = astrm(strm); }, 7); } /** * Pushes a chunk to be inflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ // @ts-ignore push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously expands DEFLATE data with no wrapper * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function inflate(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously expands DEFLATE data with no wrapper * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function inflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; export function inflate(data: Uint8Array, opts: AsyncInflateOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); return cbify(data, opts as AsyncInflateOptions, [ bInflt ], ev => pbf(inflateSync(ev.data[0], gu8(ev.data[1]))), 1, cb); } /** * Expands DEFLATE data with no wrapper * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ export function inflateSync(data: Uint8Array, out?: Uint8Array) { return inflt(data, out); } // before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. /** * Streaming GZIP compression */ export class Gzip { private c = crc(); private l = 0; private v = 1; private o: GzipOptions; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a GZIP stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: GzipOptions, cb?: FlateStreamHandler); /** * Creates a GZIP stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: FlateStreamHandler); constructor(opts?: GzipOptions | FlateStreamHandler, cb?: FlateStreamHandler) { Deflate.call(this, opts, cb); } /** * Pushes a chunk to be GZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { Deflate.prototype.push.call(this, chunk, final); } private p(c: Uint8Array, f: boolean) { this.c.p(c); this.l += c.length; const raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f); if (this.v) gzh(raw, this.o), this.v = 0; if (f) wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); this.ondata(raw, f); } } /** * Asynchronous streaming GZIP compression */ export class AsyncGzip { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous GZIP stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: GzipOptions, cb?: AsyncFlateStreamHandler); /** * Creates an asynchronous GZIP stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); constructor(opts?: GzipOptions | AsyncFlateStreamHandler, cb?: AsyncFlateStreamHandler) { astrmify([ bDflt, gze, () => [astrm, Deflate, Gzip] ], this as unknown as Astrm, AsyncCmpStrm.call(this, opts, cb), ev => { const strm = new Gzip(ev.data); onmessage = astrm(strm); }, 8); } /** * Pushes a chunk to be GZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ // @ts-ignore push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously compresses data with GZIP * @param data The data to compress * @param opts The compression options * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the compression */ export function gzip(data: Uint8Array, opts: AsyncGzipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously compresses data with GZIP * @param data The data to compress * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the decompression */ export function gzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; export function gzip(data: Uint8Array, opts: AsyncGzipOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); return cbify(data, opts as AsyncGzipOptions, [ bDflt, gze, () => [gzipSync] ], ev => pbf(gzipSync(ev.data[0], ev.data[1])), 2, cb); } /** * Compresses data with GZIP * @param data The data to compress * @param opts The compression options * @returns The gzipped version of the data */ export function gzipSync(data: Uint8Array, opts?: GzipOptions) { if (!opts) opts = {}; const c = crc(), l = data.length; c.p(data); const d = dopt(data, opts, gzhl(opts), 8), s = d.length; return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; } /** * Streaming GZIP decompression */ export class Gunzip { private v = 1; private p: Uint8Array; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a GUNZIP stream * @param cb The callback to call whenever data is inflated */ constructor(cb?: FlateStreamHandler) { Inflate.call(this, cb); } /** * Pushes a chunk to be GUNZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { (Inflate.prototype as unknown as { e: typeof Inflate.prototype['e'] }).e.call(this, chunk); if (this.v) { const s = this.p.length > 3 ? gzs(this.p) : 4; if (s >= this.p.length && !final) return; this.p = this.p.subarray(s), this.v = 0; } if (final) { if (this.p.length < 8) err(6, 'invalid gzip data'); this.p = this.p.subarray(0, -8); } // necessary to prevent TS from using the closure value // This allows for workerization to function correctly (Inflate.prototype as unknown as { c: typeof Inflate.prototype['c'] }).c.call(this, final); } } /** * Asynchronous streaming GZIP decompression */ export class AsyncGunzip { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous GUNZIP stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler) { this.ondata = cb; astrmify([ bInflt, guze, () => [astrm, Inflate, Gunzip] ], this as unknown as Astrm, 0, () => { const strm = new Gunzip(); onmessage = astrm(strm); }, 9); } /** * Pushes a chunk to be GUNZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ // @ts-ignore push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously expands GZIP data * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function gunzip(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously expands GZIP data * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function gunzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; export function gunzip(data: Uint8Array, opts: AsyncGunzipOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); return cbify(data, opts as AsyncGunzipOptions, [ bInflt, guze, () => [gunzipSync] ], ev => pbf(gunzipSync(ev.data[0])), 3, cb); } /** * Expands GZIP data * @param data The data to decompress * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory. * @returns The decompressed version of the data */ export function gunzipSync(data: Uint8Array, out?: Uint8Array) { return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data))); } /** * Streaming Zlib compression */ export class Zlib { private c = adler(); private v = 1; private o: GzipOptions; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a Zlib stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: ZlibOptions, cb?: FlateStreamHandler); /** * Creates a Zlib stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: FlateStreamHandler); constructor(opts?: ZlibOptions | FlateStreamHandler, cb?: FlateStreamHandler) { Deflate.call(this, opts, cb); } /** * Pushes a chunk to be zlibbed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { Deflate.prototype.push.call(this, chunk, final); } private p(c: Uint8Array, f: boolean) { this.c.p(c); const raw = dopt(c, this.o, this.v && 2, f && 4, !f); if (this.v) zlh(raw, this.o), this.v = 0; if (f) wbytes(raw, raw.length - 4, this.c.d()); this.ondata(raw, f); } } /** * Asynchronous streaming Zlib compression */ export class AsyncZlib { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous DEFLATE stream * @param opts The compression options * @param cb The callback to call whenever data is deflated */ constructor(opts: ZlibOptions, cb?: AsyncFlateStreamHandler); /** * Creates an asynchronous DEFLATE stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler); constructor(opts?: ZlibOptions | AsyncFlateStreamHandler, cb?: AsyncFlateStreamHandler) { astrmify([ bDflt, zle, () => [astrm, Deflate, Zlib] ], this as unknown as Astrm, AsyncCmpStrm.call(this, opts, cb), ev => { const strm = new Zlib(ev.data); onmessage = astrm(strm); }, 10); } /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ // @ts-ignore push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously compresses data with Zlib * @param data The data to compress * @param opts The compression options * @param cb The function to be called upon compression completion */ export function zlib(data: Uint8Array, opts: AsyncZlibOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously compresses data with Zlib * @param data The data to compress * @param cb The function to be called upon compression completion * @returns A function that can be used to immediately terminate the compression */ export function zlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; export function zlib(data: Uint8Array, opts: AsyncZlibOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); return cbify(data, opts as AsyncZlibOptions, [ bDflt, zle, () => [zlibSync] ], ev => pbf(zlibSync(ev.data[0], ev.data[1])), 4, cb); } /** * Compress data with Zlib * @param data The data to compress * @param opts The compression options * @returns The zlib-compressed version of the data */ export function zlibSync(data: Uint8Array, opts?: ZlibOptions) { if (!opts) opts = {}; const a = adler(); a.p(data); const d = dopt(data, opts, 2, 4); return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; } /** * Streaming Zlib decompression */ export class Unzlib { private v = 1; private p: Uint8Array; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; /** * Creates a Zlib decompression stream * @param cb The callback to call whenever data is inflated */ constructor(cb?: FlateStreamHandler) { Inflate.call(this, cb); } /** * Pushes a chunk to be unzlibbed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { (Inflate.prototype as unknown as { e: typeof Inflate.prototype['e'] }).e.call(this, chunk); if (this.v) { if (this.p.length < 2 && !final) return; this.p = this.p.subarray(2), this.v = 0; } if (final) { if (this.p.length < 4) err(6, 'invalid zlib data'); this.p = this.p.subarray(0, -4); } // necessary to prevent TS from using the closure value // This allows for workerization to function correctly (Inflate.prototype as unknown as { c: typeof Inflate.prototype['c'] }).c.call(this, final); } } /** * Asynchronous streaming Zlib decompression */ export class AsyncUnzlib { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Creates an asynchronous Zlib decompression stream * @param cb The callback to call whenever data is deflated */ constructor(cb?: AsyncFlateStreamHandler) { this.ondata = cb; astrmify([ bInflt, zule, () => [astrm, Inflate, Unzlib] ], this as unknown as Astrm, 0, () => { const strm = new Unzlib(); onmessage = astrm(strm); }, 11); } /** * Pushes a chunk to be decompressed from Zlib * @param chunk The chunk to push * @param final Whether this is the last chunk */ // @ts-ignore push(chunk: Uint8Array, final?: boolean): void; /** * A method to terminate the stream's internal worker. Subsequent calls to * push() will silently fail. */ terminate: AsyncTerminable; } /** * Asynchronously expands Zlib data * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function unzlib(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously expands Zlib data * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function unzlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; export function unzlib(data: Uint8Array, opts: AsyncGunzipOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); return cbify(data, opts as AsyncUnzlibOptions, [ bInflt, zule, () => [unzlibSync] ], ev => pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))), 5, cb); } /** * Expands Zlib data * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ export function unzlibSync(data: Uint8Array, out?: Uint8Array) { return inflt((zlv(data), data.subarray(2, -4)), out); } // Default algorithm for compression (used because having a known output size allows faster decompression) export { gzip as compress, AsyncGzip as AsyncCompress } // Default algorithm for compression (used because having a known output size allows faster decompression) export { gzipSync as compressSync, Gzip as Compress } /** * Streaming GZIP, Zlib, or raw DEFLATE decompression */ export class Decompress { private G = Gunzip; private I = Inflate; private Z = Unzlib; /** * Creates a decompression stream * @param cb The callback to call whenever data is decompressed */ constructor(cb?: FlateStreamHandler) { this.ondata = cb; } private s: Inflate | Gunzip | Unzlib; /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; private p: Uint8Array; /** * Pushes a chunk to be decompressed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { if (!this.ondata) err(5); if (!this.s) { if (this.p && this.p.length) { const n = new u8(this.p.length + chunk.length); n.set(this.p), n.set(chunk, this.p.length); } else this.p = chunk; if (this.p.length > 2) { const _this = this; const cb: FlateStreamHandler = function() { _this.ondata.apply(_this, arguments); } this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) ? new this.G(cb) : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) ? new this.I(cb) : new this.Z(cb); this.s.push(this.p, final); this.p = null; } } else this.s.push(chunk, final); } } /** * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression */ export class AsyncDecompress { private G = AsyncGunzip; private I = AsyncInflate; private Z = AsyncUnzlib; /** * Creates an asynchronous decompression stream * @param cb The callback to call whenever data is decompressed */ constructor(cb?: AsyncFlateStreamHandler) { this.ondata = cb; } /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Pushes a chunk to be decompressed * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { Decompress.prototype.push.call(this, chunk, final); } } /** * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format * @param data The data to decompress * @param opts The decompression options * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function decompress(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format * @param data The data to decompress * @param cb The function to be called upon decompression completion * @returns A function that can be used to immediately terminate the decompression */ export function decompress(data: Uint8Array, cb: FlateCallback): AsyncTerminable; export function decompress(data: Uint8Array, opts: AsyncInflateOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); return (data[0] == 31 && data[1] == 139 && data[2] == 8) ? gunzip(data, opts as AsyncInflateOptions, cb) : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) ? inflate(data, opts as AsyncInflateOptions, cb) : unzlib(data, opts as AsyncInflateOptions, cb); } /** * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ export function decompressSync(data: Uint8Array, out?: Uint8Array) { return (data[0] == 31 && data[1] == 139 && data[2] == 8) ? gunzipSync(data, out) : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) ? inflateSync(data, out) : unzlibSync(data, out); } /** * Attributes for files added to a ZIP archive object */ export interface ZipAttributes { /** * The operating system of origin for this file. The value is defined * by PKZIP's APPNOTE.txt, section 4.4.2.2. For example, 0 (the default) * is MS/DOS, 3 is UNIX, 19 is macOS. */ os?: number; /** * The file's attributes. These are traditionally somewhat complicated * and platform-dependent, so using them is scarcely necessary. However, * here is a representation of what this is, bit by bit: * * `TTTTugtrwxrwxrwx0000000000ADVSHR` * * TTTT = file type (rarely useful) * * u = setuid, g = setgid, t = sticky * * rwx = user permissions, rwx = group permissions, rwx = other permissions * * 0000000000 = unused * * A = archive, D = directory, V = volume label, S = system file, H = hidden, R = read-only * * If you want to set the Unix permissions, for instance, just bit shift by 16, e.g. 0644 << 16 */ attrs?: number; /** * Extra metadata to add to the file. This field is defined by PKZIP's APPNOTE.txt, * section 4.4.28. At most 65,535 bytes may be used in each ID. The ID must be an * integer between 0 and 65,535, inclusive. * * This field is incredibly rare and almost never needed except for compliance with * proprietary standards and software. */ extra?: Record<number, Uint8Array>; /** * The comment to attach to the file. This field is defined by PKZIP's APPNOTE.txt, * section 4.4.26. The comment must be at most 65,535 bytes long UTF-8 encoded. This * field is not read by consumer software. */ comment?: string; /** * When the file was last modified. Defaults to the current time. */ mtime?: GzipOptions['mtime']; } /** * Options for creating a ZIP archive */ export interface ZipOptions extends DeflateOptions, ZipAttributes {} /** * Options for expanding a ZIP archive */ export interface UnzipOptions { /** * A filter function to extract only certain files from a ZIP archive */ filter?: UnzipFileFilter; } /** * Options for asynchronously creating a ZIP archive */ export interface AsyncZipOptions extends AsyncDeflateOptions, ZipAttributes {} /** * Options for asynchronously expanding a ZIP archive */ export interface AsyncUnzipOptions extends UnzipOptions {} /** * A file that can be used to create a ZIP archive */ export type ZippableFile = Uint8Array | [Uint8Array, ZipOptions]; /** * A file that can be used to asynchronously create a ZIP archive */ export type AsyncZippableFile = Uint8Array | [Uint8Array, AsyncZipOptions]; /** * The complete directory structure of a ZIPpable archive */ export interface Zippable { [path: string]: Zippable | ZippableFile; } /** * The complete directory structure of an asynchronously ZIPpable archive */ export interface AsyncZippable { [path: string]: AsyncZippable | AsyncZippableFile; } /** * An unzipped archive. The full path of each file is used as the key, * and the file is the value */ export interface Unzipped { [path: string]: Uint8Array } /** * Handler for string generation streams * @param data The string output from the stream processor * @param final Whether this is the final block */ export type StringStreamHandler = (data: string, final: boolean) => void; /** * Callback for asynchronous ZIP decompression * @param err Any error that occurred * @param data The decompressed ZIP archive */ export type UnzipCallback = (err: FlateError, data: Unzipped) => void; /** * Handler for streaming ZIP decompression * @param file The file that was found in the archive */ export type UnzipFileHandler = (file: UnzipFile) => void; // flattened Zippable type FlatZippable<A extends boolean> = Record<string, [Uint8Array, (A extends true ? AsyncZipOptions : ZipOptions)]>; // flatten a directory structure const fltn = <A extends boolean>(d: A extends true ? AsyncZippable : Zippable, p: string, t: FlatZippable<A>, o: ZipOptions) => { for (const k in d) { const val = d[k], n = p + k; if (val instanceof u8) t[n] = [val, o] as unknown as FlatZippable<A>[string]; else if (Array.isArray(val)) t[n] = [val[0], mrg(o, val[1])] as FlatZippable<A>[string]; else fltn(val as unknown as (A extends true ? AsyncZippable : Zippable), n + '/', t, o); } } // text encoder const te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); // text decoder const td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); // text decoder stream let tds = 0; try { td.decode(et, { stream: true }); tds = 1; } catch(e) {} // decode UTF8 const dutf8 = (d: Uint8Array) => { for (let r = '', i = 0;;) { let c = d[i++]; const eb = ((c > 127) as unknown as number) + ((c > 223) as unknown as number) + ((c > 239) as unknown as number); if (i + eb > d.length) return [r, slc(d, i - 1)] as const; if (!eb) r += String.fromCharCode(c) else if (eb == 3) { c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); } else if (eb & 1) r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); else r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); } } /** * Streaming UTF-8 decoding */ export class DecodeUTF8 { private p: Uint8Array; private t: TextDecoder; /** * Creates a UTF-8 decoding stream * @param cb The callback to call whenever data is decoded */ constructor(cb?: StringStreamHandler) { this.ondata = cb; if (tds) this.t = new TextDecoder(); else this.p = et; } /** * Pushes a chunk to be decoded from UTF-8 binary * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { if (!this.ondata) err(5); final = !!final; if (this.t) { this.ondata(this.t.decode(chunk, { stream: true }), final); if (final) { if (this.t.decode().length) err(8); this.t = null; } return; } if (!this.p) err(4); const dat = new u8(this.p.length + chunk.length); dat.set(this.p); dat.set(chunk, this.p.length); const [ch, np] = dutf8(dat); if (final) { if (np.length) err(8); this.p = null; } else this.p = np; this.ondata(ch, final); } /** * The handler to call whenever data is available */ ondata: StringStreamHandler; } /** * Streaming UTF-8 encoding */ export class EncodeUTF8 { private d: boolean; /** * Creates a UTF-8 decoding stream * @param cb The callback to call whenever data is encoded */ constructor(cb?: FlateStreamHandler) { this.ondata = cb; } /** * Pushes a chunk to be encoded to UTF-8 * @param chunk The string data to push * @param final Whether this is the last chunk */ push(chunk: string, final?: boolean) { if (!this.ondata) err(5); if (this.d) err(4); this.ondata(strToU8(chunk), this.d = final || false); } /** * The handler to call whenever data is available */ ondata: FlateStreamHandler; } /** * Converts a string into a Uint8Array for use with compression/decompression methods * @param str The string to encode * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless decoding a binary string. * @returns The string encoded in UTF-8/Latin-1 binary */ export function strToU8(str: string, latin1?: boolean): Uint8Array { if (latin1) { const ar = new u8(str.length); for (let i = 0; i < str.length; ++i) ar[i] = str.charCodeAt(i); return ar; } if (te) return te.encode(str); const l = str.length; let ar = new u8(str.length + (str.length >> 1)); let ai = 0; const w = (v: number) => { ar[ai++] = v; }; for (let i = 0; i < l; ++i) { if (ai + 5 > ar.length) { const n = new u8(ai + 8 + ((l - i) << 1)); n.set(ar); ar = n; } let c = str.charCodeAt(i); if (c < 128 || latin1) w(c); else if (c < 2048) w(192 | (c >> 6)), w(128 | (c & 63)); else if (c > 55295 && c < 57344) c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); else w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); } return slc(ar, 0, ai); } /** * Converts a Uint8Array to a string * @param dat The data to decode to string * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless encoding to binary string. * @returns The original UTF-8/Latin-1 string */ export function strFromU8(dat: Uint8Array, latin1?: boolean) { if (latin1) { let r = ''; for (let i = 0; i < dat.length; i += 16384) r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); return r; } else if (td) return td.decode(dat) else { const [out, ext] = dutf8(dat); if (ext.length) err(8); return out; } }; // deflate bit flag const dbf = (l: number) => l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; // skip local zip header const slzh = (d: Uint8Array, b: number) => b + 30 + b2(d, b + 26) + b2(d, b + 28); // read zip header const zh = (d: Uint8Array, b: number, z: boolean) => { const fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20); const [sc, su, off] = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)]; return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off] as const; } // read zip64 extra field const z64e = (d: Uint8Array, b: number) => { for (; b2(d, b) != 1; b += 4 + b2(d, b + 2)); return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)] as const; } // zip header file type ZHF = Omit<ZipInputFile, 'terminate' | 'ondata' | 'filename'>; // extra field length const exfl = (ex?: ZHF['extra']) => { let le = 0; if (ex) { for (const k in ex) { const l = ex[k].length; if (l > 65535) err(9); le += l + 4; } } return le; } // write zip header const wzh = (d: Uint8Array, b: number, f: ZHF, fn: Uint8Array, u: boolean, c?: number, ce?: number, co?: Uint8Array) => { const fl = fn.length, ex = f.extra, col = co && co.length; let exl = exfl(ex); wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; if (ce != null) d[b++] = 20, d[b++] = f.os; d[b] = 20, b += 2; // spec compliance? what's that? d[b++] = (f.flag << 1) | (c == null && 8), d[b++] = u && 8; d[b++] = f.compression & 255, d[b++] = f.compression >> 8; const dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; if (y < 0 || y > 119) err(10); wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4; if (c != null) { wbytes(d, b, f.crc); wbytes(d, b + 4, c); wbytes(d, b + 8, f.size); } wbytes(d, b + 12, fl); wbytes(d, b + 14, exl), b += 16; if (ce != null) { wbytes(d, b, col); wbytes(d, b + 6, f.attrs); wbytes(d, b + 10, ce), b += 14; } d.set(fn, b); b += fl; if (exl) { for (const k in ex) { const exf = ex[k], l = exf.length; wbytes(d, b, +k); wbytes(d, b + 2, l); d.set(exf, b + 4), b += 4 + l; } } if (col) d.set(co, b), b += col; return b; } // write zip footer (end of central directory) const wzf = (o: Uint8Array, b: number, c: number, d: number, e: number) => { wbytes(o, b, 0x6054B50); // skip disk wbytes(o, b + 8, c); wbytes(o, b + 10, c); wbytes(o, b + 12, d); wbytes(o, b + 16, e); } /** * A stream that can be used to create a file in a ZIP archive */ export interface ZipInputFile extends ZipAttributes { /** * The filename to associate with the data provided to this stream. If you * want a file in a subdirectory, use forward slashes as a separator (e.g. * `directory/filename.ext`). This will still work on Windows. */ filename: string; /** * The size of the file in bytes. This attribute may be invalid after * the file is added to the ZIP archive; it must be correct only before the * stream completes. * * If you don't want to have to compute this yourself, consider extending the * ZipPassThrough class and overriding its process() method, or using one of * ZipDeflate or AsyncZipDeflate. */ size: number; /** * A CRC of the original file contents. This attribute may be invalid after * the file is added to the ZIP archive; it must be correct only before the * stream completes. * * If you don't want to have to generate this yourself, consider extending the * ZipPassThrough class and overriding its process() method, or using one of * ZipDeflate or AsyncZipDeflate. */ crc: number; /** * The compression format for the data stream. This number is determined by * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no * compression, 8 = deflate, 14 = LZMA */ compression: number; /** * Bits 1 and 2 of the general purpose bit flag, specified in PKZIP's * APPNOTE.txt, section 4.4.4. Should be between 0 and 3. This is unlikely * to be necessary. */ flag?: number; /** * The handler to be called when data is added. After passing this stream to * the ZIP file object, this handler will always be defined. To call it: * * `stream.ondata(error, chunk, final)` * * error = any error that occurred (null if there was no error) * * chunk = a Uint8Array of the data that was added (null if there was an * error) * * final = boolean, whether this is the final chunk in the stream */ ondata?: AsyncFlateStreamHandler; /** * A method called when the stream is no longer needed, for clean-up * purposes. This will not always be called after the stream completes, * so you may wish to call this.terminate() after the final chunk is * processed if you have clean-up logic. */ terminate?: AsyncTerminable; } type AsyncZipDat = ZHF & { // compressed data c: Uint8Array; // filename f: Uint8Array; // comment m?: Uint8Array; // unicode u: boolean; }; type ZipDat = AsyncZipDat & { // offset o: number; } /** * A pass-through stream to keep data uncompressed in a ZIP archive. */ export class ZipPassThrough implements ZipInputFile { filename: string; crc: number; size: number; compression: number; os?: number; attrs?: number; comment?: string; extra?: Record<number, Uint8Array>; mtime?: GzipOptions['mtime']; ondata: AsyncFlateStreamHandler; private c: CRCV; /** * Creates a pass-through stream that can be added to ZIP archives * @param filename The filename to associate with this data stream */ constructor(filename: string) { this.filename = filename; this.c = crc(); this.size = 0; this.compression = 0; } /** * Processes a chunk and pushes to the output stream. You can override this * method in a subclass for custom behavior, but by default this passes * the data through. You must call this.ondata(err, chunk, final) at some * point in this method. * @param chunk The chunk to process * @param final Whether this is the last chunk */ protected process(chunk: Uint8Array, final: boolean) { this.ondata(null, chunk, final); } /** * Pushes a chunk to be added. If you are subclassing this with a custom * compression algorithm, note that you must push data from the source * file only, pre-compression. * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { if (!this.ondata) err(5); this.c.p(chunk); this.size += chunk.length; if (final) this.crc = this.c.d(); this.process(chunk, final || false); } } // I don't extend because TypeScript extension adds 1kB of runtime bloat /** * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate * for better performance */ export class ZipDeflate implements ZipInputFile { filename: string; crc: number; size: number; compression: number; flag: 0 | 1 | 2 | 3; os?: number; attrs?: number; comment?: string; extra?: Record<number, Uint8Array>; mtime?: GzipOptions['mtime']; ondata: AsyncFlateStreamHandler; private d: Deflate; /** * Creates a DEFLATE stream that can be added to ZIP archives * @param filename The filename to associate with this data stream * @param opts The compression options */ constructor(filename: string, opts?: DeflateOptions) { if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new Deflate(opts, (dat, final) => { this.ondata(null, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); } process(chunk: Uint8Array, final: boolean) { try { this.d.push(chunk, final); } catch(e) { this.ondata(e, null, final); } } /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { ZipPassThrough.prototype.push.call(this, chunk, final); } } /** * Asynchronous streaming DEFLATE compression for ZIP archives */ export class AsyncZipDeflate implements ZipInputFile { filename: string; crc: number; size: number; compression: number; flag: 0 | 1 | 2 | 3; os?: number; attrs?: number; comment?: string; extra?: Record<number, Uint8Array>; mtime?: GzipOptions['mtime']; ondata: AsyncFlateStreamHandler; private d: AsyncDeflate; terminate: AsyncTerminable; /** * Creates a DEFLATE stream that can be added to ZIP archives * @param filename The filename to associate with this data stream * @param opts The compression options */ constructor(filename: string, opts?: DeflateOptions) { if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new AsyncDeflate(opts, (err, dat, final) => { this.ondata(err, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); this.terminate = this.d.terminate; } process(chunk: Uint8Array, final: boolean) { this.d.push(chunk, final); } /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { ZipPassThrough.prototype.push.call(this, chunk, final); } } type ZIFE = { // compressed size c: number; // filename f: Uint8Array; // comment o?: Uint8Array; // unicode u: boolean; // byte offset b: number; // header offset h: number; // terminator t: () => void; // turn r: () => void; }; type ZipInternalFile = ZHF & ZIFE; // TODO: Better tree shaking /** * A zippable archive to which files can incrementally be added */ export class Zip { private u: ZipInternalFile[]; private d: number; /** * Creates an empty ZIP archive to which files can be added * @param cb The callback to call whenever data for the generated ZIP archive * is available */ constructor(cb?: AsyncFlateStreamHandler) { this.ondata = cb; this.u = []; this.d = 1; } /** * Adds a file to the ZIP archive * @param file The file stream to add */ add(file: ZipInputFile) { if (!this.ondata) err(5); // finishing or finished if (this.d & 2) this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); else { const f = strToU8(file.filename), fl = f.length; const com = file.comment, o = com && strToU8(com); const u = fl != file.filename.length || (o && (com.length != o.length)); const hl = fl + exfl(file.extra) + 30; if (fl > 65535) this.ondata(err(11, 0, 1), null, false); const header = new u8(hl); wzh(header, 0, file, f, u); let chks: Uint8Array[] = [header]; const pAll = () => { for (const chk of chks) this.ondata(null, chk, false); chks = []; }; let tr = this.d; this.d = 0; const ind = this.u.length; const uf = mrg(file, { f, u, o, t: () => { if (file.terminate) file.terminate(); }, r: () => { pAll(); if (tr) { const nxt = this.u[ind + 1]; if (nxt) nxt.r(); else this.d = 1; } tr = 1; } } as ZIFE); let cl = 0; file.ondata = (err, dat, final) => { if (err) { this.ondata(err, dat, final); this.terminate(); } else { cl += dat.length; chks.push(dat); if (final) { const dd = new u8(16); wbytes(dd, 0, 0x8074B50) wbytes(dd, 4, file.crc); wbytes(dd, 8, cl); wbytes(dd, 12, file.size); chks.push(dd); uf.c = cl, uf.b = hl + cl + 16, uf.crc = file.crc, uf.size = file.size; if (tr) uf.r(); tr = 1; } else if (tr) pAll(); } } this.u.push(uf); } } /** * Ends the process of adding files and prepares to emit the final chunks. * This *must* be called after adding all desired files for the resulting * ZIP file to work properly. */ end() { if (this.d & 2) { this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); return; } if (this.d) this.e(); else this.u.push({ r: () => { if (!(this.d & 1)) return; this.u.splice(-1, 1); this.e(); }, t: () => {} } as unknown as ZipInternalFile); this.d = 3; } private e() { let bt = 0, l = 0, tl = 0; for (const f of this.u) tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); const out = new u8(tl + 22); for (const f of this.u) { wzh(out, bt, f, f.f, f.u, f.c, l, f.o); bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; } wzf(out, bt, this.u.length, tl, l) this.ondata(null, out, true); this.d = 2; } /** * A method to terminate any internal workers used by the stream. Subsequent * calls to add() will fail. */ terminate() { for (const f of this.u) f.t(); this.d = 2; } /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; } /** * Asynchronously creates a ZIP file * @param data The directory structure for the ZIP archive * @param opts The main options, merged with per-file options * @param cb The callback to call with the generated ZIP archive * @returns A function that can be used to immediately terminate the compression */ export function zip(data: AsyncZippable, opts: AsyncZipOptions, cb: FlateCallback): AsyncTerminable; /** * Asynchronously creates a ZIP file * @param data The directory structure for the ZIP archive * @param cb The callback to call with the generated ZIP archive * @returns A function that can be used to immediately terminate the compression */ export function zip(data: AsyncZippable, cb: FlateCallback): AsyncTerminable; export function zip(data: AsyncZippable, opts: AsyncZipOptions | FlateCallback, cb?: FlateCallback) { if (!cb) cb = opts as FlateCallback, opts = {}; if (typeof cb != 'function') err(7); const r: FlatZippable<true> = {}; fltn(data, '', r, opts as AsyncZipOptions); const k = Object.keys(r); let lft = k.length, o = 0, tot = 0; const slft = lft, files = new Array<AsyncZipDat>(lft); const term: AsyncTerminable[] = []; const tAll = () => { for (let i = 0; i < term.length; ++i) term[i](); } let cbd: FlateCallback = (a, b) => { mt(() => { cb(a, b); }); } mt(() => { cbd = cb; }); const cbf = () => { const out = new u8(tot + 22), oe = o, cdl = tot - o; tot = 0; for (let i = 0; i < slft; ++i) { const f = files[i]; try { const l = f.c.length; wzh(out, tot, f, f.f, f.u, l); const badd = 30 + f.f.length + exfl(f.extra); const loc = tot + badd; out.set(f.c, loc); wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; } catch(e) { return cbd(e, null); } } wzf(out, o, files.length, cdl, oe); cbd(null, out); } if (!lft) cbf(); // Cannot use lft because it can decrease for (let i = 0; i < slft; ++i) { const fn = k[i]; const [file, p] = r[fn]; const c = crc(), size = file.length; c.p(file); const f = strToU8(fn), s = f.length; const com = p.comment, m = com && strToU8(com), ms = m && m.length; const exl = exfl(p.extra); const compression = p.level == 0 ? 0 : 8; const cbl: FlateCallback = (e, d) => { if (e) { tAll(); cbd(e, null); } else { const l = d.length; files[i] = mrg(p, { size, crc: c.d(), c: d, f, m, u: s != fn.length || (m && (com.length != ms)), compression }); o += 30 + s + exl + l; tot += 76 + 2 * (s + exl) + (ms || 0) + l; if (!--lft) cbf(); } } if (s > 65535) cbl(err(11, 0, 1), null); if (!compression) cbl(null, file); else if (size < 160000) { try { cbl(null, deflateSync(file, p)); } catch(e) { cbl(e, null); } } else term.push(deflate(file, p, cbl)); } return tAll; } /** * Synchronously creates a ZIP file. Prefer using `zip` for better performance * with more than one file. * @param data The directory structure for the ZIP archive * @param opts The main options, merged with per-file options * @returns The generated ZIP archive */ export function zipSync(data: Zippable, opts?: ZipOptions) { if (!opts) opts = {}; const r: FlatZippable<false> = {}; const files: ZipDat[] = []; fltn(data, '', r, opts); let o = 0; let tot = 0; for (const fn in r) { const [file, p] = r[fn]; const compression = p.level == 0 ? 0 : 8; const f = strToU8(fn), s = f.length; const com = p.comment, m = com && strToU8(com), ms = m && m.length; const exl = exfl(p.extra); if (s > 65535) err(11); const d = compression ? deflateSync(file, p) : file, l = d.length; const c = crc(); c.p(file); files.push(mrg(p, { size: file.length, crc: c.d(), c: d, f, m, u: s != fn.length || (m && (com.length != ms)), o, compression })); o += 30 + s + exl + l; tot += 76 + 2 * (s + exl) + (ms || 0) + l; } const out = new u8(tot + 22), oe = o, cdl = tot - o; for (let i = 0; i < files.length; ++i) { const f = files[i]; wzh(out, f.o, f, f.f, f.u, f.c.length); const badd = 30 + f.f.length + exfl(f.extra); out.set(f.c, f.o + badd); wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); } wzf(out, o, files.length, cdl, oe); return out; } /** * A decoder for files in ZIP streams */ export interface UnzipDecoder { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * Pushes a chunk to be decompressed * @param data The data in this chunk. Do not consume (detach) this data. * @param final Whether this is the last chunk in the data stream */ push(data: Uint8Array, final: boolean): void; /** * A method to terminate any internal workers used by the stream. Subsequent * calls to push() should silently fail. */ terminate?: AsyncTerminable } /** * A constructor for a decoder for unzip streams */ export interface UnzipDecoderConstructor { /** * Creates an instance of the decoder * @param filename The name of the file * @param size The compressed size of the file * @param originalSize The original size of the file */ new(filename: string, size?: number, originalSize?: number): UnzipDecoder; /** * The compression format for the data stream. This number is determined by * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no * compression, 8 = deflate, 14 = LZMA */ compression: number; } /** * Information about a file to be extracted from a ZIP archive */ export interface UnzipFileInfo { /** * The name of the file */ name: string; /** * The compressed size of the file */ size: number; /** * The original size of the file */ originalSize: number; /** * The compression format for the data stream. This number is determined by * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no * compression, 8 = deflate, 14 = LZMA. If the filter function returns true * but this value is not 8, the unzip function will throw. */ compression: number; } /** * A filter for files to be extracted during the unzipping process * @param file The info for the current file being processed * @returns Whether or not to extract the current file */ export type UnzipFileFilter = (file: UnzipFileInfo) => boolean; /** * Streaming file extraction from ZIP archives */ export interface UnzipFile { /** * The handler to call whenever data is available */ ondata: AsyncFlateStreamHandler; /** * The name of the file */ name: string; /** * The compression format for the data stream. This number is determined by * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no * compression, 8 = deflate, 14 = LZMA. If start() is called but there is no * decompression stream available for this method, start() will throw. */ compression: number; /** * The compressed size of the file. Will not be present for archives created * in a streaming fashion. */ size?: number; /** * The original size of the file. Will not be present for archives created * in a streaming fashion. */ originalSize?: number; /** * Starts reading from the stream. Calling this function will always enable * this stream, but ocassionally the stream will be enabled even without * this being called. */ start(): void; /** * A method to terminate any internal workers used by the stream. ondata * will not be called any further. */ terminate: AsyncTerminable } /** * Streaming pass-through decompression for ZIP archives */ export class UnzipPassThrough implements UnzipDecoder { static compression = 0; ondata: AsyncFlateStreamHandler; push(data: Uint8Array, final: boolean) { this.ondata(null, data, final); } } /** * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for * better performance. */ export class UnzipInflate implements UnzipDecoder { static compression = 8; private i: Inflate; ondata: AsyncFlateStreamHandler; /** * Creates a DEFLATE decompression that can be used in ZIP archives */ constructor() { this.i = new Inflate((dat, final) => { this.ondata(null, dat, final); }); } push(data: Uint8Array, final: boolean) { try { this.i.push(data, final); } catch(e) { this.ondata(e, null, final); } } } /** * Asynchronous streaming DEFLATE decompression for ZIP archives */ export class AsyncUnzipInflate implements UnzipDecoder { static compression = 8; private i: AsyncInflate | Inflate; ondata: AsyncFlateStreamHandler; terminate: AsyncTerminable; /** * Creates a DEFLATE decompression that can be used in ZIP archives */ constructor(_: string, sz?: number) { if (sz < 320000) { this.i = new Inflate((dat, final) => { this.ondata(null, dat, final); }); } else { this.i = new AsyncInflate((err, dat, final) => { this.ondata(err, dat, final); }); this.terminate = this.i.terminate; } } push(data: Uint8Array, final: boolean) { if ((this.i as AsyncInflate).terminate) data = slc(data, 0); this.i.push(data, final); } } /** * A ZIP archive decompression stream that emits files as they are discovered */ export class Unzip { private d: UnzipDecoder; private c: number; private p: Uint8Array; private k: Uint8Array[][]; private o: Record<number, UnzipDecoderConstructor>; /** * Creates a ZIP decompression stream * @param cb The callback to call whenever a file in the ZIP archive is found */ constructor(cb?: UnzipFileHandler) { this.onfile = cb; this.k = []; this.o = { 0: UnzipPassThrough }; this.p = et; } /** * Pushes a chunk to be unzipped * @param chunk The chunk to push * @param final Whether this is the last chunk */ push(chunk: Uint8Array, final?: boolean) { if (!this.onfile) err(5); if (!this.p) err(4); if (this.c > 0) { const len = Math.min(this.c, chunk.length); const toAdd = chunk.subarray(0, len); this.c -= len; if (this.d) this.d.push(toAdd, !this.c); else this.k[0].push(toAdd); chunk = chunk.subarray(len); if (chunk.length) return this.push(chunk, final); } else { let f = 0, i = 0, is: number, buf: Uint8Array; if (!this.p.length) buf = chunk; else if (!chunk.length) buf = this.p; else { buf = new u8(this.p.length + chunk.length) buf.set(this.p), buf.set(chunk, this.p.length); } const l = buf.length, oc = this.c, add = oc && this.d; for (; i < l - 4; ++i) { const sig = b4(buf, i); if (sig == 0x4034B50) { f = 1, is = i; this.d = null; this.c = 0; const bf = b2(buf, i + 6), cmp = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); if (l > i + 30 + fnl + es) { const chks: Uint8Array[] = []; this.k.unshift(chks); f = 2; let sc = b4(buf, i + 18), su = b4(buf, i + 22); const fn = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); if (sc == 4294967295) { [sc, su] = dd ? [-2] : z64e(buf, i); } else if (dd) sc = -1; i += es; this.c = sc; let d: UnzipDecoder; const file = { name: fn, compression: cmp, start: () => { if (!file.ondata) err(5); if (!sc) file.ondata(null, et, true); else { const ctr = this.o[cmp]; if (!ctr) file.ondata(err(14, 'unknown compression type ' + cmp, 1), null, false); d = sc < 0 ? new ctr(fn) : new ctr(fn, sc, su); d.ondata = (err, dat, final) => { file.ondata(err, dat, final); } for (const dat of chks) d.push(dat, false); if (this.k[0] == chks && this.c) this.d = d; else d.push(et, true); } }, terminate: () => { if (d && d.terminate) d.terminate(); } } as UnzipFile; if (sc >= 0) file.size = sc, file.originalSize = su; this.onfile(file); } break; } else if (oc) { if (sig == 0x8074B50) { is = i += 12 + (oc == -2 && 8), f = 3, this.c = 0; break; } else if (sig == 0x2014B50) { is = i -= 4, f = 3, this.c = 0; break; } } } this.p = et if (oc < 0) { const dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); if (add) add.push(dat, !!f); else this.k[+(f == 2)].push(dat); } if (f & 2) return this.push(buf.subarray(i), final); this.p = buf.subarray(i); } if (final) { if (this.c) err(13); this.p = null; } } /** * Registers a decoder with the stream, allowing for files compressed with * the compression type provided to be expanded correctly * @param decoder The decoder constructor */ register(decoder: UnzipDecoderConstructor) { this.o[decoder.compression] = decoder; } /** * The handler to call whenever a file is discovered */ onfile: UnzipFileHandler; } const mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : (fn: Function) => { fn(); }; /** * Asynchronously decompresses a ZIP archive * @param data The raw compressed ZIP file * @param opts The ZIP extraction options * @param cb The callback to call with the decompressed files * @returns A function that can be used to immediately terminate the unzipping */ export function unzip(data: Uint8Array, opts: AsyncUnzipOptions, cb: UnzipCallback): AsyncTerminable; /** * Asynchronously decompresses a ZIP archive * @param data The raw compressed ZIP file * @param cb The callback to call with the decompressed files * @returns A function that can be used to immediately terminate the unzipping */ export function unzip(data: Uint8Array, cb: UnzipCallback): AsyncTerminable; export function unzip(data: Uint8Array, opts: AsyncUnzipOptions | UnzipCallback, cb?: UnzipCallback): AsyncTerminable { if (!cb) cb = opts as UnzipCallback, opts = {}; if (typeof cb != 'function') err(7); const term: AsyncTerminable[] = []; const tAll = () => { for (let i = 0; i < term.length; ++i) term[i](); } const files: Unzipped = {}; let cbd: UnzipCallback = (a, b) => { mt(() => { cb(a, b); }); } mt(() => { cbd = cb; }); let e = data.length - 22; for (; b4(data, e) != 0x6054B50; --e) { if (!e || data.length - e > 65558) { cbd(err(13, 0, 1), null); return tAll; } }; let lft = b2(data, e + 8); if (lft) { let c = lft; let o = b4(data, e + 16); const z = o == 4294967295; if (z) { e = b4(data, e - 12); if (b4(data, e) != 0x6064B50) { cbd(err(13, 0, 1), null); return tAll; } c = lft = b4(data, e + 32); o = b4(data, e + 48); } const fltr = opts && (opts as AsyncUnzipOptions).filter; for (let i = 0; i < c; ++i) { const [c, sc, su, fn, no, off] = zh(data, o, z), b = slzh(data, off); o = no const cbl: FlateCallback = (e, d) => { if (e) { tAll(); cbd(e, null); } else { if (d) files[fn] = d; if (!--lft) cbd(null, files); } } if (!fltr || fltr({ name: fn, size: sc, originalSize: su, compression: c })) { if (!c) cbl(null, slc(data, b, b + sc)) else if (c == 8) { const infl = data.subarray(b, b + sc); if (sc < 320000) { try { cbl(null, inflateSync(infl, new u8(su))); } catch(e) { cbl(e, null); } } else term.push(inflate(infl, { size: su }, cbl)); } else cbl(err(14, 'unknown compression type ' + c, 1), null); } else cbl(null, null); } } else cbd(null, {}); return tAll; } /** * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better * performance with more than one file. * @param data The raw compressed ZIP file * @param opts The ZIP extraction options * @returns The decompressed files */ export function unzipSync(data: Uint8Array, opts?: UnzipOptions) { const files: Unzipped = {}; let e = data.length - 22; for (; b4(data, e) != 0x6054B50; --e) { if (!e || data.length - e > 65558) err(13); }; let c = b2(data, e + 8); if (!c) return {}; let o = b4(data, e + 16); const z = o == 4294967295; if (z) { e = b4(data, e - 12); if (b4(data, e) != 0x6064B50) err(13); c = b4(data, e + 32); o = b4(data, e + 48); } const fltr = opts && opts.filter; for (let i = 0; i < c; ++i) { const [c, sc, su, fn, no, off] = zh(data, o, z), b = slzh(data, off); o = no; if (!fltr || fltr({ name: fn, size: sc, originalSize: su, compression: c })) { if (!c) files[fn] = slc(data, b, b + sc); else if (c == 8) files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su)); else err(14, 'unknown compression type ' + c); } } return files; }
the_stack
import type {GlyphMetadata, GlyphTransformFn} from "../types"; import crypto from "crypto"; import isEot from "is-eot"; import isSvg from "is-svg"; import isTtf from "is-ttf"; import isWoff from "is-woff"; import isWoff2 from "is-woff2"; import path from "path"; import standalone from "../standalone"; const fixturesGlob = "src/fixtures"; describe("standalone", () => { it("should throw error if `files` not passed", async () => { try { await standalone(); } catch (error) { expect(error.message).toMatch("You must pass webfont a `files` glob"); } }); it("should throw error `files glob patterns specified did not match any files` if not found files", async () => { expect.assertions(1); try { await standalone({ files: `${fixturesGlob}/not-found-svg-icons/**/*`, }); } catch (error) { // eslint-disable-next-line jest/no-conditional-expect expect(error.message).toMatch("Files glob patterns specified did not match any files"); } }); it("should generate all fonts", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); }); // Need search better way to test `fs` delay it("should generate all fonts and will be deterministic", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); const svgHash = crypto.createHash("md5").update(result.svg). digest("hex"); const ttfHash = crypto.createHash("md5").update(result.ttf). digest("hex"); const eotHash = crypto.createHash("md5").update(result.eot). digest("hex"); const woffHash = crypto.createHash("md5").update(result.woff). digest("hex"); const woff2Hash = crypto. createHash("md5"). update(result.woff2). digest("hex"); expect(svgHash).toBe("1154313a3843c5f5ec70890715e8a527"); expect(ttfHash).toBe("a78de3c54fa46d77540c2c96c4194f16"); expect(eotHash).toBe("90ed04c53c7534b2e66979f6c0a94afe"); expect(woffHash).toBe("20d0a901f75c638e7be9df714a93d5a0"); expect(woff2Hash).toBe("60fe7d6d658fef07b9e8af362e4b8f36"); }); it("should generate only `svg`, `ttf` and `eot` fonts", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, formats: ["svg", "ttf", "eot"], }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(result.woff).toBeUndefined(); expect(result.woff2).toBeUndefined(); }); it("should generate only `woff2` font", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, formats: ["woff2"], }); expect(result.svg).toBeUndefined(); expect(result.ttf).toBeUndefined(); expect(result.eot).toBeUndefined(); expect(result.woff).toBeUndefined(); expect(isWoff2(result.woff2)).toBe(true); }); it("should generate all fonts with build-in template", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, template: "css", templateCacheString: "test", }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); expect(result.template).toMatchSnapshot(); }); it("should generate only `woff` and `woff2` fonts with build-in template", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, formats: ["woff", "woff2"], template: "css", templateCacheString: "test", }); expect(result.svg).toBeUndefined(); expect(result.ttf).toBeUndefined(); expect(result.eot).toBeUndefined(); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); expect(result.template).toMatchSnapshot(); }); it("should generate all fonts with custom `template` with absolute path", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, template: path.join(fixturesGlob, "templates/template.css"), templateCacheString: "test", }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); expect(result.template).toMatchSnapshot(); }); it("should generate all fonts with custom `template` with relative path", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, template: "src/fixtures/templates/template.css", templateCacheString: "test", }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); expect(result.template).toMatchSnapshot(); }); it("should load config and export file path in result", async () => { const configFile = path.join(fixturesGlob, "configs/.webfontrc"); const result = await standalone({ configFile, files: `${fixturesGlob}/svg-icons/**/*`, }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore expect(result.config.foo).toBe("bar"); }); it("should load config and respect `template` option with build-in template value", async () => { const configFile = path.join(fixturesGlob, "configs/.webfontrc-with-build-in-template"); const result = await standalone({ configFile, files: `${fixturesGlob}/svg-icons/**/*`, templateCacheString: "test", }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); expect(result.config.template).toBe("scss"); expect(result.template).toMatchSnapshot(); }); it("should load config and respect `template` option with external template value", async () => { const configFile = path.join(fixturesGlob, "configs/.webfontrc-with-external-template"); const result = await standalone({ configFile, files: `${fixturesGlob}/svg-icons/**/*`, }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); expect(result.config.template).toBe("src/fixtures/templates/template.css"); expect(result.template).toMatchSnapshot(); }); it("should load config and respect `formats` option", async () => { const configFile = path.join(fixturesGlob, "configs/.webfontrc-with-custom-formats"); const result = await standalone({ configFile, files: `${fixturesGlob}/svg-icons/**/*`, }); expect(result.svg).toBeUndefined(); expect(result.ttf).toBeUndefined(); expect(result.eot).toBeUndefined(); expect(result.woff).toBeUndefined(); expect(isWoff2(result.woff2)).toBe(true); }); it("should generate the ordered output source in the same order of entry", async () => { expect.assertions(1); const templateOutput = ` .webfont-envelope::before { content: "\\ea01"; } .webfont-avatar::before { content: "\\ea02"; } `; const result = await standalone({ files: [ `${fixturesGlob}/svg-icons/envelope.svg`, `${fixturesGlob}/svg-icons/avatar.svg`, ], sort: false, template: path.join(fixturesGlob, "templates/template-ordered.css"), }); // eslint-disable-next-line prefer-named-capture-group const actual = templateOutput.replace(/(\s)/gu, ""); // eslint-disable-next-line prefer-named-capture-group const expected = result.template.replace(/(\s)/gu, ""); expect(actual).toBe(expected); }); it("should throw error on bad svg images - `Unclosed root tag`", async () => { expect.assertions(1); const configFile = path.join(fixturesGlob, "configs/.webfontrc"); try { await standalone({ configFile, files: `${fixturesGlob}/bad-svg-icons/avatar.svg`, }); } catch (error) { // eslint-disable-next-line jest/no-conditional-expect expect(error.message).toMatch(/Unclosed root tag/u); } }); it("should throw error on bad svg images - `Unterminated command at index`", async () => { expect.assertions(1); const configFile = path.join(fixturesGlob, "configs/.webfontrc"); try { await standalone({ configFile, files: `${fixturesGlob}/bad-svg-icons/avatar-1.svg`, }); } catch (error) { // eslint-disable-next-line jest/no-conditional-expect expect(error.message).toMatch(/Unterminated command at index/u); } }); it("should throw error on bad svg images - `Unexpected character \"N\"`", async () => { expect.assertions(1); const configFile = path.join(fixturesGlob, "configs/.webfontrc"); try { await standalone({ configFile, files: `${fixturesGlob}/bad-svg-icons/avatar-2.svg`, }); } catch (error) { // eslint-disable-next-line jest/no-conditional-expect expect(error.message).toMatch(/Unexpected character "N"/u); } }); it("should throw error on bad svg images - empty file", async () => { expect.assertions(1); const configFile = path.join(fixturesGlob, "configs/.webfontrc"); try { await standalone({ configFile, files: `${fixturesGlob}/bad-svg-icons/avatar-3.svg`, }); } catch (error) { // eslint-disable-next-line jest/no-conditional-expect expect(error.message).toMatch(/Empty file/u); } }); it("should throw error of config file not found", async () => { expect.assertions(1); const configFile = path.join(fixturesGlob, "configs/.not-exist-webfontrc"); try { await standalone({ configFile, files: `${fixturesGlob}/svg-icons/**/*`, }); } catch (error) { // eslint-disable-next-line jest/no-conditional-expect expect(error.code).toBe("ENOENT"); } }); it("should create css selectors with transform titles through function", async () => { const glyphTransformFn : GlyphTransformFn = (obj) => { obj.name += "_transform"; return obj; }; const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, formats: ["eot"], glyphTransformFn, template: "css", templateCacheString: "test", }); expect(result.template).toMatchSnapshot(); }); it("should change unicode symbols in the result using sync function", async () => { const { template } = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, formats: ["eot"], glyphTransformFn: (obj: GlyphMetadata) => { obj.unicode = ["\u0001"]; return obj; }, template: "css", templateCacheString: "test", }); expect(template).toMatchSnapshot(); }); it("should change unicode symbols in the result using async function", async () => { const { template } = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, formats: ["eot"], glyphTransformFn: (obj: GlyphMetadata) => { obj.unicode = ["\u0001"]; return Promise.resolve(obj); }, template: "css", templateCacheString: "test", }); expect(template).toMatchSnapshot(); }); it("should handle errors properly", async () => { try { await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, formats: ["eot"], glyphTransformFn: () => { throw new Error("Name is invalid"); }, template: "css", }); } catch (error) { expect(error.message).toMatch("Name is invalid"); } }); it("should respect `template` options", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, template: "css", templateCacheString: "test", templateClassName: "foo", templateFontName: "bar", templateFontPath: "./foo-bar", }); expect(isSvg(result.svg)).toBe(true); expect(isTtf(result.ttf)).toBe(true); expect(isEot(result.eot)).toBe(true); expect(isWoff(result.woff)).toBe(true); expect(isWoff2(result.woff2)).toBe(true); expect(result.config.template).toBe("css"); expect(result.usedBuildInTemplate).toBe(true); expect(result.template).toMatchSnapshot(); }); it("should export `glyphsData` in `result`", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, template: "css", }); expect(Array.isArray(result.glyphsData)).toBe(true); expect(result.glyphsData.length > 0).toBe(true); }); it("should remove ligature unicode when `ligatures` set to `false`", async () => { const result = await standalone({ files: `${fixturesGlob}/svg-icons/**/*`, ligatures: false, template: "css", }); expect(Array.isArray(result.glyphsData)).toBe(true); expect(result.glyphsData.length > 0).toBe(true); result.glyphsData.forEach((glyph) => { expect(glyph.metadata?.unicode).toHaveLength(1); }); }); it("should export `hash` in `result`", () => { expect.assertions(1); return standalone({ files: `${fixturesGlob}/svg-icons/**/*`, }).then((result) => { expect(result.hash).toBe("1154313a3843c5f5ec70890715e8a527"); return result; }); }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Manages a CodeBuild webhook, which is an endpoint accepted by the CodeBuild service to trigger builds from source code repositories. Depending on the source type of the CodeBuild project, the CodeBuild service may also automatically create and delete the actual repository webhook as well. * * ## Example Usage * ### Bitbucket and GitHub * * When working with [Bitbucket](https://bitbucket.org) and [GitHub](https://github.com) source CodeBuild webhooks, the CodeBuild service will automatically create (on `aws.codebuild.Webhook` resource creation) and delete (on `aws.codebuild.Webhook` resource deletion) the Bitbucket/GitHub repository webhook using its granted OAuth permissions. This behavior cannot be controlled by this provider. * * > **Note:** The AWS account that this provider uses to create this resource *must* have authorized CodeBuild to access Bitbucket/GitHub's OAuth API in each applicable region. This is a manual step that must be done *before* creating webhooks with this resource. If OAuth is not configured, AWS will return an error similar to `ResourceNotFoundException: Could not find access token for server type github`. More information can be found in the CodeBuild User Guide for [Bitbucket](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-bitbucket-pull-request.html) and [GitHub](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-github-pull-request.html). * * > **Note:** Further managing the automatically created Bitbucket/GitHub webhook with the `bitbucketHook`/`githubRepositoryWebhook` resource is only possible with importing that resource after creation of the `aws.codebuild.Webhook` resource. The CodeBuild API does not ever provide the `secret` attribute for the `aws.codebuild.Webhook` resource in this scenario. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.codebuild.Webhook("example", { * projectName: aws_codebuild_project.example.name, * buildType: "BUILD", * filterGroups: [{ * filters: [ * { * type: "EVENT", * pattern: "PUSH", * }, * { * type: "HEAD_REF", * pattern: "master", * }, * ], * }], * }); * ``` * ### GitHub Enterprise * * When working with [GitHub Enterprise](https://enterprise.github.com/) source CodeBuild webhooks, the GHE repository webhook must be separately managed (e.g. manually or with the `githubRepositoryWebhook` resource). * * More information creating webhooks with GitHub Enterprise can be found in the [CodeBuild User Guide](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-github-enterprise.html). * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * import * as github from "@pulumi/github"; * * const exampleWebhook = new aws.codebuild.Webhook("exampleWebhook", {projectName: aws_codebuild_project.example.name}); * const exampleRepositoryWebhook = new github.RepositoryWebhook("exampleRepositoryWebhook", { * active: true, * events: ["push"], * repository: github_repository.example.name, * configuration: { * url: exampleWebhook.payloadUrl, * secret: exampleWebhook.secret, * contentType: "json", * insecureSsl: false, * }, * }); * ``` * * ## Import * * CodeBuild Webhooks can be imported using the CodeBuild Project name, e.g. * * ```sh * $ pulumi import aws:codebuild/webhook:Webhook example MyProjectName * ``` */ export class Webhook extends pulumi.CustomResource { /** * Get an existing Webhook resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: WebhookState, opts?: pulumi.CustomResourceOptions): Webhook { return new Webhook(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:codebuild/webhook:Webhook'; /** * Returns true if the given object is an instance of Webhook. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Webhook { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Webhook.__pulumiType; } /** * A regular expression used to determine which branches get built. Default is all branches are built. It is recommended to use `filterGroup` over `branchFilter`. */ public readonly branchFilter!: pulumi.Output<string | undefined>; /** * The type of build this webhook will trigger. Valid values for this parameter are: `BUILD`, `BUILD_BATCH`. */ public readonly buildType!: pulumi.Output<string | undefined>; /** * Information about the webhook's trigger. Filter group blocks are documented below. */ public readonly filterGroups!: pulumi.Output<outputs.codebuild.WebhookFilterGroup[] | undefined>; /** * The CodeBuild endpoint where webhook events are sent. */ public /*out*/ readonly payloadUrl!: pulumi.Output<string>; /** * The name of the build project. */ public readonly projectName!: pulumi.Output<string>; /** * The secret token of the associated repository. Not returned by the CodeBuild API for all source types. */ public /*out*/ readonly secret!: pulumi.Output<string>; /** * The URL to the webhook. */ public /*out*/ readonly url!: pulumi.Output<string>; /** * Create a Webhook resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: WebhookArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: WebhookArgs | WebhookState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as WebhookState | undefined; inputs["branchFilter"] = state ? state.branchFilter : undefined; inputs["buildType"] = state ? state.buildType : undefined; inputs["filterGroups"] = state ? state.filterGroups : undefined; inputs["payloadUrl"] = state ? state.payloadUrl : undefined; inputs["projectName"] = state ? state.projectName : undefined; inputs["secret"] = state ? state.secret : undefined; inputs["url"] = state ? state.url : undefined; } else { const args = argsOrState as WebhookArgs | undefined; if ((!args || args.projectName === undefined) && !opts.urn) { throw new Error("Missing required property 'projectName'"); } inputs["branchFilter"] = args ? args.branchFilter : undefined; inputs["buildType"] = args ? args.buildType : undefined; inputs["filterGroups"] = args ? args.filterGroups : undefined; inputs["projectName"] = args ? args.projectName : undefined; inputs["payloadUrl"] = undefined /*out*/; inputs["secret"] = undefined /*out*/; inputs["url"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Webhook.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Webhook resources. */ export interface WebhookState { /** * A regular expression used to determine which branches get built. Default is all branches are built. It is recommended to use `filterGroup` over `branchFilter`. */ branchFilter?: pulumi.Input<string>; /** * The type of build this webhook will trigger. Valid values for this parameter are: `BUILD`, `BUILD_BATCH`. */ buildType?: pulumi.Input<string>; /** * Information about the webhook's trigger. Filter group blocks are documented below. */ filterGroups?: pulumi.Input<pulumi.Input<inputs.codebuild.WebhookFilterGroup>[]>; /** * The CodeBuild endpoint where webhook events are sent. */ payloadUrl?: pulumi.Input<string>; /** * The name of the build project. */ projectName?: pulumi.Input<string>; /** * The secret token of the associated repository. Not returned by the CodeBuild API for all source types. */ secret?: pulumi.Input<string>; /** * The URL to the webhook. */ url?: pulumi.Input<string>; } /** * The set of arguments for constructing a Webhook resource. */ export interface WebhookArgs { /** * A regular expression used to determine which branches get built. Default is all branches are built. It is recommended to use `filterGroup` over `branchFilter`. */ branchFilter?: pulumi.Input<string>; /** * The type of build this webhook will trigger. Valid values for this parameter are: `BUILD`, `BUILD_BATCH`. */ buildType?: pulumi.Input<string>; /** * Information about the webhook's trigger. Filter group blocks are documented below. */ filterGroups?: pulumi.Input<pulumi.Input<inputs.codebuild.WebhookFilterGroup>[]>; /** * The name of the build project. */ projectName: pulumi.Input<string>; }
the_stack
import 'babel-polyfill'; import { app, BrowserWindow, shell, Menu, screen, dialog, ipcMain } from 'electron'; import { autoUpdater } from 'electron-updater'; import * as url from 'url'; import * as path from 'path'; import { initialize } from './lib/ledger'; import * as settings from 'electron-settings'; const log = require('electron-log'); // Don't want errors to display when checking for update // Too annoying if there would be long-term problems with the source // Error would pop up on every launch let showUpdateErrors = false; let saveTimeout = null; let isDownloading = false; const nano_schemes = ['nano', 'nanorep', 'nanoseed', 'nanokey', 'nanosign', 'nanoprocess']; /** * By default, the logger writes logs to the following locations: on Linux: ~/.config/nault/logs/{process type}.log on macOS: ~/Library/Logs/nault/{process type}.log on Windows: %USERPROFILE%\AppData\Roaming\nault\logs\{process type}.log error, warn, info, verbose, debug, silly * */ // determine log location let logLocation = 'Unknown'; switch (process.platform) { case 'win32': logLocation = '%USERPROFILE%\\AppData\\Roaming\\nault\\logs\\main.log'; break; case 'linux': logLocation = '~/.config/nault/logs/main.log'; break; case 'darwin': logLocation = '~/Library/Logs/nault/main.log'; break; } // Keep track of window size and position function windowStateKeeper() { let window, windowState; let newWidth = 1000; let newHeight = 600; try { const mainScreen = screen.getPrimaryDisplay(); const dimensions = mainScreen.size; newWidth = Math.max(newWidth, Math.round(dimensions.width * 0.8)); newHeight = Math.max(newHeight, Math.round(dimensions.height * 0.85)); } catch {log.warn('Could not calculate default screen size')} async function setBounds() { // Restore from appConfig if (settings.hasSync(`windowState.${'main'}`)) { windowState = settings.getSync(`windowState.${'main'}`); return; } // Default windowState = { x: undefined, y: undefined, width: newWidth, height: newHeight, }; } function saveState() { if (saveTimeout !== null) { clearTimeout(saveTimeout); } saveTimeout = setTimeout( () => { if (!windowState.isMaximized) { windowState = window.getBounds(); } windowState.isMaximized = window.isMaximized(); settings.setSync(`windowState.${'main'}`, windowState); }, 100 ); } function track(win) { window = win; ['resize', 'move'].forEach(event => { win.on(event, saveState); }); } setBounds(); return({ x: windowState.x, y: windowState.y, width: windowState.width, height: windowState.height, isMaximized: windowState.isMaximized, track, }); } class AppUpdater { constructor() { // We want the user to proactively download the install autoUpdater.autoDownload = false; autoUpdater.logger = log; autoUpdater.on('update-available', (event, releaseNotes, releaseName) => { if (isDownloading) return; const dialogOpts = { type: 'info', buttons: ['Update', 'Ask Later'], title: 'New Version', message: 'An update for Nault is available!', detail: 'Do you want to download and install it?' } isDownloading = true; dialog.showMessageBox(dialogOpts).then((returnValue) => { if (returnValue.response === 0) { showUpdateErrors = true; // enable errors autoUpdater.downloadUpdate(); } else { isDownloading = false; } }) }) autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => { autoUpdater.quitAndInstall(true, true); }) autoUpdater.on('download-progress', (progressObj) => { sendStatusToWindow(progressObj); }) autoUpdater.on('error', message => { log.error('There was a problem updating the application'); log.error(message); isDownloading = false; if (!showUpdateErrors) { return; } mainWindow.setTitle(`Nault - ${autoUpdater.currentVersion}`); // reset title showUpdateErrors = false; // disable errors const dialogOpts = { type: 'error', buttons: ['OK'], title: 'Update Error', message: 'Something went wrong while downloading Nault.', detail: `You will be notified again on next start.\nMore details in the log at: ${logLocation}` } dialog.showMessageBox(dialogOpts).then((returnValue) => {}) }) } } new AppUpdater(); // Register handler for nano: links if (process.platform === 'darwin') { nano_schemes.forEach((scheme) => app.setAsDefaultProtocolClient(scheme)); } else { const args = process.argv[1] ? [path.resolve(process.argv[1])] : []; nano_schemes.forEach((scheme) => app.setAsDefaultProtocolClient(scheme, process.execPath, args)); } // Initialize Ledger device detection initialize(); let mainWindow: BrowserWindow; function createWindow () { // Get window state const mainWindowStateKeeper = windowStateKeeper(); // Create the browser window. mainWindow = new BrowserWindow({ x: mainWindowStateKeeper.x, y: mainWindowStateKeeper.y, width: mainWindowStateKeeper.width, height: mainWindowStateKeeper.height, webPreferences: { webSecurity: false, devTools: true, nodeIntegration: true } }); // Track window state mainWindowStateKeeper.track(mainWindow); // mainWindow.loadURL('http://localhost:4200/'); // Only use this for development mainWindow.loadURL(url.format({ pathname: path.join(__dirname, '../../dist/index.html'), protocol: 'file:', slashes: true })); // Emitted when the window is closed. mainWindow.on('closed', function () { mainWindow = null; }); // Detect link clicks to new windows and open them in the default browser mainWindow.webContents.on('new-window', function(e, externalurl) { e.preventDefault(); shell.openExternal(externalurl); }); mainWindow.webContents.on('did-finish-load', function () { mainWindow.setTitle(`Nault - ${autoUpdater.currentVersion}`); }); const menuTemplate = getApplicationMenu(); // Create our menu entries so that we can use MAC shortcuts Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate)); } function sendStatusToWindow(progressObj) { let log_message = "Download speed: " + progressObj.bytesPerSecond; log_message = log_message + ' - Downloaded ' + Math.round(progressObj.percent) + '%'; log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')'; log.info(log_message); // sending message to ipcRenderer can be done as well but not sure where and how to display it // using the title bar instead // mainWindow.webContents.send('downloading', Math.round(progressObj.percent)); mainWindow.setTitle(`Nault - ${autoUpdater.currentVersion} - Downloading Update: ${Math.round(progressObj.percent)} %`); } // run only one app const appLock = app.requestSingleInstanceLock(); if (!appLock) { app.quit(); } else { app.on('ready', () => { // Once the app is ready, launch the wallet window createWindow(); // on windows, handle deep links on launch if (process.platform === 'win32') { const deeplink = findDeeplink(process.argv); if (deeplink) handleDeeplink(deeplink); } // Check for any updates on GitHub checkForUpdates(); }); // Refocus the window if the user attempts to open Nault while it is already open app.on('second-instance', (event, argv, workingDirectory) => { if (mainWindow) { // Detect on windows when the application has been loaded using a nano: link, send it to the wallet to load if (process.platform === 'win32') { const deeplink = findDeeplink(argv); if (deeplink) handleDeeplink(deeplink); } if (mainWindow.isMinimized()) { mainWindow.restore(); } mainWindow.focus(); } }); // Detect on macos when the application has been loaded using a nano: link, send it to the wallet to load app.on('will-finish-launching', () => { app.on('open-url', (event, eventpath) => { if (!mainWindow) { createWindow(); } handleDeeplink(eventpath); event.preventDefault(); }); }); // Quit when all windows are closed. app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', function () { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow(); } }); } function checkForUpdates() { autoUpdater.checkForUpdates(); } // Build up the menu bar options based on platform function getApplicationMenu() { const template: any = [ { label: 'Edit', submenu: [ {role: 'undo'}, {role: 'redo'}, {type: 'separator'}, {role: 'cut'}, {role: 'copy'}, {role: 'paste'}, {role: 'pasteandmatchstyle'}, {role: 'delete'}, {role: 'selectall'} ] }, { label: 'View', submenu: [ {role: 'reload'}, {role: 'forcereload'}, {role: 'toggledevtools'}, {type: 'separator'}, {role: 'resetzoom'}, {role: 'zoomin'}, {role: 'zoomout'}, {type: 'separator'}, {role: 'togglefullscreen'} ] }, { role: 'window', submenu: [ {role: 'minimize'}, {role: 'close'} ] }, { role: 'help', submenu: [ { label: 'Nault Help Docs', click () { loadExternal('https://docs.nault.cc/'); } }, { label: 'Reddit (r/nanocurrency)', click () { loadExternal('https://www.reddit.com/r/nanocurrency'); } }, { label: 'Discord (#nault)', click () { loadExternal('https://discord.nanocenter.org/'); } }, {type: 'separator'}, { label: 'View GitHub', click () { loadExternal('https://github.com/Nault/Nault'); } }, { label: 'Submit a bug report', click () { loadExternal('https://github.com/Nault/Nault/issues/new'); } }, { label: 'Release notes', click () { loadExternal('https://github.com/Nault/Nault/releases'); } }, {type: 'separator'}, { label: `Check for Updates`, click (menuItem, browserWindow) { checkForUpdates(); } }, ] } ]; if (process.platform === 'darwin') { template.unshift({ label: 'Nault', submenu: [ {role: 'about'}, {type: 'separator'}, { label: `Check for Updates`, click (menuItem, browserWindow) { checkForUpdates(); } }, {type: 'separator'}, // {role: 'services', submenu: []}, // {type: 'separator'}, {role: 'hide'}, {role: 'hideothers'}, {role: 'unhide'}, {type: 'separator'}, {role: 'quit'} ] }); // Edit menu template[1].submenu.push( {type: 'separator'}, { label: 'Speech', submenu: [ {role: 'startspeaking'}, {role: 'stopspeaking'} ] } ); // Window menu template[3].submenu = [ {role: 'close'}, {role: 'minimize'}, {role: 'zoom'}, {type: 'separator'}, {role: 'front'} ]; } return template; } function loadExternal(externalurl: string) { shell.openExternal(externalurl); } let deeplinkReady = false; ipcMain.once('deeplink-ready', () => deeplinkReady = true); function handleDeeplink(deeplink: string) { if (!deeplinkReady) { ipcMain.once('deeplink-ready', (e) => { mainWindow.webContents.send('deeplink', deeplink); }); } else { mainWindow.webContents.send('deeplink', deeplink); } } function findDeeplink(argv: string[]) { const nano_scheme = new RegExp(`^(${nano_schemes.join('|')}):.+$`, 'g'); return argv.find((s) => nano_scheme.test(s)); }
the_stack
import * as ethUtil from 'ethereumjs-util'; import { recoverTypedSignature, signTypedData, TypedDataUtils, typedSignatureHash, SignTypedDataVersion, } from './sign-typed-data'; const privateKey = Buffer.from( '4af1bceebf7f3634ec3cff8a2c38e51178d5d4ce585c52d6043e5e2cc3418bb0', 'hex', ); const encodeDataExamples = { // dynamic types supported by EIP-712: bytes: [10, '10', '0x10', Buffer.from('10', 'utf8')], string: [ 'Hello!', '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', '0xabcd', '😁', 10, ], // atomic types supported by EIP-712: address: [ '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', '0x0', 10, 'bBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', Number.MAX_SAFE_INTEGER, ], bool: [true, false, 'true', 'false', 0, 1, -1, Number.MAX_SAFE_INTEGER], bytes1: [ '0x10', 10, 0, 1, -1, Number.MAX_SAFE_INTEGER, Buffer.from('10', 'utf8'), ], bytes32: [ '0x10', 10, 0, 1, -1, Number.MAX_SAFE_INTEGER, Buffer.from('10', 'utf8'), ], int8: [0, '0', '0x0', 255, -255], int256: [0, '0', '0x0', Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], uint8: [0, '0', '0x0', 255], uint256: [0, '0', '0x0', Number.MAX_SAFE_INTEGER], // atomic types not supported by EIP-712: int: [0, '0', '0x0', Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], // interpreted as `int256` by `ethereumjs-abi` uint: [0, '0', '0x0', Number.MAX_SAFE_INTEGER], // interpreted as `uint256` by `ethereumjs-abi` // `fixed` and `ufixed` types omitted because their encoding in `ethereumjs-abi` is very broken at the moment. // `function` type omitted because it is not supported by `ethereumjs-abi`. }; const encodeDataErrorExamples = { address: [ { input: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB0', errorMessage: 'Supplied uint exceeds width: 160 vs 164', }, ], int8: [{ input: '256', errorMessage: 'Supplied int exceeds width: 8 vs 9' }], uint: [{ input: -1, errorMessage: 'Supplied uint is negative' }], uint8: [{ input: -1, errorMessage: 'Supplied uint is negative' }], uint256: [{ input: -1, errorMessage: 'Supplied uint is negative' }], bytes1: [ { input: 'a', errorMessage: 'Cannot convert string to buffer' }, { input: 'test', errorMessage: 'Cannot convert string to buffer' }, ], bytes32: [ { input: 'a', errorMessage: 'Cannot convert string to buffer' }, { input: 'test', errorMessage: 'Cannot convert string to buffer' }, ], }; // Union of all types from both sets of examples const allExampleTypes = [ ...new Set( Object.keys(encodeDataExamples).concat( Object.keys(encodeDataErrorExamples), ), ), ]; describe('TypedDataUtils.encodeData', function () { // The `TypedDataUtils.encodeData` function accepts most Solidity data types, as well as custom // data types defined by the types provided. The supported Solidity data types are divided into // two types: atomic and dynamic. Atomic types are of a fixed size (e.g. `int8`), whereas dynamic // types can vary in size (e.g. strings, bytes). We also test arrays of each of these types. // // The tests below test all boundary conditions of each Solidity type. These tests are // automatically constructed using the example data above ("encodeDataExamples" and // "encodeDataErrorExamples"). The behaviour for `null` and `undefined` inputs does vary between // atomic, dynamic, and custom types though, so each of these three categories is tested // separately with `null` and `undefined` input. Lastly, there are more tests for various other // edge cases. // // The behavior differs between V3 and V4, so each test has been run for each version. We also // have a block of tests to verify that signatures that match between V3 and V4 remain identical, // and that signatures that differ between V3 and V4 remain different. // // To make reading and maintaining these tests easier, the order will be the same throughout all // 4 of these test suites. Here is a table showing that order, as well as the compatibility of // each input type with V3 and V4 `encodeData`. The table also shows whether the signature is // identical between versions in the cases where the input can be encoded in both versions. // // | Input type | V3 | V4 | Matching Signatures | // | ---------------------------------------------------- | -- | -- | ------------------- | // | Auto-generated tests from the example data | Y | Y | Y | // | Arrays using the example data | N | Y | | // | Custom type | Y | Y | Y | // | Recursive custom type | Y | Y | N | // | Custom type array | N | Y | | // | Custom type with extra properties | Y | Y | Y | // | Atomic type with `null` input | N | N | | // | Atomic type with `undefined` input | Y | N | | // | Dynamic type with `null` input | Y | Y | Y | // | Dynamic type with `undefined` input | Y | N | | // | Custom type with `null` input | N | Y | | // | Custom type with `undefined` input | Y | Y | N | // | Functions | N | N | | // | Unrecognized primary type | N | N | | // | Unrecognized non-primary type | N | N | | // | Extra type specified that isn't used by primary type | Y | Y | Y | // // Note that these tests should mirror the `TypedDataUtils.hashStruct` tests. The `hashStruct` // function just calls `encodeData` and hashes the result. describe('V3', function () { describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should encode "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect( TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); } // Test all examples that crash const errorInputs = encodeDataErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to encode "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow(errorMessage); }, ); } _it( `should fail to encode array of all ${type} example data`, function () { const types = { Message: [{ name: 'data', type: `${type}[]` }], }; const message = { data: inputs }; _expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow( 'Arrays are unimplemented in encodeData; use V4 extension', ); }, ); }); } }); it('should encode data with custom type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data with a recursive data type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when trying to encode a custom type array', function () { const types = { Message: [{ name: 'data', type: 'string[]' }], }; const message = { data: ['1', '2', '3'] }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('Arrays are unimplemented in encodeData; use V4 extension'); }); it('should ignore extra unspecified message properties', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalSignature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const messageWithExtraProperties = { ...message, foo: 'bar' }; const signatureWithExtraProperties = TypedDataUtils.encodeData( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V3, ).toString('hex'); expect(originalSignature).toBe(signatureWithExtraProperties); }); it('should throw an error when an atomic property is set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: null, }; expect(() => TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow(`Cannot read property 'toArray' of null`); }); it('should encode data with an atomic property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: undefined, }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data with a dynamic property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data with a dynamic property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: undefined, }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when a custom type property is set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { to: null, from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; expect(() => TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow(`Cannot read property 'name' of null`); }); it('should encode data with a custom type property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: undefined, contents: 'Hello, Bob!', }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when trying to encode a function', function () { const types = { Message: [{ name: 'data', type: 'function' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('Unsupported or invalid type: function'); }); it('should throw an error when trying to encode with a missing primary type definition', function () { const types = {}; const message = { data: 'test' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('No type definition specified: Message'); }); it('should throw an error when trying to encode an unrecognized type', function () { const types = { Message: [{ name: 'data', type: 'foo' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('Unsupported or invalid type: foo'); }); it('should encode data when given extraneous types', function () { const types = { Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect( TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data when called unbound', function () { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const primaryType = 'Message'; const { hashStruct } = TypedDataUtils; expect( hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); }); describe('V4', function () { describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should encode "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect( TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); } // Test all examples that crash const errorInputs = encodeDataErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to encode "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow(errorMessage); }, ); } _it(`should encode array of all ${type} example data`, function () { const types = { Message: [{ name: 'data', type: `${type}[]` }], }; const message = { data: inputs }; _expect( TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); }); } }); it('should encode data with custom type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data with a recursive data type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data with a custom data type array', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address[]' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person[]' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: [ '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', '0xDD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', ], }, to: [ { name: 'Bob', wallet: ['0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB'], }, ], contents: 'Hello, Bob!', }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should ignore extra unspecified message properties', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalSignature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); const messageWithExtraProperties = { ...message, foo: 'bar' }; const signatureWithExtraProperties = TypedDataUtils.encodeData( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V4, ).toString('hex'); expect(originalSignature).toBe(signatureWithExtraProperties); }); it('should throw an error when an atomic property is set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: null, }; expect(() => TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow(`Cannot read property 'toArray' of null`); }); it('should throw an error when an atomic property is set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: undefined, }; expect(() => TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('missing value for field length of type int32'); }); it('should encode data with a dynamic property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when a dynamic property is set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: undefined, }; expect(() => TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('missing value for field contents of type string'); }); it('should encode data with a custom type property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { to: null, from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data with a custom type property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: undefined, contents: 'Hello, Bob!', }; expect( TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when trying to encode a function', function () { const types = { Message: [{ name: 'data', type: 'function' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('Unsupported or invalid type: function'); }); it('should throw an error when trying to encode with a missing primary type definition', function () { const types = {}; const message = { data: 'test' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('No type definition specified: Message'); }); it('should throw an error when trying to encode an unrecognized type', function () { const types = { Message: [{ name: 'data', type: 'foo' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('Unsupported or invalid type: foo'); }); it('should encode data when given extraneous types', function () { const types = { Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect( TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should encode data when called unbound', function () { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const primaryType = 'Message'; const { encodeData } = TypedDataUtils; expect( encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); }); // This test suite covers all cases where data should be encoded identically // on V3 and V4 describe('V3/V4 identical encodings', function () { describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should encode "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; const v3Signature = TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'); _expect(v3Signature).toBe(v4Signature); }); } }); } }); it('should encode data with custom type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const v3Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).toBe(v4Signature); }); it('should ignore extra unspecified message properties', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalV3Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const originalV4Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); const messageWithExtraProperties = { ...message, foo: 'bar' }; const v3signatureWithExtraProperties = TypedDataUtils.encodeData( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V3, ).toString('hex'); const v4signatureWithExtraProperties = TypedDataUtils.encodeData( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V4, ).toString('hex'); expect(originalV3Signature).toBe(originalV4Signature); expect(v3signatureWithExtraProperties).toBe( v4signatureWithExtraProperties, ); }); it('should encode data with a dynamic property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; const v3Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).toBe(v4Signature); }); it('should encode data when given extraneous types', function () { const types = { Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const v3Signature = TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).toBe(v4Signature); }); }); // This test suite covers all cases where data should be encoded differently // on V3 and V4 describe('V3/V4 encoding differences', () => { // Recursive data structures are encoded differently because V4 encodes // missing custom typed properties as 0 byte32 rather than omitting it, // and all recursive data structures must include a missing custom typed // property (the recursive one), or they'd be infinitely large or cyclic. // And cyclic data structures are not supported. it('should encode data with recursive data differently', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; const v3Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).not.toBe(v4Signature); }); // Missing custom type properties are omitted in V3, but encoded as 0 (bytes32) in V4 it('should encode missing custom type properties differently', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; const v3Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.encodeData( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).not.toBe(v4Signature); }); }); it('should throw if passed an invalid version', () => { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, 'V0' as any, ).toString('hex'), ).toThrow('Invalid version'); }); it('should throw if passed a version that is not allowed', () => { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect(() => TypedDataUtils.encodeData( 'Message', message, types, SignTypedDataVersion.V1 as any, ).toString('hex'), ).toThrow('SignTypedDataVersion not allowed'); }); }); describe('TypedDataUtils.hashStruct', function () { // These tests mirror the `TypedDataUtils.encodeData` tests. The same inputs are expected. // See the `encodeData` test comments for more information about these test cases. describe('V3', function () { describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should hash "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect( TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); } // Test all examples that crash const errorInputs = encodeDataErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to hash "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow(errorMessage); }, ); } _it( `should fail to hash array of all ${type} example data`, function () { const types = { Message: [{ name: 'data', type: `${type}[]` }], }; const message = { data: inputs }; _expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow( 'Arrays are unimplemented in encodeData; use V4 extension', ); }, ); }); } }); it('should hash data with custom type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data with a recursive data type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when trying to hash a custom type array', function () { const types = { Message: [{ name: 'data', type: 'string[]' }], }; const message = { data: ['1', '2', '3'] }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('Arrays are unimplemented in encodeData; use V4 extension'); }); it('should ignore extra unspecified message properties', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalSignature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const messageWithExtraProperties = { ...message, foo: 'bar' }; const signatureWithExtraProperties = TypedDataUtils.hashStruct( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V3, ).toString('hex'); expect(originalSignature).toBe(signatureWithExtraProperties); }); it('should throw an error when an atomic property is set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: null, }; expect(() => TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow(`Cannot read property 'toArray' of null`); }); it('should hash data with an atomic property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: undefined, }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data with a dynamic property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data with a dynamic property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: undefined, }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when a custom type property is set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { to: null, from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; expect(() => TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow(`Cannot read property 'name' of null`); }); it('should hash data with a custom type property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: undefined, contents: 'Hello, Bob!', }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when trying to hash a function', function () { const types = { Message: [{ name: 'data', type: 'function' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('Unsupported or invalid type: function'); }); it('should throw an error when trying to hash with a missing primary type definition', function () { const types = {}; const message = { data: 'test' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('No type definition specified: Message'); }); it('should throw an error when trying to hash an unrecognized type', function () { const types = { Message: [{ name: 'data', type: 'foo' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toThrow('Unsupported or invalid type: foo'); }); it('should hash data when given extraneous types', function () { const types = { Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect( TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data when called unbound', function () { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const primaryType = 'Message'; const { hashStruct } = TypedDataUtils; expect( hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'), ).toMatchSnapshot(); }); }); describe('V4', function () { describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should hash "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect( TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); } // Test all examples that crash const errorInputs = encodeDataErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to hash "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; _expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow(errorMessage); }, ); } _it(`should hash array of all ${type} example data`, function () { const types = { Message: [{ name: 'data', type: `${type}[]` }], }; const message = { data: inputs }; _expect( TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); }); } }); it('should hash data with custom type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data with a recursive data type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data with a custom data type array', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address[]' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person[]' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: [ '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', '0xDD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', ], }, to: [ { name: 'Bob', wallet: ['0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB'], }, ], contents: 'Hello, Bob!', }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should ignore extra unspecified message properties', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalSignature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); const messageWithExtraProperties = { ...message, foo: 'bar' }; const signatureWithExtraProperties = TypedDataUtils.hashStruct( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V4, ).toString('hex'); expect(originalSignature).toBe(signatureWithExtraProperties); }); it('should throw an error when an atomic property is set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: null, }; expect(() => TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow(`Cannot read property 'toArray' of null`); }); it('should throw an error when an atomic property is set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: undefined, }; expect(() => TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('missing value for field length of type int32'); }); it('should hash data with a dynamic property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when a dynamic property is set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: undefined, }; expect(() => TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('missing value for field contents of type string'); }); it('should hash data with a custom type property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { to: null, from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data with a custom type property set to undefined', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: undefined, contents: 'Hello, Bob!', }; expect( TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should throw an error when trying to hash a function', function () { const types = { Message: [{ name: 'data', type: 'function' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('Unsupported or invalid type: function'); }); it('should throw an error when trying to hash with a missing primary type definition', function () { const types = {}; const message = { data: 'test' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('No type definition specified: Message'); }); it('should throw an error when trying to hash an unrecognized type', function () { const types = { Message: [{ name: 'data', type: 'foo' }], }; const message = { data: 'test' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toThrow('Unsupported or invalid type: foo'); }); it('should hash data when given extraneous types', function () { const types = { Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect( TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); it('should hash data when called unbound', function () { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const primaryType = 'Message'; const { hashStruct } = TypedDataUtils; expect( hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'), ).toMatchSnapshot(); }); }); // This test suite covers all cases where data should be encoded identically // on V3 and V4 describe('V3/V4 identical encodings', function () { describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should hash "${input}" (type "${inputType}")`, function () { const types = { Message: [{ name: 'data', type }], }; const message = { data: input }; const v3Signature = TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'); _expect(v3Signature).toBe(v4Signature); }); } }); } }); it('should hash data with custom type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const v3Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).toBe(v4Signature); }); it('should ignore extra unspecified message properties', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalV3Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const originalV4Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); const messageWithExtraProperties = { ...message, foo: 'bar' }; const v3signatureWithExtraProperties = TypedDataUtils.hashStruct( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V3, ).toString('hex'); const v4signatureWithExtraProperties = TypedDataUtils.hashStruct( primaryType, messageWithExtraProperties, types, SignTypedDataVersion.V4, ).toString('hex'); expect(originalV3Signature).toBe(originalV4Signature); expect(v3signatureWithExtraProperties).toBe( v4signatureWithExtraProperties, ); }); it('should hash data with a dynamic property set to null', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; const v3Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).toBe(v4Signature); }); it('should hash data when given extraneous types', function () { const types = { Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const v3Signature = TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).toBe(v4Signature); }); }); // This test suite covers all cases where data should be encoded differently // on V3 and V4 describe('V3/V4 encoding differences', () => { // Recursive data structures are encoded differently because V4 encodes // missing custom typed properties as 0 byte32 rather than omitting it, // and all recursive data structures must include a missing custom typed // property (the recursive one), or they'd be infinitely large or cyclic. // And cyclic data structures are not supported. it('should hash data with recursive data differently', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; const v3Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).not.toBe(v4Signature); }); // Missing custom type properties are omitted in V3, but encoded as 0 (bytes32) in V4 it('should hash missing custom type properties differently', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; const v3Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V3, ).toString('hex'); const v4Signature = TypedDataUtils.hashStruct( primaryType, message, types, SignTypedDataVersion.V4, ).toString('hex'); expect(v3Signature).not.toBe(v4Signature); }); }); it('should throw if passed an invalid version', () => { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, 'V0' as any, ).toString('hex'), ).toThrow('Invalid version'); }); it('should throw if passed a version that is not allowed', () => { const types = { Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; expect(() => TypedDataUtils.hashStruct( 'Message', message, types, SignTypedDataVersion.V1 as any, ).toString('hex'), ).toThrow('SignTypedDataVersion not allowed'); }); }); describe('TypedDataUtils.encodeType', () => { // Note that these tests should mirror the `TypedDataUtils.hashType` tests. The `hashType` // function just calls `encodeType` and hashes the result. it('should encode simple type', () => { const types = { Person: [{ name: 'name', type: 'string' }], }; const primaryType = 'Person'; expect(TypedDataUtils.encodeType(primaryType, types)).toMatchInlineSnapshot( `"Person(string name)"`, ); }); it('should encode complex type', () => { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person[]' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; expect(TypedDataUtils.encodeType(primaryType, types)).toMatchInlineSnapshot( `"Mail(Person from,Person[] to,string contents)Person(string name,address wallet)"`, ); }); it('should encode recursive type', () => { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; expect(TypedDataUtils.encodeType(primaryType, types)).toMatchInlineSnapshot( `"Mail(Person from,Person to,string contents,Mail replyTo)Person(string name,address wallet)"`, ); }); it('should encode unrecognized non-primary types', () => { const types = { Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; expect(TypedDataUtils.encodeType(primaryType, types)).toMatchInlineSnapshot( `"Mail(Person from,Person to,string contents)"`, ); }); it('should throw if primary type is missing', () => { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], }; const primaryType = 'Mail'; expect(() => TypedDataUtils.encodeType(primaryType, types)).toThrow( 'No type definition specified: Mail', ); }); it('should encode type when called unbound', function () { const types = { Message: [{ name: 'data', type: 'string' }], }; const primaryType = 'Message'; const { encodeType } = TypedDataUtils; expect(encodeType(primaryType, types)).toMatchInlineSnapshot( `"Message(string data)"`, ); }); }); describe('TypedDataUtils.hashType', () => { // These tests mirror the `TypedDataUtils.encodeType` tests. The same inputs are expected. it('should hash simple type', () => { const types = { Person: [{ name: 'name', type: 'string' }], }; const primaryType = 'Person'; expect( TypedDataUtils.hashType(primaryType, types).toString('hex'), ).toMatchInlineSnapshot( `"fcbb73369ebb221abfdc626fdec0be9ca48ad89ef757b9a76eb7b31ddd261338"`, ); }); it('should hash complex type', () => { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person[]' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; expect( TypedDataUtils.hashType(primaryType, types).toString('hex'), ).toMatchInlineSnapshot( `"dd57d9596af52b430ced3d5b52d4e3d5dccfdf3e0572db1dcf526baad311fbd1"`, ); }); it('should hash recursive type', () => { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; expect( TypedDataUtils.hashType(primaryType, types).toString('hex'), ).toMatchInlineSnapshot( `"66658e9662034bcd21df657297dab8ba47f0ae05dd8aa253cc935d9aacfd9d10"`, ); }); it('should hash unrecognized non-primary types', () => { const types = { Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; expect( TypedDataUtils.hashType(primaryType, types).toString('hex'), ).toMatchInlineSnapshot( `"c0aee50a43b64ca632347f993c5a39cbddcae6ae329a7a111357622dc88dc1fb"`, ); }); it('should throw if primary type is missing', () => { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], }; const primaryType = 'Mail'; expect(() => TypedDataUtils.hashType(primaryType, types).toString('hex'), ).toThrow('No type definition specified: Mail'); }); it('should hash type when called unbound', function () { const types = { Message: [{ name: 'data', type: 'string' }], }; const primaryType = 'Message'; const { hashType } = TypedDataUtils; expect(hashType(primaryType, types).toString('hex')).toMatchInlineSnapshot( `"cddf41b07426e1a761f3da57e35474ae3deaa5b596306531f651c6dc1321e4fd"`, ); }); }); describe('TypedDataUtils.findTypeDependencies', () => { it('should return type dependencies of a simple type', function () { const types = { Person: [{ name: 'name', type: 'string' }], }; const primaryType = 'Person'; expect( TypedDataUtils.findTypeDependencies(primaryType, types), ).toStrictEqual(new Set(['Person'])); }); it('should return type dependencies of an array type', function () { const types = { Person: [{ name: 'name', type: 'string' }], }; const primaryType = 'Person[]'; expect( TypedDataUtils.findTypeDependencies(primaryType, types), ).toStrictEqual(new Set(['Person'])); }); it('should return type dependencies of a complex type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person[]' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; expect( TypedDataUtils.findTypeDependencies(primaryType, types), ).toStrictEqual(new Set(['Mail', 'Person'])); }); it('should return type dependencies of a recursive type', function () { const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person[]' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; expect( TypedDataUtils.findTypeDependencies(primaryType, types), ).toStrictEqual(new Set(['Mail', 'Person'])); }); it('should return empty set if primary type is missing', function () { const primaryType = 'Person'; expect(TypedDataUtils.findTypeDependencies(primaryType, {})).toStrictEqual( new Set(), ); }); it('should return type dependencies when called unbound', function () { const types = { Person: [{ name: 'name', type: 'string' }], }; const primaryType = 'Person'; const { findTypeDependencies } = TypedDataUtils; expect(findTypeDependencies(primaryType, types)).toStrictEqual( new Set(['Person']), ); }); }); describe('TypedDataUtils.sanitizeData', function () { it('should return correctly formatted data unchanged', function () { const typedMessage = { domain: {}, message: {}, primaryType: 'Person' as const, types: { EIP712Domain: [{ name: 'name', type: 'string' }], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], }, }; const sanitizedTypedMessage = TypedDataUtils.sanitizeData(typedMessage); expect(sanitizedTypedMessage).toStrictEqual(typedMessage); }); it("should add `EIP712Domain` to `types` if it's missing", function () { const typedMessage = { domain: {}, message: {}, primaryType: 'Person' as const, types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], }, }; const sanitizedTypedMessage = TypedDataUtils.sanitizeData( typedMessage as any, ); expect(sanitizedTypedMessage).toStrictEqual({ ...typedMessage, types: { ...typedMessage.types, EIP712Domain: [] }, }); }); it('should sanitize empty object', function () { const typedMessage = {}; const sanitizedTypedMessage = TypedDataUtils.sanitizeData( typedMessage as any, ); expect(sanitizedTypedMessage).toStrictEqual({}); }); it('should omit unrecognized properties', function () { const expectedMessage = { domain: {}, message: {}, primaryType: 'Person' as const, types: { EIP712Domain: [{ name: 'name', type: 'string' }], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], }, }; const typedMessage = { ...expectedMessage, extraStuff: 'Extra stuff' }; const sanitizedTypedMessage = TypedDataUtils.sanitizeData(typedMessage); expect(sanitizedTypedMessage).toStrictEqual(expectedMessage); }); it('should sanitize data when called unbound', function () { const typedMessage = { domain: {}, message: {}, primaryType: 'Person' as const, types: { EIP712Domain: [{ name: 'name', type: 'string' }], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], }, }; const { sanitizeData } = TypedDataUtils; const sanitizedTypedMessage = sanitizeData(typedMessage); expect(sanitizedTypedMessage).toStrictEqual(typedMessage); }); }); describe('TypedDataUtils.eip712Hash', function () { describe('V3', function () { it('should hash a minimal valid typed message', function () { const hash = TypedDataUtils.eip712Hash( // This represents the most basic "typed message" that is valid according to our types. // It's not a very useful message (it's totally empty), but it's complete according to the // spec. { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V3, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('minimal typed message hash should be identical to minimal valid typed message hash', function () { const minimalHash = TypedDataUtils.eip712Hash( // This tests that when the mandatory fields `domain`, `message`, and `types.EIP712Domain` // are omitted, the result is the same as if they were included but empty. { types: {}, primaryType: 'EIP712Domain', } as any, SignTypedDataVersion.V3, ); const minimalValidHash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V3, ); expect(minimalHash.toString('hex')).toBe( minimalValidHash.toString('hex'), ); }); it('should ignore extra top-level properties', function () { const minimalValidHash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V3, ); const extraPropertiesHash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, extra: 'stuff', moreExtra: 1, } as any, SignTypedDataVersion.V3, ); expect(minimalValidHash.toString('hex')).toBe( extraPropertiesHash.toString('hex'), ); }); it('should hash a typed message with a domain separator that uses all fields', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: {}, }, SignTypedDataVersion.V3, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should hash a typed message with extra domain seperator fields', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, SignTypedDataVersion.V3, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should hash a typed message with only custom domain seperator fields', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'customName', type: 'string', }, { name: 'customVersion', type: 'string', }, { name: 'customChainId', type: 'uint256', }, { name: 'customVerifyingContract', type: 'address', }, { name: 'customSalt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { customName: 'example.metamask.io', customVersion: '1', customChainId: 1, customVerifyingContract: '0x0000000000000000000000000000000000000000', customSalt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, SignTypedDataVersion.V3, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should hash a typed message with data', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'Message', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: { data: 'Hello!', }, }, SignTypedDataVersion.V3, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should ignore message if the primary type is EIP712Domain', function () { const hashWithMessage = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: { data: 'Hello!', }, }, SignTypedDataVersion.V3, ); const hashWithoutMessage = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: {}, }, SignTypedDataVersion.V3, ); expect(hashWithMessage.toString('hex')).toBe( hashWithoutMessage.toString('hex'), ); }); it('should hash a minimal valid typed message when called unbound', function () { const { eip712Hash } = TypedDataUtils; const hash = eip712Hash( // This represents the most basic "typed message" that is valid according to our types. // It's not a very useful message (it's totally empty), but it's complete according to the // spec. { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V3, ); expect(hash.toString('hex')).toMatchSnapshot(); }); }); describe('V4', function () { it('should hash a minimal valid typed message', function () { // This represents the most basic "typed message" that is valid according to our types. // It's not a very useful message (it's totally empty), but it's complete according to the // spec. const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V4, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('minimal typed message hash should be identical to minimal valid typed message hash', function () { // This tests that when the mandatory fields `domain`, `message`, and `types.EIP712Domain` // are omitted, the result is the same as if they were included but empty. const minimalHash = TypedDataUtils.eip712Hash( { types: {}, primaryType: 'EIP712Domain', } as any, SignTypedDataVersion.V4, ); const minimalValidHash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V4, ); expect(minimalHash.toString('hex')).toBe( minimalValidHash.toString('hex'), ); }); it('should ignore extra top-level properties', function () { const minimalValidHash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V4, ); const extraPropertiesHash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, extra: 'stuff', moreExtra: 1, } as any, SignTypedDataVersion.V4, ); expect(minimalValidHash.toString('hex')).toBe( extraPropertiesHash.toString('hex'), ); }); it('should hash a typed message with a domain separator that uses all fields.', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: {}, }, SignTypedDataVersion.V4, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should hash a typed message with extra domain seperator fields', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, SignTypedDataVersion.V4, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should hash a typed message with only custom domain seperator fields', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'customName', type: 'string', }, { name: 'customVersion', type: 'string', }, { name: 'customChainId', type: 'uint256', }, { name: 'customVerifyingContract', type: 'address', }, { name: 'customSalt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { customName: 'example.metamask.io', customVersion: '1', customChainId: 1, customVerifyingContract: '0x0000000000000000000000000000000000000000', customSalt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, SignTypedDataVersion.V4, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should hash a typed message with data', function () { const hash = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'Message', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: { data: 'Hello!', }, }, SignTypedDataVersion.V4, ); expect(hash.toString('hex')).toMatchSnapshot(); }); it('should ignore message if the primary type is EIP712Domain', function () { const hashWithMessage = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: { data: 'Hello!', }, }, SignTypedDataVersion.V4, ); const hashWithoutMessage = TypedDataUtils.eip712Hash( { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: {}, }, SignTypedDataVersion.V4, ); expect(hashWithMessage.toString('hex')).toBe( hashWithoutMessage.toString('hex'), ); }); it('should hash a minimal valid typed message when called unbound', function () { const { eip712Hash } = TypedDataUtils; // This represents the most basic "typed message" that is valid according to our types. // It's not a very useful message (it's totally empty), but it's complete according to the // spec. const hash = eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V4, ); expect(hash.toString('hex')).toMatchSnapshot(); }); }); it('should throw if passed an invalid version', () => { expect(() => TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, 'V0' as any, ), ).toThrow('Invalid version'); }); it('should throw if passed a version that is not allowed', () => { expect(() => TypedDataUtils.eip712Hash( { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, SignTypedDataVersion.V1 as any, ), ).toThrow('SignTypedDataVersion not allowed'); }); }); // Comments starting with "V1:" highlight differences relative to V3 and 4. const signTypedDataV1Examples = { // dynamic types supported by EIP-712: bytes: [10, '10', '0x10', Buffer.from('10', 'utf8')], string: [ 'Hello!', '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', '0xabcd', '😁', ], // atomic types supported by EIP-712: address: [ '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', // V1: No apparent maximum address length '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbBbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', '0x0', 10, Number.MAX_SAFE_INTEGER, ], bool: [true, false, 'true', 'false', 0, 1, -1, Number.MAX_SAFE_INTEGER], bytes1: [ '0x10', 10, 0, 1, -1, Number.MAX_SAFE_INTEGER, Buffer.from('10', 'utf8'), ], bytes32: [ '0x10', 10, 0, 1, -1, Number.MAX_SAFE_INTEGER, Buffer.from('10', 'utf8'), ], int8: [0, '0', '0x0', 255, -255], int256: [0, '0', '0x0', Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], uint8: [0, '0', '0x0', 255, -255], uint256: [ 0, '0', '0x0', Number.MAX_SAFE_INTEGER, // V1: Negative unsigned integers Number.MIN_SAFE_INTEGER, ], // atomic types not supported by EIP-712: int: [0, '0', '0x0', Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], // interpreted as `int256` by `ethereumjs-abi` uint: [0, '0', '0x0', Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], // interpreted as `uint256` by `ethereumjs-abi` // `fixed` and `ufixed` types omitted because their encoding in `ethereumjs-abi` is very broken at the moment. // `function` type omitted because it is not supported by `ethereumjs-abi`. }; const signTypedDataV1ErrorExamples = { string: [ { // V1: Does not accept numbers as strings (arguably correctly). input: 10, errorMessage: 'The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type number (10)', }, ], address: [ { // V1: Unprefixed addresses are not accepted. input: 'bBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', errorMessage: 'Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given:', }, ], int8: [{ input: '256', errorMessage: 'Supplied int exceeds width: 8 vs 9' }], bytes1: [ { input: 'a', errorMessage: 'Cannot convert string to buffer' }, { input: 'test', errorMessage: 'Cannot convert string to buffer' }, ], bytes32: [ { input: 'a', errorMessage: 'Cannot convert string to buffer' }, { input: 'test', errorMessage: 'Cannot convert string to buffer' }, ], }; // Union of all types from both sets of examples const allSignTypedDataV1ExampleTypes = [ ...new Set( Object.keys(encodeDataExamples).concat( Object.keys(encodeDataErrorExamples), ), ), ]; describe('typedSignatureHash', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allSignTypedDataV1ExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = signTypedDataV1Examples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should hash "${input}" (type "${inputType}")`, function () { const typedData = [{ type, name: 'message', value: input }]; _expect(typedSignatureHash(typedData)).toMatchSnapshot(); }); } const errorInputs = signTypedDataV1ErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to hash "${input}" (type "${inputType}")`, function () { const typedData = [{ type, name: 'message', value: input }]; _expect(() => typedSignatureHash(typedData)).toThrow(errorMessage); }, ); } }); } const invalidTypedMessages = [ { input: [], errorMessage: 'Expect argument to be non-empty array', label: 'an empty array', }, { input: 42, errorMessage: 'Expect argument to be non-empty array', label: 'a number', }, { input: null, errorMessage: "Cannot use 'in' operator to search for 'length' in null", label: 'null', }, { input: undefined, errorMessage: 'Expect argument to be non-empty array', label: 'undefined', }, { input: [ { type: 'jocker', name: 'message', value: 'Hi, Alice!', }, ], errorMessage: 'Unsupported or invalid type: jocker', label: 'an unrecognized type', }, { input: [ { name: 'message', value: 'Hi, Alice!', }, ], errorMessage: "Cannot read property 'startsWith' of undefined", label: 'no type', }, { input: [ { type: 'string', value: 'Hi, Alice!', }, ], errorMessage: 'Expect argument to be non-empty array', label: 'no name', }, ]; for (const { input, errorMessage, label } of invalidTypedMessages) { _it(`should throw when given ${label}`, function () { _expect(() => typedSignatureHash(input as any)).toThrow(errorMessage); }); } it('should hash a message with multiple entries', function () { const typedData = [ { type: 'string', name: 'message', value: 'Hi, Alice!', }, { type: 'uint8', name: 'value', value: 10, }, ]; expect(typedSignatureHash(typedData)).toMatchInlineSnapshot( `"0xf7ad23226db5c1c00ca0ca1468fd49c8f8bbc1489bc1c382de5adc557a69c229"`, ); }); }); describe('signTypedData', function () { describe('V1', function () { it('should throw when given an empty array', function () { expect(() => signTypedData({ privateKey, data: [], version: SignTypedDataVersion.V1, }), ).toThrow('Expect argument to be non-empty array'); }); describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified // variables from the outer scope" which can be dangerous to reference in // a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allSignTypedDataV1ExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = signTypedDataV1Examples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should sign "${input}" (type "${inputType}")`, function () { _expect( signTypedData({ privateKey, data: [{ name: 'data', type, value: input }], version: SignTypedDataVersion.V1, }), ).toMatchSnapshot(); }); } // Test all examples that crash const errorInputs = signTypedDataV1ErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to sign "${input}" (type "${inputType}")`, function () { _expect(() => signTypedData({ privateKey, data: [{ name: 'data', type, value: input }], version: SignTypedDataVersion.V1, }), ).toThrow(errorMessage); }, ); } if (type === 'bytes') { _it( `should fail to sign array of all ${type} example data`, function () { _expect(() => signTypedData({ privateKey, data: [{ name: 'data', type: `${type}[]`, value: inputs }], version: SignTypedDataVersion.V1, }), ).toThrow( 'The "list[0]" argument must be an instance of Buffer or Uint8Array. Received type number (10)', ); }, ); } else { _it(`should sign array of all ${type} example data`, function () { _expect( signTypedData({ privateKey, data: [{ name: 'data', type: `${type}[]`, value: inputs }], version: SignTypedDataVersion.V1, }), ).toMatchSnapshot(); }); } }); } }); it('should throw an error when an atomic property is set to null', function () { expect(() => signTypedData({ privateKey, data: [{ name: 'data', type: 'int32', value: null }], version: SignTypedDataVersion.V1, }), ).toThrow(`Cannot read property 'toArray' of null`); }); it('should sign data with an atomic property set to undefined', function () { expect(() => signTypedData({ privateKey, data: [{ name: 'data', type: 'int32', value: undefined }], version: SignTypedDataVersion.V1, }), ).toMatchSnapshot(); }); it('should sign data with a dynamic property set to null', function () { expect(() => signTypedData({ privateKey, data: [{ name: 'data', type: 'string', value: null }], version: SignTypedDataVersion.V1, }), ).toThrow( 'The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received null', ); }); it('should sign data with a dynamic property set to undefined', function () { expect(() => signTypedData({ privateKey, data: [{ name: 'data', type: 'string', value: undefined }], version: SignTypedDataVersion.V1, }), ).toMatchSnapshot(); }); it('should throw an error when trying to sign a function', function () { expect(() => signTypedData({ privateKey, data: [ { name: 'data', type: 'function', value: () => console.log(test), }, ], version: SignTypedDataVersion.V1, }), ).toThrow('Unsupported or invalid type: function'); }); it('should throw an error when trying to sign an unrecognized type', function () { expect(() => signTypedData({ privateKey, data: [{ name: 'data', type: 'foo', value: 'test' }], version: SignTypedDataVersion.V1, }), ).toThrow('Unsupported or invalid type: foo'); }); }); describe('V3', function () { // This first group of tests mirrors the `TypedDataUtils.eip712Hash` tests, because all of // those test cases are relevant here as well. it('should sign a minimal valid typed message', function () { const signature = signTypedData({ privateKey, // This represents the most basic "typed message" that is valid according to our types. // It's not a very useful message (it's totally empty), but it's complete according to the // spec. data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, version: SignTypedDataVersion.V3, }); expect(signature).toMatchSnapshot(); }); it('minimal typed message signature should be identical to minimal valid typed message signature', function () { const minimalSignature = signTypedData({ privateKey, // This tests that when the mandatory fields `domain`, `message`, and `types.EIP712Domain` // are omitted, the result is the same as if they were included but empty. data: { types: {}, primaryType: 'EIP712Domain', } as any, version: SignTypedDataVersion.V3, }); const minimalValidSignature = signTypedData({ privateKey, data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, version: SignTypedDataVersion.V3, }); expect(minimalSignature).toBe(minimalValidSignature); }); it('should ignore extra data properties', function () { const minimalValidSignature = signTypedData({ privateKey, data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, version: SignTypedDataVersion.V3, }); const extraPropertiesSignature = signTypedData({ privateKey, data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, extra: 'stuff', moreExtra: 1, } as any, version: SignTypedDataVersion.V3, }); expect(minimalValidSignature).toBe(extraPropertiesSignature); }); it('should sign a typed message with a domain separator that uses all fields', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: {}, }, version: SignTypedDataVersion.V3, }); expect(signature).toMatchSnapshot(); }); it('should sign a typed message with extra domain seperator fields', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, version: SignTypedDataVersion.V3, }); expect(signature).toMatchSnapshot(); }); it('should sign a typed message with only custom domain seperator fields', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'customName', type: 'string', }, { name: 'customVersion', type: 'string', }, { name: 'customChainId', type: 'uint256', }, { name: 'customVerifyingContract', type: 'address', }, { name: 'customSalt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { customName: 'example.metamask.io', customVersion: '1', customChainId: 1, customVerifyingContract: '0x0000000000000000000000000000000000000000', customSalt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, version: SignTypedDataVersion.V3, }); expect(signature).toMatchSnapshot(); }); it('should sign a typed message with data', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'Message', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: { data: 'Hello!', }, }, version: SignTypedDataVersion.V3, }); expect(signature).toMatchSnapshot(); }); // This second group of tests mirrors the `TypedDataUtils.encodeData` tests, because all of // those test cases are relevant here as well. describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should sign "${input}" (type "${inputType}")`, function () { _expect( signTypedData({ privateKey, data: { types: { EIP712Domain: [], Message: [{ name: 'data', type }], }, primaryType: 'Message', domain: {}, message: { data: input, }, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); } // Test all examples that crash const errorInputs = encodeDataErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to sign "${input}" (type "${inputType}")`, function () { _expect(() => signTypedData({ privateKey, data: { types: { EIP712Domain: [], Message: [{ name: 'data', type }], }, primaryType: 'Message', domain: {}, message: { data: input, }, }, version: SignTypedDataVersion.V3, }), ).toThrow(errorMessage); }, ); } _it( `should fail to sign array of all ${type} example data`, function () { _expect(() => signTypedData({ privateKey, data: { types: { EIP712Domain: [], Message: [{ name: 'data', type: `${type}[]` }], }, primaryType: 'Message', domain: {}, message: { data: inputs, }, }, version: SignTypedDataVersion.V3, }), ).toThrow( 'Arrays are unimplemented in encodeData; use V4 extension', ); }, ); }); } }); it('should sign data with custom type', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); it('should sign data with a recursive data type', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); it('should throw an error when trying to sign a custom type array', function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'string[]' }], }; const message = { data: ['1', '2', '3'] }; const primaryType = 'Message'; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toThrow('Arrays are unimplemented in encodeData; use V4 extension'); }); it('should ignore extra unspecified message properties', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalSignature = signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }); const messageWithExtraProperties = { ...message, foo: 'bar' }; const signatureWithExtraProperties = signTypedData({ privateKey, data: { types, primaryType, domain: {}, message: messageWithExtraProperties, }, version: SignTypedDataVersion.V3, }); expect(originalSignature).toBe(signatureWithExtraProperties); }); it('should throw an error when an atomic property is set to null', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: null, }; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toThrow(`Cannot read property 'toArray' of null`); }); it('should sign data with an atomic property set to undefined', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: undefined, }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); it('should sign data with a dynamic property set to null', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); it('should sign data with a dynamic property set to undefined', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: undefined, }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); it('should throw an error when a custom type property is set to null', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { to: null, from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toThrow(`Cannot read property 'name' of null`); }); it('should sign data with a custom type property set to undefined', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: undefined, contents: 'Hello, Bob!', }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); it('should throw an error when trying to sign a function', function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'function' }], }; const message = { data: 'test' }; const primaryType = 'Message'; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toThrow('Unsupported or invalid type: function'); }); it('should throw an error when trying to sign with a missing primary type definition', function () { const types = { EIP712Domain: [], }; const message = { data: 'test' }; const primaryType = 'Message'; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, } as any, version: SignTypedDataVersion.V3, }), ).toThrow('No type definition specified: Message'); }); it('should throw an error when trying to sign an unrecognized type', function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'foo' }], }; const message = { data: 'test' }; const primaryType = 'Message'; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toThrow('Unsupported or invalid type: foo'); }); it('should sign data when given extraneous types', function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const primaryType = 'Message'; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V3, }), ).toMatchSnapshot(); }); }); describe('V4', function () { // This first group of tests mirrors the `TypedDataUtils.eip712Hash` tests, because all of // those test cases are relevant here as well. it('should sign a minimal valid typed message', function () { const signature = signTypedData({ privateKey, // This represents the most basic "typed message" that is valid according to our types. // It's not a very useful message (it's totally empty), but it's complete according to the // spec. data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, version: SignTypedDataVersion.V4, }); expect(signature).toMatchSnapshot(); }); it('minimal typed message signature should be identical to minimal valid typed message signature', function () { const minimalSignature = signTypedData({ privateKey, // This tests that when the mandatory fields `domain`, `message`, and `types.EIP712Domain` // are omitted, the result is the same as if they were included but empty. data: { types: {}, primaryType: 'EIP712Domain', } as any, version: SignTypedDataVersion.V4, }); const minimalValidSignature = signTypedData({ privateKey, data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, version: SignTypedDataVersion.V4, }); expect(minimalSignature).toBe(minimalValidSignature); }); it('should ignore extra data properties', function () { const minimalValidSignature = signTypedData({ privateKey, data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, }, version: SignTypedDataVersion.V4, }); const extraPropertiesSignature = signTypedData({ privateKey, data: { types: { EIP712Domain: [], }, primaryType: 'EIP712Domain', domain: {}, message: {}, extra: 'stuff', moreExtra: 1, } as any, version: SignTypedDataVersion.V4, }); expect(minimalValidSignature).toBe(extraPropertiesSignature); }); it('should sign a typed message with a domain separator that uses all fields', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: {}, }, version: SignTypedDataVersion.V4, }); expect(signature).toMatchSnapshot(); }); it('should sign a typed message with extra domain seperator fields', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, version: SignTypedDataVersion.V4, }); expect(signature).toMatchSnapshot(); }); it('should sign a typed message with only custom domain seperator fields', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'customName', type: 'string', }, { name: 'customVersion', type: 'string', }, { name: 'customChainId', type: 'uint256', }, { name: 'customVerifyingContract', type: 'address', }, { name: 'customSalt', type: 'bytes32', }, { name: 'extraField', type: 'string', }, ], }, primaryType: 'EIP712Domain', domain: { customName: 'example.metamask.io', customVersion: '1', customChainId: 1, customVerifyingContract: '0x0000000000000000000000000000000000000000', customSalt: Buffer.from(new Int32Array([1, 2, 3])), extraField: 'stuff', }, message: {}, } as any, version: SignTypedDataVersion.V4, }); expect(signature).toMatchSnapshot(); }); it('should sign a typed message with data', function () { const signature = signTypedData({ privateKey, data: { types: { EIP712Domain: [ { name: 'name', type: 'string', }, { name: 'version', type: 'string', }, { name: 'chainId', type: 'uint256', }, { name: 'verifyingContract', type: 'address', }, { name: 'salt', type: 'bytes32', }, ], Message: [{ name: 'data', type: 'string' }], }, primaryType: 'Message', domain: { name: 'example.metamask.io', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', salt: Buffer.from(new Int32Array([1, 2, 3])), }, message: { data: 'Hello!', }, }, version: SignTypedDataVersion.V4, }); expect(signature).toMatchSnapshot(); }); // This second group of tests mirrors the `TypedDataUtils.encodeData` tests, because all of // those test cases are relevant here as well. describe('example data', function () { // Reassigned to silence "no-loop-func" ESLint rule // It was complaining because it saw that `it` and `expect` as "modified variables from the outer scope" // which can be dangerous to reference in a loop. But they aren't modified in this case, just invoked. const _expect = expect; const _it = it; for (const type of allExampleTypes) { describe(`type "${type}"`, function () { // Test all examples that do not crash const inputs = encodeDataExamples[type] || []; for (const input of inputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it(`should sign "${input}" (type "${inputType}")`, function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type }], }; const message = { data: input }; const primaryType = 'Message'; _expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); } // Test all examples that crash const errorInputs = encodeDataErrorExamples[type] || []; for (const { input, errorMessage } of errorInputs) { const inputType = input instanceof Buffer ? 'Buffer' : typeof input; _it( `should fail to sign "${input}" (type "${inputType}")`, function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type }], }; const message = { data: input }; const primaryType = 'Message'; _expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toThrow(errorMessage); }, ); } _it(`should sign array of all ${type} example data`, function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: `${type}[]` }], }; const message = { data: inputs }; const primaryType = 'Message'; _expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); }); } }); it('should sign data with custom type', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); it('should sign data with a recursive data type', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'replyTo', type: 'Mail' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', replyTo: { to: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, from: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', }, }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); it('should sign data with a custom data type array', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address[]' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person[]' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: [ '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', '0xDD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', ], }, to: [ { name: 'Bob', wallet: ['0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB'], }, ], contents: 'Hello, Bob!', }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); it('should ignore extra unspecified message properties', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }; const originalSignature = signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }); const messageWithExtraProperties = { ...message, foo: 'bar' }; const signatureWithExtraProperties = signTypedData({ privateKey, data: { types, primaryType, domain: {}, message: messageWithExtraProperties, }, version: SignTypedDataVersion.V4, }); expect(originalSignature).toBe(signatureWithExtraProperties); }); it('should throw an error when an atomic property is set to null', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: null, }; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toThrow(`Cannot read property 'toArray' of null`); }); it('should throw an error when an atomic property is set to undefined', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'length', type: 'int32' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello!', length: undefined, }; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toThrow('missing value for field length of type int32'); }); it('should sign data with a dynamic property set to null', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: null, }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); it('should throw an error when a dynamic property is set to undefined', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: undefined, }; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toThrow('missing value for field contents of type string'); }); it('should sign data with a custom type property set to null', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { to: null, from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, contents: 'Hello, Bob!', }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); it('should sign data with a custom type property set to undefined', function () { const types = { EIP712Domain: [], Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }; const primaryType = 'Mail'; const message = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: undefined, contents: 'Hello, Bob!', }; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); it('should throw an error when trying to encode a function', function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'function' }], }; const message = { data: 'test' }; const primaryType = 'Message'; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toThrow('Unsupported or invalid type: function'); }); it('should throw an error when trying to sign with a missing primary type definition', function () { const types = { EIP712Domain: [], }; const message = { data: 'test' }; const primaryType = 'Message'; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, } as any, version: SignTypedDataVersion.V4, }), ).toThrow('No type definition specified: Message'); }); it('should throw an error when trying to sign an unrecognized type', function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'foo' }], }; const message = { data: 'test' }; const primaryType = 'Message'; expect(() => signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toThrow('Unsupported or invalid type: foo'); }); it('should sign data when given extraneous types', function () { const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'string' }], Extra: [{ name: 'data', type: 'string' }], }; const message = { data: 'Hello!' }; const primaryType = 'Message'; expect( signTypedData({ privateKey, data: { types, primaryType, domain: {}, message, }, version: SignTypedDataVersion.V4, }), ).toMatchSnapshot(); }); }); describe('validation', () => { it('should throw if passed an invalid version', () => { expect(() => signTypedData({ privateKey, data: [{ name: 'data', type: 'string', value: 'Hello!' }], version: 'V0' as any, }), ).toThrow('Invalid version'); }); it('should throw if passed null data', () => { expect(() => signTypedData({ privateKey, data: null, version: SignTypedDataVersion.V1, }), ).toThrow('Missing data parameter'); }); it('should throw if passed undefined data', () => { expect(() => signTypedData({ privateKey, data: undefined, version: SignTypedDataVersion.V1, }), ).toThrow('Missing data parameter'); }); it('should throw if passed a null private key', () => { expect(() => signTypedData({ privateKey: null, data: [{ name: 'data', type: 'string', value: 'Hello!' }], version: SignTypedDataVersion.V1, }), ).toThrow('Missing private key parameter'); }); it('should throw if passed an undefined private key', () => { expect(() => signTypedData({ privateKey: undefined, data: [{ name: 'data', type: 'string', value: 'Hello!' }], version: SignTypedDataVersion.V1, }), ).toThrow('Missing private key parameter'); }); }); }); describe('recoverTypedSignature', function () { describe('V1', function () { // This is a signature of the message "[{ name: 'message', type: 'string', value: 'Hi, Alice!' }]" // that was created using the private key in the top-level `privateKey` variable. const exampleSignature = '0x49e75d475d767de7fcc67f521e0d86590723d872e6111e51c393e8c1e2f21d032dfaf5833af158915f035db6af4f37bf2d5d29781cd81f28a44c5cb4b9d241531b'; it('should recover the address of the signer', function () { const address = ethUtil.addHexPrefix( ethUtil.privateToAddress(privateKey).toString('hex'), ); expect( recoverTypedSignature({ data: [{ name: 'message', type: 'string', value: 'Hi, Alice!' }], signature: exampleSignature, version: SignTypedDataVersion.V1, }), ).toBe(address); }); it('should sign typed data and recover the address of the signer', function () { const address = ethUtil.addHexPrefix( ethUtil.privateToAddress(privateKey).toString('hex'), ); const message = [ { name: 'message', type: 'string', value: 'Hi, Alice!' }, ]; const signature = signTypedData({ privateKey, data: message, version: SignTypedDataVersion.V1, }); expect( recoverTypedSignature({ data: message, signature, version: SignTypedDataVersion.V1, }), ).toBe(address); }); }); describe('V3', function () { // This is a signature of the message in the test below that was created using the private key // in the top-level `privateKey` variable. const exampleSignature = '0xf6cda8eaf5137e8cc15d48d03a002b0512446e2a7acbc576c01cfbe40ad9345663ccda8884520d98dece9a8bfe38102851bdae7f69b3d8612b9808e6337801601b'; it('should recover the address of the signer', function () { const address = ethUtil.addHexPrefix( ethUtil.privateToAddress(privateKey).toString('hex'), ); const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'test' }; const primaryType = 'Message' as const; const typedMessage = { types, primaryType, domain: {}, message, }; expect( recoverTypedSignature({ data: typedMessage, signature: exampleSignature, version: SignTypedDataVersion.V3, }), ).toBe(address); }); it('should sign typed data and recover the address of the signer', function () { const address = ethUtil.addHexPrefix( ethUtil.privateToAddress(privateKey).toString('hex'), ); const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'test' }; const primaryType = 'Message' as const; const typedMessage = { types, primaryType, domain: {}, message, }; const signature = signTypedData({ privateKey, data: typedMessage, version: SignTypedDataVersion.V3, }); expect( recoverTypedSignature({ data: typedMessage, signature, version: SignTypedDataVersion.V3, }), ).toBe(address); }); }); describe('V4', function () { // This is a signature of the message in the test below that was created using the private key // in the top-level `privateKey` variable. const exampleSignature = '0xf6cda8eaf5137e8cc15d48d03a002b0512446e2a7acbc576c01cfbe40ad9345663ccda8884520d98dece9a8bfe38102851bdae7f69b3d8612b9808e6337801601b'; it('should recover the address of the signer', function () { const address = ethUtil.addHexPrefix( ethUtil.privateToAddress(privateKey).toString('hex'), ); const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'test' }; const primaryType = 'Message' as const; const typedMessage = { types, primaryType, domain: {}, message, }; expect( recoverTypedSignature({ data: typedMessage, signature: exampleSignature, version: SignTypedDataVersion.V4, }), ).toBe(address); }); it('should sign typed data and recover the address of the signer', function () { const address = ethUtil.addHexPrefix( ethUtil.privateToAddress(privateKey).toString('hex'), ); const types = { EIP712Domain: [], Message: [{ name: 'data', type: 'string' }], }; const message = { data: 'test' }; const primaryType = 'Message' as const; const typedMessage = { types, primaryType, domain: {}, message, }; const signature = signTypedData({ privateKey, data: typedMessage, version: SignTypedDataVersion.V4, }); expect( recoverTypedSignature({ data: typedMessage, signature, version: SignTypedDataVersion.V4, }), ).toBe(address); }); }); describe('validation', () => { // This is a signature of the message "[{ name: 'message', type: 'string', value: 'Hi, Alice!' }]" // that was created using the private key in the top-level `privateKey` variable. const exampleSignature = '0x49e75d475d767de7fcc67f521e0d86590723d872e6111e51c393e8c1e2f21d032dfaf5833af158915f035db6af4f37bf2d5d29781cd81f28a44c5cb4b9d241531b'; it('should throw if passed an invalid version', () => { expect(() => recoverTypedSignature({ data: [{ name: 'message', type: 'string', value: 'Hi, Alice!' }], signature: exampleSignature, version: 'V0' as any, }), ).toThrow('Invalid version'); }); it('should throw if passed null data', () => { expect(() => recoverTypedSignature({ data: null, signature: exampleSignature, version: SignTypedDataVersion.V1, }), ).toThrow('Missing data parameter'); }); it('should throw if passed undefined data', () => { expect(() => recoverTypedSignature({ data: undefined, signature: exampleSignature, version: SignTypedDataVersion.V1, }), ).toThrow('Missing data parameter'); }); it('should throw if passed a null signature', () => { expect(() => recoverTypedSignature({ data: [{ name: 'message', type: 'string', value: 'Hi, Alice!' }], signature: null, version: SignTypedDataVersion.V1, }), ).toThrow('Missing signature parameter'); }); it('should throw if passed a null signature', () => { expect(() => recoverTypedSignature({ data: [{ name: 'message', type: 'string', value: 'Hi, Alice!' }], signature: undefined, version: SignTypedDataVersion.V1, }), ).toThrow('Missing signature parameter'); }); }); });
the_stack
import * as angular from 'angular'; import * as _ from "underscore"; import Map = Common.Map; import '../module-require'; import './module-require'; import {ImportComponentOption, ImportComponentType, ImportService} from '../../services/ImportComponentOptionTypes'; import {Common} from '../../../../lib/common/CommonTypes'; const moduleName = require('./module-name'); export class ImportFeedController { /** * The file to upload * @type {null} */ feedFile: any = null; /** * the name of the file to upload * @type {string} */ fileName: string = null; /** * flag if uploading * @type {boolean} */ uploadInProgress: boolean = false; /** * Flag to indicate the upload produced validation errors * @type {boolean} */ validationErrors: boolean = false; /** * unique key to track upload status * @type {string} */ uploadKey: string = null; /** * Status of the current upload * @type {Array} */ uploadStatusMessages: string[] = []; /** * handle on the $interval object to cancel later * @type {null} */ uploadStatusCheck: angular.IPromise<any> = undefined; /** * Percent upload complete * @type {number} */ uploadProgress: number = 0; /** * Flag to indicate additional properties exist and a header show be shown for template options */ additionalInputNeeded: boolean = false; /** * flag to force the feed to be DISABLED upon importing * @type {boolean} */ disableFeedUponImport: boolean = false; /** * All the importOptions that will be uploaded * @type {{}} */ importComponentOptions: Map<ImportComponentOption> = {}; /** * Feed ImportOptions */ feedDataImportOption: ImportComponentOption; /** * Registered Template import options */ templateDataImportOption: ImportComponentOption; /** * NiFi template options */ nifiTemplateImportOption: ImportComponentOption; /** * Reusable template options */ reusableTemplateImportOption: ImportComponentOption; /** * User data sources options */ userDatasourcesOption: ImportComponentOption; /** * Any required feed fields */ feedUserFieldsImportOption: ImportComponentOption; /** * Any Required Category fields */ categoryUserFieldsImportOption: ImportComponentOption; /** * The angular Form for validation * @type {{}} */ importFeedForm: any = {}; /** * List of available data sources. * @type {Array.<JdbcDatasource>} */ availableDatasources: any = []; importResult: any; /** * The icon for the result */ importResultIcon: string = "check_circle"; /** * the color of the icon */ importResultIconColor: string = "#009933"; /** * Any additional errors */ errorMap: any = null; /** * the number of errors after an import */ errorCount: number = 0; /** * The category model for autocomplete * @type {{category: {}}} */ categoryModel: any = { category: {} } /** * When the category auto complete changes */ categorySearchText: string; /** * Message after upload */ message: string; static $inject = ["$scope", "$http", "$interval", "$timeout", "$mdDialog", "FileUpload", "RestUrlService", "FeedCreationErrorService", "CategoriesService", "ImportService", "DatasourcesService", "$filter"]; constructor(private $scope: any, private $http: angular.IHttpService, private $interval: angular.IIntervalService, private $timeout: angular.ITimeoutService , private $mdDialog: angular.material.IDialogService, private FileUpload: any, private RestUrlService: any , private FeedCreationErrorService: any, private categoriesService: any , private ImportService: ImportService, private DatasourcesService: any, private $filter: angular.IFilterService) { /** * Feed ImportOptions */ this.feedDataImportOption = ImportService.newFeedDataImportOption(); /** * Registered Template import options */ this.templateDataImportOption = ImportService.newTemplateDataImportOption(); /** * NiFi template options */ this.nifiTemplateImportOption = ImportService.newNiFiTemplateImportOption(); /** * Reusable template options */ this.reusableTemplateImportOption = ImportService.newReusableTemplateImportOption(); /** * User data sources options */ this.userDatasourcesOption = ImportService.newUserDatasourcesImportOption(); this.feedUserFieldsImportOption = ImportService.newFeedUserFieldsImportOption(); this.categoryUserFieldsImportOption = ImportService.newFeedCategoryUserFieldsImportOption(); } $onInit(): void { this.ngOnInit(); } /** * Initialize the Controller */ ngOnInit(): void { this.indexImportOptions(); this.setDefaultImportOptions(); this.$scope.$watch(() => { return this.feedFile; }, (newVal: any, oldValue: any) => { if (newVal != null) { this.fileName = newVal.name; } else { this.fileName = null; } //reset them if changed if (newVal != oldValue) { this.resetImportOptions(); } }) // Get the list of data sources this.DatasourcesService.findAll() .then((datasources: any) => { this.availableDatasources = datasources; }); } /** * Called when a user changes a import option for overwriting */ onOverwriteSelectOptionChanged = this.ImportService.onOverwriteSelectOptionChanged; importFeed(): void { //reset flags this.uploadInProgress = true; this.importResult = null; var file = this.feedFile; var uploadUrl = this.RestUrlService.ADMIN_IMPORT_FEED_URL; var successFn = (response: any) => { var responseData = response.data; //reassign the options back from the response data var importComponentOptions = responseData.importOptions.importComponentOptions; //map the options back to the object map this.updateImportOptions(importComponentOptions); if (!responseData.valid) { //Validation Error. Additional Input is needed by the end user this.additionalInputNeeded = true; } else { var count = 0; var errorMap: any = {"FATAL": [], "WARN": []}; this.importResult = responseData; //if(responseData.templateResults.errors) { if (responseData.template.controllerServiceErrors) { //angular.forEach(responseData.templateResults.errors, function (processor) { angular.forEach(responseData.template.controllerServiceErrors, (processor: any) => { if (processor.validationErrors) { angular.forEach(processor.validationErrors, function (error: any) { let copy: any = {}; angular.extend(copy, error); angular.extend(copy, processor); copy.validationErrors = null; this.errorMap[error.severity].push(copy); count++; }); } }); } if (responseData.nifiFeed == null || responseData.nifiFeed == undefined) { this.errorMap["FATAL"].push({message: "Unable to import feed"}); } if (responseData.nifiFeed && responseData.nifiFeed) { count += this.FeedCreationErrorService.parseNifiFeedErrors(responseData.nifiFeed, errorMap); } this.errorMap = errorMap; this.errorCount = count; var feedName = responseData.feedName != null ? responseData.feedName : ""; if (count == 0) { this.importResultIcon = "check_circle"; this.importResultIconColor = "#009933"; this.message = this.$filter('translate')('views.ImportFeedController.succes') + feedName + "."; this.resetImportOptions(); } else { if (responseData.success) { this.resetImportOptions(); this.message = "Successfully imported and registered the feed " + feedName + " but some errors were found. Please review these errors"; this.importResultIcon = "warning"; this.importResultIconColor = "#FF9901"; } else { this.importResultIcon = "error"; this.importResultIconColor = "#FF0000"; this.message = this.$filter('translate')('views.ImportFeedController.error2'); } } } this.uploadInProgress = false; this.stopUploadStatus(1000); } var errorFn = (response: any) => { var data = response.data //reset the flags this.importResult = {}; this.uploadInProgress = false; //set error indicators and messages this.importResultIcon = "error"; this.importResultIconColor = "#FF0000"; var msg = this.$filter('translate')('views.ImportFeedController.error'); if (data.developerMessage) { msg += data.developerMessage; } this.message = msg; this.stopUploadStatus(1000); } if (angular.isDefined(this.categorySearchText) && this.categorySearchText != null && this.categorySearchText != "" && this.categoryModel.category.systemName == null) { //error the category has text in it, but not selected //attempt to get it let category = this.categoriesService.findCategoryByName(this.categorySearchText); if (category != null) { this.categoryModel.category = category; } } //build up the options from the Map and into the array for uploading var importComponentOptions = this.ImportService.getImportOptionsForUpload(this.importComponentOptions); //generate a new upload key for status tracking this.uploadKey = this.ImportService.newUploadKey(); var params = { uploadKey: this.uploadKey, categorySystemName: angular.isDefined(this.categoryModel.category.systemName) && this.categoryModel.category.systemName != null ? this.categoryModel.category.systemName : "", disableFeedUponImport: this.disableFeedUponImport, importComponents: angular.toJson(importComponentOptions) }; this.startUploadStatus(); this.FileUpload.uploadFileToUrl(file, uploadUrl, successFn, errorFn, params); } categorySearchTextChanged(text: any): void { } categorySelectedItemChange(item: any) { if (item != null && item != undefined) { this.categoryModel.category.name = item.name; this.categoryModel.category.id = item.id; this.categoryModel.category.systemName = item.systemName; } else { this.categoryModel.category.name = null; this.categoryModel.category.id = null; this.categoryModel.category.systemName = null; } } /** * Set the default values for the import options */ private setDefaultImportOptions(): void { this.nifiTemplateImportOption.continueIfExists = true; // this.reusableTemplateImportOption.userAcknowledged = false; //it is assumed with a feed you will be importing the template with the feed this.templateDataImportOption.userAcknowledged = true; this.feedDataImportOption.continueIfExists = false; } private indexImportOptions(): void { var arr = [this.feedDataImportOption, this.templateDataImportOption, this.nifiTemplateImportOption, this.reusableTemplateImportOption, this.categoryUserFieldsImportOption, this.feedUserFieldsImportOption]; this.importComponentOptions = _.indexBy(arr, 'importComponent') } /** * Reset the options back to their orig. state */ private resetImportOptions(): void { this.importComponentOptions = {}; this.feedDataImportOption = this.ImportService.newFeedDataImportOption(); this.templateDataImportOption = this.ImportService.newTemplateDataImportOption(); this.nifiTemplateImportOption = this.ImportService.newNiFiTemplateImportOption(); this.reusableTemplateImportOption = this.ImportService.newReusableTemplateImportOption(); this.userDatasourcesOption = this.ImportService.newUserDatasourcesImportOption(); this.feedUserFieldsImportOption = this.ImportService.newFeedUserFieldsImportOption(); this.categoryUserFieldsImportOption = this.ImportService.newFeedCategoryUserFieldsImportOption(); this.indexImportOptions(); this.setDefaultImportOptions(); this.additionalInputNeeded = false; this.disableFeedUponImport = false; } /** * * @param importOptionsArr array of importOptions */ private updateImportOptions(importOptionsArr: ImportComponentOption[]): void { var map = _.indexBy(importOptionsArr, 'importComponent'); _.each(importOptionsArr, (option: any) => { if (option.userAcknowledged) { option.overwriteSelectValue = "" + option.overwrite; } if (option.importComponent == ImportComponentType.FEED_DATA) { this.feedDataImportOption = option; } else if (option.importComponent == ImportComponentType.TEMPLATE_DATA) { this.templateDataImportOption = option; } else if (option.importComponent == ImportComponentType.REUSABLE_TEMPLATE) { this.reusableTemplateImportOption = option; } else if (option.importComponent == ImportComponentType.NIFI_TEMPLATE) { this.nifiTemplateImportOption = option; } else if (option.importComponent === ImportComponentType.USER_DATASOURCES) { this.userDatasourcesOption = option; } else if (option.importComponent === ImportComponentType.FEED_CATEGORY_USER_FIELDS) { this.categoryUserFieldsImportOption = option; } else if (option.importComponent === ImportComponentType.FEED_USER_FIELDS) { this.feedUserFieldsImportOption = option; } this.importComponentOptions[option.importComponent] = option; }); } /** * Stop the upload status check, * @param delay wait xx millis before stopping (allows for the last status to be queried) */ private stopUploadStatus(delay: any): void { let stopStatusCheck = () => { this.uploadProgress = 0; if (angular.isDefined(this.uploadStatusCheck)) { this.$interval.cancel(this.uploadStatusCheck); this.uploadStatusCheck = undefined; } } if (delay != undefined) { this.$timeout(() => { stopStatusCheck(); }, delay) } else { stopStatusCheck(); } } /** * starts the upload status check */ private startUploadStatus(): void { this.stopUploadStatus(undefined); this.uploadStatusMessages = []; this.uploadStatusCheck = this.$interval(() => { //poll for status this.$http.get(this.RestUrlService.ADMIN_UPLOAD_STATUS_CHECK(this.uploadKey)).then((response: angular.IHttpResponse<any>) => { if (response && response.data && response.data != null) { this.uploadStatusMessages = response.data.messages; this.uploadProgress = response.data.percentComplete; } }, (err: any) => { // this.uploadStatusMessages = []; }); }, 500); } } const module = angular.module(moduleName).controller('ImportFeedController', ImportFeedController); export default module;
the_stack
import { NumericTextBox, ChangeEventArgs as NumericChangeArgs } from '@syncfusion/ej2-inputs'; import { LayoutViewer } from '../index'; import { createElement, L10n } from '@syncfusion/ej2-base'; import { SelectionParagraphFormat } from '../index'; import { Selection } from '../index'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; import { DropDownList, ChangeEventArgs as DropDownChangeArgs } from '@syncfusion/ej2-dropdowns'; import { WParagraphFormat } from '../index'; import { TextAlignment, LineSpacingType } from '../../base/types'; import { RadioButton, ChangeArgs, CheckBox, ChangeEventArgs } from '@syncfusion/ej2-buttons'; import { DocumentHelper } from '../viewer'; import { Tab, TabItemModel } from '@syncfusion/ej2-navigations'; /** * The Paragraph dialog is used to modify formatting of selected paragraphs. */ export class ParagraphDialog { /** * @private */ public documentHelper: DocumentHelper; private target: HTMLElement; private alignment: DropDownList; private lineSpacing: DropDownList; private special: DropDownList; private leftIndentIn: NumericTextBox; private rightIndentIn: NumericTextBox; private byIn: NumericTextBox; private beforeSpacingIn: NumericTextBox; private afterSpacingIn: NumericTextBox; private atIn: NumericTextBox; private rtlButton: RadioButton; private ltrButton: RadioButton; private contextSpacing: CheckBox; private keepWithNext: CheckBox; private keepLinesTogether: CheckBox; private widowControlIn: CheckBox; //paragraph Format properties private leftIndent: number = undefined; private rightIndent: number = undefined; private beforeSpacing: number = undefined; private afterSpacing: number = undefined; private textAlignment: TextAlignment = undefined; private firstLineIndent: number = undefined; private lineSpacingIn: number = undefined; private lineSpacingType: LineSpacingType = undefined; private paragraphFormat: WParagraphFormat = undefined; private bidi: boolean = undefined; private contextualSpacing: boolean = undefined; public isStyleDialog: boolean = false; private directionDiv: HTMLElement = undefined; public keepWithNextValue: boolean = undefined; public keepLineTogetherValue: boolean = undefined; public widowControlValue: boolean = undefined; private tabObj: Tab = undefined; private paginationDiv: HTMLElement; /** * @param {DocumentHelper} documentHelper - Specifies the document helper. * @private */ public constructor(documentHelper: DocumentHelper) { this.documentHelper = documentHelper; } private get owner(): LayoutViewer { return this.documentHelper.owner.viewer; } /** * @private * @returns {string} Returns module name */ public getModuleName(): string { return 'ParagraphDialog'; } /* eslint-disable */ /** * @private * @param {L10n} locale - Specifies the locale. * @returns {void} */ public initParagraphDialog(locale: L10n): void { let tabContainer: HTMLElement = <HTMLDivElement>createElement('div'); const ejtab: HTMLDivElement = <HTMLDivElement>createElement('div'); let instance: ParagraphDialog = this; let ownerId: string = this.documentHelper.owner.containerId; let id: string = ownerId + '_paragraph_dialog'; let indentContainer: HTMLElement = createElement('div', { id: id, className: 'e-de-para-dlg-container' }); this.target = tabContainer; tabContainer.appendChild(ejtab); let div: HTMLDivElement = createElement('div', { id: 'property_div', styles: 'width:400px;' }) as HTMLDivElement; let generalDiv: HTMLDivElement = createElement('div', { id: 'genral_div', className: 'e-de-para-dlg-sub-container' }) as HTMLDivElement; let genLabel: HTMLElement = createElement('div', { id: ownerId + '_genLabel', className: 'e-de-para-dlg-heading', innerHTML: locale.getConstant('General') }); let alignLabel: HTMLElement = createElement('div', { id: ownerId + '_AlignLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Alignment') }); let alignment: HTMLElement = createElement('select', { id: ownerId + '_Alignment', innerHTML: '<option value="Center">' + locale.getConstant('Center') + '</option><option value="Left">' + locale.getConstant('Left') + '</option><option value="Right">' + locale.getConstant('Right') + '</option><option value="Justify">' + locale.getConstant('Justify') + '</option>' }) as HTMLSelectElement; generalDiv.appendChild(genLabel); generalDiv.appendChild(alignLabel); generalDiv.appendChild(alignment); let dirLabel: HTMLElement = createElement('div', { id: ownerId + '_DirLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Direction') }); this.directionDiv = createElement('div', { id: ownerId + '_DirDiv', styles: 'display:flex' }); let rtlDiv: HTMLElement = createElement('div', { id: ownerId + '_DirDiv', className: 'e-de-rtl-btn-div' }); let rtlInputELe: HTMLElement = createElement('input', { id: ownerId + '_rtlEle' }); rtlDiv.appendChild(rtlInputELe); this.directionDiv.appendChild(rtlDiv) let isRtl: boolean = this.documentHelper.owner.enableRtl; if (isRtl) { rtlDiv.classList.add('e-de-rtl'); } let ltrDiv: HTMLElement = createElement('div', { id: ownerId + '_DirDiv', className: 'e-de-ltr-btn-div' }); let ltrInputELe: HTMLElement = createElement('input', { id: ownerId + '_ltrEle' }); ltrDiv.appendChild(ltrInputELe); this.directionDiv.appendChild(ltrDiv) generalDiv.appendChild(dirLabel); generalDiv.appendChild(this.directionDiv); this.rtlButton = new RadioButton({ label: locale.getConstant('Right-to-left'), enableRtl: isRtl, value: 'rtl', cssClass: 'e-small', change: this.changeBidirectional }); this.rtlButton.appendTo(rtlInputELe); this.ltrButton = new RadioButton({ label: locale.getConstant('Left-to-right'), enableRtl: isRtl, value: 'ltr', cssClass: 'e-small', change: this.changeBidirectional }); this.ltrButton.appendTo(ltrInputELe); let indentionDiv: HTMLDivElement = createElement('div', { id: 'indention_div', styles: 'width: 400px;', className: 'e-de-para-dlg-sub-container e-para-dlg-sub-height' }) as HTMLDivElement; let indentLabel: HTMLLabelElement = createElement('div', { id: ownerId + '_indentLabel', className: 'e-de-para-dlg-heading', innerHTML: locale.getConstant('Indentation'), styles: 'float:top;position:relative' }) as HTMLLabelElement; indentionDiv.appendChild(indentLabel); let leftIndentionDiv: HTMLDivElement = createElement('div', { id: 'left_indention', styles: 'float:left;position:relative;' }) as HTMLDivElement; indentionDiv.appendChild(leftIndentionDiv); let rightIndentionDiv: HTMLDivElement = createElement('div', { className: 'e-de-para-dlg-right-sub-container', styles: 'float:right;position:relative;' }) as HTMLDivElement; indentionDiv.appendChild(rightIndentionDiv); let spacingDiv: HTMLDivElement = createElement('div', { id: 'spacing_div' }) as HTMLDivElement; let leftSpacingDiv: HTMLDivElement = createElement('div', { id: 'left_spacing', styles: 'position:relative;' }) as HTMLDivElement; spacingDiv.appendChild(leftSpacingDiv); let contextSpacingStyles: string = 'float:left'; if (isRtl) { contextSpacingStyles = 'float:right;'; } let contextSpacingDiv: HTMLDivElement = createElement('div', { id: 'context_spacing', styles: contextSpacingStyles + 'position:relative;' }) as HTMLDivElement; spacingDiv.appendChild(contextSpacingDiv); let rightSpacingDiv: HTMLDivElement = createElement('div', { styles: 'display:inline-flex;' }) as HTMLDivElement; spacingDiv.appendChild(rightSpacingDiv); let contextInputEle: HTMLInputElement = createElement('input', { attrs: { type: 'checkbox' }, id: ownerId + '_contextSpacing' }) as HTMLInputElement; contextSpacingDiv.appendChild(contextInputEle); let beforeTextLabel: HTMLLabelElement = createElement('div', { id: ownerId + '_bfTextLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Before text') }) as HTMLLabelElement; let leftIndent: HTMLInputElement = createElement('input', { id: ownerId + '_leftIndent', attrs: { 'type': 'text' } }) as HTMLInputElement; let specialLabel: HTMLLabelElement = createElement('div', { id: ownerId + '_specialLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Special') }) as HTMLLabelElement; let special: HTMLElement = createElement('select', { id: ownerId + '_special', innerHTML: '<option value="None">' + locale.getConstant('None') + '</option><option value="First Line">' + locale.getConstant('First line') + '</option><option value="Hanging">' + locale.getConstant('Hanging') + '</option> ' }) as HTMLSelectElement; leftIndentionDiv.appendChild(beforeTextLabel); leftIndentionDiv.appendChild(leftIndent); leftIndentionDiv.appendChild(specialLabel); leftIndentionDiv.appendChild(special); let afterTextLabel: HTMLLabelElement = createElement('div', { id: ownerId + '_afTextLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('After text') }) as HTMLLabelElement; let rightIndent: HTMLInputElement = createElement('input', { id: ownerId + '_rightIndent', attrs: { 'type': 'text' } }) as HTMLInputElement; let byLabel: HTMLLabelElement = createElement('label', { id: ownerId + '_byLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('By') }) as HTMLLabelElement; let by: HTMLInputElement = createElement('input', { id: ownerId + '_By', attrs: { 'type': 'text' } }) as HTMLInputElement; rightIndentionDiv.appendChild(afterTextLabel); rightIndentionDiv.appendChild(rightIndent); rightIndentionDiv.appendChild(byLabel); rightIndentionDiv.appendChild(by); let spaceLabel: HTMLLabelElement = createElement('div', { innerHTML: locale.getConstant('Spacing'), className: 'e-de-para-dlg-heading', id: ownerId + '_spaceLabel' }) as HTMLLabelElement; let spacingWholeDiv: HTMLElement = createElement('div', { id: ownerId + '_spacingWholeDiv', styles: 'display:inline-flex;' }) as HTMLElement; let beforeSpacingWholeDiv: HTMLElement = createElement('div', { id: ownerId + '_beforeSpacingWholeDiv' }) as HTMLElement; let beforeLabel: HTMLLabelElement = createElement('div', { className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Before'), id: ownerId + '_beforeLabel' }) as HTMLLabelElement; let beforeSpacing: HTMLInputElement = createElement('input', { id: ownerId + '_beforeSpacing', attrs: { 'type': 'text' } }) as HTMLInputElement; let afterSpacingWholeDiv: HTMLElement = createElement('div', { id: ownerId + '_afterSpacingWholeDiv', className: 'e-de-para-dlg-spacing-div' }) as HTMLElement; let afterLabel: HTMLLabelElement = createElement('div', { innerHTML: locale.getConstant('After'), className: 'e-de-dlg-sub-header', id: ownerId + '_afterLabel' }) as HTMLLabelElement; let afterSpacing: HTMLInputElement = createElement('input', { id: ownerId + '_afterSpacing', attrs: { 'type': 'text' } }) as HTMLInputElement; leftSpacingDiv.appendChild(spaceLabel); leftSpacingDiv.appendChild(spacingWholeDiv); beforeSpacingWholeDiv.appendChild(beforeLabel); beforeSpacingWholeDiv.appendChild(beforeSpacing); spacingWholeDiv.appendChild(beforeSpacingWholeDiv); afterSpacingWholeDiv.appendChild(afterLabel); afterSpacingWholeDiv.appendChild(afterSpacing); spacingWholeDiv.appendChild(afterSpacingWholeDiv); let lineSpacingDiv: HTMLElement = createElement('div', { id: ownerId + '_lineSpacingWholeDiv' }) as HTMLElement; let lineSpaceLabel: HTMLLabelElement = createElement('div', { id: ownerId + '_lineSpaceLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Line Spacing') }) as HTMLLabelElement; let lineSpacing: HTMLElement = createElement('select', { id: ownerId + '_lineSpacing', styles: 'width:180px;', innerHTML: '<option value="At least">' + locale.getConstant('At least') + '</option><option value="Exactly">' + locale.getConstant('Exactly') + '</option><option value="Multiple">' + locale.getConstant('Multiple') + '</option>' }) as HTMLSelectElement; let lineTypeDiv: HTMLElement = createElement('div', { id: ownerId + '_lineTypeWholeDiv', className: 'e-de-para-dlg-spacing-div' }) as HTMLElement; let atLabel: HTMLLabelElement = createElement('div', { innerHTML: locale.getConstant('At'), id: ownerId + '_atLabel', className: 'e-de-dlg-sub-header' }) as HTMLLabelElement; let lineSpacingAt: HTMLInputElement = createElement('input', { id: ownerId + '_lineSpacingAt', attrs: { 'type': 'text' } }) as HTMLInputElement; lineSpacingDiv.appendChild(lineSpaceLabel); lineSpacingDiv.appendChild(lineSpacing); rightSpacingDiv.appendChild(lineSpacingDiv); lineTypeDiv.appendChild(atLabel); lineTypeDiv.appendChild(lineSpacingAt); rightSpacingDiv.appendChild(lineTypeDiv); div.appendChild(generalDiv); div.appendChild(indentionDiv); div.appendChild(spacingDiv); indentContainer.appendChild(div); this.leftIndentIn = new NumericTextBox({ format: 'n1', value: 0, min: -1584, max: 1584, width: 180, enablePersistence: false, change: this.changeLeftIndent }); this.leftIndentIn.appendTo(leftIndent); this.rightIndentIn = new NumericTextBox({ format: 'n1', value: 0, min: -1584, max: 1584, width: 180, enablePersistence: false, change: this.changeRightIndent }); this.rightIndentIn.appendTo(rightIndent); this.byIn = new NumericTextBox({ format: 'n1', value: 0, min: 0, max: 1584, width: 180, enablePersistence: false, change: this.changeFirstLineIndent }); this.byIn.appendTo(by); this.beforeSpacingIn = new NumericTextBox({ format: 'n1', value: 0, min: 0, max: 1584, width: 180, step: 6, enablePersistence: false, change: this.changeBeforeSpacing }); this.beforeSpacingIn.appendTo(beforeSpacing); this.afterSpacingIn = new NumericTextBox({ format: 'n1', value: 0, min: 0, max: 1584, width: 180, step: 6, enablePersistence: false, change: this.changeAfterSpacing }); this.afterSpacingIn.appendTo(afterSpacing); this.atIn = new NumericTextBox({ format: 'n1', value: 0, min: 1, max: 1584, width: 180, step: 0.5, enablePersistence: false, change: this.changeLineSpacingValue }); this.special = new DropDownList({ change: this.changeByValue, width: 180, enableRtl: isRtl }); this.special.appendTo(special); this.lineSpacing = new DropDownList({ change: this.changeBySpacing, width: '180px', enableRtl: isRtl }); this.lineSpacing.appendTo(lineSpacing); this.alignment = new DropDownList({ width: 180, change: this.changeByTextAlignment, enableRtl: isRtl }); this.alignment.appendTo(alignment); this.atIn.appendTo(lineSpacingAt); this.contextSpacing = new CheckBox({ change: this.changeContextualSpacing, label: locale.getConstant("Contextual Spacing"), enableRtl: isRtl, cssClass: 'e-de-para-dlg-cs-check-box' }); this.contextSpacing.appendTo(contextInputEle); indentContainer.addEventListener('keyup', instance.keyUpParagraphSettings); if (isRtl) { afterSpacingWholeDiv.classList.add('e-de-rtl'); lineTypeDiv.classList.add('e-de-rtl'); } let lineBreakContainer: HTMLDivElement = createElement('div') as HTMLDivElement; let paginationDiv: HTMLDivElement = createElement('div', { className: 'e-de-para-dlg-sub-container' }) as HTMLDivElement; this.paginationDiv = paginationDiv; let paginationLabel: HTMLElement = createElement('div', { className: 'e-de-para-dlg-heading', innerHTML: locale.getConstant('Pagination') }); paginationDiv.appendChild(paginationLabel); let widowContorlContainer: HTMLElement = createElement('div', { styles: 'display:block' }); paginationDiv.appendChild(widowContorlContainer); let keepNextContainer: HTMLElement = createElement('div', { styles: 'display:block' }); paginationDiv.appendChild(keepNextContainer); let keepLines: HTMLElement = createElement('div', { styles: 'display:block' }); paginationDiv.appendChild(keepLines); let keepWithNext: HTMLInputElement = createElement('input', { attrs: { type: 'checkbox' }, }) as HTMLInputElement; keepNextContainer.appendChild(keepWithNext); this.keepWithNext = new CheckBox({ change: this.changeKeepWithNext, label: locale.getConstant('Keep With Next'), enableRtl: isRtl, cssClass: 'e-de-para-dlg-cs-check-box' }); this.keepWithNext.appendTo(keepWithNext); let keepLinesTogether: HTMLInputElement = createElement('input', { attrs: { type: 'checkbox' }, }) as HTMLInputElement; keepLines.appendChild(keepLinesTogether); this.keepLinesTogether = new CheckBox({ change: this.changeKeepLinesTogether, label: locale.getConstant('Keep Lines Together'), enableRtl: isRtl, cssClass: 'e-de-para-dlg-cs-check-box' }); this.keepLinesTogether.appendTo(keepLinesTogether); let widowControl: HTMLInputElement = createElement('input', { attrs: { type: 'checkbox' }, }) as HTMLInputElement; widowContorlContainer.appendChild(widowControl); this.widowControlIn = new CheckBox({ change: this.changeWidowControl, label: locale.getConstant('WidowControl'), enableRtl: isRtl, cssClass: 'e-de-para-dlg-cs-check-box' }); this.widowControlIn.appendTo(widowControl); lineBreakContainer.appendChild(paginationDiv); const items: TabItemModel[] = [ { header: { text: locale.getConstant('Indents and Spacing') }, content: indentContainer }, { header: { text: locale.getConstant('Line and Page Breaks') }, content: lineBreakContainer }]; this.tabObj = new Tab({ items: items, enableRtl: isRtl, animation: { previous: { effect: 'None' }, next: { effect: 'None' } } }, ejtab); this.tabObj.isStringTemplate = true; } /** * @private * @param {KeyboardEvent} event - Specifies the event args. * @returns {void} */ public keyUpParagraphSettings = (event: KeyboardEvent): void => { if (event.keyCode === 13) { this.applyParagraphFormat(); } } /** * @private * @param {KeyboardEvent} event - Specifies the event args. * @returns {void} */ private changeBeforeSpacing = (event: NumericChangeArgs): void => { this.beforeSpacing = event.value; } /** * @private * @param {NumericChangeArgs} event - Specifies the event args. * @returns {void} */ private changeAfterSpacing = (event: NumericChangeArgs): void => { this.afterSpacing = event.value as number; } /** * @private * @param {NumericChangeArgs} event - Specifies the event args. * @returns {void} */ private changeLeftIndent = (event: NumericChangeArgs): void => { this.leftIndent = event.value as number; } /** * @private * @param {NumericChangeArgs} event - Specifies the event args. * @returns {void} */ private changeRightIndent = (event: NumericChangeArgs): void => { this.rightIndent = event.value as number; } /** * @private * @param {NumericChangeArgs} event - Specifies the event args. * @returns {void} */ private changeLineSpacingValue = (event: NumericChangeArgs): void => { this.lineSpacingIn = event.value as number; } /** * @private * @param {NumericChangeArgs} event - Specifies the event args. * @returns {void} */ private changeFirstLineIndent = (event: NumericChangeArgs): void => { this.firstLineIndent = event.value as number; if (this.special.index === 2) { this.firstLineIndent = -(this.firstLineIndent); this.leftIndent = this.leftIndentIn.value + event.value as number; } } /** * @private * @param {DropDownChangeArgs} event - Specifies the event args. * @returns {void} */ private changeByTextAlignment = (args: DropDownChangeArgs): void => { this.textAlignment = args.value as TextAlignment; } /** * @private * @param {ChangeArgs} event - Specifies change event args. * @returns {void} */ private changeBidirectional = (event: ChangeArgs): void => { if (event.value === 'ltr') { this.rtlButton.checked = !this.ltrButton.checked; this.bidi = false; } else { this.ltrButton.checked = !this.rtlButton.checked; this.bidi = true; } this.changeAlignmentByBidi(); }; /** * @private * @param {ChangeEventArgs} args - Specifies change event args. * @returns {void} */ private changeContextualSpacing = (args: ChangeEventArgs): void => { this.contextualSpacing = args.checked; }; /** * @private * @param {ChangeEventArgs} args - Specifies change event args. * @returns {void} */ private changeKeepWithNext = (args: ChangeEventArgs): void => { this.keepWithNextValue = args.checked; }; /** * @private * @param {ChangeEventArgs} args - Specifies change event args. * @returns {void} */ private changeKeepLinesTogether = (args: ChangeEventArgs): void => { this.keepLineTogetherValue = args.checked; }; /** * @private * @param {ChangeEventArgs} args - Specifies change event args. * @returns {void} */ private changeWidowControl= (args: ChangeEventArgs): void => { this.widowControlValue = args.checked; }; private changeAlignmentByBidi(): void { if (this.textAlignment === 'Left') { this.textAlignment = 'Right'; } else if (this.textAlignment === 'Right') { this.textAlignment = 'Left'; } if (!isNullOrUndefined(this.textAlignment)) { this.alignment.index = this.getAlignmentValue(this.textAlignment); } else { if (this.alignment.index === 0) { this.textAlignment = 'Center'; } else { this.textAlignment = 'Justify'; } } } /** * @private * @returns {void} */ public changeByValue = (): void => { let paragraphFormat: SelectionParagraphFormat = this.documentHelper.selection.paragraphFormat; switch (this.special.index) { case 0: if (paragraphFormat.firstLineIndent !== 0) { this.byIn.value = 0; this.leftIndent = this.leftIndentIn.value; } break; case 1: if (paragraphFormat.firstLineIndent === 0 || isNullOrUndefined(paragraphFormat.firstLineIndent)) { this.byIn.value = 0.1; } else if (paragraphFormat.firstLineIndent < 0) { this.byIn.value = -(paragraphFormat.firstLineIndent); if (Math.abs(paragraphFormat.firstLineIndent) <= this.leftIndent) { this.leftIndent = paragraphFormat.firstLineIndent + this.leftIndent; } } break; case 2: if (paragraphFormat.firstLineIndent === 0 || isNullOrUndefined(paragraphFormat.firstLineIndent)) { paragraphFormat.firstLineIndent = -0.1; } else if (paragraphFormat.firstLineIndent > 0) { this.byIn.value = (paragraphFormat.firstLineIndent); if (!isNullOrUndefined(this.leftIndent)) { this.leftIndent = this.leftIndent + paragraphFormat.firstLineIndent; } else { this.leftIndent = paragraphFormat.firstLineIndent; } } break; } } /** * @private * @returns {void} */ public changeBySpacing = (): void => { if (isNullOrUndefined(this.lineSpacing)) { return; } switch (this.lineSpacing.index) { case 0: this.lineSpacingType = 'AtLeast'; this.atIn.value = 12; break; case 1: this.lineSpacingType = 'Exactly'; this.atIn.value = 12; break; case 2: this.lineSpacingType = 'Multiple'; this.atIn.value = 1; break; } } /* eslint-enable */ /** * @private * @returns {void} */ public loadParagraphDialog = (): void => { if (this.isStyleDialog) { this.directionDiv.classList.add('e-de-disabledbutton'); } else { this.directionDiv.classList.remove('e-de-disabledbutton'); } let selectionFormat: SelectionParagraphFormat | WParagraphFormat; if (this.paragraphFormat) { selectionFormat = this.paragraphFormat; } else { selectionFormat = this.documentHelper.selection.paragraphFormat; } const alignValue: number = this.getAlignmentValue(selectionFormat.textAlignment); this.alignment.index = alignValue; this.beforeSpacingIn.value = selectionFormat.beforeSpacing; this.afterSpacingIn.value = selectionFormat.afterSpacing; this.leftIndentIn.value = selectionFormat.leftIndent; this.rightIndentIn.value = selectionFormat.rightIndent; this.byIn.value = Math.abs(selectionFormat.firstLineIndent); let lineSpaceValue: number = this.lineSpacing.index; this.keepWithNextValue = undefined; this.keepLineTogetherValue = undefined; this.widowControlValue = undefined; if (selectionFormat.firstLineIndent > 0) { this.special.index = 1; } else if (selectionFormat.firstLineIndent < 0) { this.special.index = 2; this.leftIndentIn.value = selectionFormat.leftIndent - this.byIn.value; } if (selectionFormat.lineSpacingType === 'AtLeast') { lineSpaceValue = 0; } else if (selectionFormat.lineSpacingType === 'Exactly') { lineSpaceValue = 1; } else { lineSpaceValue = 2; } this.lineSpacing.index = lineSpaceValue; this.atIn.value = selectionFormat.lineSpacing; if (this.documentHelper.selection.caret.style.display !== 'none') { this.documentHelper.selection.caret.style.display = 'none'; } if (selectionFormat.bidi) { this.rtlButton.checked = true; this.ltrButton.checked = false; } else { this.ltrButton.checked = true; this.rtlButton.checked = false; } if (isNullOrUndefined(selectionFormat.keepWithNext)) { this.keepWithNext.indeterminate = true; } else { this.keepWithNext.checked = selectionFormat.keepWithNext; } if (isNullOrUndefined(selectionFormat.keepLinesTogether)) { this.keepLinesTogether.indeterminate = true; } else { this.keepLinesTogether.checked = selectionFormat.keepLinesTogether; } if (isNullOrUndefined(selectionFormat.widowControl)) { this.widowControlIn.indeterminate = true; } else { this.widowControlIn.checked = selectionFormat.widowControl; } this.contextSpacing.checked = selectionFormat.contextualSpacing; }; private getAlignmentValue(textAlignment: TextAlignment): number { let alignValue: number; if (textAlignment === 'Center') { alignValue = 0; } else if (textAlignment === 'Left') { alignValue = 1; } else if (textAlignment === 'Right') { alignValue = 2; } else { alignValue = 3; } return alignValue; } /** * @private * @returns {void} */ public applyParagraphFormat = (): void => { let paraFormat: WParagraphFormat; let isApply: boolean; if (this.paragraphFormat) { paraFormat = this.paragraphFormat; isApply = false; } else { paraFormat = new WParagraphFormat(); isApply = true; } if (!isNullOrUndefined(this.beforeSpacing)) { paraFormat.beforeSpacing = this.beforeSpacing; } if (!isNullOrUndefined(this.afterSpacing)) { paraFormat.afterSpacing = this.afterSpacing; } if (!isNullOrUndefined(this.lineSpacingType)) { paraFormat.lineSpacingType = this.lineSpacingType; } if (!isNullOrUndefined(this.leftIndent)) { paraFormat.leftIndent = this.leftIndent; } if (!isNullOrUndefined(this.rightIndent)) { paraFormat.rightIndent = this.rightIndent; } if (!isNullOrUndefined(this.lineSpacingIn)) { paraFormat.lineSpacing = this.lineSpacingIn; } if (!isNullOrUndefined(this.firstLineIndent)) { paraFormat.firstLineIndent = Math.abs(this.firstLineIndent); if (this.special.index === 2) { paraFormat.firstLineIndent = -paraFormat.firstLineIndent; } } if (!isNullOrUndefined(this.bidi)) { paraFormat.bidi = this.bidi; } if (!isNullOrUndefined(this.textAlignment)) { paraFormat.textAlignment = this.textAlignment; } if (!isNullOrUndefined(this.contextualSpacing)) { paraFormat.contextualSpacing = this.contextualSpacing; } if (!isNullOrUndefined(this.keepWithNextValue)) { paraFormat.keepWithNext = this.keepWithNextValue; } else if (this.documentHelper.selection.paragraphFormat.keepWithNext) { paraFormat.keepWithNext = this.documentHelper.selection.paragraphFormat.keepWithNext; } if (!isNullOrUndefined(this.keepLineTogetherValue)) { paraFormat.keepLinesTogether = this.keepLineTogetherValue; } else if (this.documentHelper.selection.paragraphFormat.keepLinesTogether) { paraFormat.keepLinesTogether = this.documentHelper.selection.paragraphFormat.keepLinesTogether; } if (!isNullOrUndefined(this.widowControlValue)) { paraFormat.widowControl = this.widowControlValue; } else if (this.documentHelper.selection.paragraphFormat.widowControl) { paraFormat.widowControl = this.documentHelper.selection.paragraphFormat.widowControl; } if (isApply) { this.onParagraphFormat(paraFormat); } else { this.documentHelper.owner.styleDialogModule.updateParagraphFormat(); } this.documentHelper.hideDialog(); }; /** * Applies Paragraph Format * * @private * @param {WParagraphFormat} paragraphFormat - Specifies the paragraph format. * @returns {void} */ public onParagraphFormat(paragraphFormat: WParagraphFormat): void { const selection: Selection = this.documentHelper.selection; const isListBidi: boolean = paragraphFormat.bidi && selection.paragraphFormat.listId !== -1; if (!isListBidi) { this.documentHelper.layout.isBidiReLayout = true; } this.documentHelper.owner.editor.setPreviousBlockToLayout(); this.documentHelper.owner.editorModule.initHistory('ParagraphFormat'); this.documentHelper.owner.isShiftingEnabled = true; if (this.documentHelper.selection.isEmpty) { this.documentHelper.owner.editorModule.applyParaFormatProperty(selection.start.paragraph, undefined, paragraphFormat, false); this.documentHelper.owner.editor.layoutItemBlock(selection.start.paragraph, false); } else { this.documentHelper.owner.editorModule.updateSelectionParagraphFormatting('ParagraphFormat', paragraphFormat, false); } this.documentHelper.owner.editorModule.reLayout(selection); if (!isListBidi) { this.documentHelper.layout.isBidiReLayout = false; } } /** * @private * @returns {void} */ public closeParagraphDialog = (): void => { this.leftIndent = undefined; this.afterSpacing = undefined; this.beforeSpacing = undefined; this.firstLineIndent = undefined; this.textAlignment = undefined; this.rightIndent = undefined; this.lineSpacingIn = undefined; this.lineSpacingType = undefined; this.paragraphFormat = undefined; this.documentHelper.hideDialog(); }; /** * @private * @param {WParagraphFormat} paragraphFormat - Specifies the paragraph format. * @returns {void} */ public show(paragraphFormat?: WParagraphFormat): void { if (paragraphFormat) { this.isStyleDialog = true; this.paragraphFormat = paragraphFormat; } else { this.isStyleDialog = false; } const local: L10n = new L10n('documenteditor', this.documentHelper.owner.defaultLocale); local.setLocale(this.documentHelper.owner.locale); if (!this.target) { this.initParagraphDialog(local); } this.loadParagraphDialog(); this.documentHelper.dialog.header = local.getConstant('Paragraph'); this.documentHelper.dialog.content = this.target; this.documentHelper.dialog.height = 'auto'; this.documentHelper.dialog.width = 'auto'; this.documentHelper.dialog.buttons = [{ click: this.applyParagraphFormat, buttonModel: { content: local.getConstant('Ok'), cssClass: 'e-flat e-para-okay', isPrimary: true } }, { click: this.closeParagraphDialog, buttonModel: { content: local.getConstant('Cancel'), cssClass: 'e-flat e-para-cancel' } }]; this.documentHelper.dialog.beforeOpen = this.documentHelper.updateFocus; this.documentHelper.dialog.close = this.documentHelper.updateFocus; this.documentHelper.dialog.dataBind(); this.documentHelper.dialog.show(); let dialogElement: HTMLElement = this.documentHelper.dialog.element; if (dialogElement) { //Update dialog height let header: HTMLElement = dialogElement.getElementsByClassName('e-dlg-header-content')[0] as HTMLElement; let contentElement: HTMLElement = dialogElement.getElementsByClassName('e-dlg-content')[0] as HTMLElement; let footer: HTMLElement = dialogElement.getElementsByClassName('e-footer-content')[0] as HTMLElement; let contentStyle: CSSStyleDeclaration = getComputedStyle(contentElement); let dialogStyle: CSSStyleDeclaration = getComputedStyle(dialogElement); let paddingTop: number = parseInt(contentStyle.paddingTop); let paddingBottom: number = parseInt(contentStyle.paddingBottom); let paddingVertical: number = (isNaN(paddingTop) ? 0 : paddingTop) + (isNaN(paddingBottom) ? 0 : paddingBottom); let borderTop: number = parseInt(dialogStyle.borderTop); let borderBottom: number = parseInt(dialogStyle.borderBottom); let borderVertical: number = (isNaN(borderTop) ? 0 : borderTop) + (isNaN(borderBottom) ? 0 : borderBottom); let contentHeight: number = dialogElement.offsetHeight - (header.offsetHeight + footer.offsetHeight + paddingVertical + borderVertical); this.target.style.height = contentHeight + 'px'; //Update dialog width let paddingLeft: number = parseInt(contentStyle.paddingLeft); let paddingRight = parseInt(contentStyle.paddingRight); let paddingHorizontal: number = (isNaN(paddingLeft) ? 0 : paddingLeft) + (isNaN(paddingRight) ? 0 : paddingRight); let borderLeft: number = parseInt(dialogStyle.borderLeft); let borderRight = parseInt(dialogStyle.borderRight); let borderHorizontal: number = (isNaN(borderLeft) ? 0 : borderLeft) + (isNaN(borderRight) ? 0 : borderRight); let contentWidth: number = dialogElement.offsetWidth - (paddingHorizontal + borderHorizontal); this.paginationDiv.style.width = contentWidth + 'px'; } } /** * @private * @returns {void} */ public destroy(): void { if (this.afterSpacingIn) { this.afterSpacingIn.destroy(); this.afterSpacingIn = undefined; } if (this.beforeSpacingIn) { this.beforeSpacingIn.destroy(); this.beforeSpacingIn = undefined; } if (this.leftIndentIn) { this.leftIndentIn.destroy(); this.leftIndentIn = undefined; } if (this.rightIndentIn) { this.rightIndentIn.destroy(); this.rightIndentIn = undefined; } if (this.byIn) { this.byIn.destroy(); this.byIn = undefined; } if (this.special) { this.special.destroy(); this.special = undefined; } if (this.atIn) { this.atIn.destroy(); this.atIn = undefined; } if (this.alignment) { this.alignment.change = undefined; this.alignment.destroy(); } this.alignment = undefined; if (this.lineSpacing) { this.lineSpacing.change = undefined; this.lineSpacing.destroy(); } this.lineSpacing = undefined; if (this.special) { this.special.change = undefined; this.special.destroy(); } this.special = undefined; this.documentHelper = undefined; if (!isNullOrUndefined(this.target)) { if (this.target.parentElement) { this.target.parentElement.removeChild(this.target); } for (let q: number = 0; q < this.target.childNodes.length; q++) { this.target.removeChild(this.target.childNodes[q]); q--; } this.target = undefined; } } }
the_stack
import chalk from "chalk"; import { Embark, EmbarkEvents } from "embark-core"; import constants from "embark-core/constants.json"; import { __ } from "embark-i18n"; import { dappPath, escapeHtml, exit, jsonFunctionReplacer, warnIfPackageNotDefinedLocally } from "embark-utils"; import stringify from "json-stringify-safe"; import { dirname } from "path"; import util from "util"; type MatchFunction = (cmd: string) => boolean; interface HelpDescription { matches: string[] | MatchFunction; description: string; usage?: string; } export default class Console { private embark: Embark; private events: EmbarkEvents; private plugins: any; private version: string; private logger: any; private ipc: any; private fs: any; private config: any; private history: string[]; private cmdHistoryFile: string; // private providerReady: boolean; private helpCmds: any; constructor(embark: Embark, options: any) { this.embark = embark; this.events = options.events; this.plugins = options.plugins; this.version = options.version; this.logger = options.logger; this.fs = embark.fs; this.ipc = options.ipc; this.config = options.config; this.history = []; this.cmdHistoryFile = options.cmdHistoryFile || dappPath(".embark", "cmd_history"); this.loadHistory(); this.helpCmds = {}; if (this.ipc.isServer()) { this.ipc.on("console:executeCmd", (cmd: string, cb: any) => { this.executeCmd(cmd, (err: any, result: any) => { if (err) { // reformat for IPC reply const error = { name: "Console error", message: err, stack: err.stack }; return cb(error); } cb(null, typeof result !== "string" ? util.inspect(result) : result); }); }); this.ipc.on("console:executePartial", (cmd: string, cb: any) => { this.executePartial(cmd, (_: any, result: any) => { cb(null, util.inspect(result)); }); }); this.ipc.on("console:history:save", true, (cmd: string) => { this.saveHistory(cmd, true); }); } this.events.setCommandHandler("console:register:helpCmd", (cmdOptions: any, cb: any) => { const {cmdName, cmdHelp} = cmdOptions; this.helpCmds[cmdName] = cmdHelp; if (cb) { cb(); } }); this.events.setCommandHandler("console:unregister:helpCmd", (cmdName: string, cb: any) => { delete this.helpCmds[cmdName]; if (cb) { cb(); } }); this.events.setCommandHandler("console:executeCmd", this.executeCmd.bind(this)); this.events.setCommandHandler("console:executePartial", this.executePartial.bind(this)); this.events.setCommandHandler("console:history", (cb: any) => this.getHistory(this.cmdHistorySize(), cb)); this.registerConsoleCommands(); if (this.isEmbarkConsole) { return; } this.registerApi(); } private get isEmbarkConsole() { return this.ipc.connected && this.ipc.isClient() && this.embark.currentContext && this.embark.currentContext.includes(constants.contexts.console); } private cmdHistorySize() { return parseInt(process.env.CMD_HISTORY_SIZE || constants.console.commandHistorySize, 10); } private registerApi() { const plugin = this.plugins.createPlugin("consoleApi", {}); plugin.registerAPICall("post", "/embark-api/command", (req: any, res: any) => { this.executeCmd(req.body.command, (err: any, result: any, shouldEscapeHtml = true) => { if (err) { return res.send({ result: err.message || err }); } let response = result; if (typeof result !== "string") { response = stringify(result, jsonFunctionReplacer, 2); } else if (shouldEscapeHtml) { // Avoid HTML injection in the Cockpit response = escapeHtml(response); } const jsonResponse = { result: response }; if (res.headersSent) { return res.end(jsonResponse); } return res.send(jsonResponse); }); }); } private processEmbarkCmd(cmd: string, helpDescriptions: HelpDescription[]) { if (cmd === "help" || cmd === __("help") || cmd === "01189998819991197253") { const helpText = [ __("Welcome to Embark") + " " + this.version, "", __("possible commands are:"), // TODO: this help commands should be passed through an API // chalk.cyan("swarm") + " - " + __("instantiated swarm-api object configured to the current environment (available if swarm is enabled)"), // chalk.cyan("EmbarkJS") + " - " + __("EmbarkJS static functions for Storage, Messages, Names, etc."), chalk.cyan("log [process] on/off") + " - " + __("Activate or deactivate the logs of a sub-process. Options: blockchain, ipfs, webserver"), ]; for (const cmdName of Object.keys(this.helpCmds)) { const helpCmd = this.helpCmds[cmdName]; helpText.push(chalk.cyan(cmdName) + " - " + helpCmd); } // TODO: remove old helpDescriptions helpDescriptions.forEach((helpDescription) => { let matches = [] as string[]; if (Array.isArray(helpDescription.matches)) { matches = helpDescription.matches as string[]; } helpText.push(`${chalk.cyan(helpDescription.usage || matches.join("/"))} - ${helpDescription.description}`); }); // Add end commands helpText.push(chalk.cyan("quit") + " - " + __("to immediately exit (alias: exit)"), "", __("The web3 object and the interfaces for the deployed contracts and their methods are also available")); return helpText.join("\n"); } else if (["quit", "exit", "sair", "sortir", __("quit")].indexOf(cmd) >= 0) { exit(0); } return false; } private executePartial(cmd: string, callback: any) { // if this is the embark console process, send the command to the process // running all the needed services (ie the process running `embark run`) if (this.isEmbarkConsole) { return this.ipc.request("console:executePartial", cmd, callback); } this.executeCmd(cmd, (_: any, result: any) => { callback(null, result); }); } private executeCmd(cmd: string, callback?: any, logEvalCode = false, logEvalError = false) { // if this is the embark console process, send the command to the process // running all the needed services (ie the process running `embark run`) if (this.isEmbarkConsole) { return this.ipc.request("console:executeCmd", cmd, callback); } if (cmd.indexOf("profile") === 0 && warnIfPackageNotDefinedLocally("embark-profiler", this.embark.logger.warn, this.embark.config.embarkConfig) !== true) { return callback(null, "please install embark-profiler plugin"); } if (!(cmd.split(" ")[0] === "history" || cmd === __("history"))) { this.saveHistory(cmd); } const plugins = this.plugins.getPluginsProperty("console", "console"); const helpDescriptions: any[] = []; for (const plugin of plugins) { if (plugin.description) { helpDescriptions.push({ description: plugin.description, matches: plugin.matches, usage: plugin.usage, }); } if (plugin.matches) { const isFunction = typeof plugin.matches === "function"; if ((isFunction && plugin.matches.call(this, cmd)) || (!isFunction && plugin.matches.includes(cmd))) { return plugin.process.call(this, cmd, callback); } continue; } const pluginResult = plugin.call(this, cmd, {}); if (typeof pluginResult !== "object") { if (pluginResult !== false && pluginResult !== "false" && pluginResult !== undefined) { this.logger.warn("[DEPRECATED] In future versions of embark, we expect the console command to return an object " + "having 2 functions: match and process." + " The documentation with example can be found here: https://framework.embarklabs.io/docs/plugin_reference.html#embark-registerConsoleCommand-callback-options"); return callback(null, pluginResult); } } else if (pluginResult.match()) { return pluginResult.process(callback); } } const output = this.processEmbarkCmd(cmd, helpDescriptions); if (output) { return callback(null, output); } this.events.request("runcode:eval", cmd, callback, true, logEvalCode, logEvalError); } private registerConsoleCommands() { this.embark.registerConsoleCommand({ description: __("display console commands history"), matches: (cmd: string) => { const [cmdName] = cmd.split(" "); return cmdName === "history"; }, process: (cmd: string, callback: any) => { const [_cmdName, length] = cmd.split(" "); this.getHistory(length, callback); }, usage: "history [optionalLength]", }); } private loadHistory() { if (this.fs.existsSync(this.cmdHistoryFile)) { this.fs.readFileSync(this.cmdHistoryFile) .toString() .split("\n") .reverse() .forEach((cmd: string) => { this.history.push(cmd); }); } } private getHistory(historySize: any, callback: any) { if (typeof historySize === "string") { historySize = parseInt(historySize, 10); if (isNaN(historySize)) { return callback("Invalid argument. Please provide an integer."); } } const length = historySize || this.cmdHistorySize(); return callback(null, this.history .slice(Math.max(0, this.history.length - length)) .filter((line: string) => line.trim()) .reverse() .join("\n")); } private saveHistory(cmd: string, fromIpcClient = false) { const history = this.history; if (fromIpcClient) { if (history[history.length - 1] !== cmd) { history.push(cmd); } this.events.emit("console:history:save", cmd); return this.ipc.broadcast("console:history:save", cmd, true); } history.push(cmd); if (this.ipc.isServer()) { this.ipc.broadcast("console:history:save", cmd, true); } else if (this.ipc.connected) { this.ipc.client.emit("console:history:save", cmd); } if (this.fs.existsSync(dirname(this.cmdHistoryFile))) { this.fs.writeFileSync( this.cmdHistoryFile, history .slice(Math.max(0, history.length - this.cmdHistorySize())) .reverse() .filter((line: string) => line.trim()) .join("\n"), ); } } }
the_stack
export const LATEST_VERSION = 20180209; export const DIGITAL = 0; export const ANALOG = 1; export type CSBoolean = boolean; export type CSFloat = number; export type CSInteger = number; export type CSString = string; export type ALLOWED_ASSERTION_TYPES = "abort" | "abort_recover" | "continue" | "recover"; export type ALLOWED_AXIS = "all" | "x" | "y" | "z"; export type ALLOWED_CHANNEL_NAMES = "email" | "espeak" | "ticker" | "toast"; export type ALLOWED_MESSAGE_TYPES = "assertion" | "busy" | "debug" | "error" | "fun" | "info" | "success" | "warn"; export type ALLOWED_OPS = "<" | ">" | "is" | "is_undefined" | "not"; export type ALLOWED_PACKAGES = "arduino_firmware" | "farmbot_os"; export type ALLOWED_PIN_MODES = 0 | 1; export type ALLOWED_SPECIAL_VALUE = "current_location" | "safe_height" | "soil_height"; export type AllowedPinTypes = "BoxLed3" | "BoxLed4" | "Peripheral" | "Sensor"; export type Color = "blue" | "gray" | "green" | "orange" | "pink" | "purple" | "red" | "yellow"; export type DataChangeType = "add" | "remove" | "update"; export type LegalArgString = "_else" | "_then" | "assertion_type" | "axis" | "axis_operand" | "channel_name" | "data_value" | "default_value" | "label" | "lhs" | "locals" | "location" | "lua" | "message" | "message_type" | "milliseconds" | "number" | "offset" | "op" | "package" | "pin_id" | "pin_mode" | "pin_number" | "pin_type" | "pin_value" | "point_group_id" | "pointer_id" | "pointer_type" | "priority" | "radius" | "resource" | "resource_id" | "resource_type" | "rhs" | "sequence_id" | "speed" | "speed_setting" | "string" | "tool_id" | "url" | "value" | "variance" | "version" | "x" | "y" | "z"; export type LegalKindString = "Assertion" | "AxisAddition" | "AxisOverwrite" | "Calibrate" | "ChangeOwnership" | "Channel" | "CheckUpdates" | "Coordinate" | "EmergencyLock" | "EmergencyUnlock" | "Execute" | "ExecuteScript" | "Explanation" | "FactoryReset" | "FindHome" | "FlashFirmware" | "Home" | "Identifier" | "If" | "InstallFarmware" | "InstallFirstPartyFarmware" | "InternalEntryPoint" | "InternalFarmEvent" | "InternalRegimen" | "Lua" | "Move" | "MoveAbsolute" | "MoveRelative" | "NamedPin" | "Nothing" | "Numeric" | "Pair" | "ParameterApplication" | "ParameterDeclaration" | "Point" | "PointGroup" | "PowerOff" | "Random" | "ReadPin" | "ReadStatus" | "Reboot" | "RemoveFarmware" | "Resource" | "ResourceUpdate" | "RpcError" | "RpcOk" | "RpcRequest" | "SafeZ" | "ScopeDeclaration" | "SendMessage" | "Sequence" | "SetServoAngle" | "SetUserEnv" | "SpecialValue" | "SpeedOverwrite" | "Sync" | "TakePhoto" | "Text" | "TogglePin" | "Tool" | "UpdateFarmware" | "UpdateResource" | "VariableDeclaration" | "Wait" | "WritePin" | "Zero"; export type LegalSequenceKind = "_if" | "assertion" | "calibrate" | "change_ownership" | "check_updates" | "emergency_lock" | "emergency_unlock" | "execute" | "execute_script" | "factory_reset" | "find_home" | "flash_firmware" | "home" | "install_farmware" | "install_first_party_farmware" | "lua" | "move" | "move_absolute" | "move_relative" | "power_off" | "read_pin" | "read_status" | "reboot" | "remove_farmware" | "send_message" | "set_servo_angle" | "set_user_env" | "sync" | "take_photo" | "toggle_pin" | "update_farmware" | "update_resource" | "wait" | "write_pin" | "zero"; export type PlantStage = "active" | "harvested" | "pending" | "planned" | "planted" | "removed" | "sprouted"; export type PointType = "GenericPointer" | "Plant" | "ToolSlot" | "Weed"; export type lhs = "pin0" | "pin1" | "pin10" | "pin11" | "pin12" | "pin13" | "pin14" | "pin15" | "pin16" | "pin17" | "pin18" | "pin19" | "pin2" | "pin20" | "pin21" | "pin22" | "pin23" | "pin24" | "pin25" | "pin26" | "pin27" | "pin28" | "pin29" | "pin3" | "pin30" | "pin31" | "pin32" | "pin33" | "pin34" | "pin35" | "pin36" | "pin37" | "pin38" | "pin39" | "pin4" | "pin40" | "pin41" | "pin42" | "pin43" | "pin44" | "pin45" | "pin46" | "pin47" | "pin48" | "pin49" | "pin5" | "pin50" | "pin51" | "pin52" | "pin53" | "pin54" | "pin55" | "pin56" | "pin57" | "pin58" | "pin59" | "pin6" | "pin60" | "pin61" | "pin62" | "pin63" | "pin64" | "pin65" | "pin66" | "pin67" | "pin68" | "pin69" | "pin7" | "pin8" | "pin9" | "x" | "y" | "z"; export type resource_type = "Device" | "GenericPointer" | "Plant" | "Point" | "ToolSlot" | "Weed"; export type AssertionBodyItem = never; /** assertion Tag properties: *. */ export interface Assertion { comment?: string | undefined; kind: "assertion"; args: { _then: Execute | Nothing; assertion_type: ALLOWED_ASSERTION_TYPES; lua: CSString; } body?: AssertionBodyItem[] | undefined; } export type IfBodyItem = (Pair); /** _if Tag properties: *. */ export interface If { comment?: string | undefined; kind: "_if"; args: { _else: Execute | Nothing; _then: Execute | Nothing; lhs: CSString | NamedPin; op: ALLOWED_OPS; rhs: CSInteger; } body?: IfBodyItem[] | undefined; } export type CalibrateBodyItem = never; /** calibrate Tag properties: firmware_user, function. */ export interface Calibrate { comment?: string | undefined; kind: "calibrate"; args: { axis: ALLOWED_AXIS; } body?: CalibrateBodyItem[] | undefined; } export type ChangeOwnershipBodyItem = (Pair); /** change_ownership Not a commonly used node. May be removed without notice. Tag properties: api_writer, cuts_power, disk_user, function, network_user. */ export interface ChangeOwnership { comment?: string | undefined; kind: "change_ownership"; args: { } body?: ChangeOwnershipBodyItem[] | undefined; } export type ChannelBodyItem = never; /** channel Specifies a communication path for log messages. Tag properties: data. */ export interface Channel { comment?: string | undefined; kind: "channel"; args: { channel_name: ALLOWED_CHANNEL_NAMES; } body?: ChannelBodyItem[] | undefined; } export type CheckUpdatesBodyItem = never; /** check_updates Tag properties: cuts_power, disk_user, function, network_user. */ export interface CheckUpdates { comment?: string | undefined; kind: "check_updates"; args: { package: CSString; } body?: CheckUpdatesBodyItem[] | undefined; } export type CoordinateBodyItem = never; /** coordinate Tag properties: data, location_like. */ export interface Coordinate { comment?: string | undefined; kind: "coordinate"; args: { x: CSInteger | CSFloat; y: CSInteger | CSFloat; z: CSInteger | CSFloat; } body?: CoordinateBodyItem[] | undefined; } export type EmergencyLockBodyItem = never; /** emergency_lock Tag properties: control_flow, firmware_user, function. */ export interface EmergencyLock { comment?: string | undefined; kind: "emergency_lock"; args: { } body?: EmergencyLockBodyItem[] | undefined; } export type EmergencyUnlockBodyItem = never; /** emergency_unlock Tag properties: firmware_user, function. */ export interface EmergencyUnlock { comment?: string | undefined; kind: "emergency_unlock"; args: { } body?: EmergencyUnlockBodyItem[] | undefined; } export type ExecuteScriptBodyItem = (Pair); /** execute_script Tag properties: *. */ export interface ExecuteScript { comment?: string | undefined; kind: "execute_script"; args: { label: CSString; } body?: ExecuteScriptBodyItem[] | undefined; } export type ExecuteBodyItem = (ParameterApplication); /** execute Tag properties: *. */ export interface Execute { comment?: string | undefined; kind: "execute"; args: { sequence_id: CSInteger; } body?: ExecuteBodyItem[] | undefined; } export type ExplanationBodyItem = never; /** explanation Tag properties: data. */ export interface Explanation { comment?: string | undefined; kind: "explanation"; args: { message: CSString; } body?: ExplanationBodyItem[] | undefined; } export type FactoryResetBodyItem = never; /** factory_reset Tag properties: cuts_power, function. */ export interface FactoryReset { comment?: string | undefined; kind: "factory_reset"; args: { package: CSString; } body?: FactoryResetBodyItem[] | undefined; } export type FindHomeBodyItem = never; /** find_home Tag properties: firmware_user, function. */ export interface FindHome { comment?: string | undefined; kind: "find_home"; args: { axis: ALLOWED_AXIS; speed: CSInteger; } body?: FindHomeBodyItem[] | undefined; } export type FlashFirmwareBodyItem = never; /** flash_firmware Tag properties: api_writer, disk_user, firmware_user, function, network_user. */ export interface FlashFirmware { comment?: string | undefined; kind: "flash_firmware"; args: { package: CSString; } body?: FlashFirmwareBodyItem[] | undefined; } export type HomeBodyItem = never; /** home Tag properties: firmware_user, function. */ export interface Home { comment?: string | undefined; kind: "home"; args: { axis: ALLOWED_AXIS; speed: CSInteger; } body?: HomeBodyItem[] | undefined; } export type IdentifierBodyItem = never; /** identifier Tag properties: data. */ export interface Identifier { comment?: string | undefined; kind: "identifier"; args: { label: CSString; } body?: IdentifierBodyItem[] | undefined; } export type InstallFarmwareBodyItem = never; /** install_farmware Tag properties: api_writer, disk_user, function, network_user. */ export interface InstallFarmware { comment?: string | undefined; kind: "install_farmware"; args: { url: CSString; } body?: InstallFarmwareBodyItem[] | undefined; } export type InstallFirstPartyFarmwareBodyItem = never; /** install_first_party_farmware Tag properties: function, network_user. */ export interface InstallFirstPartyFarmware { comment?: string | undefined; kind: "install_first_party_farmware"; args: { } body?: InstallFirstPartyFarmwareBodyItem[] | undefined; } export type InternalFarmEventBodyItem = (ParameterApplication); /** internal_farm_event Tag properties: . */ export interface InternalFarmEvent { comment?: string | undefined; kind: "internal_farm_event"; args: { } body?: InternalFarmEventBodyItem[] | undefined; } export type InternalRegimenBodyItem = (ParameterApplication | ParameterDeclaration | VariableDeclaration); /** internal_regimen Tag properties: . */ export interface InternalRegimen { comment?: string | undefined; kind: "internal_regimen"; args: { } body?: InternalRegimenBodyItem[] | undefined; } export type MoveRelativeBodyItem = never; /** move_relative Tag properties: firmware_user, function. */ export interface MoveRelative { comment?: string | undefined; kind: "move_relative"; args: { speed: CSInteger; x: CSInteger | CSFloat; y: CSInteger | CSFloat; z: CSInteger | CSFloat; } body?: MoveRelativeBodyItem[] | undefined; } export type NothingBodyItem = never; /** nothing Tag properties: data, function. */ export interface Nothing { comment?: string | undefined; kind: "nothing"; args: { } body?: NothingBodyItem[] | undefined; } export type PairBodyItem = never; /** pair Tag properties: data. */ export interface Pair { comment?: string | undefined; kind: "pair"; args: { label: CSString; value: CSString | CSInteger | CSBoolean; } body?: PairBodyItem[] | undefined; } export type ParameterApplicationBodyItem = never; /** parameter_application Tag properties: control_flow, function, scope_writer. */ export interface ParameterApplication { comment?: string | undefined; kind: "parameter_application"; args: { data_value: Tool | Coordinate | Point | Identifier | Numeric | Text | PointGroup; label: CSString; } body?: ParameterApplicationBodyItem[] | undefined; } export type ParameterDeclarationBodyItem = never; /** parameter_declaration Tag properties: scope_writer. */ export interface ParameterDeclaration { comment?: string | undefined; kind: "parameter_declaration"; args: { default_value: Tool | Coordinate | Point | Identifier | Numeric | Text; label: CSString; } body?: ParameterDeclarationBodyItem[] | undefined; } export type PointBodyItem = never; /** point Tag properties: data, location_like. */ export interface Point { comment?: string | undefined; kind: "point"; args: { pointer_id: CSInteger; pointer_type: PointType; } body?: PointBodyItem[] | undefined; } export type PowerOffBodyItem = never; /** power_off Tag properties: cuts_power, function. */ export interface PowerOff { comment?: string | undefined; kind: "power_off"; args: { } body?: PowerOffBodyItem[] | undefined; } export type ReadStatusBodyItem = never; /** read_status Tag properties: function. */ export interface ReadStatus { comment?: string | undefined; kind: "read_status"; args: { } body?: ReadStatusBodyItem[] | undefined; } export type RebootBodyItem = never; /** reboot Tag properties: cuts_power, firmware_user, function. */ export interface Reboot { comment?: string | undefined; kind: "reboot"; args: { package: CSString; } body?: RebootBodyItem[] | undefined; } export type RemoveFarmwareBodyItem = never; /** remove_farmware Tag properties: function. */ export interface RemoveFarmware { comment?: string | undefined; kind: "remove_farmware"; args: { package: CSString; } body?: RemoveFarmwareBodyItem[] | undefined; } export type RpcErrorBodyItem = (Explanation); /** rpc_error Tag properties: data. */ export interface RpcError { comment?: string | undefined; kind: "rpc_error"; args: { label: CSString; } body?: RpcErrorBodyItem[] | undefined; } export type RpcOkBodyItem = never; /** rpc_ok Tag properties: data. */ export interface RpcOk { comment?: string | undefined; kind: "rpc_ok"; args: { label: CSString; } body?: RpcOkBodyItem[] | undefined; } export type RpcRequestBodyItem = (If | Assertion | Calibrate | ChangeOwnership | CheckUpdates | EmergencyLock | EmergencyUnlock | Execute | ExecuteScript | FactoryReset | FindHome | FlashFirmware | Home | InstallFarmware | InstallFirstPartyFarmware | Lua | Move | MoveAbsolute | MoveRelative | PowerOff | ReadPin | ReadStatus | Reboot | RemoveFarmware | SendMessage | SetServoAngle | SetUserEnv | Sync | TakePhoto | TogglePin | UpdateFarmware | UpdateResource | Wait | WritePin | Zero); /** rpc_request Tag properties: *. */ export interface RpcRequest { comment?: string | undefined; kind: "rpc_request"; args: { label: CSString; priority: CSInteger; } body?: RpcRequestBodyItem[] | undefined; } export type ScopeDeclarationBodyItem = (ParameterDeclaration | VariableDeclaration); /** scope_declaration Tag properties: scope_writer. */ export interface ScopeDeclaration { comment?: string | undefined; kind: "scope_declaration"; args: { } body?: ScopeDeclarationBodyItem[] | undefined; } export type SendMessageBodyItem = (Channel); /** send_message Tag properties: function. */ export interface SendMessage { comment?: string | undefined; kind: "send_message"; args: { message: CSString; message_type: ALLOWED_MESSAGE_TYPES; } body?: SendMessageBodyItem[] | undefined; } export type SequenceBodyItem = (If | Assertion | Calibrate | ChangeOwnership | CheckUpdates | EmergencyLock | EmergencyUnlock | Execute | ExecuteScript | FactoryReset | FindHome | FlashFirmware | Home | InstallFarmware | InstallFirstPartyFarmware | Lua | Move | MoveAbsolute | MoveRelative | PowerOff | ReadPin | ReadStatus | Reboot | RemoveFarmware | SendMessage | SetServoAngle | SetUserEnv | Sync | TakePhoto | TogglePin | UpdateFarmware | UpdateResource | Wait | WritePin | Zero); /** sequence Tag properties: *. */ export interface Sequence { comment?: string | undefined; kind: "sequence"; args: { locals: ScopeDeclaration; version: CSInteger; } body?: SequenceBodyItem[] | undefined; } export type SetServoAngleBodyItem = never; /** set_servo_angle Tag properties: firmware_user, function. */ export interface SetServoAngle { comment?: string | undefined; kind: "set_servo_angle"; args: { pin_number: CSInteger | NamedPin; pin_value: CSInteger; } body?: SetServoAngleBodyItem[] | undefined; } export type SetUserEnvBodyItem = (Pair); /** set_user_env Tag properties: disk_user, function. */ export interface SetUserEnv { comment?: string | undefined; kind: "set_user_env"; args: { } body?: SetUserEnvBodyItem[] | undefined; } export type SyncBodyItem = never; /** sync Tag properties: disk_user, function, network_user. */ export interface Sync { comment?: string | undefined; kind: "sync"; args: { } body?: SyncBodyItem[] | undefined; } export type TakePhotoBodyItem = never; /** take_photo Tag properties: disk_user, function. */ export interface TakePhoto { comment?: string | undefined; kind: "take_photo"; args: { } body?: TakePhotoBodyItem[] | undefined; } export type TextBodyItem = never; /** text Tag properties: . */ export interface Text { comment?: string | undefined; kind: "text"; args: { string: CSString; } body?: TextBodyItem[] | undefined; } export type TogglePinBodyItem = never; /** toggle_pin Tag properties: firmware_user, function. */ export interface TogglePin { comment?: string | undefined; kind: "toggle_pin"; args: { pin_number: CSInteger | NamedPin; } body?: TogglePinBodyItem[] | undefined; } export type ToolBodyItem = never; /** tool Tag properties: api_validated, data, location_like. */ export interface Tool { comment?: string | undefined; kind: "tool"; args: { tool_id: CSInteger; } body?: ToolBodyItem[] | undefined; } export type UpdateFarmwareBodyItem = never; /** update_farmware Tag properties: api_validated, function, network_user. */ export interface UpdateFarmware { comment?: string | undefined; kind: "update_farmware"; args: { package: CSString; } body?: UpdateFarmwareBodyItem[] | undefined; } export type VariableDeclarationBodyItem = never; /** variable_declaration Tag properties: function, scope_writer. */ export interface VariableDeclaration { comment?: string | undefined; kind: "variable_declaration"; args: { data_value: Tool | Coordinate | Point | Identifier | Numeric | Text | PointGroup; label: CSString; } body?: VariableDeclarationBodyItem[] | undefined; } export type WaitBodyItem = never; /** wait Tag properties: function. */ export interface Wait { comment?: string | undefined; kind: "wait"; args: { milliseconds: CSInteger; } body?: WaitBodyItem[] | undefined; } export type ZeroBodyItem = never; /** zero Tag properties: firmware_user, function. */ export interface Zero { comment?: string | undefined; kind: "zero"; args: { axis: ALLOWED_AXIS; } body?: ZeroBodyItem[] | undefined; } export type NamedPinBodyItem = never; /** named_pin Tag properties: api_validated, data, firmware_user, function, rpi_user. */ export interface NamedPin { comment?: string | undefined; kind: "named_pin"; args: { pin_id: CSInteger; pin_type: AllowedPinTypes; } body?: NamedPinBodyItem[] | undefined; } export type MoveAbsoluteBodyItem = never; /** move_absolute Tag properties: firmware_user, function. */ export interface MoveAbsolute { comment?: string | undefined; kind: "move_absolute"; args: { location: Tool | Coordinate | Point | Identifier; offset: Coordinate; speed: CSInteger; } body?: MoveAbsoluteBodyItem[] | undefined; } export type WritePinBodyItem = never; /** write_pin Tag properties: firmware_user, function, rpi_user. */ export interface WritePin { comment?: string | undefined; kind: "write_pin"; args: { pin_mode: ALLOWED_PIN_MODES; pin_number: CSInteger | NamedPin; pin_value: CSInteger; } body?: WritePinBodyItem[] | undefined; } export type ReadPinBodyItem = never; /** read_pin Tag properties: firmware_user, function, rpi_user. */ export interface ReadPin { comment?: string | undefined; kind: "read_pin"; args: { label: CSString; pin_mode: ALLOWED_PIN_MODES; pin_number: CSInteger | NamedPin; } body?: ReadPinBodyItem[] | undefined; } export type ResourceUpdateBodyItem = never; /** resource_update Tag properties: api_writer, function, network_user. */ export interface ResourceUpdate { comment?: string | undefined; kind: "resource_update"; args: { label: CSString; resource_id: CSInteger; resource_type: resource_type; value: CSString | CSInteger | CSBoolean; } body?: ResourceUpdateBodyItem[] | undefined; } export type ResourceBodyItem = never; /** resource Tag properties: network_user. */ export interface Resource { comment?: string | undefined; kind: "resource"; args: { resource_id: CSInteger; resource_type: resource_type; } body?: ResourceBodyItem[] | undefined; } export type UpdateResourceBodyItem = (Pair); /** update_resource Tag properties: api_writer, function, network_user. */ export interface UpdateResource { comment?: string | undefined; kind: "update_resource"; args: { resource: Identifier | Resource | Point; } body?: UpdateResourceBodyItem[] | undefined; } export type PointGroupBodyItem = never; /** point_group Tag properties: data, list_like. */ export interface PointGroup { comment?: string | undefined; kind: "point_group"; args: { point_group_id: CSInteger; } body?: PointGroupBodyItem[] | undefined; } export type NumericBodyItem = never; /** numeric Tag properties: data. */ export interface Numeric { comment?: string | undefined; kind: "numeric"; args: { number: CSInteger; } body?: NumericBodyItem[] | undefined; } export type LuaBodyItem = never; /** lua Tag properties: *. */ export interface Lua { comment?: string | undefined; kind: "lua"; args: { lua: CSString; } body?: LuaBodyItem[] | undefined; } export type SpecialValueBodyItem = never; /** special_value Tag properties: data. */ export interface SpecialValue { comment?: string | undefined; kind: "special_value"; args: { label: CSString; } body?: SpecialValueBodyItem[] | undefined; } export type AxisOverwriteBodyItem = never; /** axis_overwrite Tag properties: data. */ export interface AxisOverwrite { comment?: string | undefined; kind: "axis_overwrite"; args: { axis: ALLOWED_AXIS; axis_operand: Coordinate | Identifier | Lua | Numeric | Point | Random | SpecialValue | Tool; } body?: AxisOverwriteBodyItem[] | undefined; } export type AxisAdditionBodyItem = never; /** axis_addition Tag properties: data. */ export interface AxisAddition { comment?: string | undefined; kind: "axis_addition"; args: { axis: ALLOWED_AXIS; axis_operand: Coordinate | Identifier | Lua | Numeric | Point | Random | SpecialValue | Tool; } body?: AxisAdditionBodyItem[] | undefined; } export type SpeedOverwriteBodyItem = never; /** speed_overwrite Tag properties: data. */ export interface SpeedOverwrite { comment?: string | undefined; kind: "speed_overwrite"; args: { axis: ALLOWED_AXIS; speed_setting: Lua | Numeric; } body?: SpeedOverwriteBodyItem[] | undefined; } export type SafeZBodyItem = never; /** safe_z Tag properties: data. */ export interface SafeZ { comment?: string | undefined; kind: "safe_z"; args: { } body?: SafeZBodyItem[] | undefined; } export type RandomBodyItem = never; /** random Tag properties: data. */ export interface Random { comment?: string | undefined; kind: "random"; args: { variance: CSInteger; } body?: RandomBodyItem[] | undefined; } export type MoveBodyItem = (AxisAddition | AxisOverwrite | SafeZ | SpeedOverwrite); /** move Tag properties: firmware_user, function. */ export interface Move { comment?: string | undefined; kind: "move"; args: { } body?: MoveBodyItem[] | undefined; } export type CeleryNode = Assertion | AxisAddition | AxisOverwrite | Calibrate | ChangeOwnership | Channel | CheckUpdates | Coordinate | EmergencyLock | EmergencyUnlock | Execute | ExecuteScript | Explanation | FactoryReset | FindHome | FlashFirmware | Home | Identifier | If | InstallFarmware | InstallFirstPartyFarmware | InternalFarmEvent | InternalRegimen | Lua | Move | MoveAbsolute | MoveRelative | NamedPin | Nothing | Numeric | Pair | ParameterApplication | ParameterDeclaration | Point | PointGroup | PowerOff | Random | ReadPin | ReadStatus | Reboot | RemoveFarmware | Resource | ResourceUpdate | RpcError | RpcOk | RpcRequest | SafeZ | ScopeDeclaration | SendMessage | Sequence | SetServoAngle | SetUserEnv | SpecialValue | SpeedOverwrite | Sync | TakePhoto | Text | TogglePin | Tool | UpdateFarmware | UpdateResource | VariableDeclaration | Wait | WritePin | Zero;
the_stack
import { ASUtil, instantiateSync as instantiateBuffer, instantiate, instantiateStreaming } from "assemblyscript/lib/loader"; import { ICanvasSYS } from "../util/ICanvasSYS"; import { CanvasInstruction } from "../shared/CanvasInstruction"; const CanvasPatternRepetitionValues = ["repeat", "repeat_x", "repeat_y", "no_repeat"]; const FillRuleValues = ["nonzero", "evenodd"]; const LineCapValues = ["butt", "round", "square"]; const LineJoinValues = ["bevel", "round", "miter"]; const TextBaselineValues = ["top", "hanging", "middle", "alphabetic", "ideographic", "bottom"]; const TextAlignValues = ["left", "right", "center", "start", "end"]; const CanvasDirectionValues = ["ltr", "rtl", "inherit"]; const ImageSmoothingQualityValues = ["low", "medium", "high"]; const GlobalCompositeOperationValues = [ "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity", ]; const bool = { "true": 1, "false": 0, }; export class AS2DGlue<T> { public imports: any = null; public wasm: (ASUtil & T & ICanvasSYS) | null = null; private id: number = -1; public instantiateBuffer(buffer: any, imports: any): ASUtil & T & ICanvasSYS { this.imports = imports; this.hookImports(); this.wasm = instantiateBuffer<T & ICanvasSYS>(buffer, this.imports); this.hookWasmApi(); return this.wasm!; } public async instantiateStreaming(response: Promise<Response>, imports: any): Promise<ASUtil & T & ICanvasSYS> { this.imports = imports; this.hookImports(); this.wasm = await instantiateStreaming<T & ICanvasSYS>(response, this.imports); this.hookWasmApi(); return this.wasm!; } public instantiate(module: any, imports: any): ASUtil & T & ICanvasSYS { this.imports = imports; this.hookImports(); this.wasm = instantiate(module, this.imports) as any; this.hookWasmApi(); return this.wasm!; } private hookImports(): void { this.imports.__canvas_sys = { addColorStop: this.addColorStop.bind(this), createLinearGradient: this.createLinearGradient.bind(this), createPattern: this.createPattern.bind(this), createRadialGradient: this.createRadialGradient.bind(this), disposeCanvasGradient: this.disposeCanvasGradient.bind(this), disposeCanvasPattern: this.disposeCanvasPattern.bind(this), disposeImage: this.disposeImage.bind(this), isPointInPath: this.isPointInPath.bind(this), isPointInStroke: this.isPointInStroke.bind(this), loadImage: this.loadImage.bind(this), measureText: this.measureText.bind(this), render: this.render.bind(this), }; } private hookWasmApi(): void { this.wasm!.contexts = {}; this.wasm!.gradients = {}; this.wasm!.images = {}; this.wasm!.loading = {}; this.wasm!.patterns = {}; this.wasm!.useContext = this.useContext.bind(this); } private useContext(name: string, ctx: CanvasRenderingContext2D): number { this.id += 1; this.wasm!.contexts[this.id] = ctx; this.wasm!.__use_context(this.wasm!.__allocString(name), this.id); return this.id; } private createLinearGradient(objid: number, x0: number, y0: number, x1: number, y1: number): number { this.id += 1; if (!this.wasm!.contexts[objid]) throw new Error("Cannot find canvas: " + objid); this.wasm!.gradients[this.id] = this.wasm!.contexts[objid].createLinearGradient(x0, y0, x1, y1); return this.id; } private createRadialGradient(objid: number, x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): number { this.id += 1; if (!this.wasm!.contexts[objid]) throw new Error("Cannot find canvas: " + objid); this.wasm!.gradients[this.id] = this.wasm!.contexts[objid].createRadialGradient(x0, y0, r0, x1, y1, r1); return this.id; } private addColorStop(objid: number, offset: number, color: number): void { if (!this.wasm!.gradients[objid]) throw new Error("Cannot find gradient: " + objid); this.wasm!.gradients[objid].addColorStop(offset, this.wasm!.__getString(color)); } private loadImage(imgPointer: number, srcPointer: number): number { var src: string = this.wasm!.__getString(srcPointer); this.id += 1; var result: number = this.id; this.wasm!.loading[result] = fetch(src) .then(e => e.blob()) .then(createImageBitmap) .then(e => { this.wasm!.__image_loaded(imgPointer, e.width, e.height); this.wasm!.images[result] = e; return e; }); return this.id; } private createPattern(cvsobjid: number, objid: number, repetition: number): number { this.id += 1; if (!this.wasm!.contexts[cvsobjid]) throw new Error("Cannot find canvas: " + cvsobjid); if (!this.wasm!.images[objid]) throw new Error("Cannot find image: " + objid); this.wasm!.patterns[this.id] = this.wasm!.contexts[cvsobjid].createPattern( this.wasm!.images[objid], CanvasPatternRepetitionValues[repetition].replace("_", "-"), )!; return this.id; } public measureText(cvsobjid: number, text: number): number { // The canvas exists, because render was already called // if (!this.wasm!.contexts[cvsobjid]) throw new Error("Cannot find canvas: " + cvsobjid); var ctx: CanvasRenderingContext2D = this.wasm!.contexts[cvsobjid]; return ctx.measureText(this.wasm!.__getString(text)).width; } private render(cvsobjid: number, pointer: number): void { if (!this.wasm!.contexts[cvsobjid]) throw new Error("Cannot find canvas: " + cvsobjid); var wasm: ASUtil & T & ICanvasSYS = this.wasm!; var ctx: CanvasRenderingContext2D = wasm.contexts[cvsobjid]; var data = new Float64Array(wasm.memory.buffer, pointer, 0x10000); var i = 0; var strings: { [pointer: number]: string; } = {}; while (i < 0x10000 && data[i] !== CanvasInstruction.Commit) { switch (data[i]) { case CanvasInstruction.Arc: { ctx.arc(data[i + 2], data[i + 3], data[i + 4], data[i + 5], data[i + 6], data[i + 7] === 1); break; } case CanvasInstruction.ArcTo: { ctx.arcTo(data[i + 2], data[i + 3], data[i + 4], data[i + 5], data[i + 6]); break; } case CanvasInstruction.BeginPath: { ctx.beginPath(); break; } case CanvasInstruction.BezierCurveTo: { ctx.bezierCurveTo(data[i + 2], data[i + 3], data[i + 4], data[i + 5], data[i + 6], data[i + 7]); break; } case CanvasInstruction.Clip: { ctx.clip(); break; } case CanvasInstruction.ClosePath: { ctx.closePath(); break; } case CanvasInstruction.ClearRect: { ctx.clearRect(data[i + 2], data[i + 3], data[i + 4], data[i + 5]); break; } case CanvasInstruction.Direction: { ctx.direction = CanvasDirectionValues[data[i + 2]] as CanvasDirection; break; } case CanvasInstruction.DrawImage: { ctx.drawImage(wasm.images[data[i + 2]], data[i + 3], data[i + 4], data[i + 5], data[i + 6], data[i + 7], data[i + 8], data[i + 9], data[i + 10]); break; } case CanvasInstruction.Ellipse: { ctx.ellipse(data[i + 2], data[i + 3], data[i + 4], data[i + 5], data[i + 6], data[i + 7], data[i + 8], data[i + 9] === 1); break; } case CanvasInstruction.Fill: { ctx.fill(FillRuleValues[data[i + 2]] as CanvasFillRule); break; } case CanvasInstruction.FillGradient: { ctx.fillStyle = wasm.gradients[data[i + 2]]; break; } case CanvasInstruction.FillPattern: { ctx.fillStyle = wasm.patterns[data[i + 2]]; break; } case CanvasInstruction.FillRect: { ctx.fillRect(data[i + 2], data[i + 3], data[i + 4], data[i + 5]); break; } case CanvasInstruction.FillStyle: { ctx.fillStyle = strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])); break; } case CanvasInstruction.FillText: { ctx.fillText( strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])), data[i + 3], data[i + 4], ); break; } case CanvasInstruction.FillTextWidth: { ctx.fillText( strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])), data[i + 3], data[i + 4], data[i + 5], ); break; } case CanvasInstruction.Filter: { ctx.filter = strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])); break; } case CanvasInstruction.Font: { ctx.font = strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])); break; } case CanvasInstruction.GlobalAlpha: { ctx.globalAlpha = data[i + 2]; break; } case CanvasInstruction.GlobalCompositeOperation: { ctx.globalCompositeOperation = GlobalCompositeOperationValues[data[i + 2]]; break; } case CanvasInstruction.ImageSmoothingEnabled: { ctx.imageSmoothingEnabled = data[i + 1] === 1; break; } case CanvasInstruction.ImageSmoothingQuality: { ctx.imageSmoothingQuality = ImageSmoothingQualityValues[data[i + 2]] as "low" | "medium" | "high"; break; } case CanvasInstruction.LineCap: { ctx.lineCap = LineCapValues[data[i + 2]] as CanvasLineCap; break; } case CanvasInstruction.LineDash: { // @ts-ignore setLineDash accepts a Float64Array as a parameter ctx.setLineDash(wasm.__getFloat64Array(data[i + 2])); break; } case CanvasInstruction.LineDashOffset: { ctx.lineDashOffset = data[i + 2]; break; } case CanvasInstruction.LineJoin: { ctx.lineJoin = LineJoinValues[data[i + 2]] as CanvasLineJoin; break; } case CanvasInstruction.LineTo: { ctx.lineTo(data[i + 2], data[i + 3]); break; } case CanvasInstruction.LineWidth: { ctx.lineWidth = data[i + 2]; break; } case CanvasInstruction.MiterLimit: { ctx.miterLimit = data[i + 2]; break; } case CanvasInstruction.MoveTo: { ctx.moveTo(data[i + 2], data[i + 3]); break; } case CanvasInstruction.QuadraticCurveTo: { ctx.quadraticCurveTo(data[i + 2], data[i + 3], data[i + 4], data[i + 5]); break; } case CanvasInstruction.Rect: { ctx.rect(data[i + 2], data[i + 3], data[i + 4], data[i + 5]); break; } case CanvasInstruction.Restore: { ctx.restore(); break; } case CanvasInstruction.Save: { ctx.save(); break; } case CanvasInstruction.SetTransform: { ctx.setTransform(data[i + 2], data[i + 3], data[i + 4], data[i + 5], data[i + 6], data[i + 7]); break; } case CanvasInstruction.ShadowBlur: { ctx.shadowBlur = data[i + 2]; break; } case CanvasInstruction.ShadowColor: { ctx.shadowColor = strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])); break; } case CanvasInstruction.ShadowOffsetX: { ctx.shadowOffsetX = data[i + 2]; break; } case CanvasInstruction.ShadowOffsetY: { ctx.shadowOffsetY = data[i + 2]; break; } case CanvasInstruction.Stroke: { ctx.stroke(); break; } case CanvasInstruction.StrokeGradient: { ctx.strokeStyle = wasm.gradients[data[i + 2]]; break; } case CanvasInstruction.StrokePattern: { ctx.strokeStyle = wasm.patterns[data[i + 2]]; break; } case CanvasInstruction.StrokeRect: { ctx.strokeRect(data[i + 2], data[i + 3], data[i + 4], data[i + 5]); break; } case CanvasInstruction.StrokeStyle: { ctx.strokeStyle = strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])); break; } case CanvasInstruction.StrokeText: { ctx.strokeText( strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])), data[i + 3], data[i + 4], ); break; } case CanvasInstruction.StrokeTextWidth: { ctx.strokeText( strings[data[i + 2]] || (strings[data[i + 2]] = wasm.__getString(data[i + 2])), data[i + 3], data[i + 4], data[i + 5], ); break; } case CanvasInstruction.TextAlign: { ctx.textAlign = TextAlignValues[data[i + 2]] as CanvasTextAlign; break; } case CanvasInstruction.TextBaseline: { ctx.textBaseline = TextBaselineValues[data[i + 2]] as CanvasTextBaseline; break; } } i = data[i + 1]; } } disposeCanvasPattern(id: number): void { delete this.wasm!.patterns[id]; } disposeImage(id: number): void { delete this.wasm!.images[id]; } disposeCanvasGradient(id: number): void { delete this.wasm!.gradients[id]; } isPointInPath(id: number, x: number, y: number, fillRule: number): number { return bool[(<any>this.wasm!.contexts[id]).isPointInPath(x, y, FillRuleValues[fillRule]).toString() as "true" | "false"]; } isPointInStroke(id: number, x: number, y: number): number { return bool[(<any>this.wasm!.contexts[id]).isPointInStroke(x, y).toString() as "true" | "false"]; } }
the_stack
import { unwrap } from "idb"; import orderBy from "lodash-es/orderBy"; import { DEFAULT_PLAY_THROUGH_INJURIES, DIFFICULTY, gameAttributesArrayToObject, isSport, MAX_SUPPORTED_LEAGUE_VERSION, PHASE, PLAYER, unwrapGameAttribute, } from "../../common"; import { player, season } from "../core"; import { idb } from "."; import iterate from "./iterate"; import { defaultGameAttributes, helpers, logEvent } from "../util"; import connectIndexedDB from "./connectIndexedDB"; import type { DBSchema, IDBPDatabase, IDBPTransaction, StoreNames } from "idb"; import type { DraftLotteryResult, DraftPickWithoutKey, ReleasedPlayerWithoutKey, AllStars, EventBBGMWithoutKey, GameAttribute, Game, MessageWithoutKey, Negotiation, PlayerFeatWithoutKey, PlayerWithoutKey, MinimalPlayerRatings, PlayoffSeries, ScheduleGameWithoutKey, TeamSeasonWithoutKey, TeamStatsWithoutKey, Team, Trade, ScheduledEventWithoutKey, HeadToHead, } from "../../common/types"; import getInitialNumGamesConfDivSettings from "../core/season/getInitialNumGamesConfDivSettings"; export interface LeagueDB extends DBSchema { allStars: { key: number; value: AllStars; }; awards: { key: number; value: any; }; draftLotteryResults: { key: number; value: DraftLotteryResult; }; draftPicks: { key: number; value: DraftPickWithoutKey; autoIncrementKeyPath: "dpid"; }; events: { key: number; value: EventBBGMWithoutKey; autoIncrementKeyPath: "eid"; indexes: { dpids: number; pids: number; season: number; }; }; gameAttributes: { key: string; value: GameAttribute; }; games: { key: number; value: Game; indexes: { season: number; }; }; headToHeads: { key: number; value: HeadToHead; }; messages: { key: number; value: MessageWithoutKey; autoIncrementKeyPath: "mid"; }; negotiations: { key: number; value: Negotiation; }; playerFeats: { key: number; value: PlayerFeatWithoutKey; autoIncrementKeyPath: "fid"; }; players: { key: number; value: PlayerWithoutKey<MinimalPlayerRatings>; autoIncrementKeyPath: "pid"; indexes: { "draft.year, retiredYear": [number, number]; statsTids: number; tid: number; }; }; playoffSeries: { key: number; value: PlayoffSeries; }; releasedPlayers: { key: number; value: ReleasedPlayerWithoutKey; autoIncrementKeyPath: "rid"; }; schedule: { key: number; value: ScheduleGameWithoutKey; autoIncrementKeyPath: "gid"; }; scheduledEvents: { key: number; value: ScheduledEventWithoutKey; autoIncrementKeyPath: "id"; indexes: { season: number; }; }; teamSeasons: { key: number; value: TeamSeasonWithoutKey; autoIncrementKeyPath: "rid"; indexes: { "season, tid": [number, number]; "tid, season": [number, number]; }; }; teamStats: { key: number; value: TeamStatsWithoutKey; autoIncrementKeyPath: "rid"; indexes: { "season, tid": [number, number]; tid: number; }; }; teams: { key: number; value: Team; }; trade: { key: number; value: Trade; }; } type VersionChangeTransaction = IDBPTransaction< LeagueDB, StoreNames<LeagueDB>[], "versionchange" >; // I did it this way (with the raw IDB API) because I was afraid it would read all players into memory before getting // the stats and writing them back to the database. Promises/async/await would help, but Firefox before 60 does not like // that. const upgrade29 = (tx: IDBTransaction) => { let lastCentury = 0; // Iterate over players tx.objectStore("players").openCursor().onsuccess = (event: any) => { const cursor = event.target.result; if (cursor) { const p = cursor.value; if (!Array.isArray(p.relatives)) { p.relatives = []; } // This can be really slow, so need some UI for progress const century = Math.floor(p.draft.year / 100); if (century > lastCentury) { const text = `Upgrading players drafted in the ${century}00s...`; logEvent({ type: "upgrade", text, saveToDb: false, }); console.log(text); lastCentury = century; } tx .objectStore("playerStats") .index("pid, season, tid") .getAll(IDBKeyRange.bound([p.pid], [p.pid, ""])).onsuccess = ( event2: any, ) => { // Index brings them back maybe out of order p.stats = orderBy(event2.target.result, ["season", "playoffs", "psid"]); cursor.update(p); cursor.continue(); }; } else { // This seems to trigger a memory leak in Chrome, so leave playerStats behind... // tx.db.deleteObjectStore("playerStats"); } }; }; const upgrade31 = (tx: IDBTransaction) => { tx.objectStore("gameAttributes").get("season").onsuccess = (event: any) => { if (event.target.result === undefined) { throw new Error("Missing season in gameAttributes during upgrade"); } const season = event.target.result.value; if (typeof season !== "number") { throw new Error("Invalid season in gameAttributes during upgrade"); } tx.objectStore("gameAttributes").get("phase").onsuccess = (event2: any) => { if (event2.target.result === undefined) { throw new Error("Missing phase in gameAttributes during upgrade"); } const phase = event2.target.result.value; if (typeof phase !== "number") { throw new Error("Invalid phase in gameAttributes during upgrade"); } tx.objectStore("draftOrder").get(0).onsuccess = (event3: any) => { if (event3.target.result === undefined) { throw new Error( "Missing draftOrder in gameAttributes during upgrade", ); } const draftOrder = event3.target.result.draftOrder; if (!Array.isArray(draftOrder)) { throw new Error( "Invalid draftOrder in gameAttributes during upgrade", ); } tx.objectStore("draftPicks").openCursor().onsuccess = (event4: any) => { const cursor = event4.target.result; if (cursor) { const dp = cursor.value; dp.pick = 0; cursor.update(dp); cursor.continue(); } else { for (const dp2 of draftOrder) { if (phase === PHASE.FANTASY_DRAFT) { dp2.season = "fantasy"; } else { dp2.season = season; } tx.objectStore("draftPicks").put(dp2); } } }; }; }; }; }; const upgrade33 = (transaction: VersionChangeTransaction) => { const tx = unwrap(transaction); tx.objectStore("gameAttributes").get("season").onsuccess = (event: any) => { if (event.target.result === undefined) { throw new Error("Missing season in gameAttributes during upgrade"); } const season = event.target.result.value; if (typeof season !== "number") { throw new Error("Invalid season in gameAttributes during upgrade"); } tx.objectStore("gameAttributes").get("phase").onsuccess = (event2: any) => { if (event2.target.result === undefined) { throw new Error("Missing phase in gameAttributes during upgrade"); } const phase = event2.target.result.value; if (typeof phase !== "number") { throw new Error("Invalid phase in gameAttributes during upgrade"); } const offset = phase >= PHASE.RESIGN_PLAYERS ? 1 : 0; iterate(transaction.objectStore("players"), undefined, undefined, p => { if (p.tid === PLAYER.UNDRAFTED) { const draftYear = season + offset; if (p.ratings[0].season !== draftYear || p.draft.year !== draftYear) { p.ratings[0].season = draftYear; p.draft.year = draftYear; return p; } } else if (p.tid === PLAYER.UNDRAFTED_2) { p.tid = PLAYER.UNDRAFTED; p.ratings[0].season = season + 1 + offset; p.draft.year = p.ratings[0].season; return p; } else if (p.tid === PLAYER.UNDRAFTED_3) { p.tid = PLAYER.UNDRAFTED; p.ratings[0].season = season + 2 + offset; p.draft.year = p.ratings[0].season; return p; } }); }; }; }; const upgrade38 = (transaction: VersionChangeTransaction) => { const tx = unwrap(transaction); const scheduleStore = tx.objectStore("schedule"); scheduleStore.getAll().onsuccess = (event: any) => { const schedule = event.target.result; const updated = season.addDaysToSchedule(schedule); scheduleStore.clear().onsuccess = () => { for (const game of updated) { scheduleStore.put(game); } }; }; }; const upgrade45 = (transaction: VersionChangeTransaction) => { const tx = unwrap(transaction); const gameAttributesStore = tx.objectStore("gameAttributes"); gameAttributesStore.getAll().onsuccess = (event: any) => { const gameAttributes = gameAttributesArrayToObject(event.target.result); const settings = { divs: unwrapGameAttribute(gameAttributes, "divs"), numGames: gameAttributes.numGames, numGamesConf: defaultGameAttributes.numGamesConf, numGamesDiv: defaultGameAttributes.numGamesDiv, }; tx.objectStore("teams").getAll().onsuccess = (event2: any) => { const teams = event2.target.result; let numGamesDiv = null; let numGamesConf = null; try { const response = getInitialNumGamesConfDivSettings(teams, settings); numGamesDiv = response.numGamesDiv; numGamesConf = response.numGamesConf; } catch (error) { console.error(error); } gameAttributesStore.put({ key: "numGamesDiv", value: numGamesDiv, }); gameAttributesStore.put({ key: "numGamesConf", value: numGamesConf, }); }; }; }; /** * Create a new league database with the latest structure. * * @param {Object} event Event from onupgradeneeded, with oldVersion 0. * @param {number} lid Integer league ID number for new league. */ const create = (db: IDBPDatabase<LeagueDB>) => { // rid ("row id") is used as the keyPath for objects without an innate unique identifier db.createObjectStore("awards", { keyPath: "season", }); db.createObjectStore("draftPicks", { keyPath: "dpid", autoIncrement: true, }); const eventStore = db.createObjectStore("events", { keyPath: "eid", autoIncrement: true, }); db.createObjectStore("gameAttributes", { keyPath: "key", }); const gameStore = db.createObjectStore("games", { keyPath: "gid", }); db.createObjectStore("headToHeads", { keyPath: "season", }); db.createObjectStore("messages", { keyPath: "mid", autoIncrement: true, }); db.createObjectStore("negotiations", { keyPath: "pid", }); db.createObjectStore("playerFeats", { keyPath: "fid", autoIncrement: true, }); const playerStore = db.createObjectStore("players", { keyPath: "pid", autoIncrement: true, }); db.createObjectStore("playoffSeries", { keyPath: "season", }); db.createObjectStore("releasedPlayers", { keyPath: "rid", autoIncrement: true, }); db.createObjectStore("schedule", { keyPath: "gid", autoIncrement: true, }); const teamSeasonsStore = db.createObjectStore("teamSeasons", { keyPath: "rid", autoIncrement: true, }); const teamStatsStore = db.createObjectStore("teamStats", { keyPath: "rid", autoIncrement: true, }); db.createObjectStore("teams", { keyPath: "tid", }); db.createObjectStore("trade", { keyPath: "rid", }); db.createObjectStore("draftLotteryResults", { keyPath: "season", }); db.createObjectStore("allStars", { keyPath: "season", }); eventStore.createIndex("season", "season", { unique: false, }); eventStore.createIndex("pids", "pids", { unique: false, multiEntry: true, }); eventStore.createIndex("dpids", "dpids", { unique: false, multiEntry: true, }); gameStore.createIndex("season", "season", { unique: false, }); playerStore.createIndex( "draft.year, retiredYear", ["draft.year", "retiredYear"], { unique: false, }, ); playerStore.createIndex("statsTids", "statsTids", { unique: false, multiEntry: true, }); playerStore.createIndex("tid", "tid", { unique: false, }); teamSeasonsStore.createIndex("season, tid", ["season", "tid"], { unique: true, }); teamSeasonsStore.createIndex("tid, season", ["tid", "season"], { unique: false, }); teamStatsStore.createIndex("season, tid", ["season", "tid"], { unique: false, }); teamStatsStore.createIndex("tid", "tid", { unique: false, }); const scheduledEventsStore = db.createObjectStore("scheduledEvents", { keyPath: "id", autoIncrement: true, }); scheduledEventsStore.createIndex("season", "season", { unique: false, }); }; const migrate = ({ db, lid, oldVersion, transaction, }: { db: IDBPDatabase<LeagueDB>; lid: number; oldVersion: number; transaction: VersionChangeTransaction; }) => { console.log(db, lid, oldVersion, transaction); let upgradeMsg = `Upgrading league${lid} database from version ${oldVersion} to version ${db.version}.`; let slowUpgradeCalled = false; const slowUpgrade = () => { if (slowUpgradeCalled) { return; } slowUpgradeCalled = true; upgradeMsg += " For large leagues, this can take several minutes or more."; console.log(upgradeMsg); logEvent({ type: "upgrade", text: upgradeMsg, saveToDb: false, }); }; if (isSport("basketball") || isSport("football")) { if (oldVersion <= 15) { throw new Error(`League is too old to upgrade (version ${oldVersion})`); } if (oldVersion <= 16) { const teamSeasonsStore = db.createObjectStore("teamSeasons", { keyPath: "rid", autoIncrement: true, }); const teamStatsStore = db.createObjectStore("teamStats", { keyPath: "rid", autoIncrement: true, }); teamSeasonsStore.createIndex("tid, season", ["tid", "season"], { unique: false, }); teamSeasonsStore.createIndex("season, tid", ["season", "tid"], { unique: true, }); teamStatsStore.createIndex("tid", "tid", { unique: false, }); teamStatsStore.createIndex("season, tid", ["season", "tid"], { unique: false, }); iterate(transaction.objectStore("teams"), undefined, undefined, t => { for (const teamStats of (t as any).stats) { teamStats.tid = t.tid; if (!teamStats.hasOwnProperty("ba")) { teamStats.ba = 0; } teamStatsStore.add(teamStats); } for (const teamSeason of (t as any).seasons) { teamSeason.tid = t.tid; teamSeasonsStore.add(teamSeason); } delete (t as any).stats; delete (t as any).seasons; return t; }); } if (oldVersion <= 17) { // This used to upgrade team logos to the new ones, but Firefox } if (oldVersion <= 18) { // Split old single string p.name into two names iterate(transaction.objectStore("players"), undefined, undefined, p => { if ((p as any).name) { const bothNames = (p as any).name.split(" "); p.firstName = bothNames[0]; p.lastName = bothNames[1]; delete (p as any).name; } return p; }); } if (oldVersion <= 19) { // New best records format in awards iterate(transaction.objectStore("awards"), undefined, undefined, a => { if (a.bre && a.brw) { a.bestRecordConfs = [a.bre, a.brw]; a.bestRecord = a.bre.won >= a.brw.won ? a.bre : a.brw; delete a.bre; delete a.brw; return a; } }); } if (oldVersion <= 20) { // Removing indexes when upgrading to cache version transaction.objectStore("draftPicks").deleteIndex("season"); transaction.objectStore("draftPicks").deleteIndex("tid"); transaction.objectStore("playerFeats").deleteIndex("pid"); transaction.objectStore("playerFeats").deleteIndex("tid"); transaction.objectStore("players").deleteIndex("draft.year"); transaction.objectStore("players").deleteIndex("retiredYear"); transaction.objectStore("releasedPlayers").deleteIndex("tid"); transaction.objectStore("releasedPlayers").deleteIndex("contract.exp"); } if (oldVersion <= 21) { transaction .objectStore("players") .createIndex("draft.year, retiredYear", ["draft.year", "retiredYear"], { unique: false, }); iterate(transaction.objectStore("players"), undefined, undefined, p => { if (p.retiredYear === null || p.retiredYear === undefined) { p.retiredYear = Infinity; return p; } }); } if (oldVersion <= 22) { db.createObjectStore("draftLotteryResults", { keyPath: "season", }); } if (oldVersion <= 23) { iterate(transaction.objectStore("players"), undefined, undefined, p => { for (const r of p.ratings) { r.hgt = player.heightToRating(p.hgt); } return p; }); } if (oldVersion <= 24) { iterate( transaction.objectStore("teamStats"), undefined, undefined, ts => { ts.oppBlk = ts.ba; delete ts.ba; return ts; }, ); } if (oldVersion <= 25) { iterate(transaction.objectStore("games"), undefined, undefined, gm => { for (const t of gm.teams) { delete t.trb; for (const p of t.players) { delete p.trb; } } return gm; }); iterate( transaction.objectStore("playerStats" as any), undefined, undefined, ps => { delete ps.trb; return ps; }, ); iterate( transaction.objectStore("teamStats"), undefined, undefined, ts => { delete ts.trb; delete ts.oppTrb; return ts; }, ); } if (oldVersion <= 26) { slowUpgrade(); // Only non-retired players, for efficiency iterate( transaction.objectStore("players"), undefined, undefined, (p: any) => { for (const r of p.ratings) { // Replace blk/stl with diq if (typeof r.diq !== "number") { if (typeof r.blk === "number" && typeof r.stl === "number") { r.diq = Math.round((r.blk + r.stl) / 2); delete r.blk; delete r.stl; } else { r.diq = 50; } } // Add oiq if (typeof r.oiq !== "number") { r.oiq = Math.round((r.drb + r.pss + r.tp + r.ins) / 4); if (typeof r.oiq !== "number") { r.oiq = 50; } } // Scale ratings const ratingKeys = [ "stre", "spd", "jmp", "endu", "ins", "dnk", "ft", "fg", "tp", "oiq", "diq", "drb", "pss", "reb", ]; for (const key of ratingKeys) { if (typeof r[key] === "number") { // 100 -> 80 // 0 -> 20 // Linear in between r[key] -= (20 * (r[key] - 50)) / 50; } else { console.log(p); throw new Error(`Missing rating: ${key}`); } } r.ovr = player.ovr(r); r.skills = player.skills(r); // Don't want to deal with bootstrapPot now being async r.pot = r.ovr; if (p.draft.year === r.season) { p.draft.ovr = r.ovr; p.draft.skills = r.skills; p.draft.pot = r.pot; } } if (!Array.isArray(p.relatives)) { p.relatives = []; } return p; }, ); } if (oldVersion <= 27) { iterate( transaction.objectStore("teamSeasons"), undefined, undefined, teamSeason => { if (typeof teamSeason.stadiumCapacity !== "number") { teamSeason.stadiumCapacity = 25000; return teamSeason; } }, ); } if (oldVersion <= 28) { slowUpgrade(); upgrade29(unwrap(transaction)); } if (oldVersion === 29) { // === rather than <= is to prevent the 30 and 27/29 upgrades from having a race condition on updating players iterate(transaction.objectStore("players"), undefined, undefined, p => { if (!Array.isArray(p.relatives)) { p.relatives = []; return p; } }); } if (oldVersion <= 30) { upgrade31(unwrap(transaction)); } if (oldVersion <= 31) { // Gets need to use raw IDB API because Firefox < 60 const tx = unwrap(transaction); tx.objectStore("gameAttributes").get("difficulty").onsuccess = ( event: any, ) => { let difficulty = event.target.result !== undefined ? event.target.result.value : undefined; if (typeof difficulty === "number") { // Migrating from initial test implementation difficulty -= 0.5; } else { difficulty = 0; } tx.objectStore("gameAttributes").put({ key: "difficulty", value: difficulty, }); unwrap(idb.meta.transaction("leagues").objectStore("leagues")).get( lid, ).onsuccess = (event2: any) => { const l = event2.target.result; l.difficulty = difficulty; idb.meta.put("leagues", l); }; }; } if (oldVersion <= 32) { upgrade33(transaction); } if (oldVersion <= 33) { db.createObjectStore("allStars", { keyPath: "season", }); } if (oldVersion <= 34) { const teamsDefault = helpers.getTeamsDefault(); iterate(transaction.objectStore("teams"), undefined, undefined, t => { if (!(t as any).colors) { if ( (teamsDefault as any)[t.tid] && teamsDefault[t.tid].region === t.region && teamsDefault[t.tid].name === t.name ) { t.colors = teamsDefault[t.tid].colors; } else { t.colors = ["#000000", "#cccccc", "#ffffff"]; } return t; } }); } if (oldVersion <= 35) { slowUpgrade(); iterate(transaction.objectStore("players"), undefined, undefined, p => { if (!(p as any).injuries) { p.injuries = []; return p; } }); } if (oldVersion <= 36) { const scheduledEventsStore = db.createObjectStore("scheduledEvents", { keyPath: "id", autoIncrement: true, }); scheduledEventsStore.createIndex("season", "season", { unique: false, }); } if (oldVersion <= 37) { upgrade38(transaction); } if (oldVersion <= 38) { slowUpgrade(); let lastCentury = 0; // Iterate over players iterate(transaction.objectStore("players"), undefined, undefined, p => { // This can be really slow, so need some UI for progress const century = Math.floor(p.draft.year / 100); if (century > lastCentury) { const text = `Upgrading players drafted in the ${century}00s...`; logEvent({ type: "upgrade", text, saveToDb: false, }); console.log(text); lastCentury = century; } delete (p as any).freeAgentMood; p.moodTraits = player.genMoodTraits(); p.numDaysFreeAgent = 0; return p; }); iterate( transaction.objectStore("teamSeasons"), undefined, undefined, teamSeason => { teamSeason.numPlayersTradedAway = 0; return teamSeason; }, ); } if (oldVersion <= 39) { transaction.objectStore("events").createIndex("dpids", "dpids", { unique: false, multiEntry: true, }); } if (oldVersion <= 40) { const tx = unwrap(transaction); tx.objectStore("gameAttributes").get("userTids").onsuccess = ( event: any, ) => { let userTids: number[] = []; console.log("userTids result", event.target.result); if (event.target.result) { userTids = event.target.result.value; } tx.objectStore("gameAttributes").get("keepRosterSorted").onsuccess = ( event: any, ) => { let keepRosterSorted = true; if (event.target.result) { keepRosterSorted = !!event.target.result.value; } iterate(transaction.objectStore("teams"), undefined, undefined, t => { t.keepRosterSorted = userTids.includes(t.tid) ? keepRosterSorted : true; if (t.adjustForInflation === undefined) { t.adjustForInflation = true; } if (t.disabled === undefined) { t.disabled = false; } return t; }); }; }; } if (oldVersion <= 41) { db.createObjectStore("headToHeads", { keyPath: "season", }); } if (oldVersion <= 42) { const tx = unwrap(transaction); tx.objectStore("gameAttributes").get("season").onsuccess = ( event: any, ) => { if (event.target.result === undefined) { throw new Error("Missing season in gameAttributes during upgrade"); } const season = event.target.result.value; if (typeof season !== "number") { throw new Error("Invalid season in gameAttributes during upgrade"); } tx.objectStore("gameAttributes").get("phase").onsuccess = ( event2: any, ) => { if (event2.target.result === undefined) { throw new Error("Missing phase in gameAttributes during upgrade"); } const phase = event2.target.result.value; if (typeof phase !== "number") { throw new Error("Invalid phase in gameAttributes during upgrade"); } tx.objectStore("gameAttributes").get("nextPhase").onsuccess = ( event3: any, ) => { if (event3.target.result === undefined) { throw new Error( "Missing nextPhase in gameAttributes during upgrade", ); } const nextPhase = event3.target.result.value; const actualPhase = nextPhase ?? phase; let currentSeason = season; if (actualPhase >= PHASE.PLAYOFFS) { currentSeason += 1; } // Apply default tiebreakers, while keeping track of when that happened const tiebreakers = [ { start: -Infinity, value: ["coinFlip"], }, { start: currentSeason, value: defaultGameAttributes.tiebreakers[0].value, }, ]; transaction.objectStore("gameAttributes").put({ key: "tiebreakers", value: tiebreakers, }); }; }; }; } } if (oldVersion <= 43) { iterate(transaction.objectStore("teams"), undefined, undefined, t => { if (!t.playThroughInjuries) { t.playThroughInjuries = DEFAULT_PLAY_THROUGH_INJURIES; return t; } }); } if (oldVersion <= 44) { upgrade45(transaction); } if (oldVersion <= 45) { transaction.objectStore("gameAttributes").put({ key: "playIn", value: false, }); } if (oldVersion <= 46) { slowUpgrade(); iterate(transaction.objectStore("players"), undefined, undefined, p => { if ((p as any).mood) { // Delete mood property that was accidentally saved previously delete (p as any).mood; return p; } }); } if (oldVersion <= 47) { // Gets need to use raw IDB API because Firefox < 60 const tx = unwrap(transaction); tx.objectStore("gameAttributes").get("difficulty").onsuccess = ( event: any, ) => { let difficulty = event.target.result !== undefined ? event.target.result.value : undefined; tx.objectStore("gameAttributes").get("easyDifficultyInPast").onsuccess = ( event: any, ) => { let easyDifficultyInPast = event.target.result !== undefined ? event.target.result.value : undefined; if (typeof difficulty !== "number") { difficulty = 0; } if (typeof easyDifficultyInPast !== "boolean") { easyDifficultyInPast = false; } let lowestDifficulty = difficulty; if (easyDifficultyInPast && lowestDifficulty > DIFFICULTY.Easy) { lowestDifficulty = DIFFICULTY.Easy; } console.log(difficulty, easyDifficultyInPast, lowestDifficulty); tx.objectStore("gameAttributes").put({ key: "lowestDifficulty", value: lowestDifficulty, }); }; }; } }; const connectLeague = (lid: number) => connectIndexedDB<LeagueDB>({ name: `league${lid}`, version: MAX_SUPPORTED_LEAGUE_VERSION, lid, create, migrate, }); export default connectLeague;
the_stack
import * as AppVersion from "nativescript-appversion"; import { Application, ApplicationSettings, Device } from "@nativescript/core"; import { confirm } from "@nativescript/core/ui/dialogs"; import { TNSAcquisitionManager } from "./TNSAcquisitionManager"; import { TNSLocalPackage } from "./TNSLocalPackage"; import { TNSRemotePackage } from "./TNSRemotePackage"; export { TNSLocalPackage } from './TNSLocalPackage'; export enum InstallMode { /** * The update will be applied to the running application immediately. The application will be reloaded with the new content immediately. */ IMMEDIATE = <any>"IMMEDIATE", /** * The update is downloaded but not installed immediately. The new content will be available the next time the application is started. */ ON_NEXT_RESTART = <any>"ON_NEXT_RESTART", /** * The update is downloaded but not installed immediately. The new content will be available the next time the application is resumed or restarted, whichever event happends first. */ ON_NEXT_RESUME = <any>"ON_NEXT_RESUME", } export enum SyncStatus { /** * The application is up to date. */ UP_TO_DATE = <any>"UP_TO_DATE", /** * An update is available, it has been downloaded, unzipped and copied to the deployment folder. * After the completion of the callback invoked with SyncStatus.UPDATE_INSTALLED, the application will be reloaded with the updated code and resources. */ UPDATE_INSTALLED = <any>"UPDATE_INSTALLED", /** * An optional update is available, but the user declined to install it. The update was not downloaded. */ UPDATE_IGNORED = <any>"UPDATE_IGNORED", /** * An error happened during the sync operation. This might be an error while communicating with the server, downloading or unziping the update. * The console logs should contain more information about what happened. No update has been applied in this case. */ ERROR = <any>"ERROR", /** * Returned if HMR is enabled and not overridden by the user. */ SKIPPING_BECAUSE_HMR_ENABLED = <any>"SKIPPING_BECAUSE_HMR_ENABLED", /** * There is an ongoing sync in progress, so this attempt to sync has been aborted. */ IN_PROGRESS = <any>"IN_PROGRESS", /** * Intermediate status - the plugin is about to check for updates. */ CHECKING_FOR_UPDATE = <any>"CHECKING_FOR_UPDATE", /** * Intermediate status - a user dialog is about to be displayed. This status will be reported only if user interaction is enabled. */ AWAITING_USER_ACTION = <any>"AWAITING_USER_ACTION", /** * Intermediate status - the update package is about to be downloaded. */ DOWNLOADING_PACKAGE = <any>"DOWNLOADING_PACKAGE", /** * Intermediate status - the update package is about to be installed. */ INSTALLING_UPDATE = <any>"INSTALLING_UPDATE" } export interface DownloadProgress { totalBytes: number; receivedBytes: number; } export class AppSync { public static CURRENT_HASH_KEY: string = "APPSYNC_CURRENT_HASH"; // same as native private static PENDING_HASH_KEY: string = "APPSYNC_PENDING_HASH"; // same as native private static CLEAN_KEY: string = "APPSYNC_CLEAN"; // same as native (Android) private static BINARY_FIRST_RUN_KEY: string = "BINARY_FIRST_RUN"; private static UNCONFIRMED_INSTALL_KEY: string = "UNCONFIRMED_INSTALL"; private static syncInProgress = false; static sync(options: SyncOptions, syncCallback?: SuccessCallback<SyncStatus>, downloadProgress?: SuccessCallback<DownloadProgress>): void { if (!options || !options.deploymentKey) { throw new Error("Missing deploymentKey, pass it as part of the first parameter of the 'sync' function: { deploymentKey: 'your-key' }"); } // skip AppSync when HMR is detected, unless it's explicitly allowed if (typeof (<any>global).hmrRefresh === "function" && !options.enabledWhenUsingHmr) { syncCallback && syncCallback(SyncStatus.SKIPPING_BECAUSE_HMR_ENABLED); return; } AppSync.syncInProgress = true; // by default, use our Cloud server options.serverUrl = options.serverUrl || "https://appsync-server.nativescript.org/"; AppSync.cleanPackagesIfNeeded(); AppSync.notifyApplicationReady(options.deploymentKey, options.serverUrl); syncCallback && syncCallback(SyncStatus.CHECKING_FOR_UPDATE); AppSync.checkForUpdate(options.deploymentKey, options.serverUrl).then( (remotePackage?: IRemotePackage) => { if (!remotePackage) { syncCallback && syncCallback(SyncStatus.UP_TO_DATE); AppSync.syncInProgress = false; return; } if (options.ignoreFailedUpdates === undefined) { options.ignoreFailedUpdates = true; } const updateShouldBeIgnored = remotePackage.failedInstall && options.ignoreFailedUpdates; if (updateShouldBeIgnored) { console.log("An update is available, but it is being ignored due to having been previously rolled back."); syncCallback && syncCallback(SyncStatus.UP_TO_DATE); AppSync.syncInProgress = false; return; } const onError = (error: Error) => { console.log("Download error: " + error); syncCallback && syncCallback(SyncStatus.ERROR); AppSync.syncInProgress = false; }; const onInstallSuccess = () => { ApplicationSettings.setString(AppSync.PENDING_HASH_KEY, remotePackage.packageHash); ApplicationSettings.setString(AppSync.CURRENT_HASH_KEY, remotePackage.packageHash); const onSuspend = () => { Application.off("suspend", onSuspend); this.killApp(false); }; syncCallback && syncCallback(SyncStatus.UPDATE_INSTALLED, remotePackage.label); const installMode = options.installMode || InstallMode.ON_NEXT_RESTART; const mandatoryInstallMode = options.mandatoryInstallMode || InstallMode.ON_NEXT_RESUME; switch (remotePackage.isMandatory ? mandatoryInstallMode : installMode) { case InstallMode.ON_NEXT_RESTART: console.log("Update is installed and will be run on the next app restart."); break; case InstallMode.ON_NEXT_RESUME: console.log("Update is installed and will be run when the app next resumes."); Application.on("suspend", onSuspend); break; case InstallMode.IMMEDIATE: const updateDialogOptions = <UpdateDialogOptions>(options.updateDialog || {}); confirm({ title: updateDialogOptions.updateTitle, message: (remotePackage.isMandatory ? updateDialogOptions.mandatoryUpdateMessage : updateDialogOptions.optionalUpdateMessage) + (updateDialogOptions.appendReleaseDescription ? "\n" + remotePackage.description : ""), okButtonText: updateDialogOptions.mandatoryContinueButtonLabel || "Restart", cancelButtonText: updateDialogOptions.optionalIgnoreButtonLabel || "Cancel", cancelable: true }).then(confirmed => { if (confirmed) { setTimeout(() => this.killApp(true), 300); } else { // fall back to next suspend/resume instead Application.on("suspend", onSuspend); } }); break; } AppSync.syncInProgress = false; }; const onDownloadSuccess = (localPackage: ILocalPackage) => { syncCallback && syncCallback(SyncStatus.INSTALLING_UPDATE, remotePackage.label); localPackage.install(onInstallSuccess, onError); }; syncCallback && syncCallback(SyncStatus.DOWNLOADING_PACKAGE, remotePackage.label); remotePackage.download( onDownloadSuccess, onError, downloadProgress ); }, (error: string) => { console.log(error); AppSync.syncInProgress = false; if (syncCallback) { syncCallback(SyncStatus.ERROR); } } ); } static checkForUpdate(deploymentKey: string, serverUrl?: string): Promise<IRemotePackage | undefined> { return new Promise((resolve, reject) => { // by default, use our Cloud server serverUrl = serverUrl || "https://appsync-server.nativescript.org/"; const config: Configuration = { serverUrl, appVersion: AppVersion.getVersionNameSync(), clientUniqueId: Device.uuid, deploymentKey }; AppSync.getCurrentPackage(config) .then((queryPackage?: IPackage) => { new TNSAcquisitionManager(deploymentKey, serverUrl).queryUpdateWithCurrentPackage(queryPackage, (error: Error, result: IRemotePackage | NativeUpdateNotification) => { if (error) { reject(error.message || error.toString()); } if (!result || (<NativeUpdateNotification>result).updateAppVersion) { resolve(); return; } // At this point we know there's an update available for the current version const remotePackage: IRemotePackage = <IRemotePackage>result; let tnsRemotePackage: IRemotePackage = new TNSRemotePackage(); tnsRemotePackage.description = remotePackage.description; tnsRemotePackage.label = remotePackage.label; tnsRemotePackage.appVersion = remotePackage.appVersion; tnsRemotePackage.isMandatory = remotePackage.isMandatory; tnsRemotePackage.packageHash = remotePackage.packageHash; tnsRemotePackage.packageSize = remotePackage.packageSize; tnsRemotePackage.downloadUrl = remotePackage.downloadUrl; // the server doesn't send back the deploymentKey tnsRemotePackage.deploymentKey = config.deploymentKey; // TODO (low prio) see https://github.com/Microsoft/cordova-plugin-code-push/blob/055d9e625d47d56e707d9624c9a14a37736516bb/www/codePush.ts#L182 // .. or https://github.com/Microsoft/react-native-code-push/blob/2cd2ef0ca2e27a95f84579603c2d222188bb9ce5/CodePush.js#L84 tnsRemotePackage.failedInstall = false; tnsRemotePackage.serverUrl = serverUrl; resolve(tnsRemotePackage); }); }) .catch(e => reject(e)); }); } private static getCurrentPackage(config: Configuration): Promise<IPackage> { return new Promise((resolve, reject) => { resolve({ appVersion: config.appVersion, deploymentKey: config.deploymentKey, packageHash: ApplicationSettings.getString(AppSync.CURRENT_HASH_KEY), isMandatory: false, failedInstall: false, description: undefined, label: undefined, packageSize: undefined, serverUrl: config.serverUrl }); }); } private static notifyApplicationReady(deploymentKey: string, serverUrl?: string): void { if (AppSync.isBinaryFirstRun()) { // first run of a binary from the AppStore AppSync.markBinaryAsFirstRun(); new TNSAcquisitionManager(deploymentKey, serverUrl).reportStatusDeploy(null, "DeploymentSucceeded"); } else if (!AppSync.hasPendingHash()) { const currentPackageHash = ApplicationSettings.getString(AppSync.CURRENT_HASH_KEY, null); if (currentPackageHash !== null && currentPackageHash !== AppSync.firstLaunchValue()) { // first run of an update from AppSync AppSync.markPackageAsFirstRun(currentPackageHash); const currentPackage: ILocalPackage = <ILocalPackage>TNSLocalPackage.getCurrentPackage(); if (currentPackage !== null) { currentPackage.isFirstRun = true; new TNSAcquisitionManager(deploymentKey, serverUrl).reportStatusDeploy(currentPackage, "DeploymentSucceeded"); } } } } private static killApp(restartOnAndroid: boolean): void { if (Application.android) { if (restartOnAndroid) { //noinspection JSUnresolvedFunction,JSUnresolvedVariable const mStartActivity = new android.content.Intent(Application.android.context, Application.android.startActivity.getClass()); const mPendingIntentId = parseInt("" + (Math.random() * 100000), 10); //noinspection JSUnresolvedFunction,JSUnresolvedVariable const mPendingIntent = android.app.PendingIntent.getActivity(Application.android.context, mPendingIntentId, mStartActivity, android.app.PendingIntent.FLAG_CANCEL_CURRENT); //noinspection JSUnresolvedFunction,JSUnresolvedVariable const mgr = Application.android.context.getSystemService(android.content.Context.ALARM_SERVICE); //noinspection JSUnresolvedFunction,JSUnresolvedVariable mgr.set(android.app.AlarmManager.RTC, java.lang.System.currentTimeMillis() + 100, mPendingIntent); //noinspection JSUnresolvedFunction,JSUnresolvedVariable } android.os.Process.killProcess(android.os.Process.myPid()); } else if (Application.ios) { exit(0); } } private static cleanPackagesIfNeeded(): void { const shouldClean = ApplicationSettings.getBoolean(AppSync.CLEAN_KEY, false); if (!shouldClean) { return; } ApplicationSettings.remove(AppSync.CLEAN_KEY); ApplicationSettings.remove(AppSync.BINARY_FIRST_RUN_KEY); TNSLocalPackage.clean(); } private static isBinaryFirstRun(): boolean { const firstRunFlagSet = ApplicationSettings.getBoolean(AppSync.BINARY_FIRST_RUN_KEY, false); return !firstRunFlagSet; } /** * This key exists until a restart is done (removed by native upon start). * @returns {boolean} */ private static hasPendingHash(): boolean { return ApplicationSettings.hasKey(AppSync.PENDING_HASH_KEY); } private static markBinaryAsFirstRun(): void { ApplicationSettings.setBoolean(AppSync.BINARY_FIRST_RUN_KEY, true); } private static firstLaunchValue(): string { return ApplicationSettings.getString(AppSync.UNCONFIRMED_INSTALL_KEY, null); } private static markPackageAsFirstRun(pack: string): void { ApplicationSettings.setString(AppSync.UNCONFIRMED_INSTALL_KEY, pack); } }
the_stack
'use strict' // **Github:** https://github.com/fidm/quic // // **License:** MIT import { suite, it } from 'tman' import { ok, strictEqual, throws, equal } from 'assert' import { bufferFromBytes } from './common' import { BufferVisitor, toBuffer } from '../src/internal/common' import { ConnectionID, PacketNumber, StreamID, SocketAddress, Offset, QuicTags, Tag, } from '../src/internal/protocol' suite('QUIC Protocol', function () { suite('ConnectionID', function () { it('ConnectionID.random, ConnectionID.fromString', function () { const connectionID = ConnectionID.random() strictEqual(connectionID.byteLen(), 8) strictEqual(connectionID.valueOf().length, 16) ok(connectionID.equals(new ConnectionID(connectionID.toString()))) ok(connectionID.equals(ConnectionID.fromBuffer(new BufferVisitor(toBuffer(connectionID))))) }) }) suite('PacketNumber', function () { it('PacketNumber.fromBuffer', function () { throws(() => PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([])), 0)) let packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1) strictEqual(packetNumber.valueOf(), 1) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x1]))) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x1, 0x0])), 4) strictEqual(packetNumber.valueOf(), 0x100) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x1, 0x0]))) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x1, 0x0, 0x0])), 4) strictEqual(packetNumber.valueOf(), 0x10000) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x0, 0x1, 0x0, 0x0]))) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x1, 0x0, 0x0, 0x0])), 6) strictEqual(packetNumber.valueOf(), 0x1000000) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0]))) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x0, 0x0, 0x0, 0x0, 0x1, 0x0])), 6) strictEqual(packetNumber.valueOf(), 0x100) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x1, 0x0]))) throws(() => PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), 8)) }) it('new PacketNumber', function () { throws(() => new PacketNumber(0)) let id = 1 // 8 bits let packetNumber = new PacketNumber(id) strictEqual(packetNumber.valueOf(), id) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x1]))) id = 0x100 // 16 bits packetNumber = new PacketNumber(id) strictEqual(packetNumber.valueOf(), id) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x1, 0x0]))) id = 0x10000 // 32 bits packetNumber = new PacketNumber(id) strictEqual(packetNumber.valueOf(), id) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x0, 0x1, 0x0, 0x0]))) id = 0x100000000 // 48 bits packetNumber = new PacketNumber(id) strictEqual(packetNumber.valueOf(), id) ok(toBuffer(packetNumber).equals(bufferFromBytes([0x0, 0x1, 0x0, 0x0, 0x0, 0x0]))) id = 0x1000000000000 // > 48 bit throws(() => new PacketNumber(id)) }) it('packetNumber.equals', function () { ok(new PacketNumber(1).equals(PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1))) ok(new PacketNumber(0x10000) .equals(PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x0, 0x1, 0x0, 0x0])), 6))) ok(!new PacketNumber(0x10000) .equals(PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x1, 0x0, 0x0, 0x0])), 6))) }) it('packetNumber.byteLen', function () { equal(new PacketNumber(1).byteLen(), 1) equal(new PacketNumber(1).byteLen(true), 6) }) it('packetNumber.nextNumber', function () { let packetNumber = new PacketNumber(1) packetNumber = packetNumber.nextNumber() strictEqual(packetNumber.isLimitReached(), false) strictEqual(packetNumber.valueOf(), 2) strictEqual(packetNumber.nextNumber().valueOf(), 3) packetNumber = new PacketNumber(0xffffffffffff - 1) strictEqual(packetNumber.isLimitReached(), false) packetNumber = packetNumber.nextNumber() strictEqual(packetNumber.isLimitReached(), true) throws(() => packetNumber = packetNumber.nextNumber()) }) it('packetNumber.flagBits()', function () { let packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1) strictEqual(packetNumber.flagBits(), 0b00) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1])), 2) strictEqual(packetNumber.flagBits(), 0b01) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1])), 3) strictEqual(packetNumber.flagBits(), 0b10) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1, 0x1])), 4) strictEqual(packetNumber.flagBits(), 0b10) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1, 0x1, 0x1])), 5) strictEqual(packetNumber.flagBits(), 0b11) packetNumber = PacketNumber.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1, 0x1, 0x1, 0x1])), 6) strictEqual(packetNumber.flagBits(), 0b11) }) it('PacketNumber.flagToByteLen', function () { strictEqual(PacketNumber.flagToByteLen(0b00), 1) strictEqual(PacketNumber.flagToByteLen(0b01), 2) strictEqual(PacketNumber.flagToByteLen(0b10), 4) strictEqual(PacketNumber.flagToByteLen(0b11), 6) }) }) suite('StreamID', function () { it('StreamID.fromBuffer', function () { throws(() => StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([])), 0)) let streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x0])), 1) strictEqual(streamID.valueOf(), 0) ok(toBuffer(streamID).equals(bufferFromBytes([0x0]))) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1) strictEqual(streamID.valueOf(), 1) ok(toBuffer(streamID).equals(bufferFromBytes([0x1]))) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x1, 0x0])), 4) strictEqual(streamID.valueOf(), 0x100) ok(toBuffer(streamID).equals(bufferFromBytes([0x1, 0x0]))) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x1, 0x0, 0x0])), 4) strictEqual(streamID.valueOf(), 0x10000) ok(toBuffer(streamID).equals(bufferFromBytes([0x1, 0x0, 0x0]))) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x0, 0x1, 0x0, 0x0])), 6) strictEqual(streamID.valueOf(), 0x10000) ok(toBuffer(streamID).equals(bufferFromBytes([0x1, 0x0, 0x0]))) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x0, 0x0, 0x1, 0x0, 0x0, 0x0])), 6) strictEqual(streamID.valueOf(), 0x1000000) ok(toBuffer(streamID).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0]))) throws(() => StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0])), 8)) }) it('new StreamID', function () { throws(() => new StreamID(-1)) let id = 0 // 8 bits let streamID = new StreamID(id) strictEqual(streamID.valueOf(), id) ok(toBuffer(streamID).equals(bufferFromBytes([0x0]))) id = 1 // 8 bits streamID = new StreamID(id) strictEqual(streamID.valueOf(), id) ok(toBuffer(streamID).equals(bufferFromBytes([0x1]))) id = 0x100 // 16 bits streamID = new StreamID(id) strictEqual(streamID.valueOf(), id) ok(toBuffer(streamID).equals(bufferFromBytes([0x1, 0x0]))) id = 0x10000 // 24 bits streamID = new StreamID(id) strictEqual(streamID.valueOf(), id) ok(toBuffer(streamID).equals(bufferFromBytes([0x1, 0x0, 0x0]))) id = 0x1000000 // 32 bits streamID = new StreamID(id) strictEqual(streamID.valueOf(), id) ok(toBuffer(streamID).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0]))) id = 0x100000000 // > 32 bit throws(() => new StreamID(id)) }) it('StreamID.equals', function () { ok(new StreamID(1).equals(StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1))) ok(new StreamID(0x10000) .equals(StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x0, 0x1, 0x0, 0x0])), 6))) ok(!new StreamID(0x10000) .equals(StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x1, 0x0, 0x0, 0x0])), 6))) }) it('StreamID.byteLen', function () { equal(new StreamID(1).byteLen(), 1) equal(new StreamID(1).byteLen(true), 4) }) it('StreamID.nextID', function () { let streamID1 = new StreamID(1) const streamID2 = new StreamID(2) streamID1 = streamID1.nextID() strictEqual(streamID1.valueOf(), 3) strictEqual(streamID1.nextID().valueOf(), 5) strictEqual(streamID2.nextID().valueOf(), 4) strictEqual(new StreamID(0xffffffff).nextID().valueOf(), 2) strictEqual(new StreamID(0xffffffff - 1).nextID().valueOf(), 1) }) it('streamID.flagBits()', function () { let streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1) strictEqual(streamID.flagBits(), 0b00) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1])), 2) strictEqual(streamID.flagBits(), 0b01) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1])), 3) strictEqual(streamID.flagBits(), 0b10) streamID = StreamID.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1, 0x1])), 4) strictEqual(streamID.flagBits(), 0b11) }) it('StreamID.flagToByteLen', function () { strictEqual(StreamID.flagToByteLen(0b00), 1) strictEqual(StreamID.flagToByteLen(0b01), 2) strictEqual(StreamID.flagToByteLen(0b10), 3) strictEqual(StreamID.flagToByteLen(0b11), 4) }) }) suite('SocketAddress', function () { it('SocketAddress, IPv4', function () { let socketAddress = new SocketAddress( { port: 3000, family: 'IPv4', address: '127.0.0.1' }) const res = SocketAddress.fromBuffer(new BufferVisitor(toBuffer(socketAddress))) ok(socketAddress.equals(res)) socketAddress = new SocketAddress( { port: 0x1234, family: 'IPv4', address: '4.31.198.44' }) ok(toBuffer(socketAddress).equals(bufferFromBytes([ 0x00, 0x02, 0x04, 0x1f, 0xc6, 0x2c, 0x12, 0x34]))) }) it('SocketAddress, IPv6', function () { let socketAddress = new SocketAddress( { port: 65534, family: 'IPv6', address: '::1' }) const res = SocketAddress.fromBuffer(new BufferVisitor(toBuffer(socketAddress))) ok(socketAddress.equals(res)) socketAddress = new SocketAddress({ address: '2001:700:300:1800::', family: 'IPv6', port: 0x5678}) ok(socketAddress.equals(SocketAddress.fromBuffer(new BufferVisitor(toBuffer(socketAddress))))) socketAddress = new SocketAddress({ address: '2001:700:300:1800::f', family: 'IPv6', port: 0x5678}) ok(toBuffer(socketAddress).equals(bufferFromBytes([ 0x00, 0x0a, 0x20, 0x01, 0x07, 0x00, 0x03, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x56, 0x78]))) }) }) suite('Offset', function () { it('Offset.fromBuffer', function () { let offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([])), 0) strictEqual(offset.valueOf(), 0) ok(toBuffer(offset).equals(bufferFromBytes([]))) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1) strictEqual(offset.valueOf(), 1) ok(toBuffer(offset).equals(bufferFromBytes([0x0, 0x1]))) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x1, 0x0])), 4) strictEqual(offset.valueOf(), 0x100) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0]))) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x0, 0x0, 0x0, 0x1, 0x0, 0x0])), 6) strictEqual(offset.valueOf(), 0x10000) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0, 0x0]))) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0])), 8) strictEqual(offset.valueOf(), 0x100000000) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0, 0x0]))) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0])), 8) strictEqual(offset.valueOf(), 0x010000000000) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0, 0x0, 0x0]))) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])), 8) strictEqual(offset.valueOf(), Number.MAX_SAFE_INTEGER) ok(toBuffer(offset).equals(bufferFromBytes([0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]))) throws(() => Offset.fromBuffer(new BufferVisitor(bufferFromBytes([ 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0])), 8)) }) it('new Offset', function () { let value = 0 // 0 bits let offset = new Offset(value) strictEqual(offset.valueOf(), 0) ok(toBuffer(offset).equals(bufferFromBytes([]))) value = 1 // 16 bits offset = new Offset(value) strictEqual(offset.valueOf(), value) ok(toBuffer(offset).equals(bufferFromBytes([0x0, 0x1]))) value = 0x0100 // 16 bits offset = new Offset(value) strictEqual(offset.valueOf(), value) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0]))) value = 0x010000 // 24 bits offset = new Offset(value) strictEqual(offset.valueOf(), value) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0, 0x0]))) value = 0x01000000 // 32 bits offset = new Offset(value) strictEqual(offset.valueOf(), value) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0]))) value = 0x0100000000 // 40 bits offset = new Offset(value) strictEqual(offset.valueOf(), value) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0, 0x0]))) value = 0x010000000000 // 48 bits offset = new Offset(value) strictEqual(offset.valueOf(), value) ok(toBuffer(offset).equals(bufferFromBytes([0x1, 0x0, 0x0, 0x0, 0x0, 0x0]))) value = Number.MAX_SAFE_INTEGER offset = new Offset(value) strictEqual(offset.valueOf(), value) strictEqual(offset.byteLen(), 7) Offset.fromBuffer(new BufferVisitor(toBuffer(offset)), offset.byteLen()).equals(offset) value = 0x100000000000000 // > MaxOffset throws(() => new Offset(value)) }) it('offset.byteLen', function () { equal(new Offset(1).byteLen(), 2) equal(new Offset(1).byteLen(true), 8) equal(new Offset(0).byteLen(true), 8) }) it('offset.flagBits()', function () { let offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([])), 0) strictEqual(offset.flagBits(), 0b000) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x1])), 1) strictEqual(offset.flagBits(), 0b001) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1])), 2) strictEqual(offset.flagBits(), 0b001) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1])), 3) strictEqual(offset.flagBits(), 0b010) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1, 0x1])), 4) strictEqual(offset.flagBits(), 0b011) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1, 0x1, 0x1])), 5) strictEqual(offset.flagBits(), 0b100) offset = Offset.fromBuffer(new BufferVisitor(bufferFromBytes([0x1, 0x1, 0x1, 0x1, 0x1, 0x1])), 6) strictEqual(offset.flagBits(), 0b101) }) it('Offset.flagToByteLen', function () { strictEqual(Offset.flagToByteLen(0b000), 0) strictEqual(Offset.flagToByteLen(0b001), 2) strictEqual(Offset.flagToByteLen(0b010), 3) strictEqual(Offset.flagToByteLen(0b011), 4) strictEqual(Offset.flagToByteLen(0b100), 5) strictEqual(Offset.flagToByteLen(0b101), 6) strictEqual(Offset.flagToByteLen(0b110), 7) strictEqual(Offset.flagToByteLen(0b111), 8) }) }) suite('QUIC Tag', function () { const data = bufferFromBytes([ // message tag (kPRST) 'PRST', // num_entries (2) + padding 0x03, 0x00, 0x00, 0x00, 'CADR', // end offset 8 0x08, 0x00, 0x00, 0x00, // tag kRNON 'RNON', // end offset 16 0x10, 0x00, 0x00, 0x00, // tag kRSEQ 'RSEQ', // end offset 24 0x18, 0x00, 0x00, 0x00, // client address 0x00, 0x02, 0x04, 0x1F, 0xC6, 0x2C, 0x01, 0xBB, // nonce proof 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, // rejected packet number 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0xAA, 0x00, ]) it('new QuicTags', function () { const quicTag = new QuicTags(Tag.PRST) quicTag.set(Tag.RNON, bufferFromBytes([ 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB])) quicTag.set(Tag.RSEQ, bufferFromBytes([ 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0xAA, 0x00])) quicTag.set(Tag.CADR, bufferFromBytes([ 0x00, 0x02, 0x04, 0x1F, 0xC6, 0x2C, 0x01, 0xBB])) const bufv = new BufferVisitor(Buffer.alloc(quicTag.byteLen())) quicTag.writeTo(bufv) ok(data.equals(bufv.buf)) }) it('QuicTags.fromBuffer', function () { const buf = data.slice() const quicTag = QuicTags.fromBuffer(new BufferVisitor(buf)) strictEqual(quicTag.name, Tag.PRST) let tag = quicTag.get(Tag.RNON) ok(tag && tag.equals(bufferFromBytes([ 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB]))) tag = quicTag.get(Tag.RSEQ) ok(tag && tag.equals(bufferFromBytes([ 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0xAA, 0x00]))) tag = quicTag.get(Tag.CADR) ok(tag && tag.equals(bufferFromBytes([ 0x00, 0x02, 0x04, 0x1F, 0xC6, 0x2C, 0x01, 0xBB]))) const bufv = new BufferVisitor(Buffer.alloc(8 + quicTag.byteLen())) bufv.walk(4) quicTag.writeTo(bufv) const empty4 = bufferFromBytes([0x0, 0x0, 0x0, 0x0]) ok(empty4.equals(bufv.buf.slice(0, 4))) ok(empty4.equals(bufv.buf.slice(bufv.end))) bufv.reset(4, 4) const quicTag2 = QuicTags.fromBuffer(bufv) ok(quicTag.equals(quicTag2)) ok(data.equals(toBuffer(quicTag2))) }) it('handshake message from Chrome', function () { const buf = bufferFromBytes([ 0x43, 0x48, 0x4c, 0x4f, 0x12, 0x0, 0x0, 0x0, 0x50, 0x41, 0x44, 0x0, 0xe1, 0x3, 0x0, 0x0, 0x53, 0x4e, 0x49, 0x0, 0xf1, 0x3, 0x0, 0x0, 0x56, 0x45, 0x52, 0x0, 0xf5, 0x3, 0x0, 0x0, 0x43, 0x43, 0x53, 0x0, 0x5, 0x4, 0x0, 0x0, 0x4d, 0x53, 0x50, 0x43, 0x9, 0x4, 0x0, 0x0, 0x55, 0x41, 0x49, 0x44, 0x34, 0x4, 0x0, 0x0, 0x54, 0x43, 0x49, 0x44, 0x38, 0x4, 0x0, 0x0, 0x50, 0x44, 0x4d, 0x44, 0x3c, 0x4, 0x0, 0x0, 0x53, 0x4d, 0x48, 0x4c, 0x40, 0x4, 0x0, 0x0, 0x49, 0x43, 0x53, 0x4c, 0x44, 0x4, 0x0, 0x0, 0x43, 0x54, 0x49, 0x4d, 0x4c, 0x4, 0x0, 0x0, 0x4e, 0x4f, 0x4e, 0x50, 0x6c, 0x4, 0x0, 0x0, 0x4d, 0x49, 0x44, 0x53, 0x70, 0x4, 0x0, 0x0, 0x53, 0x43, 0x4c, 0x53, 0x74, 0x4, 0x0, 0x0, 0x43, 0x53, 0x43, 0x54, 0x74, 0x4, 0x0, 0x0, 0x43, 0x4f, 0x50, 0x54, 0x74, 0x4, 0x0, 0x0, 0x43, 0x46, 0x43, 0x57, 0x78, 0x4, 0x0, 0x0, 0x53, 0x46, 0x43, 0x57, 0x7c, 0x4, 0x0, 0x0, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x71, 0x75, 0x69, 0x63, 0x2e, 0x63, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x2e, 0x69, 0x6f, 0x51, 0x30, 0x33, 0x39, 0x1, 0xe8, 0x81, 0x60, 0x92, 0x92, 0x1a, 0xe8, 0x7e, 0xed, 0x80, 0x86, 0xa2, 0x15, 0x82, 0x91, 0x64, 0x0, 0x0, 0x0, 0x43, 0x68, 0x72, 0x6f, 0x6d, 0x65, 0x2f, 0x36, 0x36, 0x2e, 0x30, 0x2e, 0x33, 0x33, 0x35, 0x39, 0x2e, 0x31, 0x33, 0x39, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x6c, 0x20, 0x4d, 0x61, 0x63, 0x20, 0x4f, 0x53, 0x20, 0x58, 0x20, 0x31, 0x30, 0x5f, 0x31, 0x33, 0x5f, 0x34, 0x0, 0x0, 0x0, 0x0, 0x58, 0x35, 0x30, 0x39, 0x1, 0x0, 0x0, 0x0, 0x1e, 0x0, 0x0, 0x0, 0x6e, 0x69, 0xe8, 0x5a, 0x0, 0x0, 0x0, 0x0, 0x6d, 0x2, 0x1a, 0xcb, 0x7b, 0x67, 0x12, 0x66, 0x39, 0x24, 0x1f, 0x6f, 0x6a, 0x9e, 0x28, 0xd8, 0x44, 0xdf, 0x75, 0xfd, 0xb2, 0xe4, 0xfd, 0xd, 0xd6, 0xc4, 0x55, 0x30, 0x1d, 0x10, 0xe, 0xbf, 0x64, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf0, 0x0, 0x0, 0x0, 0x60, 0x0, ]) // { name: 'CHLO', // tags: { // PAD: <Buffer 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d // 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d ... >, // SNI: <Buffer 71 75 69 63 2e 63 6c 65 6d 65 6e 74 65 2e 69 6f>, // VER: <Buffer 51 30 33 39>, // CCS: <Buffer 01 e8 81 60 92 92 1a e8 7e ed 80 86 a2 15 82 91>, // MSPC: <Buffer 64 00 00 00>, // UAID: <Buffer 43 68 72 6f 6d 65 2f 36 36 2e 30 2e 33 33 35 39 2e 31 33 39 20 49 6e 74 65 6c 20 4d 61 63 // 20 4f 53 20 58 20 31 30 5f 31 33 5f 34>, // TCID: <Buffer 00 00 00 00>, // PDMD: <Buffer 58 35 30 39>, // SMHL: <Buffer 01 00 00 00>, // ICSL: <Buffer 1e 00 00 00>, // CTIM: <Buffer 6e 69 e8 5a 00 00 00 00>, // NONP: <Buffer 6d 02 1a cb 7b 67 12 66 39 24 1f 6f 6a 9e 28 d8 44 df 75 fd b2 e4 fd 0d d6 c4 55 30 1d // 10 0e bf>, // MIDS: <Buffer 64 00 00 00>, // SCLS: <Buffer 01 00 00 00>, // CSCT: <Buffer >, // COPT: <Buffer >, // CFCW: <Buffer 00 00 f0 00>, // SFCW: <Buffer 00 00 60 00> } } const quicTag = QuicTags.fromBuffer(new BufferVisitor(buf)) strictEqual(quicTag.size, 18) strictEqual((quicTag.get(Tag.PAD) as Buffer).length, 993) strictEqual((quicTag.get(Tag.SNI) as Buffer).toString(), 'quic.clemente.io') strictEqual((quicTag.get(Tag.VER) as Buffer).toString(), 'Q039') strictEqual((quicTag.get(Tag.UAID) as Buffer).toString(), 'Chrome/66.0.3359.139 Intel Mac OS X 10_13_4') strictEqual((quicTag.get(Tag.COPT) as Buffer).toString(), '') strictEqual((quicTag.get(Tag.PDMD) as Buffer).toString(), 'X509') // ok(toBuffer(quicTag).equals(buf)) sort it? }) }) })
the_stack
'use strict' // **Github:** https://github.com/fidm/quic // // **License:** MIT import { debuglog } from 'util' import { Duplex } from 'stream' import { StreamError } from './internal/error' import { MaxStreamReadCacheSize, ReceiveStreamWindow, DefaultMaxReceiveStreamWindowClient, DefaultMaxReceiveStreamWindowServer, } from './internal/constant' import { Offset, StreamID, } from './internal/protocol' import { StreamFrame, RstStreamFrame, BlockedFrame } from './internal/frame' import { StreamFlowController } from './internal/flowcontrol' import { BufferVisitor } from './internal/common' import { kID, kFC, kSession, kState, kRTT, } from './internal/symbol' import { Session } from './session' const debug = debuglog('quic:stream') export class Stream extends Duplex { // Event: 'close' // Event: 'connect' // Event: 'data' // Event: 'drain' // Event: 'end' // Event: 'error' // Event: 'timeout' // Event: 'aborted' // Event: 'finish' // Event: 'frameError' private [kID]: StreamID private [kSession]: Session private [kState]: StreamState private [kFC]: StreamFlowController constructor (streamID: StreamID, session: Session, options: any) { options.allowHalfOpen = true options.objectMode = false super(options) this[kID] = streamID this[kSession] = session this[kState] = new StreamState() this[kFC] = session.isClient ? // TODO: small window will make "packets loss" test failure new StreamFlowController(ReceiveStreamWindow, DefaultMaxReceiveStreamWindowClient, session[kFC]) : new StreamFlowController(ReceiveStreamWindow, DefaultMaxReceiveStreamWindowServer, session[kFC]) this.once('close', () => this[kState].lastActivityTime = Date.now()) debug(`session %s - new stream: %d`, session.id, streamID.valueOf()) } // The socket owned by this session get id (): number { return this[kID].valueOf() } get session (): Session { return this[kSession] } get aborted (): boolean { return this[kState].aborted } get destroyed (): boolean { return this[kState].destroyed } get bytesRead (): number { return this[kFC].consumedOffset } get bytesWritten (): number { return this[kFC].writtenOffset } // close closes the stream with an error. close (err: any): Promise<any> { this[kState].localFIN = true const offset = new Offset(this[kFC].writtenOffset) const rstStreamFrame = new RstStreamFrame(this[kID], offset, StreamError.fromError(err)) debug(`stream %s - close stream, offset: %d, error: %j`, this.id, offset.valueOf(), err) return new Promise((resolve) => { this[kSession]._sendFrame(rstStreamFrame, (e) => { if (e != null) { this.destroy(e) } resolve() }) }) } _write (chunk: Buffer, encoding: string, callback: (...args: any[]) => void) { if (this[kState].localFIN) { return callback(new StreamError('QUIC_RST_ACKNOWLEDGEMENT')) } if (!(chunk instanceof Buffer)) { chunk = Buffer.from(chunk, encoding) } if (chunk.length === 0) { return callback(null) } this[kState].outgoingChunksList.push(chunk, callback) this._tryFlushCallbacks() } _writev (chunks: any[], callback: (...args: any[]) => void) { if (this[kState].localFIN) { return callback(new StreamError('QUIC_RST_ACKNOWLEDGEMENT')) } let len = 0 const list = [] for (const item of chunks) { // { chunk: ..., encoding: ... } let chunk = item.chunk if (!(chunk instanceof Buffer)) { chunk = Buffer.from(chunk, item.encoding) } len += chunk.length list.push(chunk) } if (len === 0) { return callback(null) } this[kState].outgoingChunksList.push(Buffer.concat(list, len), callback) this._tryFlushCallbacks() } _final (callback: (...args: any[]) => void): void { this[kState].outgoingChunksList.push(null, callback) this._tryFlushCallbacks() } _read (size: number = 0) { let data = this[kState].incomingSequencer.read() while (data != null) { if (this.push(data) && size > data.length) { size -= data.length data = this[kState].incomingSequencer.read() continue } break } this[kFC].updateConsumedOffset(this[kState].incomingSequencer.consumedOffset) if (!this[kState].remoteFIN) { process.nextTick(() => this._trySendUpdateWindow()) } if (!this[kState].ended && this[kState].incomingSequencer.isFIN()) { this[kState].ended = true this.push(null) } } _destroy (err: any, callback: (...args: any[]) => void) { debug(`stream %s - stream destroyed, error: %j`, this.id, err) this[kSession][kState].liveStreamCount -= 1 const state = this[kState] state.localFIN = true state.remoteFIN = true state.aborted = true state.destroyed = true state.finished = true state.incomingSequencer.reset() state.outgoingChunksList.reset() err = StreamError.checkAny(err) if (err != null && err.isNoError) { err = null } callback(err) } _sendBlockFrame () { this[kSession]._sendFrame(new BlockedFrame(this[kID])) } _trySendUpdateWindow () { if (this[kFC].shouldUpdateWindow()) { const offset = this[kFC].updateWindowOffset(this[kSession][kRTT].msRTT) this[kSession]._sendWindowUpdate(new Offset(offset), this[kID]) } } _handleFrame (frame: StreamFrame, rcvTime: number) { this[kState].lastActivityTime = rcvTime const offset = frame.offset.valueOf() const byteLen = frame.data == null ? 0 : frame.data.length debug(`stream %s - received StreamFrame, offset: %d, data size: %d, isFIN: %s`, this.id, offset, byteLen, frame.isFIN) this[kFC].updateHighestReceived(offset + byteLen) if (this[kFC].isBlocked()) { this.emit('error', new Error('The window of byte offset overflowed')) this.close(StreamError.fromError(StreamError.QUIC_ERROR_PROCESSING_STREAM)) return } if (frame.isFIN) { this[kState].remoteFIN = true this[kState].incomingSequencer.setFinalOffset(offset + byteLen) } if (frame.data != null) { if (this[kState].incomingSequencer.hasOffset(offset)) { return // duplicated frame } this[kState].incomingSequencer.push(frame) } this._read() if (this[kState].incomingSequencer.byteLen > MaxStreamReadCacheSize) { this.emit('error', new Error('Too large caching, stream data maybe lost')) this.destroy(StreamError.fromError(StreamError.QUIC_ERROR_PROCESSING_STREAM)) } } _handleRstFrame (frame: RstStreamFrame, rcvTime: number) { this[kState].lastActivityTime = rcvTime this[kState].remoteFIN = true this[kState].incomingSequencer.setFinalOffset(frame.offset.valueOf()) debug(`stream %s - received RstStreamFrame, offset: %d, error: %j`, this.id, frame.offset.valueOf(), frame.error) if (this[kState].localFIN) { this.destroy(frame.error) } else { this.emit('error', frame.error) this.close(StreamError.fromError(StreamError.QUIC_RST_ACKNOWLEDGEMENT)) } return } _tryFlushCallbacks () { const entry = this[kState].outgoingChunksList.first() if (entry == null || this[kState].flushing) { return } if (entry.data != null && !this._isRemoteWriteable(this[kSession][kState].maxPacketSize)) { return } const callback = entry.callback this[kState].flushing = true this._flushData(entry.data, (err) => { this[kState].flushing = false if (entry.checkConsumed()) { this[kState].outgoingChunksList.shift() callback(err) } if (err == null && this[kState].outgoingChunksList.pendingCb > 0) { return this._tryFlushCallbacks() } }) } private _isRemoteWriteable (byteLen: number): boolean { if (this[kFC].willBlocked(byteLen)) { // should wait for WINDOW_UPDATE debug(`stream %s - wait for WINDOW_UPDATE, writtenOffset: %d, maxSendOffset: %d, to write size: %d`, this.id, this[kFC].writtenOffset, this[kFC].maxSendOffset, byteLen) this._sendBlockFrame() return false } return true } private _flushData (bufv: BufferVisitor | null, callback: (err: any) => void): void { let byteLen = 0 // bytes to write let nextByteLen = 0 // bytes for next write const offet = new Offset(this[kFC].writtenOffset) const streamFrame = new StreamFrame(this[kID], offet, bufv == null) const packet = this[kSession]._newRegularPacket() if (bufv != null) { byteLen = Math.min(bufv.length - bufv.end, this[kSession][kState].maxPacketSize - packet.headerLen() - streamFrame.headerLen(true)) bufv.walk(byteLen) nextByteLen = Math.min(byteLen, bufv.length - bufv.end) streamFrame.setData(bufv.buf.slice(bufv.start, bufv.end)) this[kFC].updateWrittenOffset(byteLen) } if (streamFrame.isFIN) { this[kState].localFIN = true } debug(`stream %s - write streamFrame, isFIN: %s, offset: %d, data size: %d`, this.id, streamFrame.isFIN, streamFrame.offset.valueOf(), byteLen) packet.addFrames(streamFrame) packet.isRetransmittable = true this[kSession]._sendPacket(packet, (err) => { // Packet Number length maybe increase 1 byte if (err != null || nextByteLen === 0 || !this._isRemoteWriteable(nextByteLen + 1)) { return callback(err) } this._flushData(bufv, callback) }) } } class StreamState { localFIN: boolean remoteFIN: boolean flushing: boolean ended: boolean aborted: boolean destroyed: boolean finished: boolean lastActivityTime: number incomingSequencer: StreamSequencer outgoingChunksList: StreamDataList constructor () { this.localFIN = false // local endpoint will not send data this.remoteFIN = false // remote endpoint should not send data this.flushing = false this.ended = false this.aborted = false this.destroyed = false this.finished = false this.lastActivityTime = Date.now() this.incomingSequencer = new StreamSequencer() this.outgoingChunksList = new StreamDataList() } } class StreamDataEntry { callback: (...args: any[]) => void next: StreamDataEntry | null data: BufferVisitor | null constructor (callback: (...args: any[]) => void, buf: Buffer | null) { this.callback = callback this.next = null this.data = buf == null ? null : new BufferVisitor(buf) } get byteLen (): number { return this.data == null ? 0 : this.data.length } checkConsumed (): boolean { return this.data == null || this.data.end === this.data.length } } class StreamDataList { head: StreamDataEntry | null tail: StreamDataEntry | null pendingCb: number byteLen: number constructor () { this.head = null this.tail = null this.pendingCb = 0 this.byteLen = 0 } reset () { this.head = null this.tail = null this.pendingCb = 0 this.byteLen = 0 } push (buf: Buffer | null, callback: (...args: any[]) => void) { const entry = new StreamDataEntry(callback, buf) if (this.tail != null) { this.tail.next = entry } else { this.head = entry } this.tail = entry this.pendingCb += 1 this.byteLen += entry.byteLen } first (): StreamDataEntry | null { return this.head } shift (): StreamDataEntry | null { if (this.head == null) { return null } const entry = this.head if (this.pendingCb === 1) { this.head = this.tail = null } else { this.head = this.head.next } this.pendingCb -= 1 this.byteLen -= entry.byteLen return entry } } class StreamFrameEntry { data: Buffer | null offset: number next: StreamFrameEntry | null constructor (frame: StreamFrame, entry: StreamFrameEntry | null) { this.data = frame.data this.offset = frame.offset.valueOf() this.next = entry } } // sequencer class StreamSequencer { head: StreamFrameEntry | null byteLen: number consumedOffset: number finalOffset: number pendingOffsets: Set<number> constructor () { this.head = null this.byteLen = 0 this.consumedOffset = 0 this.finalOffset = -1 this.pendingOffsets = new Set() } hasOffset (offset: number): boolean { if (offset < this.consumedOffset) { return true } return this.pendingOffsets.has(offset) } reset () { this.head = null this.byteLen = 0 this.consumedOffset = 0 this.finalOffset = -1 this.pendingOffsets.clear() } setFinalOffset (offset: number) { this.finalOffset = offset } isFIN (): boolean { return this.consumedOffset === this.finalOffset } /** * @param {StreamFrame} */ push (frame: StreamFrame) { const entry = new StreamFrameEntry(frame, null) const offset = entry.offset this.pendingOffsets.add(offset) if (entry.data != null) { this.byteLen += entry.data.length } if (this.head == null) { this.head = entry } else if (this.head.offset > offset) { entry.next = this.head this.head = entry } else { let prev = this.head while (true) { if (prev.next == null) { prev.next = entry break } if (prev.next.offset > offset) { entry.next = prev.next prev.next = entry break } prev = prev.next } } } read (): Buffer | null { let data = null if (this.head != null && this.consumedOffset === this.head.offset) { data = this.head.data if (data != null) { this.pendingOffsets.delete(this.consumedOffset) this.byteLen -= data.length this.consumedOffset += data.length } this.head = this.head.next } return data } }
the_stack
import * as oceanicNext from 'monaco-themes/themes/Oceanic Next.json'; import * as blackboard from 'monaco-themes/themes/Blackboard.json'; import * as cloudsMidnight from 'monaco-themes/themes/Clouds Midnight.json'; import * as merbivore from 'monaco-themes/themes/Merbivore.json'; import * as monokai from 'monaco-themes/themes/Monokai.json' import * as nightOwl from 'monaco-themes/themes/Night Owl.json' import * as tomorrowNight from 'monaco-themes/themes/Tomorrow-Night.json' export const themes = [ { name: 'oceanic-next', data: oceanicNext }, { name: 'blackboard', data: blackboard }, { name: 'clouds-midnight', data: cloudsMidnight }, { name: 'merbivore', data: merbivore }, { name: 'monokai', data: monokai }, { name: 'night-owl', data: nightOwl }, { name: 'tomorrow-night', data: tomorrowNight }, { name: 'one-dark', data: getOneDark() }, { name: 'nord', data: getNord() } ] export const visualStudioDarkBackgroundColor = '#1e1e1e'; function getOneDark() { // Generated from "One Dark theme for Sublime Text" by Andres Michel (https://github.com/andresmichel/one-dark-theme) (MIT) // using https://bitwiser.in/monaco-themes/ by Brijesh Bittu (https://github.com/brijeshb42/monaco-themes/) (MIT) return { 'base': 'vs-dark', 'inherit': true, 'rules': [ { 'foreground': 'abb2bf', 'token': 'text' }, { 'foreground': 'abb2bf', 'token': 'source' }, { 'foreground': 'adb7c9', 'token': 'variable.parameter.function' }, { 'foreground': '5f697a', 'fontStyle': ' italic', 'token': 'comment' }, { 'foreground': '5f697a', 'fontStyle': ' italic', 'token': 'punctuation.definition.comment' }, { 'foreground': 'adb7c9', 'token': 'none' }, { 'foreground': 'adb7c9', 'token': 'keyword.operator' }, { 'foreground': 'cd74e8', 'token': 'keyword' }, { 'foreground': 'eb6772', 'token': 'variable' }, { 'foreground': '5cb3fa', 'token': 'entity.name.function' }, { 'foreground': '5cb3fa', 'token': 'meta.require' }, { 'foreground': '5cb3fa', 'token': 'support.function.any-method' }, { 'foreground': 'f0c678', 'token': 'support.class' }, { 'foreground': 'f0c678', 'token': 'entity.name.class' }, { 'foreground': 'f0c678', 'token': 'entity.name.type.class' }, { 'foreground': 'adb7c9', 'token': 'meta.class' }, { 'foreground': '5cb3fa', 'token': 'keyword.other.special-method' }, { 'foreground': 'cd74e8', 'token': 'storage' }, { 'foreground': '5ebfcc', 'token': 'support.function' }, { 'foreground': '9acc76', 'token': 'string' }, { 'foreground': '9acc76', 'token': 'constant.other.symbol' }, { 'foreground': '9acc76', 'token': 'entity.other.inherited-class' }, { 'foreground': 'db9d63', 'token': 'constant.numeric' }, { 'foreground': 'db9d63', 'token': 'none' }, { 'foreground': 'db9d63', 'token': 'none' }, { 'foreground': 'db9d63', 'token': 'constant' }, { 'foreground': 'eb6772', 'token': 'entity.name.tag' }, { 'foreground': 'db9d63', 'token': 'entity.other.attribute-name' }, { 'foreground': 'db9d63', 'token': 'entity.other.attribute-name.id' }, { 'foreground': 'db9d63', 'token': 'punctuation.definition.entity' }, { 'foreground': 'cd74e8', 'token': 'meta.selector' }, { 'foreground': 'db9d63', 'token': 'none' }, { 'foreground': '5cb3fa', 'token': 'markup.heading punctuation.definition.heading' }, { 'foreground': '5cb3fa', 'token': 'entity.name.section' }, { 'foreground': 'db9d63', 'token': 'keyword.other.unit' }, { 'foreground': 'f0c678', 'token': 'markup.bold' }, { 'foreground': 'f0c678', 'token': 'punctuation.definition.bold' }, { 'foreground': 'cd74e8', 'token': 'markup.italic' }, { 'foreground': 'cd74e8', 'token': 'punctuation.definition.italic' }, { 'foreground': '9acc76', 'token': 'markup.raw.inline' }, { 'foreground': 'eb6772', 'token': 'string.other.link' }, { 'foreground': 'eb6772', 'token': 'punctuation.definition.string.end.markdown' }, { 'foreground': 'db9d63', 'token': 'meta.link' }, { 'foreground': 'eb6772', 'token': 'markup.list' }, { 'foreground': 'db9d63', 'token': 'markup.quote' }, { 'foreground': 'adb7c9', 'background': '515151', 'token': 'meta.separator' }, { 'foreground': '9acc76', 'token': 'markup.inserted' }, { 'foreground': 'eb6772', 'token': 'markup.deleted' }, { 'foreground': 'cd74e8', 'token': 'markup.changed' }, { 'foreground': '5ebfcc', 'token': 'constant.other.color' }, { 'foreground': '5ebfcc', 'token': 'string.regexp' }, { 'foreground': '5ebfcc', 'token': 'constant.character.escape' }, { 'foreground': 'c94e42', 'token': 'punctuation.section.embedded' }, { 'foreground': 'c94e42', 'token': 'variable.interpolation' }, { 'foreground': 'ffffff', 'background': 'e05252', 'token': 'invalid.illegal' }, { 'foreground': '2d2d2d', 'background': 'f99157', 'token': 'invalid.broken' }, { 'foreground': '2c323d', 'background': 'd27b53', 'token': 'invalid.deprecated' }, { 'foreground': '2c323d', 'background': '747369', 'token': 'invalid.unimplemented' }, { 'foreground': 'eb6772', 'token': 'source.json meta.structure.dictionary.json string.quoted.double.json' }, { 'foreground': '9acc76', 'token': 'source.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json' }, { 'foreground': 'eb6772', 'token': 'source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json string.quoted.double.json' }, { 'foreground': '9acc76', 'token': 'source.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json string.quoted.double.json' }, { 'foreground': 'cd74e8', 'token': 'text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade' }, { 'foreground': 'cd74e8', 'token': 'text.html.laravel-blade source.php.embedded.line.html support.constant.laravel-blade' }, { 'foreground': 'db9d63', 'token': 'source.python meta.function.python meta.function.parameters.python variable.parameter.function.python' }, { 'foreground': '5ebfcc', 'token': 'source.python meta.function-call.python support.type.python' }, { 'foreground': 'cd74e8', 'token': 'source.python keyword.operator.logical.python' }, { 'foreground': 'f0c678', 'token': 'source.python meta.class.python punctuation.definition.inheritance.begin.python' }, { 'foreground': 'f0c678', 'token': 'source.python meta.class.python punctuation.definition.inheritance.end.python' }, { 'foreground': 'db9d63', 'token': 'source.python meta.function-call.python meta.function-call.arguments.python variable.parameter.function.python' }, { 'foreground': 'db9d63', 'token': 'text.html.basic source.php.embedded.block.html support.constant.std.php' }, { 'foreground': 'f0c678', 'token': 'text.html.basic source.php.embedded.block.html meta.namespace.php entity.name.type.namespace.php' }, { 'foreground': 'db9d63', 'token': 'source.js meta.function.js support.constant.js' }, { 'foreground': 'cd74e8', 'token': 'text.html.basic` source.php.embedded.block.html constant.other.php' }, { 'foreground': 'db9d63', 'token': 'text.html.basic source.php.embedded.block.html support.other.namespace.php' }, { 'foreground': 'adb7c9', 'token': 'text.tex.latex meta.function.environment.math.latex string.other.math.block.environment.latex meta.definition.label.latex variable.parameter.definition.label.latex' }, { 'foreground': 'cd74e8', 'fontStyle': ' italic', 'token': 'text.tex.latex meta.function.emph.latex markup.italic.emph.latex' }, { 'foreground': 'adb7c9', 'token': 'source.js variable.other.readwrite.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.function-call.with-arguments.js variable.function.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.group.braces.round meta.group.braces.curly meta.function-call.method.without-arguments.js variable.function.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.group.braces.round meta.group.braces.curly variable.other.object.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.group.braces.round meta.group.braces.curly constant.other.object.key.js string.unquoted.label.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.group.braces.round meta.group.braces.curly constant.other.object.key.js punctuation.separator.key-value.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.group.braces.round meta.group.braces.curly meta.function-call.method.with-arguments.js variable.function.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.function-call.method.with-arguments.js variable.function.js' }, { 'foreground': 'adb7c9', 'token': 'source.js meta.function-call.method.without-arguments.js variable.function.js' } ], 'colors': { 'editor.foreground': '#abb2bf', // modified 'editor.background': '#2B303B', 'editor.selectionBackground': '#bbccf51b', 'editor.inactiveSelectionBackground': '#bbccf51b', 'editor.lineHighlightBackground': '#8cc2fc0b', 'editorCursor.foreground': '#528bff', 'editorWhitespace.foreground': '#747369', 'editorIndentGuide.background': '#464c55', 'editorIndentGuide.activeBackground': '#464c55', 'editor.selectionHighlightBorder': '#bbccf51b' } }; } function getNord() { // Generated from "Nord Textmate" by Ryan Bloom (https://github.com/ryanbloom/nord-textmate) (Unlicense) // using https://bitwiser.in/monaco-themes/ by Brijesh Bittu (https://github.com/brijeshb42/monaco-themes/) (MIT) return { 'base': 'vs-dark', 'inherit': true, 'rules': [ { 'foreground': '616e88', 'token': 'comment' }, { 'foreground': 'a3be8c', 'token': 'string' }, { 'foreground': 'b48ead', 'token': 'constant.numeric' }, { 'foreground': '81a1c1', 'token': 'constant.language' }, { 'foreground': '81a1c1', 'token': 'keyword' }, { 'foreground': '81a1c1', 'token': 'storage' }, { 'foreground': '81a1c1', 'token': 'storage.type' }, { 'foreground': '8fbcbb', 'token': 'entity.name.class' }, { 'foreground': '8fbcbb', 'fontStyle': ' bold', 'token': 'entity.other.inherited-class' }, { 'foreground': '88c0d0', 'token': 'entity.name.function' }, { 'foreground': '81a1c1', 'token': 'entity.name.tag' }, { 'foreground': '8fbcbb', 'token': 'entity.other.attribute-name' }, { 'foreground': '88c0d0', 'token': 'support.function' }, { 'foreground': 'f8f8f0', 'background': 'f92672', 'token': 'invalid' }, { 'foreground': 'f8f8f0', 'background': 'ae81ff', 'token': 'invalid.deprecated' }, { 'foreground': 'b48ead', 'token': 'constant.color.other.rgb-value' }, { 'foreground': 'ebcb8b', 'token': 'constant.character.escape' }, { 'foreground': '8fbcbb', 'token': 'variable.other.constant' } ], 'colors': { 'editor.foreground': '#D8DEE9', 'editor.background': '#2E3440', 'editor.selectionBackground': '#434C5ECC', 'editor.lineHighlightBackground': '#3B4252', 'editorCursor.foreground': '#D8DEE9', 'editorWhitespace.foreground': '#434C5ECC' } }; }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; import { Readable } from "stream"; /** * <p> * The operation did not succeed because of an unauthorized access attempt. * </p> */ export interface AccessDeniedException extends __SmithyException, $MetadataBearer { name: "AccessDeniedException"; $fault: "client"; message: string | undefined; } export namespace AccessDeniedException { /** * @internal */ export const filterSensitiveLog = (obj: AccessDeniedException): any => ({ ...obj, }); } export enum HashAlgorithm { MD5 = "MD5", SHA1 = "SHA-1", SHA256 = "SHA-256", SHA512 = "SHA-512", } /** * <p> * Contains details about a package version asset. * </p> */ export interface AssetSummary { /** * <p> * The name of the asset. * </p> */ name: string | undefined; /** * <p> * The size of the asset. * </p> */ size?: number; /** * <p> * The hashes of the asset. * </p> */ hashes?: { [key: string]: string }; } export namespace AssetSummary { /** * @internal */ export const filterSensitiveLog = (obj: AssetSummary): any => ({ ...obj, }); } export interface AssociateExternalConnectionRequest { /** * <p>The name of the domain that contains the repository.</p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository to which the external connection is added. * </p> */ repository: string | undefined; /** * <p> * The name of the external connection to add to the repository. The following values are supported: * </p> * <ul> * <li> * <p> * <code>public:npmjs</code> - for the npm public repository. * </p> * </li> * <li> * <p> * <code>public:pypi</code> - for the Python Package Index. * </p> * </li> * <li> * <p> * <code>public:maven-central</code> - for Maven Central. * </p> * </li> * <li> * <p> * <code>public:maven-googleandroid</code> - for the Google Android repository. * </p> * </li> * <li> * <p> * <code>public:maven-gradleplugins</code> - for the Gradle plugins repository. * </p> * </li> * <li> * <p> * <code>public:maven-commonsware</code> - for the CommonsWare Android repository. * </p> * </li> * </ul> */ externalConnection: string | undefined; } export namespace AssociateExternalConnectionRequest { /** * @internal */ export const filterSensitiveLog = (obj: AssociateExternalConnectionRequest): any => ({ ...obj, }); } export enum PackageFormat { MAVEN = "maven", NPM = "npm", NUGET = "nuget", PYPI = "pypi", } export enum ExternalConnectionStatus { AVAILABLE = "Available", } /** * <p> * Contains information about the external connection of a repository. * </p> */ export interface RepositoryExternalConnectionInfo { /** * <p> The name of the external connection associated with a repository. </p> */ externalConnectionName?: string; /** * <p> * The package format associated with a repository's external connection. The valid package formats are: * </p> * <ul> * <li> * <p> * <code>npm</code>: A Node Package Manager (npm) package. * </p> * </li> * <li> * <p> * <code>pypi</code>: A Python Package Index (PyPI) package. * </p> * </li> * <li> * <p> * <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. * </p> * </li> * </ul> */ packageFormat?: PackageFormat | string; /** * <p> * The status of the external connection of a repository. There is one valid value, <code>Available</code>. * </p> */ status?: ExternalConnectionStatus | string; } export namespace RepositoryExternalConnectionInfo { /** * @internal */ export const filterSensitiveLog = (obj: RepositoryExternalConnectionInfo): any => ({ ...obj, }); } /** * <p> * Information about an upstream repository. * </p> */ export interface UpstreamRepositoryInfo { /** * <p> The name of an upstream repository. </p> */ repositoryName?: string; } export namespace UpstreamRepositoryInfo { /** * @internal */ export const filterSensitiveLog = (obj: UpstreamRepositoryInfo): any => ({ ...obj, }); } /** * <p> The details of a repository stored in AWS CodeArtifact. A CodeArtifact repository contains a set of * package versions, each of which maps to a set of assets. Repositories are polyglot—a single * repository can contain packages of any supported type. Each repository exposes endpoints for * fetching and publishing packages using tools like the <code>npm</code> CLI, the Maven CLI * (<code>mvn</code>), and <code>pip</code>. You can create up to 100 repositories per AWS * account. </p> */ export interface RepositoryDescription { /** * <p> * The name of the repository. * </p> */ name?: string; /** * <p> The 12-digit account number of the AWS account that manages the repository. </p> */ administratorAccount?: string; /** * <p> * The name of the domain that contains the repository. * </p> */ domainName?: string; /** * <p> * The 12-digit account number of the AWS account that owns the domain that contains the repository. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> The Amazon Resource Name (ARN) of the repository. </p> */ arn?: string; /** * <p> * A text description of the repository. * </p> */ description?: string; /** * <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories * in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more * information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> */ upstreams?: UpstreamRepositoryInfo[]; /** * <p> * An array of external connections associated with the repository. * </p> */ externalConnections?: RepositoryExternalConnectionInfo[]; } export namespace RepositoryDescription { /** * @internal */ export const filterSensitiveLog = (obj: RepositoryDescription): any => ({ ...obj, }); } export interface AssociateExternalConnectionResult { /** * <p> * Information about the connected repository after processing the request. * </p> */ repository?: RepositoryDescription; } export namespace AssociateExternalConnectionResult { /** * @internal */ export const filterSensitiveLog = (obj: AssociateExternalConnectionResult): any => ({ ...obj, }); } export enum ResourceType { ASSET = "asset", DOMAIN = "domain", PACKAGE = "package", PACKAGE_VERSION = "package-version", REPOSITORY = "repository", } /** * <p> * The operation did not succeed because prerequisites are not met. * </p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; message: string | undefined; /** * <p> * The ID of the resource. * </p> */ resourceId?: string; /** * <p> * The type of AWS resource. * </p> */ resourceType?: ResourceType | string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } /** * <p> The operation did not succeed because of an error that occurred inside AWS CodeArtifact. </p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; message: string | undefined; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p> * The operation did not succeed because the resource requested is not found in the service. * </p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; message: string | undefined; /** * <p> * The ID of the resource. * </p> */ resourceId?: string; /** * <p> * The type of AWS resource. * </p> */ resourceType?: ResourceType | string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } /** * <p> * The operation did not succeed because it would have exceeded a service limit for your account. * </p> */ export interface ServiceQuotaExceededException extends __SmithyException, $MetadataBearer { name: "ServiceQuotaExceededException"; $fault: "client"; message: string | undefined; /** * <p> * The ID of the resource. * </p> */ resourceId?: string; /** * <p> * The type of AWS resource. * </p> */ resourceType?: ResourceType | string; } export namespace ServiceQuotaExceededException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceQuotaExceededException): any => ({ ...obj, }); } /** * <p> * The operation did not succeed because too many requests are sent to the service. * </p> */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; message: string | undefined; /** * <p> * The time period, in seconds, to wait before retrying the request. * </p> */ retryAfterSeconds?: number; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } export enum ValidationExceptionReason { CANNOT_PARSE = "CANNOT_PARSE", ENCRYPTION_KEY_ERROR = "ENCRYPTION_KEY_ERROR", FIELD_VALIDATION_FAILED = "FIELD_VALIDATION_FAILED", OTHER = "OTHER", UNKNOWN_OPERATION = "UNKNOWN_OPERATION", } /** * <p> * The operation did not succeed because a parameter in the request was sent with an invalid value. * </p> */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; message: string | undefined; /** * <p> * * </p> */ reason?: ValidationExceptionReason | string; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } export interface CopyPackageVersionsRequest { /** * <p> * The name of the domain that contains the source and destination repositories. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository that contains the package versions to copy. * </p> */ sourceRepository: string | undefined; /** * <p> * The name of the repository into which package versions are copied. * </p> */ destinationRepository: string | undefined; /** * <p> * The format of the package that is copied. The valid package types are: * </p> * <ul> * <li> * <p> * <code>npm</code>: A Node Package Manager (npm) package. * </p> * </li> * <li> * <p> * <code>pypi</code>: A Python Package Index (PyPI) package. * </p> * </li> * <li> * <p> * <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package that is copied. * </p> */ package: string | undefined; /** * <p> * The versions of the package to copy. * </p> * <note> * <p> * You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. * </p> * </note> */ versions?: string[]; /** * <p> * A list of key-value pairs. The keys are package versions and the values are package version revisions. A <code>CopyPackageVersion</code> operation * succeeds if the specified versions in the source repository match the specified package version revision. * </p> * <note> * <p> * You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. * </p> * </note> */ versionRevisions?: { [key: string]: string }; /** * <p> * Set to true to overwrite a package version that already exists in the destination repository. * If set to false and the package version already exists in the destination repository, * the package version is returned in the <code>failedVersions</code> field of the response with * an <code>ALREADY_EXISTS</code> error code. * </p> */ allowOverwrite?: boolean; /** * <p> Set to true to copy packages from repositories that are upstream from the source * repository to the destination repository. The default setting is false. For more information, * see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with * upstream repositories</a>. </p> */ includeFromUpstream?: boolean; } export namespace CopyPackageVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: CopyPackageVersionsRequest): any => ({ ...obj, }); } export enum PackageVersionErrorCode { ALREADY_EXISTS = "ALREADY_EXISTS", MISMATCHED_REVISION = "MISMATCHED_REVISION", MISMATCHED_STATUS = "MISMATCHED_STATUS", NOT_ALLOWED = "NOT_ALLOWED", NOT_FOUND = "NOT_FOUND", SKIPPED = "SKIPPED", } /** * <p> * An error associated with package. * </p> */ export interface PackageVersionError { /** * <p> The error code associated with the error. Valid error codes are: </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> */ errorCode?: PackageVersionErrorCode | string; /** * <p> * The error message associated with the error. * </p> */ errorMessage?: string; } export namespace PackageVersionError { /** * @internal */ export const filterSensitiveLog = (obj: PackageVersionError): any => ({ ...obj, }); } export enum PackageVersionStatus { ARCHIVED = "Archived", DELETED = "Deleted", DISPOSED = "Disposed", PUBLISHED = "Published", UNFINISHED = "Unfinished", UNLISTED = "Unlisted", } /** * <p> * Contains the revision and status of a package version. * </p> */ export interface SuccessfulPackageVersionInfo { /** * <p> * The revision of a package version. * </p> */ revision?: string; /** * <p> * The status of a package version. Valid statuses are: * </p> * <ul> * <li> * <p> * <code>Published</code> * </p> * </li> * <li> * <p> * <code>Unfinished</code> * </p> * </li> * <li> * <p> * <code>Unlisted</code> * </p> * </li> * <li> * <p> * <code>Archived</code> * </p> * </li> * <li> * <p> * <code>Disposed</code> * </p> * </li> * </ul> */ status?: PackageVersionStatus | string; } export namespace SuccessfulPackageVersionInfo { /** * @internal */ export const filterSensitiveLog = (obj: SuccessfulPackageVersionInfo): any => ({ ...obj, }); } export interface CopyPackageVersionsResult { /** * <p> * A list of the package versions that were successfully copied to your repository. * </p> */ successfulVersions?: { [key: string]: SuccessfulPackageVersionInfo }; /** * <p> * A map of package versions that failed to copy and their error codes. The possible error codes are in * the <code>PackageVersionError</code> data type. They are: * </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> */ failedVersions?: { [key: string]: PackageVersionError }; } export namespace CopyPackageVersionsResult { /** * @internal */ export const filterSensitiveLog = (obj: CopyPackageVersionsResult): any => ({ ...obj, }); } /** * <p>A tag is a key-value pair that can be used to manage, search for, or filter resources in AWS CodeArtifact.</p> */ export interface Tag { /** * <p>The tag key.</p> */ key: string | undefined; /** * <p>The tag value.</p> */ value: string | undefined; } export namespace Tag { /** * @internal */ export const filterSensitiveLog = (obj: Tag): any => ({ ...obj, }); } export interface CreateDomainRequest { /** * <p> The name of the domain to create. All domain names in an AWS Region that are in the * same AWS account must be unique. The domain name is used as the prefix in DNS hostnames. Do * not use sensitive information in a domain name because it is publicly discoverable. </p> */ domain: string | undefined; /** * <p> The encryption key for the domain. This is used to encrypt content stored in a domain. * An encryption key can be a key ID, a key Amazon Resource Name (ARN), a key alias, or a key * alias ARN. To specify an <code>encryptionKey</code>, your IAM role must have * <code>kms:DescribeKey</code> and <code>kms:CreateGrant</code> permissions on the encryption * key that is used. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestSyntax">DescribeKey</a> in the <i>AWS Key Management Service API Reference</i> * and <a href="https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html">AWS KMS API Permissions * Reference</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> * <important> * <p> CodeArtifact supports only symmetric CMKs. Do not associate an asymmetric CMK with your * domain. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html">Using symmetric and asymmetric * keys</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> * </important> */ encryptionKey?: string; /** * <p>One or more tag key-value pairs for the domain.</p> */ tags?: Tag[]; } export namespace CreateDomainRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateDomainRequest): any => ({ ...obj, }); } export enum DomainStatus { ACTIVE = "Active", DELETED = "Deleted", } /** * <p> * Information about a domain. A domain is a container for repositories. When you create a domain, it is empty until you * add one or more repositories. * </p> */ export interface DomainDescription { /** * <p> * The name of the domain. * </p> */ name?: string; /** * <p> The AWS account ID that owns the domain. </p> */ owner?: string; /** * <p> The Amazon Resource Name (ARN) of the domain. </p> */ arn?: string; /** * <p> The current status of a domain. The valid values are </p> * <ul> * <li> * <p> * <code>Active</code> * </p> * </li> * <li> * <p> * <code>Deleted</code> * </p> * </li> * </ul> */ status?: DomainStatus | string; /** * <p> * A timestamp that represents the date and time the domain was created. * </p> */ createdTime?: Date; /** * <p> The ARN of an AWS Key Management Service (AWS KMS) key associated with a domain. </p> */ encryptionKey?: string; /** * <p> * The number of repositories in the domain. * </p> */ repositoryCount?: number; /** * <p> * The total size of all assets in the domain. * </p> */ assetSizeBytes?: number; /** * <p>The Amazon Resource Name (ARN) of the Amazon S3 bucket that is used to store package assets in the domain.</p> */ s3BucketArn?: string; } export namespace DomainDescription { /** * @internal */ export const filterSensitiveLog = (obj: DomainDescription): any => ({ ...obj, }); } export interface CreateDomainResult { /** * <p> * Contains information about the created domain after processing the request. * </p> */ domain?: DomainDescription; } export namespace CreateDomainResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateDomainResult): any => ({ ...obj, }); } /** * <p> * Information about an upstream repository. A list of <code>UpstreamRepository</code> objects is an input parameter to * <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_CreateRepository.html">CreateRepository</a> * and <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_UpdateRepository.html">UpdateRepository</a>. * </p> */ export interface UpstreamRepository { /** * <p> The name of an upstream repository. </p> */ repositoryName: string | undefined; } export namespace UpstreamRepository { /** * @internal */ export const filterSensitiveLog = (obj: UpstreamRepository): any => ({ ...obj, }); } export interface CreateRepositoryRequest { /** * <p> * The name of the domain that contains the created repository. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> The name of the repository to create. </p> */ repository: string | undefined; /** * <p> * A description of the created repository. * </p> */ description?: string; /** * <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories * in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more * information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> */ upstreams?: UpstreamRepository[]; /** * <p>One or more tag key-value pairs for the repository.</p> */ tags?: Tag[]; } export namespace CreateRepositoryRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateRepositoryRequest): any => ({ ...obj, }); } export interface CreateRepositoryResult { /** * <p> * Information about the created repository after processing the request. * </p> */ repository?: RepositoryDescription; } export namespace CreateRepositoryResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateRepositoryResult): any => ({ ...obj, }); } export interface DeleteDomainRequest { /** * <p> * The name of the domain to delete. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; } export namespace DeleteDomainRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteDomainRequest): any => ({ ...obj, }); } export interface DeleteDomainResult { /** * <p> * Contains information about the deleted domain after processing the request. * </p> */ domain?: DomainDescription; } export namespace DeleteDomainResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteDomainResult): any => ({ ...obj, }); } export interface DeleteDomainPermissionsPolicyRequest { /** * <p> * The name of the domain associated with the resource policy to be deleted. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The current revision of the resource policy to be deleted. This revision is used for optimistic locking, which * prevents others from overwriting your changes to the domain's resource policy. * </p> */ policyRevision?: string; } export namespace DeleteDomainPermissionsPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteDomainPermissionsPolicyRequest): any => ({ ...obj, }); } /** * <p> * An AWS CodeArtifact resource policy that contains a resource ARN, document details, and a revision. * </p> */ export interface ResourcePolicy { /** * <p> * The ARN of the resource associated with the resource policy * </p> */ resourceArn?: string; /** * <p> * The current revision of the resource policy. * </p> */ revision?: string; /** * <p> * The resource policy formatted in JSON. * </p> */ document?: string; } export namespace ResourcePolicy { /** * @internal */ export const filterSensitiveLog = (obj: ResourcePolicy): any => ({ ...obj, }); } export interface DeleteDomainPermissionsPolicyResult { /** * <p> * Information about the deleted resource policy after processing the request. * </p> */ policy?: ResourcePolicy; } export namespace DeleteDomainPermissionsPolicyResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteDomainPermissionsPolicyResult): any => ({ ...obj, }); } export interface DeletePackageVersionsRequest { /** * <p> * The name of the domain that contains the package to delete. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository that contains the package versions to delete. * </p> */ repository: string | undefined; /** * <p> * The format of the package versions to delete. The valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package with the versions to delete. * </p> */ package: string | undefined; /** * <p> * An array of strings that specify the versions of the package to delete. * </p> */ versions: string[] | undefined; /** * <p> * The expected status of the package version to delete. Valid values are: * </p> * <ul> * <li> * <p> * <code>Published</code> * </p> * </li> * <li> * <p> * <code>Unfinished</code> * </p> * </li> * <li> * <p> * <code>Unlisted</code> * </p> * </li> * <li> * <p> * <code>Archived</code> * </p> * </li> * <li> * <p> * <code>Disposed</code> * </p> * </li> * </ul> */ expectedStatus?: PackageVersionStatus | string; } export namespace DeletePackageVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeletePackageVersionsRequest): any => ({ ...obj, }); } export interface DeletePackageVersionsResult { /** * <p> * A list of the package versions that were successfully deleted. * </p> */ successfulVersions?: { [key: string]: SuccessfulPackageVersionInfo }; /** * <p> * A <code>PackageVersionError</code> object that contains a map of errors codes for the * deleted package that failed. The possible error codes are: * </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> */ failedVersions?: { [key: string]: PackageVersionError }; } export namespace DeletePackageVersionsResult { /** * @internal */ export const filterSensitiveLog = (obj: DeletePackageVersionsResult): any => ({ ...obj, }); } export interface DeleteRepositoryRequest { /** * <p> * The name of the domain that contains the repository to delete. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> The name of the repository to delete. </p> */ repository: string | undefined; } export namespace DeleteRepositoryRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRepositoryRequest): any => ({ ...obj, }); } export interface DeleteRepositoryResult { /** * <p> * Information about the deleted repository after processing the request. * </p> */ repository?: RepositoryDescription; } export namespace DeleteRepositoryResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRepositoryResult): any => ({ ...obj, }); } export interface DeleteRepositoryPermissionsPolicyRequest { /** * <p> * The name of the domain that contains the repository associated with the resource policy to be deleted. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository that is associated with the resource policy to be deleted * </p> */ repository: string | undefined; /** * <p> * The revision of the repository's resource policy to be deleted. This revision is used for optimistic locking, which * prevents others from accidentally overwriting your changes to the repository's resource policy. * </p> */ policyRevision?: string; } export namespace DeleteRepositoryPermissionsPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRepositoryPermissionsPolicyRequest): any => ({ ...obj, }); } export interface DeleteRepositoryPermissionsPolicyResult { /** * <p> * Information about the deleted policy after processing the request. * </p> */ policy?: ResourcePolicy; } export namespace DeleteRepositoryPermissionsPolicyResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRepositoryPermissionsPolicyResult): any => ({ ...obj, }); } export interface DescribeDomainRequest { /** * <p> * A string that specifies the name of the requested domain. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; } export namespace DescribeDomainRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDomainRequest): any => ({ ...obj, }); } export interface DescribeDomainResult { /** * <p> * Information about a domain. A domain is a container for repositories. When you create a domain, it is empty until you * add one or more repositories. * </p> */ domain?: DomainDescription; } export namespace DescribeDomainResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDomainResult): any => ({ ...obj, }); } export interface DescribePackageVersionRequest { /** * <p> * The name of the domain that contains the repository that contains the package version. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> The name of the repository that contains the package version. </p> */ repository: string | undefined; /** * <p> * A format that specifies the type of the requested package version. The valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> The name of the requested package version. </p> */ package: string | undefined; /** * <p> * A string that contains the package version (for example, <code>3.5.2</code>). * </p> */ packageVersion: string | undefined; } export namespace DescribePackageVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribePackageVersionRequest): any => ({ ...obj, }); } /** * <p> * Details of the license data. * </p> */ export interface LicenseInfo { /** * <p> * Name of the license. * </p> */ name?: string; /** * <p> * The URL for license data. * </p> */ url?: string; } export namespace LicenseInfo { /** * @internal */ export const filterSensitiveLog = (obj: LicenseInfo): any => ({ ...obj, }); } /** * <p> * Details about a package version. * </p> */ export interface PackageVersionDescription { /** * <p> * The format of the package version. The valid package formats are: * </p> * <ul> * <li> * <p> * <code>npm</code>: A Node Package Manager (npm) package. * </p> * </li> * <li> * <p> * <code>pypi</code>: A Python Package Index (PyPI) package. * </p> * </li> * <li> * <p> * <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. * </p> * </li> * </ul> */ format?: PackageFormat | string; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the requested package. * </p> */ packageName?: string; /** * <p> * The name of the package that is displayed. The <code>displayName</code> varies depending * on the package version's format. For example, if an npm package is named <code>ui</code>, * is in the namespace <code>vue</code>, and has the format <code>npm</code>, then * the <code>displayName</code> is <code>@vue/ui</code>. * </p> */ displayName?: string; /** * <p> * The version of the package. * </p> */ version?: string; /** * <p> * A summary of the package version. The summary is extracted from the package. The information in and * detail level of the summary depends on the package version's format. * </p> */ summary?: string; /** * <p> * The homepage associated with the package. * </p> */ homePage?: string; /** * <p> * The repository for the source code in the package version, or the source code used to build it. * </p> */ sourceCodeRepository?: string; /** * <p> * A timestamp that contains the date and time the package version was published. * </p> */ publishedTime?: Date; /** * <p> * Information about licenses associated with the package version. * </p> */ licenses?: LicenseInfo[]; /** * <p> * The revision of the package version. * </p> */ revision?: string; /** * <p> * A string that contains the status of the package version. It can be one of the following: * </p> * <ul> * <li> * <p> * <code>Published</code> * </p> * </li> * <li> * <p> * <code>Unfinished</code> * </p> * </li> * <li> * <p> * <code>Unlisted</code> * </p> * </li> * <li> * <p> * <code>Archived</code> * </p> * </li> * <li> * <p> * <code>Disposed</code> * </p> * </li> * </ul> */ status?: PackageVersionStatus | string; } export namespace PackageVersionDescription { /** * @internal */ export const filterSensitiveLog = (obj: PackageVersionDescription): any => ({ ...obj, }); } export interface DescribePackageVersionResult { /** * <p> * A <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionDescription.html">PackageVersionDescription</a> * object that contains information about the requested package version. * </p> */ packageVersion: PackageVersionDescription | undefined; } export namespace DescribePackageVersionResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribePackageVersionResult): any => ({ ...obj, }); } export interface DescribeRepositoryRequest { /** * <p> * The name of the domain that contains the repository to describe. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * A string that specifies the name of the requested repository. * </p> */ repository: string | undefined; } export namespace DescribeRepositoryRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRepositoryRequest): any => ({ ...obj, }); } export interface DescribeRepositoryResult { /** * <p> * A <code>RepositoryDescription</code> object that contains the requested repository information. * </p> */ repository?: RepositoryDescription; } export namespace DescribeRepositoryResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRepositoryResult): any => ({ ...obj, }); } export interface DisassociateExternalConnectionRequest { /** * <p>The name of the domain that contains the repository from which to remove the external * repository. </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p>The name of the repository from which the external connection will be removed. </p> */ repository: string | undefined; /** * <p>The name of the external connection to be removed from the repository. </p> */ externalConnection: string | undefined; } export namespace DisassociateExternalConnectionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateExternalConnectionRequest): any => ({ ...obj, }); } export interface DisassociateExternalConnectionResult { /** * <p> * The repository associated with the removed external connection. * </p> */ repository?: RepositoryDescription; } export namespace DisassociateExternalConnectionResult { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateExternalConnectionResult): any => ({ ...obj, }); } export interface DisposePackageVersionsRequest { /** * <p> * The name of the domain that contains the repository you want to dispose. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository that contains the package versions you want to dispose. * </p> */ repository: string | undefined; /** * <p> * A format that specifies the type of package versions you want to dispose. The valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package with the versions you want to dispose. * </p> */ package: string | undefined; /** * <p> * The versions of the package you want to dispose. * </p> */ versions: string[] | undefined; /** * <p> * The revisions of the package versions you want to dispose. * </p> */ versionRevisions?: { [key: string]: string }; /** * <p> * The expected status of the package version to dispose. Valid values are: * </p> * <ul> * <li> * <p> * <code>Published</code> * </p> * </li> * <li> * <p> * <code>Unfinished</code> * </p> * </li> * <li> * <p> * <code>Unlisted</code> * </p> * </li> * <li> * <p> * <code>Archived</code> * </p> * </li> * <li> * <p> * <code>Disposed</code> * </p> * </li> * </ul> */ expectedStatus?: PackageVersionStatus | string; } export namespace DisposePackageVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DisposePackageVersionsRequest): any => ({ ...obj, }); } export interface DisposePackageVersionsResult { /** * <p> * A list of the package versions that were successfully disposed. * </p> */ successfulVersions?: { [key: string]: SuccessfulPackageVersionInfo }; /** * <p> * A <code>PackageVersionError</code> object that contains a map of errors codes for the * disposed package versions that failed. The possible error codes are: * </p> * <ul> * <li> * <p> * <code>ALREADY_EXISTS</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_REVISION</code> * </p> * </li> * <li> * <p> * <code>MISMATCHED_STATUS</code> * </p> * </li> * <li> * <p> * <code>NOT_ALLOWED</code> * </p> * </li> * <li> * <p> * <code>NOT_FOUND</code> * </p> * </li> * <li> * <p> * <code>SKIPPED</code> * </p> * </li> * </ul> */ failedVersions?: { [key: string]: PackageVersionError }; } export namespace DisposePackageVersionsResult { /** * @internal */ export const filterSensitiveLog = (obj: DisposePackageVersionsResult): any => ({ ...obj, }); } export interface GetAuthorizationTokenRequest { /** * <p> * The name of the domain that is in scope for the generated authorization token. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p>The time, in seconds, that the generated authorization token is valid. Valid values are * <code>0</code> and any number between <code>900</code> (15 minutes) and <code>43200</code> (12 hours). * A value of <code>0</code> will set the expiration of the authorization token to the same expiration of * the user's role's temporary credentials.</p> */ durationSeconds?: number; } export namespace GetAuthorizationTokenRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetAuthorizationTokenRequest): any => ({ ...obj, }); } export interface GetAuthorizationTokenResult { /** * <p> * The returned authentication token. * </p> */ authorizationToken?: string; /** * <p> * A timestamp that specifies the date and time the authorization token expires. * </p> */ expiration?: Date; } export namespace GetAuthorizationTokenResult { /** * @internal */ export const filterSensitiveLog = (obj: GetAuthorizationTokenResult): any => ({ ...obj, }); } export interface GetDomainPermissionsPolicyRequest { /** * <p> * The name of the domain to which the resource policy is attached. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; } export namespace GetDomainPermissionsPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetDomainPermissionsPolicyRequest): any => ({ ...obj, }); } export interface GetDomainPermissionsPolicyResult { /** * <p> * The returned resource policy. * </p> */ policy?: ResourcePolicy; } export namespace GetDomainPermissionsPolicyResult { /** * @internal */ export const filterSensitiveLog = (obj: GetDomainPermissionsPolicyResult): any => ({ ...obj, }); } export interface GetPackageVersionAssetRequest { /** * <p> * The name of the domain that contains the repository that contains the package version with the requested asset. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The repository that contains the package version with the requested asset. * </p> */ repository: string | undefined; /** * <p> * A format that specifies the type of the package version with the requested asset file. The valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package that contains the requested asset. * </p> */ package: string | undefined; /** * <p> * A string that contains the package version (for example, <code>3.5.2</code>). * </p> */ packageVersion: string | undefined; /** * <p> * The name of the requested asset. * </p> */ asset: string | undefined; /** * <p> * The name of the package version revision that contains the requested asset. * </p> */ packageVersionRevision?: string; } export namespace GetPackageVersionAssetRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetPackageVersionAssetRequest): any => ({ ...obj, }); } export interface GetPackageVersionAssetResult { /** * <p> The binary file, or asset, that is downloaded.</p> */ asset?: Readable | ReadableStream | Blob; /** * <p> * The name of the asset that is downloaded. * </p> */ assetName?: string; /** * <p> * A string that contains the package version (for example, <code>3.5.2</code>). * </p> */ packageVersion?: string; /** * <p> * The name of the package version revision that contains the downloaded asset. * </p> */ packageVersionRevision?: string; } export namespace GetPackageVersionAssetResult { /** * @internal */ export const filterSensitiveLog = (obj: GetPackageVersionAssetResult): any => ({ ...obj, }); } export interface GetPackageVersionReadmeRequest { /** * <p> * The name of the domain that contains the repository that contains the package version with the requested readme file. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The repository that contains the package with the requested readme file. * </p> */ repository: string | undefined; /** * <p> * A format that specifies the type of the package version with the requested readme file. The valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package version that contains the requested readme file. * </p> */ package: string | undefined; /** * <p> * A string that contains the package version (for example, <code>3.5.2</code>). * </p> */ packageVersion: string | undefined; } export namespace GetPackageVersionReadmeRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetPackageVersionReadmeRequest): any => ({ ...obj, }); } export interface GetPackageVersionReadmeResult { /** * <p> * The format of the package with the requested readme file. Valid format types are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format?: PackageFormat | string; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package that contains the returned readme file. * </p> */ package?: string; /** * <p> * The version of the package with the requested readme file. * </p> */ version?: string; /** * <p> * The current revision associated with the package version. * </p> */ versionRevision?: string; /** * <p> * The text of the returned readme file. * </p> */ readme?: string; } export namespace GetPackageVersionReadmeResult { /** * @internal */ export const filterSensitiveLog = (obj: GetPackageVersionReadmeResult): any => ({ ...obj, }); } export interface GetRepositoryEndpointRequest { /** * <p> * The name of the domain that contains the repository. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain that contains the repository. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository. * </p> */ repository: string | undefined; /** * <p> * Returns which endpoint of a repository to return. A repository has one endpoint for each * package format: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; } export namespace GetRepositoryEndpointRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetRepositoryEndpointRequest): any => ({ ...obj, }); } export interface GetRepositoryEndpointResult { /** * <p> * A string that specifies the URL of the returned endpoint. * </p> */ repositoryEndpoint?: string; } export namespace GetRepositoryEndpointResult { /** * @internal */ export const filterSensitiveLog = (obj: GetRepositoryEndpointResult): any => ({ ...obj, }); } export interface GetRepositoryPermissionsPolicyRequest { /** * <p> * The name of the domain containing the repository whose associated resource policy is to be retrieved. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository whose associated resource policy is to be retrieved. * </p> */ repository: string | undefined; } export namespace GetRepositoryPermissionsPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetRepositoryPermissionsPolicyRequest): any => ({ ...obj, }); } export interface GetRepositoryPermissionsPolicyResult { /** * <p> * The returned resource policy. * </p> */ policy?: ResourcePolicy; } export namespace GetRepositoryPermissionsPolicyResult { /** * @internal */ export const filterSensitiveLog = (obj: GetRepositoryPermissionsPolicyResult): any => ({ ...obj, }); } export interface ListDomainsRequest { /** * <p> * The maximum number of results to return per page. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListDomainsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDomainsRequest): any => ({ ...obj, }); } /** * <p> Information about a domain, including its name, Amazon Resource Name (ARN), and status. * The <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListDomains.html">ListDomains</a> operation returns a list of <code>DomainSummary</code> * objects. </p> */ export interface DomainSummary { /** * <p> * The name of the domain. * </p> */ name?: string; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ owner?: string; /** * <p> * The ARN of the domain. * </p> */ arn?: string; /** * <p> * A string that contains the status of the domain. The valid values are: * </p> * <ul> * <li> * <p> * <code>Active</code> * </p> * </li> * <li> * <p> * <code>Deleted</code> * </p> * </li> * </ul> */ status?: DomainStatus | string; /** * <p> * A timestamp that contains the date and time the domain was created. * </p> */ createdTime?: Date; /** * <p> * The key used to encrypt the domain. * </p> */ encryptionKey?: string; } export namespace DomainSummary { /** * @internal */ export const filterSensitiveLog = (obj: DomainSummary): any => ({ ...obj, }); } export interface ListDomainsResult { /** * <p> * The returned list of <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_DomainSummary.html">DomainSummary</a> objects. * </p> */ domains?: DomainSummary[]; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListDomainsResult { /** * @internal */ export const filterSensitiveLog = (obj: ListDomainsResult): any => ({ ...obj, }); } export interface ListPackagesRequest { /** * <p> * The name of the domain that contains the repository that contains the requested list of packages. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository from which packages are to be listed. * </p> */ repository: string | undefined; /** * <p> * The format of the packages. The valid package types are: * </p> * <ul> * <li> * <p> * <code>npm</code>: A Node Package Manager (npm) package. * </p> * </li> * <li> * <p> * <code>pypi</code>: A Python Package Index (PyPI) package. * </p> * </li> * <li> * <p> * <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. * </p> * </li> * </ul> */ format?: PackageFormat | string; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * A prefix used to filter returned packages. Only packages with names that start with * <code>packagePrefix</code> are returned. * </p> */ packagePrefix?: string; /** * <p> * The maximum number of results to return per page. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListPackagesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPackagesRequest): any => ({ ...obj, }); } /** * <p> * Details about a package, including its format, namespace, and name. The * <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackages.html">ListPackages</a> * operation returns a list of <code>PackageSummary</code> objects. * </p> */ export interface PackageSummary { /** * <p> * The format of the package. Valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format?: PackageFormat | string; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package. * </p> */ package?: string; } export namespace PackageSummary { /** * @internal */ export const filterSensitiveLog = (obj: PackageSummary): any => ({ ...obj, }); } export interface ListPackagesResult { /** * <p> * The list of returned <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageSummary.html">PackageSummary</a> * objects. * </p> */ packages?: PackageSummary[]; /** * <p> * If there are additional results, this is the token for the next set of results. * </p> */ nextToken?: string; } export namespace ListPackagesResult { /** * @internal */ export const filterSensitiveLog = (obj: ListPackagesResult): any => ({ ...obj, }); } export interface ListPackageVersionAssetsRequest { /** * <p> * The name of the domain that contains the repository associated with the package version assets. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository that contains the package that contains the returned package version assets. * </p> */ repository: string | undefined; /** * <p> * The format of the package that contains the returned package version assets. The valid package types are: * </p> * <ul> * <li> * <p> * <code>npm</code>: A Node Package Manager (npm) package. * </p> * </li> * <li> * <p> * <code>pypi</code>: A Python Package Index (PyPI) package. * </p> * </li> * <li> * <p> * <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package that contains the returned package version assets. * </p> */ package: string | undefined; /** * <p> * A string that contains the package version (for example, <code>3.5.2</code>). * </p> */ packageVersion: string | undefined; /** * <p> * The maximum number of results to return per page. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListPackageVersionAssetsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPackageVersionAssetsRequest): any => ({ ...obj, }); } export interface ListPackageVersionAssetsResult { /** * <p> * The format of the package that contains the returned package version assets. * </p> */ format?: PackageFormat | string; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package that contains the returned package version assets. * </p> */ package?: string; /** * <p> * The version of the package associated with the returned assets. * </p> */ version?: string; /** * <p> * The current revision associated with the package version. * </p> */ versionRevision?: string; /** * <p> * If there are additional results, this is the token for the next set of results. * </p> */ nextToken?: string; /** * <p> * The returned list of <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> objects. * </p> */ assets?: AssetSummary[]; } export namespace ListPackageVersionAssetsResult { /** * @internal */ export const filterSensitiveLog = (obj: ListPackageVersionAssetsResult): any => ({ ...obj, }); } export interface ListPackageVersionDependenciesRequest { /** * <p> * The name of the domain that contains the repository that contains the requested package version dependencies. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository that contains the requested package version. * </p> */ repository: string | undefined; /** * <p> * The format of the package with the requested dependencies. The valid package types are: * </p> * <ul> * <li> * <p> * <code>npm</code>: A Node Package Manager (npm) package. * </p> * </li> * <li> * <p> * <code>pypi</code>: A Python Package Index (PyPI) package. * </p> * </li> * <li> * <p> * <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package versions' package. * </p> */ package: string | undefined; /** * <p> * A string that contains the package version (for example, <code>3.5.2</code>). * </p> */ packageVersion: string | undefined; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListPackageVersionDependenciesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPackageVersionDependenciesRequest): any => ({ ...obj, }); } /** * <p> * Details about a package dependency. * </p> */ export interface PackageDependency { /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package that this package depends on. * </p> */ package?: string; /** * <p> The type of a package dependency. The possible values depend on the package type. * Example types are <code>compile</code>, <code>runtime</code>, and <code>test</code> for Maven * packages, and <code>dev</code>, <code>prod</code>, and <code>optional</code> for npm packages. </p> */ dependencyType?: string; /** * <p> * The required version, or version range, of the package that this package depends on. The version format * is specific to the package type. For example, the following are possible valid required versions: <code>1.2.3</code>, * <code>^2.3.4</code>, or <code>4.x</code>. * </p> */ versionRequirement?: string; } export namespace PackageDependency { /** * @internal */ export const filterSensitiveLog = (obj: PackageDependency): any => ({ ...obj, }); } export interface ListPackageVersionDependenciesResult { /** * <p> * A format that specifies the type of the package that contains the returned dependencies. The valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format?: PackageFormat | string; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package that contains the returned package versions dependencies. * </p> */ package?: string; /** * <p> * The version of the package that is specified in the request. * </p> */ version?: string; /** * <p> * The current revision associated with the package version. * </p> */ versionRevision?: string; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; /** * <p> * The returned list of <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageDependency.html">PackageDependency</a> objects. * </p> */ dependencies?: PackageDependency[]; } export namespace ListPackageVersionDependenciesResult { /** * @internal */ export const filterSensitiveLog = (obj: ListPackageVersionDependenciesResult): any => ({ ...obj, }); } export enum PackageVersionSortType { PUBLISHED_TIME = "PUBLISHED_TIME", } export interface ListPackageVersionsRequest { /** * <p> * The name of the domain that contains the repository that contains the returned package versions. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository that contains the package. * </p> */ repository: string | undefined; /** * <p> * The format of the returned packages. The valid package types are: * </p> * <ul> * <li> * <p> * <code>npm</code>: A Node Package Manager (npm) package. * </p> * </li> * <li> * <p> * <code>pypi</code>: A Python Package Index (PyPI) package. * </p> * </li> * <li> * <p> * <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package for which you want to return a list of package versions. * </p> */ package: string | undefined; /** * <p> * A string that specifies the status of the package versions to include in the returned list. It can be one of the following: * </p> * <ul> * <li> * <p> * <code>Published</code> * </p> * </li> * <li> * <p> * <code>Unfinished</code> * </p> * </li> * <li> * <p> * <code>Unlisted</code> * </p> * </li> * <li> * <p> * <code>Archived</code> * </p> * </li> * <li> * <p> * <code>Disposed</code> * </p> * </li> * </ul> */ status?: PackageVersionStatus | string; /** * <p> * How to sort the returned list of package versions. * </p> */ sortBy?: PackageVersionSortType | string; /** * <p> * The maximum number of results to return per page. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListPackageVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPackageVersionsRequest): any => ({ ...obj, }); } /** * <p> * Details about a package version, including its status, version, and revision. The * <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackageVersions.html">ListPackageVersions</a> * operation returns a list of <code>PackageVersionSummary</code> objects. * </p> */ export interface PackageVersionSummary { /** * <p> * Information about a package version. * </p> */ version: string | undefined; /** * <p> * The revision associated with a package version. * </p> */ revision?: string; /** * <p> * A string that contains the status of the package version. It can be one of the following: * </p> * <ul> * <li> * <p> * <code>Published</code> * </p> * </li> * <li> * <p> * <code>Unfinished</code> * </p> * </li> * <li> * <p> * <code>Unlisted</code> * </p> * </li> * <li> * <p> * <code>Archived</code> * </p> * </li> * <li> * <p> * <code>Disposed</code> * </p> * </li> * </ul> */ status: PackageVersionStatus | string | undefined; } export namespace PackageVersionSummary { /** * @internal */ export const filterSensitiveLog = (obj: PackageVersionSummary): any => ({ ...obj, }); } export interface ListPackageVersionsResult { /** * <p> * The default package version to display. This depends on the package format: * </p> * <ul> * <li> * <p> * For Maven and PyPI packages, it's the most recently published package version. * </p> * </li> * <li> * <p> * For npm packages, it's the version referenced by the * <code>latest</code> tag. If the <code>latest</code> tag is not set, it's the most recently published package version. * </p> * </li> * </ul> */ defaultDisplayVersion?: string; /** * <p> * A format of the package. Valid package format values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format?: PackageFormat | string; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package. * </p> */ package?: string; /** * <p> * The returned list of * <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionSummary.html">PackageVersionSummary</a> * objects. * </p> */ versions?: PackageVersionSummary[]; /** * <p> * If there are additional results, this is the token for the next set of results. * </p> */ nextToken?: string; } export namespace ListPackageVersionsResult { /** * @internal */ export const filterSensitiveLog = (obj: ListPackageVersionsResult): any => ({ ...obj, }); } export interface ListRepositoriesRequest { /** * <p> A prefix used to filter returned repositories. Only repositories with names that start * with <code>repositoryPrefix</code> are returned.</p> */ repositoryPrefix?: string; /** * <p> * The maximum number of results to return per page. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListRepositoriesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRepositoriesRequest): any => ({ ...obj, }); } /** * <p> Details about a repository, including its Amazon Resource Name (ARN), description, and * domain information. The <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListRepositories.html">ListRepositories</a> operation returns a list of * <code>RepositorySummary</code> objects. </p> */ export interface RepositorySummary { /** * <p> * The name of the repository. * </p> */ name?: string; /** * <p> * The AWS account ID that manages the repository. * </p> */ administratorAccount?: string; /** * <p> * The name of the domain that contains the repository. * </p> */ domainName?: string; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> The ARN of the repository. </p> */ arn?: string; /** * <p> * The description of the repository. * </p> */ description?: string; } export namespace RepositorySummary { /** * @internal */ export const filterSensitiveLog = (obj: RepositorySummary): any => ({ ...obj, }); } export interface ListRepositoriesResult { /** * <p> * The returned list of <a href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_RepositorySummary.html">RepositorySummary</a> * objects. * </p> */ repositories?: RepositorySummary[]; /** * <p> * If there are additional results, this is the token for the next set of results. * </p> */ nextToken?: string; } export namespace ListRepositoriesResult { /** * @internal */ export const filterSensitiveLog = (obj: ListRepositoriesResult): any => ({ ...obj, }); } export interface ListRepositoriesInDomainRequest { /** * <p> * The name of the domain that contains the returned list of repositories. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * Filter the list of repositories to only include those that are managed by the AWS account ID. * </p> */ administratorAccount?: string; /** * <p> * A prefix used to filter returned repositories. Only repositories with names that start with * <code>repositoryPrefix</code> are returned. * </p> */ repositoryPrefix?: string; /** * <p> * The maximum number of results to return per page. * </p> */ maxResults?: number; /** * <p> * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. * </p> */ nextToken?: string; } export namespace ListRepositoriesInDomainRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRepositoriesInDomainRequest): any => ({ ...obj, }); } export interface ListRepositoriesInDomainResult { /** * <p> * The returned list of repositories. * </p> */ repositories?: RepositorySummary[]; /** * <p> * If there are additional results, this is the token for the next set of results. * </p> */ nextToken?: string; } export namespace ListRepositoriesInDomainResult { /** * @internal */ export const filterSensitiveLog = (obj: ListRepositoriesInDomainResult): any => ({ ...obj, }); } export interface ListTagsForResourceRequest { /** * <p>The Amazon Resource Name (ARN) of the resource to get tags for.</p> */ resourceArn: string | undefined; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResult { /** * <p>A list of tag key and value pairs associated with the specified resource.</p> */ tags?: Tag[]; } export namespace ListTagsForResourceResult { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResult): any => ({ ...obj, }); } export interface PutDomainPermissionsPolicyRequest { /** * <p> * The name of the domain on which to set the resource policy. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The current revision of the resource policy to be set. This revision is used for optimistic locking, which * prevents others from overwriting your changes to the domain's resource policy. * </p> */ policyRevision?: string; /** * <p> A valid displayable JSON Aspen policy string to be set as the access control resource * policy on the provided domain. </p> */ policyDocument: string | undefined; } export namespace PutDomainPermissionsPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: PutDomainPermissionsPolicyRequest): any => ({ ...obj, }); } export interface PutDomainPermissionsPolicyResult { /** * <p> The resource policy that was set after processing the request. </p> */ policy?: ResourcePolicy; } export namespace PutDomainPermissionsPolicyResult { /** * @internal */ export const filterSensitiveLog = (obj: PutDomainPermissionsPolicyResult): any => ({ ...obj, }); } export interface PutRepositoryPermissionsPolicyRequest { /** * <p> * The name of the domain containing the repository to set the resource policy on. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> The name of the repository to set the resource policy on. </p> */ repository: string | undefined; /** * <p> * Sets the revision of the resource policy that specifies permissions to access the repository. * This revision is used for optimistic locking, which prevents others from overwriting your * changes to the repository's resource policy. * </p> */ policyRevision?: string; /** * <p> A valid displayable JSON Aspen policy string to be set as the access control resource * policy on the provided repository. </p> */ policyDocument: string | undefined; } export namespace PutRepositoryPermissionsPolicyRequest { /** * @internal */ export const filterSensitiveLog = (obj: PutRepositoryPermissionsPolicyRequest): any => ({ ...obj, }); } export interface PutRepositoryPermissionsPolicyResult { /** * <p> The resource policy that was set after processing the request. </p> */ policy?: ResourcePolicy; } export namespace PutRepositoryPermissionsPolicyResult { /** * @internal */ export const filterSensitiveLog = (obj: PutRepositoryPermissionsPolicyResult): any => ({ ...obj, }); } export interface TagResourceRequest { /** * <p>The Amazon Resource Name (ARN) of the resource that you want to add or update tags for.</p> */ resourceArn: string | undefined; /** * <p>The tags you want to modify or add to the resource.</p> */ tags: Tag[] | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResult {} export namespace TagResourceResult { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResult): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * <p>The Amazon Resource Name (ARN) of the resource that you want to remove tags from.</p> */ resourceArn: string | undefined; /** * <p>The tag key for each tag that you want to remove from the resource.</p> */ tagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } export interface UntagResourceResult {} export namespace UntagResourceResult { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceResult): any => ({ ...obj, }); } export interface UpdatePackageVersionsStatusRequest { /** * <p> * The name of the domain that contains the repository that contains the package versions with a status to be updated. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The repository that contains the package versions with the status you want to update. * </p> */ repository: string | undefined; /** * <p> * A format that specifies the type of the package with the statuses to update. The valid values are: * </p> * <ul> * <li> * <p> * <code>npm</code> * </p> * </li> * <li> * <p> * <code>pypi</code> * </p> * </li> * <li> * <p> * <code>maven</code> * </p> * </li> * </ul> */ format: PackageFormat | string | undefined; /** * <p> * The namespace of the package. The package component that specifies its * namespace depends on its type. For example: * </p> * <ul> * <li> * <p> * The namespace of a Maven package is its <code>groupId</code>. * </p> * </li> * <li> * <p> * The namespace of an npm package is its <code>scope</code>. * </p> * </li> * <li> * <p> * A Python package does not contain a corresponding component, so * Python packages do not have a namespace. * </p> * </li> * </ul> */ namespace?: string; /** * <p> * The name of the package with the version statuses to update. * </p> */ package: string | undefined; /** * <p> * An array of strings that specify the versions of the package with the statuses to update. * </p> */ versions: string[] | undefined; /** * <p> A map of package versions and package version revisions. The map <code>key</code> is the * package version (for example, <code>3.5.2</code>), and the map <code>value</code> is the * package version revision. </p> */ versionRevisions?: { [key: string]: string }; /** * <p> The package version’s expected status before it is updated. If * <code>expectedStatus</code> is provided, the package version's status is updated only if its * status at the time <code>UpdatePackageVersionsStatus</code> is called matches * <code>expectedStatus</code>. </p> */ expectedStatus?: PackageVersionStatus | string; /** * <p> * The status you want to change the package version status to. * </p> */ targetStatus: PackageVersionStatus | string | undefined; } export namespace UpdatePackageVersionsStatusRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdatePackageVersionsStatusRequest): any => ({ ...obj, }); } export interface UpdatePackageVersionsStatusResult { /** * <p> * A list of <code>PackageVersionError</code> objects, one for each package version with * a status that failed to update. * </p> */ successfulVersions?: { [key: string]: SuccessfulPackageVersionInfo }; /** * <p> A list of <code>SuccessfulPackageVersionInfo</code> objects, one for each package version * with a status that successfully updated. </p> */ failedVersions?: { [key: string]: PackageVersionError }; } export namespace UpdatePackageVersionsStatusResult { /** * @internal */ export const filterSensitiveLog = (obj: UpdatePackageVersionsStatusResult): any => ({ ...obj, }); } export interface UpdateRepositoryRequest { /** * <p> * The name of the domain associated with the repository to update. * </p> */ domain: string | undefined; /** * <p> * The 12-digit account number of the AWS account that owns the domain. It does not include * dashes or spaces. * </p> */ domainOwner?: string; /** * <p> * The name of the repository to update. * </p> */ repository: string | undefined; /** * <p> * An updated repository description. * </p> */ description?: string; /** * <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories * in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more * information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> */ upstreams?: UpstreamRepository[]; } export namespace UpdateRepositoryRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRepositoryRequest): any => ({ ...obj, }); } export interface UpdateRepositoryResult { /** * <p> * The updated repository. * </p> */ repository?: RepositoryDescription; } export namespace UpdateRepositoryResult { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRepositoryResult): any => ({ ...obj, }); }
the_stack
import React, { ReactNode, useEffect, useState } from 'react'; import styled from 'styled-components'; import { Affix, Row, Select, Typography } from 'antd'; import { useGetDataProfilesLazyQuery } from '../../../../../../graphql/dataset.generated'; import { DatasetProfile, DateInterval } from '../../../../../../types.generated'; import { Message } from '../../../../../shared/Message'; import { getFixedLookbackWindow, TimeWindowSize } from '../../../../../shared/time/timeUtils'; import ProfilingRunsChart from './charts/ProfilingRunsChart'; import StatsSection from '../StatsSection'; import StatChart from './charts/StatChart'; const HeaderRow = styled(Row)` padding-top: 24px; padding-bottom: 28px; background-color: white; `; const SubHeaderText = styled(Typography.Text)` color: gray; font-size: 16px; `; const EmbeddedSelect = styled(Select)` padding-left: 8px; `; const isPresent = (val: any) => { return val !== undefined && val !== null; }; /** * Extracts a set of points used to render charts from a list of Dataset Profiles + * a particular numeric statistic name to extract. Note that the stat *must* be numeric for this utility to work. */ const extractChartValuesFromTableProfiles = (profiles: Array<any>, statName: string) => { return profiles .filter((profile) => isPresent(profile[statName])) .map((profile) => ({ timeMs: profile.timestampMillis, value: profile[statName] as number, })); }; /** * Extracts a set of field-specific points used to render charts from a list of Dataset Profiles + * a particular numeric statistic name to extract. Note that the stat *must* be numeric for this utility to work. */ const extractChartValuesFromFieldProfiles = (profiles: Array<any>, fieldPath: string, statName: string) => { return profiles .filter((profile) => profile.fieldProfiles) .map((profile) => { const fieldProfiles = profile.fieldProfiles ?.filter((field) => field.fieldPath === fieldPath) .filter((field) => field[statName] !== null && field[statName] !== undefined); if (fieldProfiles?.length === 1) { const fieldProfile = fieldProfiles[0]; return { timeMs: profile.timestampMillis, value: fieldProfile[statName], }; } return null; }) .filter((value) => value !== null); }; const computeChartTickInterval = (windowSize: TimeWindowSize): DateInterval => { switch (windowSize.interval) { case DateInterval.Day: return DateInterval.Hour; case DateInterval.Week: return DateInterval.Day; case DateInterval.Month: return DateInterval.Week; case DateInterval.Year: return DateInterval.Month; default: throw new Error(`Unrecognized DateInterval provided ${windowSize.interval}`); } }; const computeAllFieldPaths = (profiles: Array<DatasetProfile>): Set<string> => { const uniqueFieldPaths = new Set<string>(); profiles.forEach((profile) => { const fieldProfiles = profile.fieldProfiles || []; fieldProfiles.forEach((fieldProfile) => { uniqueFieldPaths.add(fieldProfile.fieldPath); }); }); return uniqueFieldPaths; }; /** * Change this to add or modify the lookback windows that are selectable via the UI. */ const LOOKBACK_WINDOWS = [ { text: '1 day', windowSize: { interval: DateInterval.Day, count: 1 } }, { text: '1 week', windowSize: { interval: DateInterval.Week, count: 1 } }, { text: '1 month', windowSize: { interval: DateInterval.Month, count: 1 } }, { text: '3 months', windowSize: { interval: DateInterval.Month, count: 3 } }, { text: '1 year', windowSize: { interval: DateInterval.Year, count: 1 } }, ]; const DEFAULT_LOOKBACK_WINDOW = '1 week'; const getLookbackWindowSize = (text: string) => { for (let i = 0; i < LOOKBACK_WINDOWS.length; i++) { const window = LOOKBACK_WINDOWS[i]; if (window.text === text) { return window.windowSize; } } throw new Error(`Unrecognized lookback window size ${text} provided`); }; export type Props = { urn: string; toggleView: ReactNode; }; export default function HistoricalStatsView({ urn, toggleView }: Props) { const [getDataProfiles, { data: profilesData, loading: profilesLoading }] = useGetDataProfilesLazyQuery(); /** * Perform initial fetch of default lookback window stats. */ useEffect(() => { getDataProfiles({ variables: { urn, ...getFixedLookbackWindow(getLookbackWindowSize(DEFAULT_LOOKBACK_WINDOW)) }, }); }, [urn, getDataProfiles]); /** * Determines which fixed lookback window is used to display historical statistics. See above for valid options. */ const [selectedLookbackWindow, setSelectedLookbackWindow] = useState(DEFAULT_LOOKBACK_WINDOW); const selectedWindowSize = getLookbackWindowSize(selectedLookbackWindow); const selectedWindow = getFixedLookbackWindow(selectedWindowSize); /** * Determines which field path is highlighted in column stats. Defaults to none. */ const [selectedFieldPath, setSelectedFieldPath] = useState(''); /** * Change handlers. */ const onChangeSelectedLookbackWindow = (text) => { const newWindowSize = getLookbackWindowSize(text); const newTimeWindow = getFixedLookbackWindow(newWindowSize); getDataProfiles({ variables: { urn, ...newTimeWindow }, }); setSelectedLookbackWindow(text); }; const onChangeSelectedFieldPath = (value) => { setSelectedFieldPath(value); }; const graphTickInterval = computeChartTickInterval(selectedWindowSize); const graphDateRange = { start: selectedWindow.startTime.toString(), end: selectedWindow.endTime.toString(), }; const profiles = profilesData?.dataset?.datasetProfiles || []; const allFieldPaths = Array.from(computeAllFieldPaths(profiles)); if (selectedFieldPath === '' && allFieldPaths.length > 0) { // Set initially selected field path. setSelectedFieldPath(allFieldPaths[0]); } const columnSelectView = ( <span> <SubHeaderText>Viewing stats for column</SubHeaderText> <EmbeddedSelect style={{ width: 200 }} value={selectedFieldPath} onChange={onChangeSelectedFieldPath}> {allFieldPaths.map((fieldPath) => ( <Select.Option value={fieldPath}>{fieldPath}</Select.Option> ))} </EmbeddedSelect> </span> ); /** * Compute Table Stat chart data. */ const rowCountChartValues = extractChartValuesFromTableProfiles(profiles, 'rowCount'); const columnCountChartValues = extractChartValuesFromTableProfiles(profiles, 'columnCount'); /** * Compute Column Stat chart data. */ const nullCountChartValues: Array<any> = extractChartValuesFromFieldProfiles( profiles, selectedFieldPath, 'nullCount', ); const nullPercentageChartValues: Array<any> = extractChartValuesFromFieldProfiles( profiles, selectedFieldPath, 'nullProportion', ); const distinctCountChartValues: Array<any> = extractChartValuesFromFieldProfiles( profiles, selectedFieldPath, 'uniqueCount', ); const distinctPercentageChartValues: Array<any> = extractChartValuesFromFieldProfiles( profiles, selectedFieldPath, 'uniqueProportion', ); return ( <> {profilesLoading && <Message type="loading" content="Loading..." style={{ marginTop: '10%' }} />} <Affix offsetTop={127}> <HeaderRow justify="space-between" align="middle"> <div> <Typography.Title level={2}>Profiling History</Typography.Title> <span> <SubHeaderText>Viewing profiling history for the past</SubHeaderText> <EmbeddedSelect value={selectedLookbackWindow} onChange={onChangeSelectedLookbackWindow}> {LOOKBACK_WINDOWS.map((lookbackWindow) => ( <Select.Option value={lookbackWindow.text}>{lookbackWindow.text}</Select.Option> ))} </EmbeddedSelect> </span> </div> {toggleView} </HeaderRow> </Affix> <StatsSection title="Profiling Runs"> <Row> <ProfilingRunsChart profiles={profiles} /> </Row> </StatsSection> <StatsSection title="Historical Table Stats"> <Row> <StatChart title="Row Count Over Time" tickInterval={graphTickInterval} dateRange={graphDateRange} values={rowCountChartValues} /> <StatChart title="Column Count Over Time" tickInterval={graphTickInterval} dateRange={graphDateRange} values={columnCountChartValues} /> </Row> </StatsSection> <StatsSection title="Historical Column Stats" rightFloatView={columnSelectView}> <Row> <StatChart title="Null Count Over Time" tickInterval={graphTickInterval} dateRange={graphDateRange} values={nullCountChartValues} /> <StatChart title="Null Percentage Over Time" tickInterval={graphTickInterval} dateRange={graphDateRange} values={nullPercentageChartValues} /> <StatChart title="Distinct Count Over Time" tickInterval={graphTickInterval} dateRange={graphDateRange} values={distinctCountChartValues} /> <StatChart title="Distinct Percentage Over Time" tickInterval={graphTickInterval} dateRange={graphDateRange} values={distinctPercentageChartValues} /> </Row> </StatsSection> </> ); }
the_stack
import { LuaLibImportKind } from "../../../src"; import * as util from "../../util"; test("Supported lua string function", () => { const tsHeader = ` declare global { interface String { upper(): string; } } `; util.testExpression`"test".upper()`.setTsHeader(tsHeader).expectToEqual("TEST"); }); test.each([[], [65], [65, 66], [65, 66, 67]])("String.fromCharCode (%p)", (...args) => { util.testExpression`String.fromCharCode(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each([ { a: 12, b: 23, c: 43 }, { a: "test", b: "hello", c: "bye" }, { a: "test", b: 42, c: "bye" }, { a: "test", b: 42, c: 12 }, { a: "test", b: 42, c: true }, { a: false, b: 42, c: 12 }, ])("String Concat Operator (%p)", ({ a, b, c }) => { util.testFunctionTemplate` let a = ${a}; let b = ${b}; let c = ${c}; return a + " " + b + " test " + c; `.expectToMatchJsResult(); }); test.each([ { input: "01234", index: 0 }, { input: "01234", index: 1 }, { input: "01234", index: 4 }, { input: "01234", index: 5 }, { input: "01234", index: -1 }, { input: "01234", index: 100 }, { input: "01234", index: NaN }, { input: "", index: 0 }, ])("string index (%p)", ({ input, index }) => { util.testExpressionTemplate`${input}[${index}]`.expectToMatchJsResult(); }); test("string index (side effect)", () => { util.testFunction` let i = 0; const mystring = "abc"; return mystring[i++]; `.expectToMatchJsResult(); }); describe.each(["replace", "replaceAll"])("string.%s", method => { const testCases = [ { inp: "hello test", searchValue: "", replaceValue: "" }, { inp: "hello test", searchValue: "", replaceValue: "_" }, { inp: "hello test", searchValue: " ", replaceValue: "" }, { inp: "hello test", searchValue: "hello", replaceValue: "" }, { inp: "hello test", searchValue: "test", replaceValue: "" }, { inp: "hello test", searchValue: "test", replaceValue: "world" }, { inp: "hello test", searchValue: "test", replaceValue: "%world" }, { inp: "hello test", searchValue: "test", replaceValue: "." }, { inp: "hello %test", searchValue: "test", replaceValue: "world" }, { inp: "hello %test", searchValue: "%test", replaceValue: "world" }, { inp: "hello test.", searchValue: ".", replaceValue: "$" }, { inp: "aaa", searchValue: "a", replaceValue: "b" }, ]; test.each(testCases)("string replacer %p", ({ inp, searchValue, replaceValue }) => { util.testExpression`"${inp}${inp}".${method}(${util.formatCode( searchValue, replaceValue )})`.expectToMatchJsResult(); }); test.each(testCases)("function replacer %p", ({ inp, searchValue, replaceValue }) => { util.testFunction` const result = { args: [], string: "" } function replacer(...args: any[]): string { result.args.push(...args) return ${util.formatCode(replaceValue)} } result.string = "${inp}${inp}".${method}(${util.formatCode(searchValue)}, replacer) return result `.expectToMatchJsResult(); }); }); test.each([ ["", ""], ["hello", "test"], ["hello", "test", "bye"], ["hello", 42], [42, "hello"], ])("string + (%p)", (...elements: any[]) => { util.testExpression(elements.map(e => util.formatCode(e)).join(" + ")).expectToMatchJsResult(); }); test.each([ { str: "", args: ["", ""] }, { str: "hello", args: ["test"] }, { str: "hello", args: [] }, { str: "hello", args: ["test", "bye"] }, ])("string.concat (%p)", ({ str, args }) => { util.testExpression`"${str}".concat(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", searchValue: "" }, { inp: "hello test", searchValue: "t" }, { inp: "hello test", searchValue: "h" }, { inp: "hello test", searchValue: "invalid" }, { inp: "hello.test", searchValue: "." }, ])("string.indexOf (%p)", ({ inp, searchValue }) => { util.testExpressionTemplate`${inp}.indexOf(${searchValue})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", searchValue: "t", offset: 5 }, { inp: "hello test", searchValue: "t", offset: 6 }, { inp: "hello test", searchValue: "t", offset: 7 }, { inp: "hello test", searchValue: "h", offset: 4 }, { inp: "00100", searchValue: "1", offset: -1 }, { inp: "00100", searchValue: "1", offset: -2 }, { inp: "01010", searchValue: "1", offset: -3 }, ])("string.indexOf with offset (%p)", ({ inp, searchValue, offset }) => { util.testExpressionTemplate`${inp}.indexOf(${searchValue}, ${offset})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", searchValue: "t", x: 4, y: 3 }, { inp: "hello test", searchValue: "h", x: 3, y: 4 }, ])("string.indexOf with offset expression (%p)", ({ inp, searchValue, x, y }) => { util.testExpressionTemplate`${inp}.indexOf(${searchValue}, 2 > 1 && ${x} || ${y})`.expectToMatchJsResult(); }); const stringPartCases = [ { inp: "0123456789", args: [0] }, { inp: "0123456789", args: [0, 0] }, { inp: "0123456789", args: [1] }, { inp: "0123456789", args: [1, 1] }, { inp: "0123456789", args: [1, 5] }, { inp: "0123456789", args: [5, 1] }, { inp: "0123456789", args: [1, 100] }, { inp: "0123456789", args: [100, 1] }, { inp: "0123456789", args: [100, 101] }, { inp: "0123456789", args: [-3] }, { inp: "0123456789", args: [1, -1] }, { inp: "0123456789", args: [-5, -2] }, { inp: "0123456789", args: [NaN, 3] }, { inp: "0123456789", args: [3, NaN] }, ]; test.each([{ inp: "0123456789", args: [] }, { inp: "0123456789", args: [undefined, 5] }, ...stringPartCases])( "string.slice (%p)", ({ inp, args }) => { util.testExpression`"${inp}".slice(${util.formatCode(...args)})`.expectToMatchJsResult(); } ); test.each(stringPartCases)("string.substring (%p)", ({ inp, args }) => { util.testExpression`"${inp}".substring(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", start: 1, ignored: 0 }, { inp: "hello test", start: 3, ignored: 0, end: 5 }, ])("string.substring with expression (%p)", ({ inp, start, ignored, end }) => { const paramStr = `2 > 1 && ${start} || ${ignored}` + (end ? `, ${end}` : ""); util.testExpression`"${inp}".substring(${paramStr})`.expectToMatchJsResult(); }); test.each(stringPartCases)("string.substr (%p)", ({ inp, args }) => { util.testExpression`"${inp}".substr(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", start: 1, ignored: 0 }, { inp: "hello test", start: 3, ignored: 0, end: 2 }, ])("string.substr with expression (%p)", ({ inp, start, ignored, end }) => { const paramStr = `2 > 1 && ${start} || ${ignored}` + (end ? `, ${end}` : ""); util.testExpression` "${inp}".substr(${paramStr}) `.expectToMatchJsResult(); }); test.each(["", "h", "hello"])("string.length (%p)", input => { util.testExpressionTemplate`${input}.length`.expectToMatchJsResult(); }); test.each(["hello TEST"])("string.toLowerCase (%p)", inp => { util.testExpressionTemplate`${inp}.toLowerCase()`.expectToMatchJsResult(); }); test.each(["hello test"])("string.toUpperCase (%p)", inp => { util.testExpressionTemplate`${inp}.toUpperCase()`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", separator: "" }, { inp: "hello test", separator: " " }, { inp: "hello test", separator: "h" }, { inp: "hello test", separator: "t" }, { inp: "hello test", separator: "l" }, { inp: "hello test", separator: "invalid" }, { inp: "hello test", separator: "hello test" }, ])("string.split (%p)", ({ inp, separator }) => { util.testExpressionTemplate`${inp}.split(${separator})`.expectToMatchJsResult(); }); test("string.split inline", () => { util.testExpression`"a, b, c".split(",")` .setOptions({ luaLibImport: LuaLibImportKind.Inline }) .expectToMatchJsResult(); }); // https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1009 test("string.split inline empty separator", () => { util.testExpression`"a, b, c".split("")` .setOptions({ luaLibImport: LuaLibImportKind.Inline }) .expectToMatchJsResult(); }); test.each([ { inp: "hello test", index: 0 }, { inp: "hello test", index: 1 }, { inp: "hello test", index: 2 }, { inp: "hello test", index: 3 }, { inp: "hello test", index: 99 }, { inp: "hello test", index: -1 }, { inp: "hello test", index: -5 }, { inp: "hello test", index: -99 }, { inp: "hello test", index: NaN }, ])("string.charAt (%p)", ({ inp, index }) => { util.testExpressionTemplate`${inp}.charAt(${index})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", index: 0 }, { inp: "hello test", index: 1 }, { inp: "hello test", index: 2 }, { inp: "hello test", index: 3 }, { inp: "hello test", index: 99 }, { inp: "hello test", index: -1 }, { inp: "hello test", index: -5 }, { inp: "hello test", index: -99 }, { inp: "hello test", index: NaN }, ])("string.charCodeAt (%p)", ({ inp, index }) => { util.testExpressionTemplate`${inp}.charCodeAt(${index})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", index: 1, ignored: 0 }, { inp: "hello test", index: 1, ignored: 2 }, { inp: "hello test", index: 3, ignored: 2 }, { inp: "hello test", index: 3, ignored: 99 }, ])("string.charAt with expression (%p)", ({ inp, index, ignored }) => { util.testExpressionTemplate`${inp}.charAt(2 > 1 && ${index} || ${ignored})`.expectToMatchJsResult(); }); test.each<{ inp: string; args: Parameters<string["startsWith"]> }>([ { inp: "hello test", args: [""] }, { inp: "hello test", args: ["hello"] }, { inp: "HELLO test", args: ["hello"] }, { inp: "hello test", args: ["test"] }, { inp: "hello test", args: ["test", 6] }, ])("string.startsWith (%p)", ({ inp, args }) => { util.testExpression`"${inp}".startsWith(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each<{ inp: string; args: Parameters<string["endsWith"]> }>([ { inp: "hello test", args: [""] }, { inp: "hello test", args: ["test"] }, { inp: "hello TEST", args: ["test"] }, { inp: "hello test", args: ["hello"] }, { inp: "hello test", args: ["hello", 5] }, ])("string.endsWith (%p)", ({ inp, args }) => { util.testExpression`"${inp}".endsWith(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each<{ inp: string; args: Parameters<string["includes"]> }>([ { inp: "hello test", args: [""] }, { inp: "hello test", args: ["test"] }, { inp: "HELLO TEST", args: ["test"] }, { inp: "hello test", args: ["hello"] }, { inp: "HELLO TEST", args: ["hello"] }, { inp: "hello test", args: ["hello", 5] }, { inp: "hello test", args: ["test", 6] }, ])("string.includes (%p)", ({ inp, args }) => { util.testExpression`"${inp}".includes(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each([ { inp: "hello test", count: 0 }, { inp: "hello test", count: 1 }, { inp: "hello test", count: 2 }, { inp: "hello test", count: 1.1 }, { inp: "hello test", count: 1.5 }, { inp: "hello test", count: 1.9 }, ])("string.repeat (%p)", ({ inp, count }) => { util.testExpression`"${inp}".repeat(${count})`.expectToMatchJsResult(); }); const padCases = [ { inp: "foo", args: [0] }, { inp: "foo", args: [3] }, { inp: "foo", args: [5] }, { inp: "foo", args: [4, " "] }, { inp: "foo", args: [10, " "] }, { inp: "foo", args: [5, "1234"] }, { inp: "foo", args: [5.9, "1234"] }, { inp: "foo", args: [NaN] }, ]; test.each(padCases)("string.padStart (%p)", ({ inp, args }) => { util.testExpression`"${inp}".padStart(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each(padCases)("string.padEnd (%p)", ({ inp, args }) => { util.testExpression`"${inp}".padEnd(${util.formatCode(...args)})`.expectToMatchJsResult(); }); test.each([ "function generic<T extends string>(string: T)", "type StringType = string; function generic<T extends StringType>(string: T)", ])("string constrained generic foreach (%p)", signature => { util.testFunction` ${signature}: number { return string.length; } return generic("string"); `.expectToMatchJsResult(); }); const trimTestCases = [ "", " ", "\t", "\t \t", " foo ", "\tfoo\t", "\ffoo\f", "\vfoo\v", "\uFEFFFoo\uFEFF", "\xA0Foo\xA0", " \t foo \t ", " foo bar ", "\r\nfoo\n\r\n", "\r\nfoo\nbar\n\r\n", ]; describe.each(["trim", "trimEnd", "trimRight", "trimStart", "trimLeft"])("string.%s", trim => { test.each(trimTestCases)("matches JS result (%p)", testString => { util.testExpression`${util.formatCode(testString)}.${trim}()`.expectToMatchJsResult(); }); }); test("string intersected method", () => { util.testFunction` type Vector = string & { abc(): Vector }; return ({ abc: () => "a" } as Vector).abc(); `.expectToMatchJsResult(); }); // Issue #1218: https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1218 test.each(['"foo"', "undefined"])("prototype call on nullable string (%p)", value => { util.testFunction` function toUpper(str?: string) { return str?.toUpperCase(); } return toUpper(${value}); ` .setOptions({ strictNullChecks: true }) .expectToMatchJsResult(); }); // Issue #1218: https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1218 test.each(["string | undefined", "string | null", "null | string", "null | undefined | string"])( "prototype call on nullable string type (%p)", type => { util.testFunction` function toUpper(str: ${type}) { return str?.toUpperCase(); } return toUpper("foo"); ` .setOptions({ strictNullChecks: true }) .expectToMatchJsResult(); } );
the_stack
import '../../jest-extensions'; import { from, fromDOMStream, toArray } from 'ix/asynciterable'; import { fromNodeStream } from 'ix/asynciterable/fromnodestream'; import 'ix/Ix.node'; import { util } from 'apache-arrow'; import { Builder } from 'apache-arrow'; import { DataType, Vector, Chunked } from 'apache-arrow'; import randstr from 'randomatic'; const rand = Math.random.bind(Math); const randnulls = <T, TNull = null>(values: T[], n: TNull = <any> null) => values.map((x) => Math.random() > 0.25 ? x : n) as (T | TNull)[]; export const randomBytes = (length: number) => fillRandom(Uint8Array, length); export const randomString = ((opts) => (length: number) => randstr('?', length, opts) )({ chars: `abcdefghijklmnopqrstuvwxyz0123456789_` }); export const stringsNoNulls = (length = 20) => Array.from({ length }, (_) => randomString(1 + (Math.random() * 19 | 0))); export const timestamp32sNoNulls = (length = 20, now = Date.now() / 86400000 | 0) => Array.from({ length }, (_) => (now + (rand() * 10000 * (rand() > 0.5 ? -1 : 1)) | 0) * 86400000); export const timestamp64sNoNulls = (length = 20, now = Date.now()) => Array.from({ length }, (_) => { const ms = now + (rand() * 31557600000 * (rand() > 0.5 ? -1 : 1) | 0); return new Int32Array([(ms % 4294967296) | 0, (ms / 4294967296) | 0]); }); export const timestamp32sWithNulls = (length = 20) => randnulls(timestamp32sNoNulls(length), null); export const timestamp64sWithNulls = (length = 20) => randnulls(timestamp64sNoNulls(length), null); export const timestamp32sWithMaxInts = (length = 20) => randnulls(timestamp32sNoNulls(length), 0x7fffffff); export const timestamp64sWithMaxInts = (length = 20) => randnulls(timestamp64sNoNulls(length), new Int32Array([0x7fffffff, 0x7fffffff])); export const boolsNoNulls = (length = 20) => Array.from({ length }, () => rand() > 0.5); export const date32sNoNulls = (length = 20) => timestamp32sNoNulls(length).map((x) => new Date(x)); export const date64sNoNulls = (length = 20) => timestamp64sNoNulls(length).map((x) => new Date(4294967296 * x[1] + (x[0] >>> 0))); export const int8sNoNulls = (length = 20) => Array.from(new Int8Array(randomBytes(length * Int8Array.BYTES_PER_ELEMENT).buffer)); export const int16sNoNulls = (length = 20) => Array.from(new Int16Array(randomBytes(length * Int16Array.BYTES_PER_ELEMENT).buffer)); export const int32sNoNulls = (length = 20) => Array.from(new Int32Array(randomBytes(length * Int32Array.BYTES_PER_ELEMENT).buffer)); export const int64sNoNulls = (length = 20) => Array.from({ length }, (_, i) => { const bn = util.BN.new(new Int32Array(randomBytes(2 * 4).buffer)); // Evenly distribute the three types of arguments we support in the Int64 // builder switch (i % 3) { // Int32Array (util.BN is-a Int32Array) case 0: return bn; // BigInt case 1: return bn[Symbol.toPrimitive](); // number case 2: default: return bn[0]; } }); export const uint8sNoNulls = (length = 20) => Array.from(new Uint8Array(randomBytes(length * Uint8Array.BYTES_PER_ELEMENT).buffer)); export const uint16sNoNulls = (length = 20) => Array.from(new Uint16Array(randomBytes(length * Uint16Array.BYTES_PER_ELEMENT).buffer)); export const uint32sNoNulls = (length = 20) => Array.from(new Uint32Array(randomBytes(length * Uint32Array.BYTES_PER_ELEMENT).buffer)); export const uint64sNoNulls = (length = 20) => Array.from({ length }, (_, i) => { const bn = util.BN.new(new Uint32Array(randomBytes(2 * 4).buffer)); // Evenly distribute the three types of arguments we support in the Uint64 // builder switch (i % 3) { // UInt32Array (util.BN is-a Uint32Array) case 0: return bn; // BigInt case 1: return bn[Symbol.toPrimitive](); // number case 2: default: return bn[0]; } }); export const float16sNoNulls = (length = 20) => Array.from(new Uint16Array(randomBytes(length * Uint16Array.BYTES_PER_ELEMENT).buffer)).map(util.uint16ToFloat64); export const float32sNoNulls = (length = 20) => Array.from(new Float32Array(randomBytes(length * Float32Array.BYTES_PER_ELEMENT).buffer)); export const float64sNoNulls = (length = 20) => Array.from(new Float64Array(randomBytes(length * Float64Array.BYTES_PER_ELEMENT).buffer)); export const stringsWithNAs = (length = 20) => randnulls(stringsNoNulls(length), 'n/a'); export const stringsWithNulls = (length = 20) => randnulls(stringsNoNulls(length), null); export const stringsWithEmpties = (length = 20) => randnulls(stringsNoNulls(length), '\0'); export const boolsWithNulls = (length = 20) => randnulls(boolsNoNulls(length), null); export const date32sWithNulls = (length = 20) => randnulls(date32sNoNulls(length), null); export const date64sWithNulls = (length = 20) => randnulls(date64sNoNulls(length), null); export const int8sWithNulls = (length = 20) => randnulls(int8sNoNulls(length), null); export const int16sWithNulls = (length = 20) => randnulls(int16sNoNulls(length), null); export const int32sWithNulls = (length = 20) => randnulls(int32sNoNulls(length), null); export const int64sWithNulls = (length = 20) => randnulls(int64sNoNulls(length), null); export const uint8sWithNulls = (length = 20) => randnulls(uint8sNoNulls(length), null); export const uint16sWithNulls = (length = 20) => randnulls(uint16sNoNulls(length), null); export const uint32sWithNulls = (length = 20) => randnulls(uint32sNoNulls(length), null); export const uint64sWithNulls = (length = 20) => randnulls(uint64sNoNulls(length), null); export const float16sWithNulls = (length = 20) => randnulls(float16sNoNulls(length), null); export const float32sWithNulls = (length = 20) => randnulls(float32sNoNulls(length), null); export const float64sWithNulls = (length = 20) => randnulls(float64sNoNulls(length), null); export const int8sWithMaxInts = (length = 20) => randnulls(int8sNoNulls(length), 0x7fffffff); export const int16sWithMaxInts = (length = 20) => randnulls(int16sNoNulls(length), 0x7fffffff); export const int32sWithMaxInts = (length = 20) => randnulls(int32sNoNulls(length), 0x7fffffff); export const int64sWithMaxInts = (length = 20) => randnulls(int64sNoNulls(length), new Int32Array([0x7fffffff, 0x7fffffff])); export const uint8sWithMaxInts = (length = 20) => randnulls(uint8sNoNulls(length), 0x7fffffff); export const uint16sWithMaxInts = (length = 20) => randnulls(uint16sNoNulls(length), 0x7fffffff); export const uint32sWithMaxInts = (length = 20) => randnulls(uint32sNoNulls(length), 0x7fffffff); export const uint64sWithMaxInts = (length = 20) => randnulls(uint64sNoNulls(length), new Uint32Array([0x7fffffff, 0x7fffffff])); export const float16sWithNaNs = (length = 20) => randnulls(float16sNoNulls(length), NaN); export const float32sWithNaNs = (length = 20) => randnulls(float32sNoNulls(length), NaN); export const float64sWithNaNs = (length = 20) => randnulls(float64sNoNulls(length), NaN); export const duplicateItems = (n: number, xs: (any | null)[]) => { const out = new Array<string | null>(n); for (let i = -1, k = xs.length; ++i < n;) { out[i] = xs[Math.random() * k | 0]; } return out; }; export function encodeAll<T extends DataType>(typeFactory: () => T) { return async function encodeAll<TNull = any>(values: (T['TValue'] | TNull)[], nullValues?: TNull[]) { const type = typeFactory(); const builder = Builder.new({ type, nullValues }); values.forEach(builder.append.bind(builder)); return builder.finish().toVector(); }; } export function encodeEach<T extends DataType>(typeFactory: () => T, chunkLen?: number) { return async function encodeEach<TNull = any>(vals: (T['TValue'] | TNull)[], nullValues?: TNull[]) { const type = typeFactory(); const opts = { type, nullValues, highWaterMark: chunkLen }; const chunks = [...Builder.throughIterable(opts)(vals)]; return Chunked.concat(...chunks) as Chunked<T>; }; } export function encodeEachDOM<T extends DataType>(typeFactory: () => T, chunkLen?: number) { return async function encodeEachDOM<TNull = any>(vals: (T['TValue'] | TNull)[], nullValues?: TNull[]) { const type = typeFactory(); const strategy = { highWaterMark: chunkLen }; const source = from(vals).toDOMStream(); const builder = Builder.throughDOM({ type, nullValues, readableStrategy: strategy, writableStrategy: strategy }); const chunks = await fromDOMStream(source.pipeThrough(builder)).pipe(toArray); return Chunked.concat(...chunks) as Chunked<T>; }; } export function encodeEachNode<T extends DataType>(typeFactory: () => T, chunkLen?: number) { return async function encodeEachNode<TNull = any>(vals: (T['TValue'] | TNull)[], nullValues?: TNull[]) { const type = typeFactory(); const vals_ = vals.map((x) => x === null ? undefined : x); const source = from(vals_).toNodeStream({ objectMode: true }); const nulls_ = nullValues ? nullValues.map((x) => x === null ? undefined : x) : nullValues; const builder = Builder.throughNode({ type, nullValues: nulls_, highWaterMark: chunkLen }); const chunks: any[] = await fromNodeStream(source.pipe(builder), chunkLen).pipe(toArray); return Chunked.concat(...chunks) as Chunked<T>; }; } const isInt64Null = (nulls: Map<any, any>, x: any) => { if (ArrayBuffer.isView(x)) { const bn = util.BN.new<Int32Array>(x as Int32Array); return nulls.has((<any> bn)[Symbol.toPrimitive]('default')); } return false; }; export function validateVector<T extends DataType>(vals: (T['TValue'] | null)[], vec: Vector, nullVals: any[]) { let i = 0, x: T['TValue'] | null, y: T['TValue'] | null; const nulls = nullVals.reduce((m, x) => m.set(x, x), new Map()); try { for (x of vec) { if (nulls.has(y = vals[i])) { expect(x).toBeNull(); } else if (isInt64Null(nulls, y)) { expect(x).toBeNull(); } else { expect(x).toArrowCompare(y); } i++; } } catch (e) { // Uncomment these two lines to catch and debug the value retrieval that failed // debugger; // vec.get(i); throw new Error([ `${(vec as any).VectorName}[${i}]: ${e?.stack || e}`, `nulls: [${nullVals.join(', ')}]`, `values: [${vals.join(', ')}]`, ].join('\n')); } } function fillRandom<T extends TypedArrayConstructor>(ArrayType: T, length: number) { const BPE = ArrayType.BYTES_PER_ELEMENT; const array = new ArrayType(length); const max = (2 ** (8 * BPE)) - 1; for (let i = -1; ++i < length; array[i] = rand() * max * (rand() > 0.5 ? -1 : 1)) { } return array as InstanceType<T>; } type TypedArrayConstructor = (typeof Int8Array) | (typeof Int16Array) | (typeof Int32Array) | (typeof Uint8Array) | (typeof Uint16Array) | (typeof Uint32Array) | (typeof Float32Array) | (typeof Float64Array);
the_stack
declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; declare function beforeEach(action: (done: DoneFn) => void, timeout?: number): void; declare function expect(spy: Function): jasmine.Matchers; declare function expect(actual: any): jasmine.Matchers; interface DoneFn extends Function { (): void; /** fails the spec and indicates that it has completed. If the message is an Error, Error.message is used */ fail: (message?: Error|string) => void; } declare namespace jasmine { interface Matchers { toEqual(expected: any, expectationFailOutput?: any): boolean; toBeDefined(expectationFailOutput?: any): boolean; toBeNull(expectationFailOutput?: any): boolean; toContainHtml(expected: string): boolean; toContainText(expected: string): boolean; not: Matchers; } } //End Jasmine definitions var dummyTemplateEngine = function (templates?) { var inMemoryTemplates = templates || {}; var inMemoryTemplateData = {}; function dummyTemplateSource(id) { this.id = id; } dummyTemplateSource.prototype = { text: function(val) { if (arguments.length >= 1) inMemoryTemplates[this.id] = val; return inMemoryTemplates[this.id]; }, data: function(key, val) { if (arguments.length >= 2) { inMemoryTemplateData[this.id] = inMemoryTemplateData[this.id] || {}; inMemoryTemplateData[this.id][key] = val; } return (inMemoryTemplateData[this.id] || {})[key]; } } this.makeTemplateSource = function(template) { if (typeof template == "string") return new dummyTemplateSource(template); // Named template comes from the in-memory collection else if ((template.nodeType == 1) || (template.nodeType == 8)) return new ko.templateSources.anonymousTemplate(template); // Anonymous template }; this.renderTemplateSource = function (templateSource, bindingContext, options) { var data = bindingContext['$data']; options = options || {}; var templateText = templateSource.text(); if (typeof templateText == "function") templateText = templateText(data, options); templateText = options.showParams ? templateText + ", data=" + data + ", options=" + options : templateText; var templateOptions = options.templateOptions; // Have templateOptions in scope to support [js:templateOptions.foo] syntax var result; //with (bindingContext) { //with (data || {}) { //with (options.templateRenderingVariablesInScope || {}) { // Dummy [renderTemplate:...] syntax result = templateText.replace(/\[renderTemplate\:(.*?)\]/g, function (match, templateName) { return ko.renderTemplate(templateName, data, options); }); var evalHandler = function (match, script) { try { var evalResult = eval(script); return (evalResult === null) || (evalResult === undefined) ? "" : evalResult.toString(); } catch (ex) { throw new Error("Error evaluating script: [js: " + script + "]\n\nException: " + ex.toString()); } } // Dummy [[js:...]] syntax (in case you need to use square brackets inside the expression) result = result.replace(/\[\[js\:([\s\S]*?)\]\]/g, evalHandler); // Dummy [js:...] syntax result = result.replace(/\[js\:([\s\S]*?)\]/g, evalHandler); } } } // Use same HTML parsing code as real template engine so as to trigger same combination of IE weirdnesses // Also ensure resulting nodelist is an array to mimic what the default templating engine does, so we see the effects of not being able to remove dead memo comment nodes. return ko.utils.arrayPushAll([], ko.utils.parseHtmlFragment(result)); }; this.rewriteTemplate = function (template, rewriterCallback) { // Only rewrite if the template isn't a function (can't rewrite those) var templateSource = new ko.templateSources.anonymousTemplate(template); //this.makeTemplateSource(template); if (typeof templateSource.text() != "function") return ko.templateEngine.prototype.rewriteTemplate.call(this, template, rewriterCallback); }; this.createJavaScriptEvaluatorBlock = function (script) { return "[js:" + script + "]"; }; }; dummyTemplateEngine.prototype = new ko.templateEngine(); describe('Templating', function() { beforeEach(function() { ko.setTemplateEngine(new ko.nativeTemplateEngine()); }); //beforeEach(jasmine.prepareTestNode); var testNode: any; it('Template engines can return an array of DOM nodes', function () { ko.setTemplateEngine(new dummyTemplateEngine({ x: [document.createElement("div"), document.createElement("span")] })); ko.renderTemplate("x", null); }); it('Should not be able to render a template until a template engine is provided', function () { var threw = false; ko.setTemplateEngine(undefined); try { ko.renderTemplate("someTemplate", {}) } catch (ex) { threw = true } expect(threw).toEqual(true); }); it('Should be able to render a template into a given DOM element', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "ABC" })); ko.renderTemplate("someTemplate", null, null, testNode); expect(testNode.childNodes.length).toEqual(1); expect(testNode.innerHTML).toEqual("ABC"); }); it('Should be able to render an empty template', function() { ko.setTemplateEngine(new dummyTemplateEngine({ emptyTemplate: "" })); ko.renderTemplate("emptyTemplate", null, null, testNode); expect(testNode.childNodes.length).toEqual(0); }); it('Should be able to access newly rendered/inserted elements in \'afterRender\' callaback', function () { var passedElement:any, passedDataItem; var myCallback = function(elementsArray, dataItem) { expect(elementsArray.length).toEqual(1); passedElement = elementsArray[0]; passedDataItem = dataItem; } var myModel = {}; ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "ABC" })); ko.renderTemplate("someTemplate", myModel, { afterRender: myCallback }, testNode); expect(passedElement.nodeValue).toEqual("ABC"); expect(passedDataItem).toEqual(myModel); }); it('Should automatically rerender into DOM element when dependencies change', function () { var dependency = ko.observable("A"); ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: function () { return "Value = " + dependency(); } })); ko.renderTemplate("someTemplate", null, null, testNode); expect(testNode.childNodes.length).toEqual(1); expect(testNode.innerHTML).toEqual("Value = A"); dependency("B"); expect(testNode.childNodes.length).toEqual(1); expect(testNode.innerHTML).toEqual("Value = B"); }); it('Should not rerender DOM element if observable accessed in \'afterRender\' callaback is changed', function () { var observable = ko.observable("A"), count = 0; var myCallback = function(elementsArray, dataItem) { observable(); // access observable in callback }; var myTemplate = function() { return "Value = " + (++count); }; ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: myTemplate })); ko.renderTemplate("someTemplate", {}, { afterRender: myCallback }, testNode); expect(testNode.childNodes.length).toEqual(1); expect(testNode.innerHTML).toEqual("Value = 1"); observable("B"); expect(testNode.childNodes.length).toEqual(1); expect(testNode.innerHTML).toEqual("Value = 1"); }); it('If the supplied data item is observable, evaluates it and has subscription on it', function () { var observable = ko.observable("A"); ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: function (data) { return "Value = " + data; } })); ko.renderTemplate("someTemplate", observable, null, testNode); expect(testNode.innerHTML).toEqual("Value = A"); observable("B"); expect(testNode.innerHTML).toEqual("Value = B"); }); it('Should stop updating DOM nodes when the dependency next changes if the DOM node has been removed from the document', function () { var dependency = ko.observable("A"); var template = { someTemplate: function () { return "Value = " + dependency() } }; ko.setTemplateEngine(new dummyTemplateEngine(template)); ko.renderTemplate("someTemplate", null, null, testNode); expect(testNode.childNodes.length).toEqual(1); expect(testNode.innerHTML).toEqual("Value = A"); testNode.parentNode.removeChild(testNode); dependency("B"); expect(testNode.childNodes.length).toEqual(1); expect(testNode.innerHTML).toEqual("Value = A"); }); it('Should be able to render a template using data-bind syntax', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "template output" })); testNode.innerHTML = "<div data-bind='template:\"someTemplate\"'></div>"; ko.applyBindings(null, testNode); expect(testNode.childNodes[0].innerHTML).toEqual("template output"); }); it('Should be able to tell data-bind syntax which object to pass as data for the template (otherwise, uses viewModel)', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "result = [js: childProp]" })); testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"; ko.applyBindings({ someProp: { childProp: 123} }, testNode); expect(testNode.childNodes[0].innerHTML).toEqual("result = 123"); }); it('Should re-render a named template when its data item notifies about mutation', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "result = [js: childProp]" })); testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"; var myData = ko.observable({ childProp: 123 }); ko.applyBindings({ someProp: myData }, testNode); expect(testNode.childNodes[0].innerHTML).toEqual("result = 123"); expect(myData).toBeDefined(); // Now mutate and notify if (myData) { myData().childProp = 456; if (myData.valueHasMutated) { myData.valueHasMutated(); } expect(testNode.childNodes[0].innerHTML).toEqual("result = 456"); } }); it('Should stop tracking inner observables immediately when the container node is removed from the document', function() { var innerObservable = ko.observable("some value"); ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "result = [js: childProp()]" })); testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"; ko.applyBindings({ someProp: { childProp: innerObservable} }, testNode); expect(innerObservable.getSubscriptionsCount()).toEqual(1); ko.removeNode(testNode.childNodes[0]); expect(innerObservable.getSubscriptionsCount()).toEqual(0); }); it('Should be able to pick template via an observable model property', function () { ko.setTemplateEngine(new dummyTemplateEngine({ firstTemplate: "First template output", secondTemplate: "Second template output" })); var chosenTemplate = ko.observable("firstTemplate"); testNode.innerHTML = "<div data-bind='template: chosenTemplate'></div>"; ko.applyBindings({ chosenTemplate: chosenTemplate }, testNode); expect(testNode.childNodes[0].innerHTML).toEqual("First template output"); chosenTemplate("secondTemplate"); expect(testNode.childNodes[0].innerHTML).toEqual("Second template output"); }); it('Should be able to pick template as a function of the data item using data-bind syntax, with the binding context available as a second parameter', function () { var templatePicker = function(dataItem, bindingContext) { // Having the entire binding context available means you can read sibling or parent level properties expect(bindingContext.$parent.anotherProperty).toEqual(456); return dataItem.myTemplate; }; ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "result = [js: childProp]" })); testNode.innerHTML = "<div data-bind='template: { name: templateSelectorFunction, data: someProp }'></div>"; ko.applyBindings({ someProp: { childProp: 123, myTemplate: "someTemplate" }, templateSelectorFunction: templatePicker, anotherProperty: 456 }, testNode); expect(testNode.childNodes[0].innerHTML).toEqual("result = 123"); }); it('Should be able to chain templates, rendering one from inside another', function () { ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: "outer template output, [renderTemplate:innerTemplate]", // [renderTemplate:...] is special syntax supported by dummy template engine innerTemplate: "inner template output <span data-bind='text: 123'></span>" })); testNode.innerHTML = "<div data-bind='template:\"outerTemplate\"'></div>"; ko.applyBindings(null, testNode); expect(testNode.childNodes[0]).toContainHtml("outer template output, inner template output <span>123</span>"); }); it('Should rerender chained templates when their dependencies change, without rerendering parent templates', function () { var observable = ko.observable("ABC"); var timesRenderedOuter = 0, timesRenderedInner = 0; ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: function () { timesRenderedOuter++; return "outer template output, [renderTemplate:innerTemplate]" }, // [renderTemplate:...] is special syntax supported by dummy template engine innerTemplate: function () { timesRenderedInner++; return observable() } })); testNode.innerHTML = "<div data-bind='template:\"outerTemplate\"'></div>"; ko.applyBindings(null, testNode); expect(testNode.childNodes[0]).toContainHtml("outer template output, abc"); expect(timesRenderedOuter).toEqual(1); expect(timesRenderedInner).toEqual(1); observable("DEF"); expect(testNode.childNodes[0]).toContainHtml("outer template output, def"); expect(timesRenderedOuter).toEqual(1); expect(timesRenderedInner).toEqual(2); }); it('Should stop tracking inner observables referenced by a chained template as soon as the chained template output node is removed from the document', function() { var innerObservable = ko.observable("some value"); ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: "outer template output, <span id='innerTemplateOutput'>[renderTemplate:innerTemplate]</span>", innerTemplate: "result = [js: childProp()]" })); testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\", data: someProp }'></div>"; ko.applyBindings({ someProp: { childProp: innerObservable} }, testNode); expect(innerObservable.getSubscriptionsCount()).toEqual(1); let innerTemplateOutputEl = document.getElementById('innerTemplateOutput'); expect(innerTemplateOutputEl).not.toBeNull(); if (innerTemplateOutputEl) { ko.removeNode(innerTemplateOutputEl); } expect(innerObservable.getSubscriptionsCount()).toEqual(0); }); it('Should handle data-bind attributes from inside templates, regardless of element and attribute casing', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<INPUT Data-Bind='value:\"Hi\"' />" })); ko.renderTemplate("someTemplate", null, null, testNode); expect(testNode.childNodes[0].value).toEqual("Hi"); }); it('Should handle data-bind attributes that include newlines from inside templates', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input data-bind='value:\n\"Hi\"' />" })); ko.renderTemplate("someTemplate", null, null, testNode); expect(testNode.childNodes[0].value).toEqual("Hi"); }); it('Data binding syntax should be able to reference variables put into scope by the template engine', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input data-bind='value:message' />" })); ko.renderTemplate("someTemplate", null, { templateRenderingVariablesInScope: { message: "hello"} }, testNode); expect(testNode.childNodes[0].value).toEqual("hello"); }); it('Data binding syntax should be able to use $element in binding value', function() { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: $element.tagName'></div>" })); ko.renderTemplate("someTemplate", null, null, testNode); expect(testNode.childNodes[0]).toContainText("DIV"); }); it('Data binding syntax should be able to use $context in binding value to refer to the context object', function() { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: $context.$data === $data'></div>" })); ko.renderTemplate("someTemplate", {}, null, testNode); expect(testNode.childNodes[0]).toContainText("true"); }); it('Data binding syntax should defer evaluation of variables until the end of template rendering (so bindings can take independent subscriptions to them)', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input data-bind='value:message' />[js: message = 'goodbye'; undefined; ]" })); ko.renderTemplate("someTemplate", null, { templateRenderingVariablesInScope: { message: "hello"} }, testNode); expect(testNode.childNodes[0].value).toEqual("goodbye"); }); it('Data binding syntax should use the template\'s \'data\' object as the viewModel value (so \'this\' is set correctly when calling click handlers etc.)', function() { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<button data-bind='click: someFunctionOnModel'>click me</button>" })); var viewModel = { didCallMyFunction : false, someFunctionOnModel : function() { this.didCallMyFunction = true } }; ko.renderTemplate("someTemplate", viewModel, null, testNode); var buttonNode = testNode.childNodes[0]; expect(buttonNode.tagName).toEqual("BUTTON"); // Be sure we're clicking the right thing buttonNode.click(); expect(viewModel.didCallMyFunction).toEqual(true); }); it('Data binding syntax should permit nested templates, and only bind inner templates once', function() { // Will verify that bindings are applied only once for both inline (rewritten) bindings, // and external (non-rewritten) ones var originalBindingProvider = ko.bindingProvider.instance; ko.bindingProvider.instance = { nodeHasBindings: function(node) { return ((<Element>node).tagName == 'EM') || originalBindingProvider.nodeHasBindings(node); }, getBindings: function(node, bindingContext) { if ((<Element>node).tagName == 'EM') return { text: ++model.numBindings }; return originalBindingProvider.getBindings(node, bindingContext); } }; ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: "Outer <div data-bind='template: { name: \"innerTemplate\", bypassDomNodeWrap: true }'></div>", innerTemplate: "Inner via inline binding: <span data-bind='text: ++numBindings'></span>" + "Inner via external binding: <em></em>" })); var model = { numBindings: 0 }; testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\", bypassDomNodeWrap: true }'></div>"; ko.applyBindings(model, testNode); expect(model.numBindings).toEqual(2); expect(testNode.childNodes[0]).toContainHtml("outer <div>inner via inline binding: <span>2</span>inner via external binding: <em>1</em></div>"); ko.bindingProvider.instance = originalBindingProvider; }); it('Data binding syntax should support \'foreach\' option, whereby it renders for each item in an array but doesn\'t rerender everything if you push or splice', function () { var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "<div>The item is [js: personName]</div>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>the item is bob</div><div>the item is frank</div>"); var originalBobNode = testNode.childNodes[0].childNodes[0]; var originalFrankNode = testNode.childNodes[0].childNodes[1]; myArray.push({ personName: "Steve" }); expect(testNode.childNodes[0]).toContainHtml("<div>the item is bob</div><div>the item is frank</div><div>the item is steve</div>"); expect(testNode.childNodes[0].childNodes[0]).toEqual(originalBobNode); expect(testNode.childNodes[0].childNodes[1]).toEqual(originalFrankNode); }); it('Data binding \'foreach\' option should apply bindings within the context of each item in the array', function () { var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is <span data-bind='text: personName'></span>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("the item is <span>bob</span>the item is <span>frank</span>"); }); it('Data binding \'foreach\' options should only bind each group of output nodes once', function() { var initCalls = 0; (<any>ko.bindingHandlers).countInits = { init: function() { initCalls++ } }; ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "<span data-bind='countInits: true'></span>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: [1,2,3] }, testNode); expect(initCalls).toEqual(3); // 3 because there were 3 items in myCollection }); it('Data binding \'foreach\' should handle templates in which the very first node has a binding', function() { // Represents https://github.com/SteveSanderson/knockout/pull/440 // Previously, the rewriting (which introduces a comment node before the bound node) was interfering // with the array-to-DOM-node mapping state tracking ko.setTemplateEngine(new dummyTemplateEngine({ mytemplate: "<div data-bind='text: $data'></div>" })); testNode.innerHTML = "<div data-bind=\"template: { name: 'mytemplate', foreach: items }\"></div>"; // Bind against initial array containing one entry. UI just shows "original" var myArray = ko.observableArray(["original"]); ko.applyBindings({ items: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>original</div>"); // Now replace the entire array contents with one different entry. // UI just shows "new" (previously with bug, showed "original" AND "new") myArray(["new"]); expect(testNode.childNodes[0]).toContainHtml("<div>new</div>"); }); it('Data binding \'foreach\' should handle chained templates in which the very first node has a binding', function() { // See https://github.com/SteveSanderson/knockout/pull/440 and https://github.com/SteveSanderson/knockout/pull/144 ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: "<div data-bind='text: $data'></div>[renderTemplate:innerTemplate]x", // [renderTemplate:...] is special syntax supported by dummy template engine innerTemplate: "inner <span data-bind='text: 123'></span>" })); testNode.innerHTML = "<div data-bind=\"template: { name: 'outerTemplate', foreach: items }\"></div>"; // Bind against initial array containing one entry. var myArray = ko.observableArray(["original"]); ko.applyBindings({ items: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>original</div>inner <span>123</span>x"); // Now replace the entire array contents with one different entry. myArray(["new"]); expect(testNode.childNodes[0]).toContainHtml("<div>new</div>inner <span>123</span>x"); }); it('Data binding \'foreach\' should handle templates in which the very first node has a binding but it does not reference any observables', function() { // Represents https://github.com/SteveSanderson/knockout/issues/739 // Previously, the rewriting (which introduces a comment node before the bound node) was interfering // with the array-to-DOM-node mapping state tracking ko.setTemplateEngine(new dummyTemplateEngine({ mytemplate: "<div data-bind='attr: {}'>[js:name()]</div>" })); testNode.innerHTML = "<div data-bind=\"template: { name: 'mytemplate', foreach: items }\"></div>"; // Bind against array, referencing an observable property var myItem = { name: ko.observable("a") }; ko.applyBindings({ items: [myItem] }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>a</div>"); // Modify the observable property and check that UI is updated // Previously with the bug, it wasn't updated because the removal of the memo comment caused the array-to-DOM-node computed to be disposed myItem.name("b"); expect(testNode.childNodes[0]).toContainHtml("<div>b</div>"); }); it('Data binding \'foreach\' option should apply bindings with an $index in the context', function () { var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item # is <span data-bind='text: $index'></span>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("the item # is <span>0</span>the item # is <span>1</span>"); }); it('Data binding \'foreach\' option should update bindings that reference an $index if the list changes', function () { var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item <span data-bind='text: personName'></span>is <span data-bind='text: $index'></span>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("the item <span>bob</span>is <span>0</span>the item <span>frank</span>is <span>1</span>"); var frank = myArray.pop(); // remove frank expect(testNode.childNodes[0]).toContainHtml("the item <span>bob</span>is <span>0</span>"); myArray.unshift(frank); // put frank in the front expect(testNode.childNodes[0]).toContainHtml("the item <span>frank</span>is <span>0</span>the item <span>bob</span>is <span>1</span>"); }); it('Data binding \'foreach\' option should accept array with "undefined" and "null" items', function () { var myArray = ko.observableArray([undefined, null]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is <span data-bind='text: String($data)'></span>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("the item is <span>undefined</span>the item is <span>null</span>"); }); it('Data binding \'foreach\' option should update DOM nodes when a dependency of their mapping function changes', function() { var myObservable = ko.observable("Steve"); var myArray = ko.observableArray([{ personName: "Bob" }, { personName: myObservable }, { personName: "Another" }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "<div>The item is [js: ko.utils.unwrapObservable(personName)]</div>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>the item is bob</div><div>the item is steve</div><div>the item is another</div>"); var originalBobNode = testNode.childNodes[0].childNodes[0]; myObservable("Steve2"); expect(testNode.childNodes[0]).toContainHtml("<div>the item is bob</div><div>the item is steve2</div><div>the item is another</div>"); expect(testNode.childNodes[0].childNodes[0]).toEqual(originalBobNode); // Ensure we can still remove the corresponding nodes (even though they've changed), and that doing so causes the subscription to be disposed expect(myObservable.getSubscriptionsCount()).toEqual(1); myArray.splice(1, 1); expect(testNode.childNodes[0]).toContainHtml("<div>the item is bob</div><div>the item is another</div>"); myObservable("Something else"); // Re-evaluating the observable causes the orphaned subscriptions to be disposed expect(myObservable.getSubscriptionsCount()).toEqual(0); }); it('Data binding \'foreach\' option should treat a null parameter as meaning \'no items\'', function() { var myArray = ko.observableArray(["A", "B"]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "hello" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0].childNodes.length).toEqual(2); // Now set the observable to null and check it's treated like an empty array // (because how else should null be interpreted?) // DefinitelyTyped note: while KO accepts this, I wouldn't consider it a well-typed usage of the API myArray(null); // $ExpectError expect(testNode.childNodes[0].childNodes.length).toEqual(0); }); it('Data binding \'foreach\' option should accept an \"as\" option to define an alias for the iteration variable', function() { // Note: There are more detailed specs (e.g., covering nesting) associated with the "foreach" binding which // uses this templating functionality internally. var myArray = ko.observableArray(["A", "B"]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "[js:myAliasedItem]" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection, as: \"myAliasedItem\" }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainText("AB"); }); it('Data binding \'foreach\' option should stop tracking inner observables when the container node is removed', function() { var innerObservable = ko.observable("some value"); var myArray = ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is [js: ko.utils.unwrapObservable(obsVal)]" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(innerObservable.getSubscriptionsCount()).toEqual(2); ko.removeNode(testNode.childNodes[0]); expect(innerObservable.getSubscriptionsCount()).toEqual(0); }); it('Data binding \'foreach\' option should stop tracking inner observables related to each array item when that array item is removed', function() { var innerObservable = ko.observable("some value"); var myArray = ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is [js: ko.utils.unwrapObservable(obsVal)]" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(innerObservable.getSubscriptionsCount()).toEqual(2); myArray.splice(1, 1); expect(innerObservable.getSubscriptionsCount()).toEqual(1); myArray([]); expect(innerObservable.getSubscriptionsCount()).toEqual(0); }); it('Data binding syntax should omit any items whose \'_destroy\' flag is set (unwrapping the flag if it is observable)', function() { var myArray = ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }, { someProp: 4, _destroy: ko.observable(false) }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "<div>someProp=[js: someProp]</div>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>someprop=1</div><div>someprop=3</div><div>someprop=4</div>"); }); it('Data binding syntax should include any items whose \'_destroy\' flag is set if you use includeDestroyed', function() { var myArray = ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "<div>someProp=[js: someProp]</div>" })); testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection, includeDestroyed: true }'></div>"; ko.applyBindings({ myCollection: myArray }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>someprop=1</div><div>someprop=2</div><div>someprop=3</div>"); }); it('Data binding syntax should support \"if\" condition', function() { ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "Value: [js: myProp().childProp]" })); testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", \"if\": myProp }'></div>"; var viewModel = { myProp: ko.observable<{childProp: string} | null>({ childProp: 'abc' }) }; ko.applyBindings(viewModel, testNode); // Initially there is a value expect(testNode.childNodes[0]).toContainText("Value: abc"); // Causing the condition to become false causes the output to be removed viewModel.myProp(null); expect(testNode.childNodes[0]).toContainText(""); // Causing the condition to become true causes the output to reappear viewModel.myProp({ childProp: 'def' }); expect(testNode.childNodes[0]).toContainText("Value: def"); }); it('Data binding syntax should support \"ifnot\" condition', function() { ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "Hello" })); testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", ifnot: shouldHide }'></div>"; var viewModel = { shouldHide: ko.observable(true) }; ko.applyBindings(viewModel, testNode); // Initially there is no output (shouldHide=true) expect(testNode.childNodes[0]).toContainText(""); // Causing the condition to become false causes the output to be displayed viewModel.shouldHide(false); expect(testNode.childNodes[0]).toContainText("Hello"); // Causing the condition to become true causes the output to disappear viewModel.shouldHide(true); expect(testNode.childNodes[0]).toContainText(""); }); it('Data binding syntax should support \"if\" condition in conjunction with foreach', function() { ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "Value: [js: myProp().childProp]" })); testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", \"if\": myProp, foreach: [$data, $data, $data] }'></div>"; var viewModel = { myProp: ko.observable<{childProp: string} | null>({ childProp: 'abc' }) }; ko.applyBindings(viewModel, testNode); expect(testNode.childNodes[0].childNodes[0].nodeValue).toEqual("Value: abc"); expect(testNode.childNodes[0].childNodes[1].nodeValue).toEqual("Value: abc"); expect(testNode.childNodes[0].childNodes[2].nodeValue).toEqual("Value: abc"); // Causing the condition to become false causes the output to be removed viewModel.myProp(null); expect(testNode.childNodes[0]).toContainText(""); // Causing the condition to become true causes the output to reappear viewModel.myProp({ childProp: 'def' }); expect(testNode.childNodes[0].childNodes[0].nodeValue).toEqual("Value: def"); expect(testNode.childNodes[0].childNodes[1].nodeValue).toEqual("Value: def"); expect(testNode.childNodes[0].childNodes[2].nodeValue).toEqual("Value: def"); }); it('Should be able to populate checkboxes from inside templates, despite IE6 limitations', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input type='checkbox' data-bind='checked:isChecked' />" })); ko.renderTemplate("someTemplate", null, { templateRenderingVariablesInScope: { isChecked: true } }, testNode); expect(testNode.childNodes[0].checked).toEqual(true); }); it('Should be able to populate radio buttons from inside templates, despite IE6 limitations', function () { ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input type='radio' name='somename' value='abc' data-bind='checked:someValue' />" })); ko.renderTemplate("someTemplate", null, { templateRenderingVariablesInScope: { someValue: 'abc' } }, testNode); expect(testNode.childNodes[0].checked).toEqual(true); }); it('Should be able to render a different template for each array entry by passing a function as template name, with the array entry\'s binding context available as a second parameter', function() { var myArray = ko.observableArray([ { preferredTemplate: 1, someProperty: 'firstItemValue' }, { preferredTemplate: 2, someProperty: 'secondItemValue' } ]); ko.setTemplateEngine(new dummyTemplateEngine({ firstTemplate: "<div>Template1Output, [js:someProperty]</div>", secondTemplate: "<div>Template2Output, [js:someProperty]</div>" })); testNode.innerHTML = "<div data-bind='template: {name: getTemplateModelProperty, foreach: myCollection}'></div>"; var getTemplate = function(dataItem, bindingContext) { // Having the item's binding context available means you can read sibling or parent level properties expect(bindingContext.$parent.anotherProperty).toEqual(123); return dataItem.preferredTemplate == 1 ? 'firstTemplate' : 'secondTemplate'; }; ko.applyBindings({ myCollection: myArray, getTemplateModelProperty: getTemplate, anotherProperty: 123 }, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>template1output, firstitemvalue</div><div>template2output, seconditemvalue</div>"); }); it('Data binding \'templateOptions\' should be passed to template', function() { var myModel = { someAdditionalData: { myAdditionalProp: "someAdditionalValue" }, people: ko.observableArray([ { name: "Alpha" }, { name: "Beta" } ]) }; ko.setTemplateEngine(new dummyTemplateEngine({myTemplate: "<div>Person [js:name] has additional property [js:templateOptions.myAdditionalProp]</div>"})); testNode.innerHTML = "<div data-bind='template: {name: \"myTemplate\", foreach: people, templateOptions: someAdditionalData }'></div>"; ko.applyBindings(myModel, testNode); expect(testNode.childNodes[0]).toContainHtml("<div>person alpha has additional property someadditionalvalue</div><div>person beta has additional property someadditionalvalue</div>"); }); it('If the template binding is updated, should dispose any template subscriptions previously associated with the element', function() { var myObservable = ko.observable("some value"), myModel = { subModel: ko.observable({ myObservable: myObservable }) }; ko.setTemplateEngine(new dummyTemplateEngine({myTemplate: "<span>The value is [js:myObservable()]</span>"})); testNode.innerHTML = "<div data-bind='template: {name: \"myTemplate\", data: subModel}'></div>"; ko.applyBindings(myModel, testNode); // Right now the template references myObservable, so there should be exactly one subscription on it expect(testNode.childNodes[0]).toContainText("The value is some value"); expect(myObservable.getSubscriptionsCount()).toEqual(1); var renderedNode1 = testNode.childNodes[0].childNodes[0]; // By changing the object for subModel, we force the data-bind value to be re-evaluated and the template to be re-rendered, // setting up a new template subscription, so there have now existed two subscriptions on myObservable... myModel.subModel({ myObservable: myObservable }); expect(testNode.childNodes[0].childNodes[0]).not.toEqual(renderedNode1); // ...but, because the old subscription should have been disposed automatically, there should only be one left expect(myObservable.getSubscriptionsCount()).toEqual(1); }); it('Should be able to specify a template engine instance using data-bind syntax', function() { ko.setTemplateEngine(new dummyTemplateEngine({ theTemplate: "Default output" })); // Not going to use this one var alternativeTemplateEngine = new dummyTemplateEngine({ theTemplate: "Alternative output" }); testNode.innerHTML = "<div data-bind='template: { name: \"theTemplate\", templateEngine: chosenEngine }'></div>"; ko.applyBindings({ chosenEngine: alternativeTemplateEngine }, testNode); expect(testNode.childNodes[0]).toContainText("Alternative output"); }); it('Should be able to bind $data to an alias using \'as\'', function() { ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "ValueLiteral: [js:item.prop], ValueBound: <span data-bind='text: item.prop'></span>" })); testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", data: someItem, as: \"item\" }'></div>"; ko.applyBindings({ someItem: { prop: 'Hello' } }, testNode); expect(testNode.childNodes[0]).toContainText("ValueLiteral: Hello, ValueBound: Hello"); }); it('Data-bind syntax should expose parent binding context as $parent if binding with an explicit \"data\" value', function() { ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "ValueLiteral: [js:$parent.parentProp], ValueBound: <span data-bind='text: $parent.parentProp'></span>" })); testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", data: someItem }'></div>"; ko.applyBindings({ someItem: {}, parentProp: 'Hello' }, testNode); expect(testNode.childNodes[0]).toContainText("ValueLiteral: Hello, ValueBound: Hello"); }); it('Data-bind syntax should expose all ancestor binding contexts as $parents', function() { ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: "<div data-bind='template: { name:\"middleTemplate\", data: middleItem }'></div>", middleTemplate: "<div data-bind='template: { name: \"innerTemplate\", data: innerItem }'></div>", innerTemplate: "(Data:[js:$data.val], Parent:[[js:$parents[0].val]], Grandparent:[[js:$parents[1].val]], Root:[js:$root.val], Depth:[js:$parents.length])" })); testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\", data: outerItem }'></div>"; ko.applyBindings({ val: "ROOT", outerItem: { val: "OUTER", middleItem: { val: "MIDDLE", innerItem: { val: "INNER" } } } }, testNode); expect(testNode.childNodes[0].childNodes[0]).toContainText("(Data:INNER, Parent:MIDDLE, Grandparent:OUTER, Root:ROOT, Depth:3)"); }); it('Should not be allowed to rewrite templates that embed anonymous templates', function() { // The reason is that your template engine's native control flow and variable evaluation logic is going to run first, independently // of any KO-native control flow, so variables would get evaluated in the wrong context. Example: // // <div data-bind="foreach: someArray"> // ${ somePropertyOfEachArrayItem } <-- This gets evaluated *before* the foreach binds, so it can't reference array entries // </div> // // It should be perfectly OK to fix this just by preventing anonymous templates within rewritten templates, because // (1) The developer can always use their template engine's native control flow syntax instead of the KO-native ones - that will work // (2) The developer can use KO's native templating instead, if they are keen on KO-native control flow or anonymous templates ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "<div data-bind='template: { data: someData }'>Childprop: [js: childProp]</div>" })); testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\" }'></div>"; var didThrow = false; try { ko.applyBindings({ someData: { childProp: 'abc' } }, testNode); } catch(ex) { didThrow = true; expect(ex.message).toEqual("This template engine does not support anonymous templates nested within its templates"); } expect(didThrow).toEqual(true); }); it('Should not be allowed to rewrite templates that embed control flow bindings', function() { // Same reason as above ko.utils.arrayForEach(['if', 'ifnot', 'with', 'foreach'], function(bindingName) { ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "<div data-bind='" + bindingName + ": \"SomeValue\"'>Hello</div>" })); testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\" }'></div>"; var didThrow = false; ko.utils.domData.clear(testNode); try { ko.applyBindings({ someData: { childProp: 'abc' } }, testNode) } catch (ex) { didThrow = true; expect(ex.message).toEqual("This template engine does not support the '" + bindingName + "' binding within its templates"); } if (!didThrow) throw new Error("Did not prevent use of " + bindingName); }); }); it('Data binding syntax should permit nested templates using virtual containers (with arbitrary internal whitespace and newlines)', function() { ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: "Outer <!-- ko template: \n" + "{ name: \"innerTemplate\" } \n" + "--><!-- /ko -->", innerTemplate: "Inner via inline binding: <span data-bind='text: \"someText\"'></span>" })); var model = { }; testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\" }'></div>"; ko.applyBindings(model, testNode); expect(testNode.childNodes[0]).toContainHtml("outer <!-- ko -->inner via inline binding: <span>sometext</span><!-- /ko -->"); }); it('Should be able to render anonymous templates using virtual containers', function() { ko.setTemplateEngine(new dummyTemplateEngine()); testNode.innerHTML = "Start <!-- ko template: { data: someData } -->Childprop: [js: childProp]<!-- /ko --> End"; ko.applyBindings({ someData: { childProp: 'abc' } }, testNode); expect(testNode).toContainHtml("start <!-- ko template: { data: somedata } -->childprop: abc<!-- /ko -->end"); }); it('Should be able to use anonymous templates that contain first-child comment nodes', function() { // This represents issue https://github.com/SteveSanderson/knockout/issues/188 // (IE < 9 strips out leading comment nodes when you use .innerHTML) ko.setTemplateEngine(new dummyTemplateEngine({})); testNode.innerHTML = "start <div data-bind='foreach: [1,2]'><span><!-- leading comment -->hello</span></div>"; ko.applyBindings(null, testNode); expect(testNode).toContainHtml('start <div data-bind="foreach: [1,2]"><span><!-- leading comment -->hello</span><span><!-- leading comment -->hello</span></div>'); }); it('Should allow anonymous templates output to include top-level virtual elements, and will bind their virtual children only once', function() { delete (<any>ko.bindingHandlers).nonexistentHandler; var initCalls = 0; (<any>ko.bindingHandlers).countInits = { init: function () { initCalls++ } }; testNode.innerHTML = "<div data-bind='template: {}'><!-- ko nonexistentHandler: true --><span data-bind='countInits: true'></span><!-- /ko --></div>"; ko.applyBindings(null, testNode); expect(initCalls).toEqual(1); }); it('Should not throw errors if trying to apply text to a non-rendered node', function() { // Represents https://github.com/SteveSanderson/knockout/issues/660 // A <span> can't go directly into a <tr>, so modern browsers will silently strip it. We need to verify this doesn't // throw errors during unmemoization (when unmemoizing, it will try to apply the text to the following text node // instead of the node you intended to bind to). // Note that IE < 9 won't strip the <tr>; instead it has much stranger behaviors regarding unexpected DOM structures. // It just happens not to give an error in this particular case, though it would throw errors in many other cases // of malformed template DOM. ko.setTemplateEngine(new dummyTemplateEngine({ myTemplate: "<tr><span data-bind=\"text: 'Some text'\"></span> </tr>" // The whitespace after the closing span is what triggers the strange HTML parsing })); testNode.innerHTML = "<div data-bind='template: \"myTemplate\"'></div>"; ko.applyBindings(null, testNode); // Since the actual template markup was invalid, we don't really care what the // resulting DOM looks like. We are only verifying there were no exceptions. }); })
the_stack
import { stringifyTestCode } from './codegen'; import { Substituter, Syntax, nullLoc, TestCode, eqSourceLocation, compEndPosition, id, replaceVarAssertion, replaceVarExpr } from './javascript'; import { Classes, FreeVars, Heap, Heaps, Locs, P, Vars, not, and } from './logic'; import { Message, MessageException, unexpected } from './message'; import { Model, valueToJavaScript, JSVal } from './model'; import { getOptions } from './options'; import { SMTInput, SMTOutput, vcToSMT } from './smt'; import { sourceAsJavaScriptAssertion, sourceAsJavaScriptExpression } from './parser'; import { VCGenerator } from './vcgen'; import { Interpreter, interpret } from './interpreter'; import { generatePreamble } from './preamble'; export type Assumption = Readonly<{source: string, prop: P, canBeDeleted: boolean}>; declare const console: { log: (s: string) => void }; declare const require: (s: string) => any; declare const fetch: (s: string, opts: any) => Promise<any>; let checkedLocalZ3Version: boolean = false; export default class VerificationCondition { private classes: Classes; private heaps: Heaps; private locs: Locs; private vars: Vars; private prop: P; private assumptions: Array<Assumption>; private assertion: P; private loc: Syntax.SourceLocation; private freeVars: FreeVars; private testBody: TestCode; private testAssertion: TestCode; private description: string; private heapHints: Array<[Syntax.SourceLocation, Heap]>; private aliases: { [from: string]: string }; private watches: Array<[string, Syntax.Expression]>; private model: Model | null; private interpreter: Interpreter | null; private result: Message | null; constructor (classes: Classes, heap: Heap, locs: Locs, vars: Vars, prop: P, assumptions: Array<Assumption>, assertion: P, loc: Syntax.SourceLocation, description: string, freeVars: FreeVars, testBody: TestCode, testAssertion: TestCode, heapHints: Array<[Syntax.SourceLocation, Heap]>, aliases: { [from: string]: string }) { this.classes = new Set([...classes]); this.heaps = new Set([...Array(heap + 1).keys()]); this.locs = new Set([...locs]); this.vars = new Set([...vars]); this.prop = prop; this.assumptions = assumptions; this.assertion = assertion; this.loc = loc; this.description = description; this.freeVars = [...freeVars]; this.testBody = testBody; this.testAssertion = testAssertion; this.heapHints = heapHints; this.aliases = aliases; this.watches = []; this.model = null; this.interpreter = null; this.result = null; } async verify (): Promise<Message> { try { this.model = null; this.interpreter = null; this.result = null; const smtin = this.prepareSMT(); const smtout = await (getOptions().remote ? this.solveRemote(smtin) : this.solveLocal(smtin)); const modelOrMessage = this.processSMTOutput(smtout); if (modelOrMessage instanceof Model) { this.model = modelOrMessage; return this.result = this.runTest(); } else { return this.result = modelOrMessage; } } catch (error) { if (error instanceof MessageException) return this.result = error.msg; return this.result = unexpected(error, this.loc, this.description); } } getDescription (): string { return this.description; } getLocation (): Syntax.SourceLocation { return this.loc; } setDescription (description: string): void { this.description = description; } hasModel (): boolean { return this.model !== null; } runTest (): Message { const code = this.testSource(); try { /* tslint:disable:no-eval */ eval(code); return { status: 'unverified', description: this.description, loc: this.loc, model: this.getModel() }; } catch (e) { if (e instanceof Error && (e instanceof TypeError || e.message === 'assertion failed')) { return { status: 'error', type: 'incorrect', description: this.description, loc: this.loc, model: this.getModel(), error: e }; } else { return unexpected(e, this.loc, this.description); } } } runWithInterpreter (): Message { const interpreter = this.getInterpreter(); try { interpreter.run(); this.result = { status: 'unverified', description: this.description, loc: this.loc, model: this.getModel() }; return this.result; } catch (e) { if (e instanceof Error && (e instanceof TypeError || e.message === 'assertion failed')) { return this.result = { status: 'error', type: 'incorrect', description: this.description, loc: this.loc, model: this.getModel(), error: e }; } else { return this.result = unexpected(e, this.loc, this.description); } } } addAssumption (source: string): void { let assumption = sourceAsJavaScriptAssertion(source); for (const aliasedVar in this.aliases) { const replacement = this.aliases[aliasedVar]; assumption = replaceVarAssertion(aliasedVar, id(replacement), id(replacement), assumption); } const maxHeap = Math.max(...this.heaps.values()); const assumptions = this.assumptions.map(({ source }) => source); const vcgen = new VCGenerator(new Set([...this.classes]), maxHeap, maxHeap, new Set([...this.locs]), new Set([...this.vars]), assumptions, this.heapHints, true, this.prop); const [assumptionP] = vcgen.assume(assumption); this.assumptions = this.assumptions.concat([{ source, prop: assumptionP, canBeDeleted: true }]); } getAssumptions (): Array<[string, boolean]> { return this.assumptions.map(({ source, canBeDeleted }): [string, boolean] => [source, canBeDeleted]); } removeAssumption (idx: number): void { const assumptionToRemove = idx < this.assumptions.length ? this.assumptions[idx] : undefined; if (assumptionToRemove === undefined) throw new Error('no such assumption'); if (!assumptionToRemove.canBeDeleted) throw new Error('cannot remove built-in assumptions'); this.assumptions = this.assumptions.filter(a => a !== assumptionToRemove); } assert (source: string): VerificationCondition { let assertion = sourceAsJavaScriptAssertion(source); for (const aliasedVar in this.aliases) { const replacement = this.aliases[aliasedVar]; assertion = replaceVarAssertion(aliasedVar, id(replacement), id(replacement), assertion); } const maxHeap = Math.max(...this.heaps.values()); const assumptions = this.assumptions.map(({ source }) => source); const vcgen = new VCGenerator(new Set([...this.classes]), maxHeap, maxHeap, new Set([...this.locs]), new Set([...this.vars]), assumptions, this.heapHints, true, this.prop); const [assertionP, , assertionT] = vcgen.assert(assertion); return new VerificationCondition(this.classes, maxHeap, this.locs, this.vars, this.prop, this.assumptions, assertionP, this.loc, source, this.freeVars, this.testBody, assertionT, this.heapHints, this.aliases); } steps (): number { return this.getInterpreter().steps; } pc (): Syntax.SourceLocation { return this.getInterpreter().loc(); } iteration (): number { return this.getInterpreter().iteration(); } callstack (): Array<[string, Syntax.SourceLocation, number]> { return this.getInterpreter().callstack(); } getScopes (frameIndex: number): Array<Array<[string, JSVal, JSVal | undefined]>> { const heap = this.guessCurrentHeap(); return this.getInterpreter().scopes(frameIndex).map(scope => scope.map(([varname, dynamicValue]): [string, JSVal, JSVal | undefined] => { const staticValue = this.modelValue(varname, heap); return [varname, this.getInterpreter().asValue(dynamicValue), staticValue]; }) ); } getWatches (): Array<[string, JSVal | undefined, JSVal | undefined]> { return this.watches.map(([src, expr]): [string, JSVal | undefined, JSVal | undefined] => { let dynamicValue: JSVal | undefined = undefined; let staticValue: JSVal | undefined = undefined; try { dynamicValue = this.getInterpreter().asValue(this.getInterpreter().evalExpression(expr, [])); staticValue = this.getInterpreter().asValue( this.getInterpreter().evalExpression(expr, this.currentBindingsFromModel())); } catch (e) { /* ignore errors */ } return [src, dynamicValue, staticValue]; }); } addWatch (source: string): void { let expr = sourceAsJavaScriptExpression(source); for (const aliasedVar in this.aliases) { const replacement = this.aliases[aliasedVar]; expr = replaceVarExpr(aliasedVar, id(replacement), id(replacement), expr); } this.watches.push([source, expr]); } removeWatch (idx: number): void { const watchToRemove = idx < this.watches.length ? this.watches[idx] : undefined; if (watchToRemove === undefined) throw new Error('no such watch'); this.watches = this.watches.filter(w => w !== watchToRemove); } restart (): void { this.getInterpreter().restart(); this.stepToSource(); } goto (pos: Syntax.Position, iteration: number = 0): void { this.getInterpreter().goto(pos, iteration); this.stepToSource(); } stepInto (): void { this.getInterpreter().stepInto(); this.stepToSource(); } stepOver (): void { this.getInterpreter().stepOver(); this.stepToSource(); } stepOut (): void { this.getInterpreter().stepOut(); this.stepToSource(); } getAnnotations (): Array<[Syntax.SourceLocation, Array<JSVal>, JSVal | undefined]> { return this.getInterpreter().annotations .filter(annotation => annotation.location.file === getOptions().filename) .map((annotation): [Syntax.SourceLocation, Array<JSVal>, JSVal | undefined] => { const heap = this.guessCurrentHeap(annotation.location); const staticValue = this.modelValue(annotation.variableName, heap); return [ annotation.location, annotation.values.map((v: any): JSVal => this.getInterpreter().asValue(v)), staticValue ]; }); } getResult (): Message | null { return this.result; } private prepareSMT (): SMTInput { const prop = and(this.prop, ...this.assumptions.map(({ prop }) => prop), not(this.assertion)); const smt = vcToSMT(this.classes, this.heaps, this.locs, this.vars, this.freeVars, prop); if (getOptions().verbose) { console.log('SMT Input:'); console.log('------------'); console.log(smt); console.log('------------'); } return smt; } private solveLocal (smt: SMTInput): Promise<SMTOutput> { if (!getOptions().quiet && getOptions().verbose) { console.log(`${this.description}: solving locally with ${getOptions().z3path}`); } let p = Promise.resolve(''); if (!checkedLocalZ3Version) { p = p.then(() => new Promise<SMTOutput>((resolve, reject) => { const exec = require('child_process').exec; exec(getOptions().z3path + ' -version', (err: Error, out: string) => { if (err) { reject(new Error('cannot invoke z3: ' + String(err))); } else { const vstr = out.toString().match(/(\d+)\.(\d+)\.\d+/); if (!vstr || +vstr[1] !== 4 || +vstr[2] !== 6) { reject(new Error('esverify requires z3 verison 4.6')); } else { checkedLocalZ3Version = true; resolve(''); } } }); })); } if (!getOptions().quiet && getOptions().verbose) { p = p.then(() => new Promise<string>((resolve, reject) => { const writeFile = require('fs').writeFile; writeFile(getOptions().logsmt, smt, (err: Error, out: string) => { if (err) { reject(new Error('cannot write: ' + String(err))); } else { resolve(''); } }); })); } p = p.then(() => new Promise<SMTOutput>((resolve, reject) => { const spawn = require('child_process').spawn; const p = spawn(getOptions().z3path, [`-T:${getOptions().timeout}`, '-smt2', '-in'], { stdio: ['pipe', 'pipe', 'ignore'] }); let result: string = ''; p.stdout.on('data', (data: Object) => { result += data.toString(); }); p.on('exit', (code: number) => { if (!getOptions().quiet && getOptions().verbose) { console.log('SMT Output:'); console.log('------------'); console.log(result); console.log('------------'); } return resolve(result); }); p.on('error', reject); p.stdin.write(smt); p.stdin.end(); })); return p; } private async solveRemote (smt: SMTInput): Promise<SMTOutput> { if (!getOptions().quiet && getOptions().verbose) { console.log(`${this.description}: sending request to ${getOptions().z3url}`); } const req = await fetch(getOptions().z3url, { method: 'POST', body: smt }); const smtout = await req.text(); if (!getOptions().quiet && getOptions().verbose) { console.log('SMT Output:'); console.log('------------'); console.log(smtout); console.log('------------'); } return smtout; } private processSMTOutput (out: SMTOutput): Model | Message { if (out && out.startsWith('sat')) { return new Model(out); } else if (out && out.startsWith('unsat')) { return { status: 'verified', description: this.description, loc: this.loc }; } else if (out && out.startsWith('unknown')) { return { status: 'unknown', description: this.description, loc: this.loc }; } else if (out && out.startsWith('timeout')) { return { status: 'timeout', description: this.description, loc: this.loc }; } else { return unexpected(new Error('unexpected: ' + out), this.loc); } } private getModel (): Model { if (!this.model) throw new Error('no model available'); return this.model; } private testCode (): TestCode { const sub: Substituter = new Substituter(); this.freeVars.forEach(freeVar => { const expr = valueToJavaScript(this.getModel().valueOf(freeVar)); const und: Syntax.Literal = { type: 'Literal', value: undefined, loc: nullLoc() }; sub.replaceVar(`__free__${typeof freeVar === 'string' ? freeVar : freeVar.name}`, und, expr); }); const testCode = this.testBody.concat(this.testAssertion); return testCode.map(s => sub.visitStatement(s)); } private testSource (): string { const code = stringifyTestCode(this.testCode()); if (!getOptions().quiet && getOptions().verbose) { console.log('Test Code:'); console.log('------------'); console.log(code); console.log('------------'); } return code; } private getInterpreter (): Interpreter { if (!this.interpreter) { const prog: Syntax.Program = { body: [...this.testCode()], invariants: [] }; this.interpreter = interpret(prog); this.stepToSource(); } return this.interpreter; } private stepToSource (): void { const interpreter = this.getInterpreter(); while (interpreter.canStep() && interpreter.loc().file !== getOptions().filename) { interpreter.stepInto(); } } private guessCurrentHeap (loc: Syntax.SourceLocation = this.pc()): Heap { // find index of heap hint const idx = this.heapHints.findIndex(([loc2]) => eqSourceLocation(loc, loc2)); if (idx >= 0) { return this.heapHints[idx][1]; } else { // no exact match found in heap hints // find index of first heap hint that is not earlier const idx = this.heapHints.findIndex(([loc2]) => !compEndPosition(loc, loc2)); if (idx >= 0) { return this.heapHints[idx][1]; } else if (this.heapHints.length > 0) { // no heap hint found that is later, so use last return this.heapHints[this.heapHints.length - 1][1]; } else { throw new Error('unable to guess current heap'); } } } private modelValue (varname: string, currentHeap: Heap): JSVal | undefined { const model = this.getModel(); if (model.mutableVariables().has(varname)) { try { return model.valueOf({ name: varname, heap: currentHeap }); } catch (e) { return undefined; } } else { return model.valueOf(varname); } } private currentBindingsFromModel (): Array<[string, any]> { const model = this.getModel(); const heap = this.guessCurrentHeap(); const bindings: Array<[string, any]> = []; for (const varname of model.variables()) { if (generatePreamble().vars.has(varname) || generatePreamble().locs.has(varname)) { continue; } const jsval = this.modelValue(varname, heap); if (jsval !== undefined) { bindings.push([varname, this.getInterpreter().fromValue(jsval)]); } } return bindings; } }
the_stack
module BABYLON { /** * Class for the ObservableArray.onArrayChanged observable */ export class ArrayChanged<T> { constructor() { this.action = 0; this.newItems = new Array<{index: number, value: T }>(); this.removedItems = new Array<{ index: number, value: T }>(); this.changedItems = new Array<{ index: number, value: T }>(); this.newStartingIndex = -1; this.removedStartingIndex = -1; } /** * Contain the action that were made on the ObservableArray, it's one of the ArrayChanged.xxxAction members. * Note the action's value can be used in the "mask" field of the Observable to only be notified about given action(s) */ public action: number; /** * Only valid if the action is newItemsAction */ public newItems: { index: number, value: T }[]; /** * Only valid if the action is removedItemsAction */ public removedItems: { index: number, value: T }[]; /** * Only valid if the action is changedItemAction */ public changedItems: { index: number, value: T }[]; /** * Get the index of the first item inserted */ public newStartingIndex: number; /** * Get the index of the first item removed */ public removedStartingIndex: number; /** * Get the index of the first changed item */ public changedStartingIndex: number; /** * The content of the array was totally cleared */ public static get clearAction() { return ArrayChanged._clearAction; } /** * A new item was added, the newItems field contains the key/value pairs */ public static get newItemsAction() { return ArrayChanged._newItemsAction; } /** * An existing item was removed, the removedKey field contains its key */ public static get removedItemsAction() { return ArrayChanged._removedItemsAction; } /** * One or many items in the array were changed, the */ public static get changedItemAction() { return ArrayChanged._changedItemAction; } /** * The array's content was totally changed * Depending on the method that used this mode the ChangedArray object may contains more information */ public static get replacedArrayAction() { return ArrayChanged._replacedArrayAction; } /** * The length of the array changed */ public static get lengthChangedAction() { return ArrayChanged._lengthChangedAction; } private static _clearAction = 0x1; private static _newItemsAction = 0x2; private static _removedItemsAction = 0x4; private static _replacedArrayAction = 0x8; private static _lengthChangedAction = 0x10; private static _changedItemAction = 0x20; clear() { this.action = 0; this.newItems.splice(0); this.removedItems.splice(0); this.changedItems.splice(0); this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0; } } export class OAWatchedObjectChangedInfo<T> { object: T; propertyChanged: PropertyChangedInfo; } /** * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern. * */ export class ObservableArray<T> extends PropertyChangedBase { /** * Create an Observable Array. * @param watchObjectsPropertyChange * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy! */ constructor(watchObjectsPropertyChange: boolean, array?: Array<T>) { super(); this._array = (array!=null) ? array : new Array<T>(); this.dci = new ArrayChanged<T>(); this._callingArrayChanged = false; this._arrayChanged = null; this._callingWatchedObjectChanged = false; this._watchObjectsPropertyChange = watchObjectsPropertyChange; this._watchedObjectList = this._watchObjectsPropertyChange ? new StringDictionary<Observer<PropertyChangedInfo>>() : null; this._woci = new OAWatchedObjectChangedInfo<T>(); } /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. */ get length(): number { return this._array.length; } set length(value: number) { if (value === this._array.length) { return; } let oldLength = this._array.length; this._array.length = value; this.onPropertyChanged("length", oldLength, this._array.length); } getAt(index: number): T { return this._array[index]; } setAt(index: number, value: T): boolean { if (index < 0) { return false; } let insertion = (index >= this._array.length) || this._array[index] === undefined; let oldLength = 0; if (insertion) { oldLength = this._array.length; } else if (this._watchObjectsPropertyChange) { this._removeWatchedElement(this._array[index]); } this._array[index] = value; if (this._watchObjectsPropertyChange) { this._addWatchedElement(value); } if (insertion) { this.onPropertyChanged("length", oldLength, this._array.length); } let ac = this.getArrayChangedObject(); if (ac) { ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction; if (insertion) { ac.newItems.splice(0, ac.newItems.length, { index: index, value: value }); ac.newStartingIndex = index; ac.changedItems.splice(0); } else { ac.newItems.splice(0); ac.changedStartingIndex = index; ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value }); } ac.removedItems.splice(0); ac.removedStartingIndex = -1; this.callArrayChanged(ac); } } /** * Returns a string representation of an array. */ toString(): string { return this._array.toString(); } toLocaleString(): string { return this._array.toLocaleString(); } /** * Appends new elements to an array, and returns the new length of the array. * @param items New elements of the Array. */ push(...items: T[]): number { let oldLength = this._array.length; let n = this._array.push(...items); if (this._watchObjectsPropertyChange) { this._addWatchedElement(...items); } this.onPropertyChanged("length", oldLength, this._array.length); let ac = this.getArrayChangedObject(); if (ac) { ac.action = ArrayChanged.newItemsAction; ac.newStartingIndex = oldLength; this.feedNotifArray(ac.newItems, oldLength, ...items); this.callArrayChanged(ac); } return n; } /** * Removes the last element from an array and returns it. */ pop(): T { let firstRemove = this._array.length - 1; let res = this._array.pop(); if (res && this._watchObjectsPropertyChange) { this._removeWatchedElement(res); } if (firstRemove !== -1) { this.onPropertyChanged("length", this._array.length + 1, this._array.length); let ac = this.getArrayChangedObject(); if (ac) { ac.action = ArrayChanged.removedItemsAction; ac.removedStartingIndex = firstRemove; this.feedNotifArray(ac.removedItems, firstRemove, res); } } return res; } /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: T[]): ObservableArray<T> { return new ObservableArray<T>(this._watchObjectsPropertyChange, this._array.concat(...items)); } /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string { return this._array.join(separator); } /** * Reverses the elements in an Array. * The arrayChanged action is */ reverse(): T[] { let res = this._array.reverse(); let ac = this.getArrayChangedObject(); ac.action = ArrayChanged.replacedArrayAction; return res; } /** * Removes the first element from an array and returns it, shift all subsequents element one element before. * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems. * */ shift(): T { let oldLength = this._array.length; let res = this._array.shift(); if (this._watchedObjectChanged && res!=null) { this._removeWatchedElement(res); } if (oldLength !== 0) { this.onPropertyChanged("length", oldLength, this._array.length); let ac = this.getArrayChangedObject(); if (ac) { ac.action = ArrayChanged.replacedArrayAction; ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res }); ac.newItems.splice(0); ac.changedItems.splice(0); ac.removedStartingIndex = 0; this.callArrayChanged(ac); } } return res; } /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): ObservableArray<T> { return new ObservableArray<T>(this._watchObjectsPropertyChange, this._array.slice(start, end)); } /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. * On the contrary of the Javascript Array's implementation, this method returns nothing */ sort(compareFn?: (a: T, b: T) => number): void { let oldLength = this._array.length; this._array.sort(compareFn); if (oldLength !== 0) { let ac = this.getArrayChangedObject(); if (ac) { ac.clear(); ac.action = ArrayChanged.replacedArrayAction; this.callArrayChanged(ac); } } } /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. * @param deleteCount The number of elements to remove. * @param items Elements to insert into the array in place of the deleted elements. */ splice(start: number, deleteCount: number, ...items: T[]): T[] { let oldLength = this._array.length; if (this._watchObjectsPropertyChange) { for (let i = start; i < start+deleteCount; i++) { let val = this._array[i]; if (this._watchObjectsPropertyChange && val != null) { this._removeWatchedElement(val); } } } let res = this._array.splice(start, deleteCount, ...items); if (this._watchObjectsPropertyChange) { this._addWatchedElement(...items); } if (oldLength !== this._array.length) { this.onPropertyChanged("length", oldLength, this._array.length); } let ac = this.getArrayChangedObject(); if (ac) { ac.clear(); ac.action = ArrayChanged.replacedArrayAction; this.callArrayChanged(ac); } return res; } /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items */ unshift(...items: T[]): number { let oldLength = this._array.length; let res = this._array.unshift(...items); if (this._watchObjectsPropertyChange) { this._addWatchedElement(...items); } this.onPropertyChanged("length", oldLength, this._array.length); let ac = this.getArrayChangedObject(); if (ac) { ac.clear(); ac.action = ArrayChanged.replacedArrayAction; ac.newStartingIndex = 0, this.feedNotifArray(ac.newItems, 0, ...items); this.callArrayChanged(ac); } return res; } /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number { return this._array.indexOf(searchElement, fromIndex); } /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number { return this._array.lastIndexOf(searchElement, fromIndex); } /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean { return this._array.every(callbackfn, thisArg); } /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean { return this._array.some(callbackfn, thisArg); } /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void { return this._array.forEach(callbackfn, thisArg); } /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[] { return this._array.map(callbackfn, thisArg); } /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[] { return this._array.filter(callbackfn, thisArg); } /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T { return this._array.reduce(callbackfn); } /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T { return this._array.reduceRight(callbackfn); } get arrayChanged(): Observable<ArrayChanged<T>> { if (!this._arrayChanged) { this._arrayChanged = new Observable<ArrayChanged<T>>(); } return this._arrayChanged; } protected getArrayChangedObject(): ArrayChanged<T> { if (this._arrayChanged && this._arrayChanged.hasObservers()) { let ac = this._callingArrayChanged ? new ArrayChanged<T>() : this.dci; return ac; } return null; } protected feedNotifArray(array: { index: number, value: T }[], startindIndex: number, ...items: T[]) { array.splice(0); for (let i = 0; i < items.length; i++) { let value = this._array[i + startindIndex]; if (value !== undefined) { array.push({ index: i + startindIndex, value: value }); } } } protected callArrayChanged(ac: ArrayChanged<T>) { try { this._callingArrayChanged = true; this.arrayChanged.notifyObservers(ac, ac.action); } finally { this._callingArrayChanged = false; } } get watchedObjectChanged(): Observable<OAWatchedObjectChangedInfo<T>> { if (!this._watchedObjectChanged) { this._watchedObjectChanged = new Observable<OAWatchedObjectChangedInfo<T>>(); } return this._watchedObjectChanged; } private _addWatchedElement(...items: T[]) { for (let curItem of items) { if (curItem["propertyChanged"]) { let key = curItem["__ObsArrayObjID__"] as string; // The object may already be part of another ObsArray, so there already be a valid ID if (!key) { key = Tools.RandomId(); curItem["__ObsArrayObjID__"] = key; } this._watchedObjectList.add(key, (<IPropertyChanged><any>curItem).propertyChanged.add((e, d) => { this.onWatchedObjectChanged(key, curItem, e); })); } } } private _removeWatchedElement(...items: T[]) { for (let curItem of items) { let key = curItem["__ObsArrayObjID__"] as string; if (key != null) { let observer = this._watchedObjectList.getAndRemove(key); (<IPropertyChanged><any>curItem).propertyChanged.remove(observer); } } } protected onWatchedObjectChanged(key: string, object: T, propChanged: PropertyChangedInfo) { if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) { let woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo<T>() : this._woci; woci.object = object; woci.propertyChanged = propChanged; try { this._callingWatchedObjectChanged = true; this.watchedObjectChanged.notifyObservers(woci); } finally { this._callingWatchedObjectChanged = false; } } } private _array: Array<T>; private _arrayChanged: Observable<ArrayChanged<T>>; private dci = new ArrayChanged<T>(); private _callingArrayChanged: boolean = false; private _watchedObjectChanged: Observable<OAWatchedObjectChangedInfo<T>>; private _woci: OAWatchedObjectChangedInfo<T>; private _callingWatchedObjectChanged: boolean; private _watchObjectsPropertyChange: boolean; private _watchedObjectList: StringDictionary<Observer<PropertyChangedInfo>>; } }
the_stack
import { AppointmentModel, FormatterFn, ValidResourceInstance, ValidResource, SelectOption, } from '../index'; /* tslint:disable no-namespace max-line-length */ export namespace AppointmentForm { /** @internal */ export interface ContainerProps { /** A React Ref that should be passed into ref property. */ ref: React.RefObject<unknown>; } /** Properties passed to a component that renders an Appointment Form overlay. */ export interface OverlayProps { /** Specifies whether the overlay is visible. */ visible: boolean; /** An event raised when the overlay hides. */ onHide: () => void; /** Specifies whether the overlay is full-size. */ fullSize: boolean; /** A React component instance or a DOM element that is used to position the overlay. */ target: React.RefObject<unknown>; /** A React node used to render the overlay content. */ children: React.ReactNode; } /** Properties passed to a component that renders the appointment form's layout. */ export interface LayoutProps { /** A component that renders a layout for command buttons. */ commandLayoutComponent: React.ComponentType<AppointmentForm.CommandLayoutProps>; /** A component that renders a layout for editors that edit basic appointment data. */ basicLayoutComponent: React.ComponentType<AppointmentForm.BasicLayoutProps>; /** A component that renders a layout for editors that specify the appointment's recurrence. */ recurrenceLayoutComponent: React.ComponentType<AppointmentForm.RecurrenceLayoutProps>; /** Specifies whether recurrence editors should be rendered. */ isRecurrence: boolean; /** A React node used to render additional components to the layout. */ children?: React.ReactNode; } /** Properties passed to a component that renders a layout for command buttons. */ export interface CommandLayoutProps { /** Specifies whether the appointment form is read-only. */ readOnly?: boolean; /** Specifies whether the command layout is full-size. */ fullSize: boolean; /** Specifies whether to disable the Save button. */ disableSaveButton?: boolean; /** Specifies whether to hide the Delete button. */ hideDeleteButton?: boolean; /** An event raised when the Commit button is clicked. The event handler should commit an appointment changes. */ onCommitButtonClick: () => void; /** An event raised when the Cancel button is clicked. The event handler should close the appointment form. */ onCancelButtonClick: () => void; /** An event raised when the Delete button is clicked. The event handler should delete an appointment. */ onDeleteButtonClick: () => void; /** Uses a localization message's key to retrieve the message. */ getMessage: (messageKey: string) => string; /** A component that renders a command button. */ commandButtonComponent: React.ComponentType<AppointmentForm.CommandButtonProps>; /** A React node used to render additional components to the Command layout. */ children?: React.ReactNode; } /** Properties passed to a component that renders a layout for editors that edit basic appointment data. */ export interface BasicLayoutProps { /* Specifies whether the layout is full-size. */ fullSize: boolean; /** The appointment's data. */ appointmentData: AppointmentModel; /** The appointment's resource items. */ appointmentResources: Array<ValidResourceInstance>; /** The all resources that were defined. */ resources: Array<ValidResource>; /** An event that is raised when a field value in the appointment form is changed. */ onFieldChange: (change: any) => void; /** Uses a localization message's key to retrieve the message. */ getMessage: (messageKey: string) => string; /** Specifies whether the appointment form is read-only. */ readOnly?: boolean; /** Specifies the locale as an IETF BCP 47 language tag or an array of such tags. The locale is used to format date-time values. */ locale: string | string[]; /** A component that renders a text editor. */ textEditorComponent: React.ComponentType<AppointmentForm.TextEditorProps>; /** A component that renders a date-time editor. */ dateEditorComponent: React.ComponentType<AppointmentForm.DateEditorProps>; /** A component that renders an editor of Boolean values. */ booleanEditorComponent: React.ComponentType<AppointmentForm.BooleanEditorProps>; /** A component that renders an options menu. */ selectComponent: React.ComponentType<AppointmentForm.SelectProps>; /** A component that renders a resource editor. */ resourceEditorComponent: React.ComponentType<AppointmentForm.ResourceEditorProps>; /** A component that renders a text label. */ labelComponent: React.ComponentType<AppointmentForm.LabelProps>; /** A React node used to render additional components to the Basic Layout. */ children?: React.ReactNode; } /** Properties passed to a component that renders the appointment form's layout for editors that edit the appointment's recurrence. */ export interface RecurrenceLayoutProps { /* Specifies whether the layout is visible. */ visible: boolean; /** The appointment's data. */ appointmentData: AppointmentModel; /** An event that is raised when a field value in the appointment form is changed. */ onFieldChange: (nextFieldValue: { [fieldName: string]: any }) => void; /** Uses a localization message's key to retrieve the message. */ getMessage: (messageKey: string) => string; /** Specifies the appointment form is read-only. */ readOnly?: boolean; /** A function that formats dates based on the locale. */ formatDate: FormatterFn; /** Specifies the locale as an IETF BCP 47 language tag or an array of such tags. The locale is used to format date-time values. */ locale: string | string[]; /** A number between 0 (Sunday) and 6 (Saturday) that specifies the first day of the week. */ firstDayOfWeek: number; /** A component that renders a radio group. */ radioGroupComponent: React.ComponentType<AppointmentForm.RadioGroupProps>; /** A component that renders a weekly recurrence selector. */ weeklyRecurrenceSelectorComponent: React.ComponentType<AppointmentForm.WeeklyRecurrenceSelectorProps>; /** A component that renders a text editor. */ textEditorComponent: React.ComponentType<AppointmentForm.TextEditorProps>; /** A component that renders a date-time editor. */ dateEditorComponent: React.ComponentType<AppointmentForm.DateEditorProps>; /** A component that renders an options menu. */ selectComponent: React.ComponentType<AppointmentForm.SelectProps>; /** A component that renders a text label. */ labelComponent: React.ComponentType<AppointmentForm.LabelProps>; /** A React node used to render additional components to the Recurrence Layout. */ children?: React.ReactNode; } /** Properties passed to a component that renders a text editor on the appointment form. */ export interface TextEditorProps { /** The editor's value. */ value: string | number; /** A placeholder displayed inside the text field. */ placeholder: string; /** Specifies whether the text editor is read-only. */ readOnly: boolean; /** Handles value changes. */ onValueChange: (nextValue: string) => void; /** The text editor's type identifier. */ type: 'titleTextEditor' | 'multilineTextEditor' | 'ordinaryTextEditor' | 'numberEditor'; } /** Properties passed to a component that renders a date-time editor on the appointment form. */ export interface DateEditorProps { /** Specifies the date editor is read-only. */ readOnly?: boolean; /** The editor's value. */ value?: string | number; /** When true, users cannot edit the time. */ excludeTime?: boolean; /** Handles value changes. */ onValueChange: (nextValue: Date) => void; /** Specifies the locale as an IETF BCP 47 language tag or an array of such tags. The locale is used to format date-time values. */ locale?: string | string[]; } /** Properties passed to a component that renders a Boolean value editor on the appointment form. */ export interface BooleanEditorProps { /** The editor's text label. */ label?: string; /** The editor's value. */ value?: boolean; /** Handles value changes. */ onValueChange: (nextValue: boolean) => void; /** Specifies the editor is read-only. */ readOnly?: boolean; } /** Properties passed to a component that renders a menu of options on the appointment form. */ export interface SelectProps { /** The selected option. */ value: string | number; /** Handles value changes. */ onValueChange: (nextValue: string | number) => void; /** Specifies available menu options. */ availableOptions?: Array<SelectOption>; /** Specifies whether the menu is read-only. */ readOnly?: boolean; /** The menu's type. */ type: 'outlinedSelect' | 'filledSelect'; } /** A component that renders a resource editor. */ export interface ResourceEditorProps { /** The appointment's resource items. */ appointmentResources: Array<ValidResourceInstance>; /** A resource being edited. */ resource: ValidResource; /** Handles value changes. */ onResourceChange: (nextValue: string | number | Array<string | number>) => void; /** Specifies whether the menu is read-only. */ readOnly?: boolean; } /** Properties passed to a component that renders a command button on the appointment form. */ export interface CommandButtonProps { /** The command button's identifier. */ id: 'saveButton' | 'deleteButton' | 'cancelButton'; /** An event that initiates the command execution. */ onExecute: () => void; /** Uses a localization message's key to retrieve the message. */ getMessage?: (messageKey: string) => string; } /** Properties passed to a component that renders a text label on the appointment form. */ export interface LabelProps { /** The label's type. */ type?: 'titleLabel' | 'ordinaryLabel'; /** The label's text. */ text?: string; } /** Properties passed to a component that renders a radio group on the appointment form. */ export interface RadioGroupProps { /** The appointment's data. */ appointmentData: AppointmentModel; /** Specifies the locale as an IETF BCP 47 language tag or an array of such tags. The locale is used to format date-time values. */ locale?: string | string[]; /** A function that formats dates based on the locale. */ formatDate: FormatterFn; /** A number between 0 (Sunday) and 6 (Saturday) that specifies the first day of the week. */ firstDayOfWeek: number; /** An event that is raised when a field value in the appointment form is changed. */ onFieldChange: (nextFieldValue: { [fieldName: string]: any }) => void; /** Specifies the date editor is read-only. */ readOnly?: boolean; /** The radio group's type. */ type: 'endRepeat' | 'monthlyRadioGroup' | 'yearlyRadioGroup'; /** Uses a localization message's key to retrieve the message. */ getMessage?: (messageKey: string) => string; /** A component that renders a text editor. */ textEditorComponent: React.ComponentType<AppointmentForm.TextEditorProps>; /** A component that renders a date-time editor. */ dateEditorComponent: React.ComponentType<AppointmentForm.DateEditorProps>; /** A component that renders an options menu. */ selectComponent: React.ComponentType<AppointmentForm.SelectProps>; /** A component that renders a text label. */ labelComponent: React.ComponentType<AppointmentForm.LabelProps>; } /** Properties passed to a component that renders a weekly recurrence selector on the appointment form. */ export interface WeeklyRecurrenceSelectorProps { /** A function that formats dates based on the locale. */ formatDate: FormatterFn; /** A number between 0 (Sunday) and 6 (Saturday) that specifies the first day of the week. */ firstDayOfWeek: number; /** Specifies the recurrence rule. */ rRule: string; /** Specifies whether the weekly recurrence selector is read-only. */ readOnly: boolean; /** Handles appointment field value changes. */ onFieldChange: (nextFieldValue: { [fieldName: string]: any }) => void; } /** Localization Messages */ export interface LocalizationMessages { /** The "All Day" editor's label text. */ allDayLabel?: string; /** The "Title" editor's label text. */ titleLabel?: string; /** The commit button's text. */ commitCommand?: string; /** The "More Information" editor’s label text. */ moreInformationLabel?: string; /** The "Repeat" editor’s label text. */ repeatLabel?: string; /** The "Notes" editor’s label text. */ notesLabel?: string; /** The "Never" label text. */ never?: string; /** The "Daily" label text. */ daily?: string; /** The "Weekly" label text. */ weekly?: string; /** The "Monthly" label text. */ monthly?: string; /** The "Yearly" label text. */ yearly?: string; /** The "Repeat every" label text. */ repeatEveryLabel?: string; /** The "day(s)" label text. */ daysLabel?: string; /** The "End repeat" label text. */ endRepeatLabel?: string; /** The "On" label text. */ onLabel?: string; /** The "After" label text. */ afterLabel?: string; /** The "Occurrences" label text. */ occurrencesLabel?: string; /** The "week(s) on:" label text. */ weeksOnLabel?: string; /** The "month(s)" label text. */ monthsLabel?: string; /** The "of every month" label text. */ ofEveryMonthLabel?: string; /** The "The" label text. */ theLabel?: string; /** The "First" label text. */ firstLabel?: string; /** The "Second" label text. */ secondLabel?: string; /** The "Third" label text. */ thirdLabel?: string; /** The "Fourth" label text. */ fourthLabel?: string; /** The "Last" label text. */ lastLabel?: string; /** The "year(s)" label text. */ yearsLabel?: string; /** The "of" label text. */ ofLabel?: string; /** The "Every" label text. */ everyLabel?: string; /** The "Details" label text. */ detailsLabel?: string; } } export interface AppointmentFormProps { /** Specifies the appointment form’s visibility. */ visible?: boolean; /** Handles changes to the appointment form’s visibility. */ onVisibilityChange?: (visible: boolean) => void; /** Specifies the appointment’s data that the form displays. */ appointmentData?: AppointmentModel; /** Handles changes to the appointment’s data. */ onAppointmentDataChange?: (appointmentData: AppointmentModel) => void; /** Specifies the appointment form is read-only. */ readOnly?: boolean; /** @internal */ containerComponent: React.ComponentType<AppointmentForm.ContainerProps>; /** A component that renders the appointment form's overlay. */ overlayComponent: React.ComponentType<AppointmentForm.OverlayProps>; /** A component that renders the appointment form's layout. */ layoutComponent: React.ComponentType<AppointmentForm.LayoutProps>; /** A component that renders a layout for command buttons. */ commandLayoutComponent: React.ComponentType<AppointmentForm.CommandLayoutProps>; /** A component that renders a layout for editors that edit basic appointment data. */ basicLayoutComponent: React.ComponentType<AppointmentForm.BasicLayoutProps>; /** A component that renders a layout for editors that specify the appointment's recurrence. */ recurrenceLayoutComponent: React.ComponentType<AppointmentForm.RecurrenceLayoutProps>; /** A component that renders a command button. */ commandButtonComponent: React.ComponentType<AppointmentForm.CommandButtonProps>; /** A component that renders a text editor. */ textEditorComponent: React.ComponentType<AppointmentForm.TextEditorProps>; /** A component that renders a text label. */ labelComponent: React.ComponentType<AppointmentForm.LabelProps>; /** A component that renders a date-time editor. */ dateEditorComponent: React.ComponentType<AppointmentForm.DateEditorProps>; /** A component that renders an editor of Boolean values. */ booleanEditorComponent: React.ComponentType<AppointmentForm.BooleanEditorProps>; /** A component that renders an options menu. */ selectComponent: React.ComponentType<AppointmentForm.SelectProps>; /** A component that renders a resource editor. */ resourceEditorComponent: React.ComponentType<AppointmentForm.ResourceEditorProps>; /** A component that renders a radio group. */ radioGroupComponent: React.ComponentType<AppointmentForm.RadioGroupProps>; /** A component that renders a weekly recurrence selector. */ weeklyRecurrenceSelectorComponent: React.ComponentType<AppointmentForm.WeeklyRecurrenceSelectorProps>; /** An object that specifies localization messages. */ messages?: AppointmentForm.LocalizationMessages; } /** @internal */ export type AppointmentFormState = { visible: boolean; appointmentData: AppointmentModel; previousAppointment: AppointmentModel; };
the_stack
import { Inject, Injectable } from '@angular/core'; import { Observable, Subject, Subscription, from } from 'rxjs'; import { SnotifyToastConfig } from '../interfaces/snotify-toast-config.interface'; import { Snotify } from '../interfaces/snotify.interface'; import { SnotifyTypeType } from '../types/snotify-type.type'; import { SafeHtml } from '@angular/platform-browser'; import { TransformArgument } from '../decorators/transform-argument.decorator'; import { mergeDeep, uuid } from '../utils'; import { SetToastType } from '../decorators/set-toast-type.decorator'; import { SnotifyDefaults } from '../interfaces/snotify-defaults.interface'; import { SnotifyToast } from '../models/snotify-toast.model'; import { SnotifyStyle } from '../enums/snotify-style.enum'; /** * SnotifyService - create, remove, config toasts */ @Injectable() // tslint:disable:unified-signatures export class SnotifyService { readonly emitter = new Subject<SnotifyToast[]>(); readonly toastChanged = new Subject<SnotifyToast>(); readonly toastDeleted = new Subject<number>(); private notifications: SnotifyToast[] = []; constructor(@Inject('SnotifyToastConfig') public config: SnotifyDefaults) {} /** * emit changes in notifications array */ private emit(): void { this.emitter.next(this.notifications.slice()); } /** * returns SnotifyToast object * @param id Number * @return SnotifyToast|undefined */ get(id: number): SnotifyToast { return this.notifications.find(toast => toast.id === id); } /** * add SnotifyToast to notifications array * @param toast SnotifyToast */ private add(toast: SnotifyToast): void { if (this.config.global.filterDuplicates && this.containsToast(toast)) { return; } if (this.config.global.newOnTop) { this.notifications.unshift(toast); } else { this.notifications.push(toast); } this.emit(); } /** * checks if the toast is in the collection. * @param inToast SnotifyToast * @returns boolean */ private containsToast(inToast: SnotifyToast): boolean { return this.notifications.some(toast => toast.equals(inToast)); } /** * If ID passed, emits toast animation remove, if ID & REMOVE passed, removes toast from notifications array * @param id number * @param remove boolean */ remove(id?: number, remove?: boolean): void { if (!id) { return this.clear(); } else if (remove) { this.notifications = this.notifications.filter(toast => toast.id !== id); return this.emit(); } this.toastDeleted.next(id); } /** * Clear notifications array */ clear(): void { this.notifications = []; this.emit(); } /** * Creates toast and add it to array, returns toast id * @param snotify Snotify * @return number */ create(snotify: Snotify): SnotifyToast { const config = mergeDeep(this.config.toast, this.config.type[snotify.config.type], snotify.config); const toast = new SnotifyToast(uuid(), snotify.title, snotify.body, config); this.add(toast); return toast; } setDefaults(defaults: SnotifyDefaults): SnotifyDefaults { return (this.config = mergeDeep(this.config, defaults) as SnotifyDefaults); } /** * Create toast with simple style returns toast id; * @param body string * @returns number */ simple(body: string): SnotifyToast; /** * Create toast with simple style returns toast id; * @param body string * @param title string * @returns number */ simple(body: string, title: string): SnotifyToast; /** * Create toast with simple style returns toast id; * @param body string * @param config SnotifyToastConfig * @returns number */ simple(body: string, config: SnotifyToastConfig): SnotifyToast; /** * Create toast with simple style returns toast id; * @param [body] string * @param [title] string * @param [config] SnotifyToastConfig * @returns number */ simple(body: string, title: string, config: SnotifyToastConfig): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType simple(args: any): SnotifyToast { return this.create(args); } /** * Create toast with success style returns toast id; * @param body string * @returns number */ success(body: string): SnotifyToast; /** * Create toast with success style returns toast id; * @param body string * @param title string * @returns number */ success(body: string, title: string): SnotifyToast; /** * Create toast with success style returns toast id; * @param body string * @param config SnotifyToastConfig * @returns number */ success(body: string, config: SnotifyToastConfig): SnotifyToast; /** * Create toast with success style returns toast id; * @param [body] string * @param [title] string * @param [config] SnotifyToastConfig * @returns number */ success(body: string, title: string, config: SnotifyToastConfig): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType success(args: any): SnotifyToast { return this.create(args); } /** * Create toast with error style returns toast id; * @param body string * @returns number */ error(body: string): SnotifyToast; /** * Create toast with error style returns toast id; * @param body string * @param title string * @returns number */ error(body: string, title: string): SnotifyToast; /** * Create toast with error style returns toast id; * @param body string * @param config SnotifyToastConfig * @returns number */ error(body: string, config: SnotifyToastConfig): SnotifyToast; /** * Create toast with error style returns toast id; * @param [body] string * @param [title] string * @param [config] SnotifyToastConfig * @returns number */ error(body: string, title: string, config: SnotifyToastConfig): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType error(args: any): SnotifyToast { return this.create(args); } /** * Create toast with info style returns toast id; * @param body string * @returns number */ info(body: string): SnotifyToast; /** * Create toast with info style returns toast id; * @param body string * @param title string * @returns number */ info(body: string, title: string): SnotifyToast; /** * Create toast with info style returns toast id; * @param body string * @param config SnotifyToastConfig * @returns number */ info(body: string, config: SnotifyToastConfig): SnotifyToast; /** * Create toast with info style returns toast id; * @param [body] string * @param [title] string * @param [config] SnotifyToastConfig * @returns number */ info(body: string, title: string, config: SnotifyToastConfig): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType info(args: any): SnotifyToast { return this.create(args); } /** * Create toast with warning style returns toast id; * @param body string * @returns number */ warning(body: string): SnotifyToast; /** * Create toast with warning style returns toast id; * @param body string * @param title string * @returns number */ warning(body: string, title: string): SnotifyToast; /** * Create toast with warning style returns toast id; * @param body string * @param config SnotifyToastConfig * @returns number */ warning(body: string, config: SnotifyToastConfig): SnotifyToast; /** * Create toast with warning style returns toast id; * @param [body] string * @param [title] string * @param [config] SnotifyToastConfig * @returns number */ warning(body: string, title: string, config: SnotifyToastConfig): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType warning(args: any): SnotifyToast { return this.create(args); } /** * Create toast with confirm style returns toast id; * @param body string * @returns number */ confirm(body: string): SnotifyToast; /** * Create toast with confirm style returns toast id; * @param body string * @param title string * @returns number */ confirm(body: string, title: string): SnotifyToast; /** * Create toast with confirm style returns toast id; * @param body string * @param config SnotifyToastConfig * @returns number */ confirm(body: string, config: SnotifyToastConfig): SnotifyToast; /** * Create toast with confirm style returns toast id; * @param [body] string * @param [title] string * @param [config] SnotifyToastConfig * @returns number */ confirm(body: string, title: string, config: SnotifyToastConfig): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType confirm(args: any): SnotifyToast { return this.create(args); } /** * Create toast with Prompt style with two buttons, returns toast id; * @param body string * @returns number */ prompt(body: string): SnotifyToast; /** * Create toast with Prompt style with two buttons, returns toast id; * @param body string * @param title string * @returns number */ prompt(body: string, title: string): SnotifyToast; /** * Create toast with Prompt style with two buttons, returns toast id; * @param body string * @param config SnotifyToastConfig * @returns number */ prompt(body: string, config: SnotifyToastConfig): SnotifyToast; /** * Create toast with Prompt style with two buttons, returns toast id; * @param [body] string * @param [title] string * @param [config] SnotifyToastConfig * @returns number */ prompt(body: string, title: string, config: SnotifyToastConfig): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType prompt(args: any): SnotifyToast { return this.create(args); } /** * Creates async toast with Info style. Pass action, and resolve or reject it. * @param body string * @param action Promise<Snotify> | Observable<Snotify> * @returns number */ async(body: string, action: Promise<Snotify> | Observable<Snotify>): SnotifyToast; /** * Creates async toast with Info style. Pass action, and resolve or reject it. * @param body string * @param title string * @param action Promise<Snotify> | Observable<Snotify> * @returns number */ async(body: string, title: string, action: Promise<Snotify> | Observable<Snotify>): SnotifyToast; /** * Creates async toast with Info style. Pass action, and resolve or reject it. * @param body string * @param action Promise<Snotify> | Observable<Snotify> * @param [config] SnotifyToastConfig * @returns number */ async(body: string, action: Promise<Snotify> | Observable<Snotify>, config: SnotifyToastConfig): SnotifyToast; /** * Creates async toast with Info style. Pass action, and resolve or reject it. * @param body string * @param title string * @param action Promise<Snotify> | Observable<Snotify> * @param [config] SnotifyToastConfig * @returns number */ async( body: string, title: string, action: Promise<Snotify> | Observable<Snotify>, config: SnotifyToastConfig ): SnotifyToast; /** * Transform toast arguments into Snotify object */ @TransformArgument /** * Determines current toast type and collects default configuration */ @SetToastType async(args: any): SnotifyToast { let async: Observable<any>; if (args.action instanceof Promise) { async = from(args.action); } else { async = args.action; } const toast = this.create(args); toast.on('mounted', () => { const subscription: Subscription = async.subscribe( (next?: Snotify) => { this.mergeToast(toast, next); }, (error?: Snotify) => { this.mergeToast(toast, error, SnotifyStyle.error); subscription.unsubscribe(); }, () => { this.mergeToast(toast, {}, SnotifyStyle.success); subscription.unsubscribe(); } ); }); return toast; } private mergeToast(toast, next, type?: SnotifyTypeType) { if (next.body) { toast.body = next.body; } if (next.title) { toast.title = next.title; } if (type) { toast.config = mergeDeep(toast.config, this.config.global, this.config.toast[type], { type }, next.config); } else { toast.config = mergeDeep(toast.config, next.config); } if (next.html) { toast.config.html = next.html; } this.emit(); this.toastChanged.next(toast); } /** * Creates empty toast with html string inside * @param html string | SafeHtml * @param config SnotifyToastConfig * @returns number */ html(html: string | SafeHtml, config?: SnotifyToastConfig): SnotifyToast { return this.create({ title: null, body: null, config: { ...config, ...{ html } } }); } }
the_stack
import { cancelClient } from ".."; import { //Promise, noderfc_binding, environment, NodeRfcEnvironment, } from "./noderfc-bindings"; // // RfcClient // enum EnumSncQop { DigSig = "1", DigSigEnc = "2", DigSigEncUserAuth = "3", BackendDefault = "8", Maximum = "9", } enum EnumTrace { Off = "0", Brief = "1", Verbose = "2", Full = "3", } type RfcConnectionParametersAllowed = | "ABAP_DEBUG" | "ALIAS_USER" | "ASHOST" | "ASXML" | "CFIT" | "CLIENT" | "CODEPAGE" | "COMPRESSION_TYPE" | "DELTA" | "DEST" | "EXTIDDATA" | "EXTIDTYPE" | "GETSSO2" | "GROUP" | "GWHOST" | "GWSERV" | "LANG" | "LCHECK" | "LOGON_GROUP_CHECK_INTERVAL" | "MAX_REG_COUNT" | "MSHOST" | "MSSERV" | "MYSAPSSO2" | "NO_COMPRESSION" | "ON_CCE" | "PASSWD" | "PASSWORD_CHANGE_ENFORCED" | "PCS" | "PROGRAM_ID" | "PROXY_HOST" | "PROXY_PASSWD" | "PROXY_PORT" | "PROXY_USER" | "R3NAME" | "REG_COUNT" | "SAPLOGON_ID" | "SAPROUTER" | "SERIALIZATION_FORMAT" | "SERVER_NAME" | "SNC_LIB" | "SNC_MODE" | "SNC_MYNAME" | "SNC_PARTNERNAME" | "SNC_PARTNER_NAMES" | "SNC_QOP" | "SNC_SSO" | "SYSID" | "SYSNR" | "SYS_IDS" | "TLS_CLIENT_CERTIFICATE_LOGON" | "TLS_CLIENT_PSE" | "TLS_SERVER_PARTNER_AUTH" | "TLS_SERVER_PSE" | "TLS_TRUST_ALL" | "TPNAME" | "TRACE" | "USER" | "USE_REPOSITORY_ROUNDTRIP_OPTIMIZATION" | "USE_SAPGUI" | "USE_SYMBOLIC_NAMES" | "USE_TLS" | "WSHOST" | "WSPORT" | "X509CERT" | "abap_debug" | "alias_user" | "ashost" | "asxml" | "cfit" | "client" | "codepage" | "compression_type" | "delta" | "dest" | "extiddata" | "extidtype" | "getsso2" | "group" | "gwhost" | "gwserv" | "lang" | "lcheck" | "logon_group_check_interval" | "max_reg_count" | "mshost" | "msserv" | "mysapsso2" | "no_compression" | "on_cce" | "passwd" | "password_change_enforced" | "pcs" | "program_id" | "proxy_host" | "proxy_passwd" | "proxy_port" | "proxy_user" | "r3name" | "reg_count" | "saplogon_id" | "saprouter" | "serialization_format" | "server_name" | "snc_lib" | "snc_mode" | "snc_myname" | "snc_partnername" | "snc_partner_names" | "snc_qop" | "snc_sso" | "sysid" | "sysnr" | "sys_ids" | "tls_client_certificate_logon" | "tls_client_pse" | "tls_server_partner_auth" | "tls_server_pse" | "tls_trust_all" | "tpname" | "trace" | "user" | "use_repository_roundtrip_optimization" | "use_sapgui" | "use_symbolic_names" | "use_tls" | "wshost" | "wsport" | "x509cert"; enum RfcParameterDirection { RFC_IMPORT = 0x01, ///< Import parameter. This corresponds to ABAP IMPORTING parameter. RFC_EXPORT = 0x02, ///< Export parameter. This corresponds to ABAP EXPORTING parameter. RFC_CHANGING = RFC_IMPORT | RFC_EXPORT, ///< Import and export parameter. This corresponds to ABAP CHANGING parameter. RFC_TABLES = 0x04 | RFC_CHANGING, ///< Table parameter. This corresponds to ABAP TABLES parameter. } export type RfcConnectionParameters = Record< RfcConnectionParametersAllowed, string >; export type RfcClientOptions = { bcd?: string | Function; date?: Function; time?: Function; filter?: RfcParameterDirection; stateless?: boolean; timeout?: number; }; export type RfcCallOptions = { notRequested?: Array<string>; timeout?: number; }; interface RfcConnectionInfo { dest: string; host: string; partnerHost: string; sysNumber: string; sysId: string; client: string; user: string; language: string; trace: string; isoLanguage: string; codepage: string; partnerCodepage: string; rfcRole: string; type: string; partnerType: string; rel: string; partnerRel: string; kernelRel: string; cpicConvId: string; progName: string; partnerBytesPerChar: string; partnerSystemCodepage: string; partnerIP: string; partnerIPv6: string; //reserved: string; } export type RfcVariable = string | number | Buffer; export type RfcArray = Array<RfcVariable>; export type RfcStructure = { [key: string]: RfcVariable | RfcStructure | RfcTable; }; export type RfcTable = Array<RfcStructure>; export type RfcParameterValue = | RfcVariable | RfcArray | RfcStructure | RfcTable; export type RfcObject = { [key: string]: RfcParameterValue }; export type RfcClientConfig = { connectionParameters: RfcConnectionParameters; clientOptions?: RfcClientOptions; }; export interface RfcClientBinding { new ( connectionParameters: RfcConnectionParameters, clientOptions?: RfcClientOptions ): RfcClientBinding; ( connectionParameters: RfcConnectionParameters, options?: RfcClientOptions ): RfcClientBinding; _id: number; _alive: boolean; _connectionHandle: number; _pool_id: number; _config: RfcClientConfig; connectionInfo(): RfcConnectionInfo; open(callback: Function): void; close(callback: Function): void; resetServerContext(callback: Function): void; ping(callback: Function): void; invoke( rfmName: string, rfmParams: RfcObject, callback: Function, callOptions?: RfcCallOptions ): void; release(oneClientBinding: [RfcClientBinding], callback: Function): void; } export class Client { private __client: RfcClientBinding; constructor( arg1: RfcClientBinding | RfcConnectionParameters, clientOptions?: RfcClientOptions ) { if (arg1 === undefined) { throw new TypeError(`Client constructor requires an argument`); } if (arg1["_pool_id"] !== undefined && arg1["_pool_id"] > 0) { this.__client = arg1 as RfcClientBinding; } else { this.__client = clientOptions ? new noderfc_binding.Client( arg1 as RfcConnectionParameters, clientOptions ) : new noderfc_binding.Client(arg1 as RfcConnectionParameters); } } static get environment(): NodeRfcEnvironment { return environment; } get environment(): NodeRfcEnvironment { return environment; } get binding(): RfcClientBinding { return this.__client; } get id(): number { return this.__client._id; } get alive(): boolean { return this.__client._alive; } get connectionHandle(): number { return this.__client._connectionHandle; } get pool_id(): number { return this.__client._pool_id; } get config(): RfcClientConfig { return this.__client._config; } get _id(): string { return `${this.__client._id} handle: ${ this.__client._connectionHandle } ${ this.__client._pool_id ? "[m] pool: " + this.__client._pool_id : "[d]" }`; } get connectionInfo(): RfcConnectionInfo { return this.__client.connectionInfo(); } static checkCallbackArg(method: string, callback?: Function) { if (callback !== undefined && typeof callback !== "function") { throw new TypeError( `Client ${method}() argument, if provided, must be a Function. Received: ${typeof callback}` ); } } // for backwards compatibility only, to be deprecated connect(callback?: Function): void | Promise<Client> { Client.checkCallbackArg("connect", callback); return this.open(callback); } open(callback?: Function): void | Promise<Client> { Client.checkCallbackArg("open", callback); if (typeof callback === "function") { try { this.__client.open(callback); } catch (ex) { callback(ex); } } else { return new Promise((resolve, reject) => { try { this.__client.open((err) => { if (err !== undefined) { reject(err); } else { resolve(this); } }); } catch (ex) { reject(ex); } }); } } ping(callback?: Function): void | Promise<boolean> { Client.checkCallbackArg("ping", callback); if (typeof callback === "function") { try { this.__client.ping(callback); } catch (ex) { callback(ex); } } else { return new Promise((resolve, reject) => { try { this.__client.ping((err: any, res: boolean) => { if (err === undefined) { resolve(res); } else { reject(err); } }); } catch (ex) { reject(ex); } }); } } close(callback?: Function): void | Promise<void> { Client.checkCallbackArg("close", callback); if (typeof callback === "function") { try { this.__client.close(callback); } catch (ex) { callback(ex); } } else { return new Promise((resolve, reject) => { try { this.__client.close((err) => { if (err === undefined) { resolve(); } else { reject(err); } }); } catch (ex) { reject(ex); } }); } } cancel(callback?: Function): void | Promise<any> { Client.checkCallbackArg("cancel", callback); if (typeof callback === "function") { return cancelClient(this, callback); } else { return cancelClient(this); } } resetServerContext(callback?: Function): void | Promise<void> { Client.checkCallbackArg("resetServerContext", callback); if (typeof callback === "function") { try { this.__client.resetServerContext(callback); } catch (ex) { callback(ex); } } else { return new Promise((resolve, reject) => { try { this.__client.resetServerContext((err) => { if (err === undefined) { resolve(); } else { reject(err); } }); } catch (ex) { reject(ex); } }); } } release(callback?: Function): void | Promise<void> { Client.checkCallbackArg("release"); if (typeof callback === "function") { try { this.__client.release([this.__client], callback); } catch (ex) { callback(ex); } } else { return new Promise((resolve, reject) => { try { this.__client.release([this.__client], (err) => { if (err === undefined) { resolve(); } else { reject(err); } }); } catch (ex) { reject(ex); } }); } } call( rfmName: string, rfmParams: RfcObject, callOptions: RfcCallOptions = {} ): Promise<RfcObject> { return new Promise( ( resolve: (arg0: RfcObject) => void, reject: (arg0: TypeError) => void ) => { if (arguments.length < 2) { reject( new TypeError( "Please provide remote function module name and parameters as arguments" ) ); } if (typeof rfmName !== "string") { reject( new TypeError( "First argument (remote function module name) must be an string" ) ); } if (typeof rfmParams !== "object") { reject( new TypeError( "Second argument (remote function module parameters) must be an object" ) ); } if ( callOptions !== undefined && typeof callOptions !== "object" ) { reject( new TypeError("Call options argument must be an object") ); } try { this.invoke( rfmName, rfmParams, (err: any, res: RfcObject) => { if (err !== undefined) { reject(err); } else { resolve(res); } }, callOptions ); } catch (ex) { reject(ex); } } ); } invoke( rfmName: string, rfmParams: RfcObject, callback: Function, callOptions?: RfcCallOptions ) { try { if (typeof callback !== "function") { throw new TypeError("Callback function must be supplied"); } if (arguments.length < 3) { throw new TypeError( "Client invoke() argument missing: RFM name, parameters or callback" ); } if (typeof rfmName !== "string") { throw new TypeError( "Client invoke() 1st argument (remote function module name) must be an string" ); } if (typeof rfmParams !== "object") { throw new TypeError( "Client invoke() 2nd argument (remote function module parameters) must be an object" ); } if (arguments.length === 4 && typeof callOptions !== "object") { throw new TypeError("Call options argument must be an object"); } const clientOptions = this.config.clientOptions; let timeout = 0, callbackFunction = callback; if (callOptions && callOptions.timeout) { timeout = callOptions.timeout; } if (timeout === 0 && clientOptions && clientOptions.timeout) { timeout = clientOptions.timeout; } if (timeout > 0) { const cancelTimeout = setTimeout(() => { this.cancel((_err: any, _res: any) => { // _res like // { connectionHandle: 140414048978432, result: 'cancelled' } }); }, (timeout as number) * 1000); callbackFunction = (err, res) => { clearTimeout(cancelTimeout); callback(err, res); }; } this.__client.invoke( rfmName, rfmParams, callbackFunction, callOptions ); } catch (ex) { if (typeof callback !== "function") { throw ex; } else { callback(ex); } } } }
the_stack
import { EventEmitter2 } from "eventemitter2"; declare namespace Moleculer { /** * Moleculer uses global.Promise as the default promise library * If you are using a third-party promise library (e.g. Bluebird), you will need to * assign type definitions to use for your promise library. You will need to have a .d.ts file * with the following code when you compile: * * - import Bluebird from "bluebird"; * declare module "moleculer" { * type Promise<T> = Bluebird<T>; * } */ type GenericObject = { [name: string]: any }; type LogLevels = "fatal" | "error" | "warn" | "info" | "debug" | "trace"; class LoggerFactory { constructor(broker: ServiceBroker); init(opts: LoggerConfig | Array<LoggerConfig>): void; stop(): void; getLogger(bindings: GenericObject): LoggerInstance; getBindingsKey(bindings: GenericObject): String; broker: ServiceBroker; } interface LoggerBindings { nodeID: string; ns: string; mod: string; svc: string; ver: string | void; } class LoggerInstance { fatal(...args: any[]): void; error(...args: any[]): void; warn(...args: any[]): void; info(...args: any[]): void; debug(...args: any[]): void; trace(...args: any[]): void; } type ActionHandler<T = any> = (ctx: Context<any, any>) => Promise<T> | T; type ActionParamSchema = { [key: string]: any }; type ActionParamTypes = | "any" | "array" | "boolean" | "custom" | "date" | "email" | "enum" | "forbidden" | "function" | "number" | "object" | "string" | "url" | "uuid" | boolean | string | ActionParamSchema; type ActionParams = { [key: string]: ActionParamTypes }; interface HotReloadOptions { modules?: Array<string>; } interface TracerExporterOptions { type: string; options?: GenericObject; } interface TracerOptions { enabled?: boolean; exporter?: string | TracerExporterOptions | Array<TracerExporterOptions|string> | null; sampling?: { rate?: number | null; tracesPerSecond?: number | null; minPriority?: number | null; } actions?: boolean; events?: boolean; errorFields?: Array<string>; stackTrace?: boolean; defaultTags?: GenericObject | Function | null; tags?: { action?: TracingActionTags; event?: TracingEventTags; } } class Tracer { constructor(broker: ServiceBroker, opts: TracerOptions | boolean); broker: ServiceBroker; logger: LoggerInstance; opts: GenericObject; exporter: Array<BaseTraceExporter>; isEnabled(): boolean; shouldSample(span: Span): boolean; startSpan(name: string, opts?: GenericObject): Span; //getCurrentSpan(): Span | null; getCurrentTraceID(): string | null; getActiveSpanID(): string | null; } interface SpanLogEntry { name: string; fields: GenericObject; time: number; elapsed: number; } class Span { constructor(tracer: Tracer, name: string, opts: GenericObject); tracer: Tracer; logger: LoggerInstance; opts: GenericObject; meta: GenericObject name: string; id: string; traceID: string; parentID: string | null; service?: { name: string; version: string | number | null | undefined; } priority: number; sampled: boolean; startTime: number | null; finishTime: number | null; duration: number | null; error: Error | null; logs: Array<SpanLogEntry>; tags: GenericObject; start(time?: number): Span; addTags(obj: GenericObject): Span; log(name: string, fields?: GenericObject, time?: number): Span; setError(err: Error): Span; finish(time?: number): Span; startSpan(name: string, opts?: GenericObject): Span; } type TracingActionTagsFuncType = (ctx: Context, response?: any) => GenericObject; type TracingActionTags = TracingActionTagsFuncType | { params?: boolean | string[]; meta?: boolean | string[]; response?: boolean | string[]; } type TracingEventTagsFuncType = (ctx: Context) => GenericObject; type TracingEventTags = TracingEventTagsFuncType | { params?: boolean | string[]; meta?: boolean | string[]; } interface TracingOptions { enabled?: boolean; tags?: TracingActionTags | TracingEventTags; } interface TracingActionOptions extends TracingOptions { tags?: TracingActionTags; } interface TracingEventOptions extends TracingOptions { tags?: TracingEventTags; } class BaseTraceExporter { opts: GenericObject; tracer: Tracer; logger: LoggerInstance; constructor(opts: GenericObject); init(tracer: Tracer): void; spanStarted(span: Span): void; spanFinished(span: Span): void; flattenTags(obj: GenericObject, convertToString?: boolean, path?: string): GenericObject; errorToObject(err: Error): GenericObject; } namespace TracerExporters { class Base extends BaseTraceExporter {} class Console extends BaseTraceExporter {} class Datadog extends BaseTraceExporter {} class Event extends BaseTraceExporter {} class EventLegacy extends BaseTraceExporter {} class Jaeger extends BaseTraceExporter {} class Zipkin extends BaseTraceExporter {} } interface MetricsReporterOptions { type: string; options?: MetricReporterOptions; } interface MetricRegistryOptions { enabled?: boolean; collectProcessMetrics?: boolean; collectInterval?: number; reporter?: string | MetricsReporterOptions | Array<MetricsReporterOptions|string> | null; defaultBuckets?: Array<number>; defaultQuantiles?: Array<number>; defaultMaxAgeSeconds?: number; defaultAgeBuckets?: number; defaultAggregator?: string; } type MetricSnapshot = GaugeMetricSnapshot | InfoMetricSnapshot | HistogramMetricSnapshot; interface BaseMetricPOJO { type: string; name: string; description?: string; labelNames: Array<string>; unit?: string; values: Array<MetricSnapshot>; } class BaseMetric { type: string; name: string; description?: string; labelNames: Array<string>; unit?: string; aggregator: string; lastSnapshot: GenericObject | null; dirty: boolean; values: Map<String, GenericObject>; constructor(opts: BaseMetricOptions, registry: MetricRegistry); setDirty(): void; clearDirty(): void; get(labels?: GenericObject): GenericObject | null; reset(labels?: GenericObject, timestamp?: number): GenericObject | null; resetAll(timestamp?: number): GenericObject | null; clear(): void; hashingLabels(labels?: GenericObject): string; snapshot(): Array<MetricSnapshot>; generateSnapshot(): Array<MetricSnapshot>; changed(value: any | null, labels?: GenericObject, timestamp?: number): void; toObject(): BaseMetricPOJO; } interface GaugeMetricSnapshot { value: number; labels: GenericObject; timestamp: number; } class GaugeMetric extends BaseMetric { increment(labels?: GenericObject, value?: number, timestamp?: number): void; decrement(labels?: GenericObject, value?: number, timestamp?: number): void; set(value: number, labels?: GenericObject, timestamp?: number): void; generateSnapshot(): Array<GaugeMetricSnapshot>; } class CounterMetric extends BaseMetric { increment(labels?: GenericObject, value?: number, timestamp?: number): void; set(value: number, labels?: GenericObject, timestamp?: number): void; generateSnapshot(): Array<GaugeMetricSnapshot>; } interface InfoMetricSnapshot { value: any; labels: GenericObject; timestamp: number; } class InfoMetric extends BaseMetric { set(value: any | null, labels?: GenericObject, timestamp?: number): void; generateSnapshot(): Array<InfoMetricSnapshot>; } interface HistogramMetricSnapshot { labels: GenericObject; count: number; sum: number; timestamp: number; buckets?: { [key: string]: number; }; min?: number | null, mean?: number | null, variance?: number | null, stdDev?: number | null, max?: number | null, quantiles?: { [key: string]: number; } } class HistogramMetric extends BaseMetric { buckets: Array<number>; quantiles: Array<number>; maxAgeSeconds?: number; ageBuckets?: number; observe(value: number, labels?: GenericObject, timestamp?: number): void; generateSnapshot(): Array<HistogramMetricSnapshot>; static generateLinearBuckets(start: number, width: number, count: number): Array<number>; static generateExponentialBuckets(start: number, factor: number, count: number): Array<number>; } namespace MetricTypes { class Base extends BaseMetric {} class Counter extends CounterMetric {} class Gauge extends GaugeMetric {} class Histogram extends HistogramMetric {} class Info extends InfoMetric {} } interface BaseMetricOptions { type: string; name: string; description?: string; labelNames?: Array<string>; unit?: string; aggregator?: string; [key: string]: unknown; } interface MetricListOptions { type: string | Array<string>; includes: string | Array<string>; excludes: string | Array<string>; } class MetricRegistry { broker: ServiceBroker; logger: LoggerInstance; dirty: boolean; store: Map<String, BaseMetric>; reporter: Array<MetricBaseReporter>; constructor(broker: ServiceBroker, opts?: MetricRegistryOptions); init(broker: ServiceBroker): void; stop(): void; isEnabled(): boolean; register(opts: BaseMetricOptions): BaseMetric | null; hasMetric(name: string): boolean; getMetric(name: string): BaseMetric; increment(name: string, labels?: GenericObject, value?: number, timestamp?: number): void; decrement(name: string, labels?: GenericObject, value?: number, timestamp?: number): void; set(name: string, value: any | null, labels?: GenericObject, timestamp?: number): void; observe(name: string, value: number, labels?: GenericObject, timestamp?: number): void; reset(name: string, labels?: GenericObject, timestamp?: number): void; resetAll(name: string, timestamp?: number): void; timer(name: string, labels?: GenericObject, timestamp?: number): () => number; changed(metric: BaseMetric, value: any | null, labels?: GenericObject, timestamp?: number): void; list(opts?: MetricListOptions): Array<BaseMetricPOJO>; } interface MetricReporterOptions { includes?: string | Array<string>; excludes?: string | Array<string>; metricNamePrefix?: string; metricNameSuffix?: string; metricNameFormatter?: (name: string) => string; labelNameFormatter?: (name: string) => string; [key: string]: any; } class MetricBaseReporter { opts: MetricReporterOptions; constructor(opts: MetricReporterOptions); init(registry: MetricRegistry): void; matchMetricName(name: string): boolean; formatMetricName(name: string): string; formatLabelName(name: string): string; metricChanged(metric: BaseMetric, value: any, labels?: GenericObject, timestamp?: number): void; } namespace MetricReporters { class Base extends MetricBaseReporter {} class Console extends MetricBaseReporter {} class CSV extends MetricBaseReporter {} class Event extends MetricBaseReporter {} class Datadog extends MetricBaseReporter {} class Prometheus extends MetricBaseReporter {} class StatsD extends MetricBaseReporter {} } interface BulkheadOptions { enabled?: boolean; concurrency?: number; maxQueueSize?: number; } type ActionCacheEnabledFuncType = (ctx: Context<any, any>) => boolean; interface ActionCacheOptions { enabled?: boolean | ActionCacheEnabledFuncType; ttl?: number; keys?: Array<string>; lock?: { enabled?: boolean; staleTime?: number; }; } type ActionVisibility = "published" | "public" | "protected" | "private"; type ActionHookBefore = (ctx: Context<any, any>) => Promise<void> | void; type ActionHookAfter = (ctx: Context<any, any>, res: any) => Promise<any> | any; type ActionHookError = (ctx: Context<any, any>, err: Error) => Promise<void> | void; interface ActionHooks { before?: string | ActionHookBefore | Array<string | ActionHookBefore>; after?: string | ActionHookAfter | Array<string | ActionHookAfter>; error?: string | ActionHookError | Array<string | ActionHookError>; } interface RestSchema{ path?: string, method?: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH', fullPath?: string, basePath?: string, } type ActionSchema<S = ServiceSettingSchema> = { name?: string; rest?: RestSchema | string | string[], visibility?: ActionVisibility; params?: ActionParams; service?: Service; cache?: boolean | ActionCacheOptions; handler?: ActionHandler; tracing?: boolean | TracingActionOptions; bulkhead?: BulkheadOptions; circuitBreaker?: BrokerCircuitBreakerOptions; retryPolicy?: RetryPolicyOptions; fallback?: string | FallbackHandler; hooks?: ActionHooks; [key: string]: any; } & ThisType<Service<S>> type EventSchema<S = ServiceSettingSchema> = { name?: string; group?: string; params?: ActionParams; service?: Service; tracing?: boolean | TracingEventOptions; bulkhead?: BulkheadOptions; handler?: ActionHandler; context?: boolean; [key: string]: any; } & ThisType<Service<S>> type ServiceActionsSchema<S = ServiceSettingSchema> = { [key: string]: ActionSchema | ActionHandler | boolean; } & ThisType<Service<S>>; class BrokerNode { id: string; instanceID: string | null; available: boolean; local: boolean; lastHeartbeatTime: number; config: GenericObject; client: GenericObject; metadata: GenericObject; ipList: Array<string>; port: number| null; hostname: string | null; udpAddress: string | null; rawInfo: GenericObject; services: [GenericObject]; cpu: number | null; cpuSeq: number | null; seq: number; offlineSince: number | null; heartbeat(payload: GenericObject): void; disconnected(): void; } class Context<P = unknown, M extends object = {}> { constructor(broker: ServiceBroker, endpoint: Endpoint); id: string; broker: ServiceBroker; endpoint: Endpoint | null; action: ActionSchema | null; event: EventSchema | null; service: Service | null; nodeID: string | null; eventName: string | null; eventType: string | null; eventGroups: Array<string> | null; options: CallingOptions; parentID: string | null; caller: string | null; tracing: boolean | null; span: Span | null; needAck: boolean | null; ackID: string | null; locals: GenericObject; level: number; params: P; meta: M; requestID: string | null; cachedResult: boolean; setEndpoint(endpoint: Endpoint): void; setParams(newParams: P, cloning?: boolean): void; call<T>(actionName: string): Promise<T>; call<T, P>(actionName: string, params: P, opts?: CallingOptions): Promise<T>; mcall<T>(def: Record<string, MCallDefinition>, opts?: MCallCallingOptions): Promise<Record<string, T>>; mcall<T>(def: Array<MCallDefinition>, opts?: MCallCallingOptions): Promise<Array<T>>; emit<D>(eventName: string, data: D, opts: GenericObject): Promise<void>; emit<D>(eventName: string, data: D, groups: Array<string>): Promise<void>; emit<D>(eventName: string, data: D, groups: string): Promise<void>; emit<D>(eventName: string, data: D): Promise<void>; emit(eventName: string): Promise<void>; broadcast<D>(eventName: string, data: D, opts: GenericObject): Promise<void>; broadcast<D>(eventName: string, data: D, groups: Array<string>): Promise<void>; broadcast<D>(eventName: string, data: D, groups: string): Promise<void>; broadcast<D>(eventName: string, data: D): Promise<void>; broadcast(eventName: string): Promise<void>; copy(endpoint: Endpoint): this; copy(): this; startSpan(name: string, opts?: GenericObject): Span; finishSpan(span: Span, time?: number): void; toJSON(): GenericObject; static create(broker: ServiceBroker, endpoint: Endpoint, params: GenericObject, opts: GenericObject): Context; static create(broker: ServiceBroker, endpoint: Endpoint, params: GenericObject): Context; static create(broker: ServiceBroker, endpoint: Endpoint): Context; static create(broker: ServiceBroker): Context; } interface ServiceSettingSchema { $noVersionPrefix?: boolean; $noServiceNamePrefix?: boolean; $dependencyTimeout?: number; $shutdownTimeout?: number; $secureSettings?: Array<string>; [name: string]: any; } type ServiceEventLegacyHandler = (payload: any, sender: string, eventName: string, ctx: Context) => void; type ServiceEventHandler = (ctx: Context) => void; type ServiceEvent<S = ServiceSettingSchema> = { name?: string; group?: string; params?: ActionParams; context?: boolean; debounce?: number; throttle?: number; handler?: ServiceEventHandler | ServiceEventLegacyHandler; } & ThisType<Service<S>> type ServiceEvents = { [key: string]: ServiceEventHandler | ServiceEventLegacyHandler | ServiceEvent }; type ServiceMethods = { [key: string]: (...args: any[]) => any } & ThisType<Service>; type CallMiddlewareHandler = (actionName: string, params: any, opts: CallingOptions) => Promise<any>; type Middleware = { [name: string]: | ((handler: ActionHandler, action: ActionSchema) => any) | ((handler: ActionHandler, event: ServiceEvent) => any) | ((handler: ActionHandler) => any) | ((service: Service) => any) | ((broker: ServiceBroker) => any) | ((handler: CallMiddlewareHandler) => CallMiddlewareHandler) } type MiddlewareInit = (broker: ServiceBroker) => Middleware; interface MiddlewareCallHandlerOptions { reverse?: boolean } interface MiddlewareHandler { list: Middleware[]; add(mw: string | Middleware | MiddlewareInit): void; wrapHandler(method: string, handler: ActionHandler, def: ActionSchema): typeof handler; callHandlers(method: string, args: any[], opts: MiddlewareCallHandlerOptions): Promise<void>; callSyncHandlers(method: string, args: any[], opts: MiddlewareCallHandlerOptions): void; count(): number; wrapMethod(method: string, handler: ActionHandler, bindTo: any, opts: MiddlewareCallHandlerOptions): typeof handler; } interface ServiceHooksBefore { [key: string]: string | ActionHookBefore | Array<string | ActionHookBefore>; } interface ServiceHooksAfter { [key: string]: string | ActionHookAfter | Array<string | ActionHookAfter>; } interface ServiceHooksError { [key: string]: string | ActionHookError | Array<string | ActionHookError>; } interface ServiceHooks { before?: ServiceHooksBefore, after?: ServiceHooksAfter, error?: ServiceHooksError, } interface ServiceDependency { name: string; version?: string | number; } interface ServiceSchema<S = ServiceSettingSchema> { name: string; version?: string | number; settings?: S; dependencies?: string | ServiceDependency | Array<string | ServiceDependency>; metadata?: GenericObject; actions?: ServiceActionsSchema; mixins?: Array<Partial<ServiceSchema>>; methods?: ServiceMethods; hooks?: ServiceHooks; events?: ServiceEvents; created?: (() => void) | Array<() => void>; started?: (() => Promise<void>) | Array<() => Promise<void>>; stopped?: (() => Promise<void>) | Array<() => Promise<void>>; [name: string]: any; } type ServiceAction = <T = Promise<any>, P extends GenericObject = GenericObject>(params?: P, opts?: CallingOptions) => T; interface ServiceActions { [name: string]: ServiceAction; } interface WaitForServicesResult { services: string[]; statuses: Array<{ name: string; available: boolean}>; } class Service<S = ServiceSettingSchema> implements ServiceSchema { constructor(broker: ServiceBroker, schema?: ServiceSchema<S>); protected parseServiceSchema(schema: ServiceSchema<S>): void; name: string; fullName: string; version?: string | number; settings: S; metadata: GenericObject; dependencies: string | ServiceDependency | Array<string | ServiceDependency>; schema: ServiceSchema<S>; originalSchema: ServiceSchema<S>; broker: ServiceBroker; logger: LoggerInstance; actions: ServiceActions; Promise: PromiseConstructorLike; //currentContext: Context | null; _init(): void; _start(): Promise<void>; _stop(): Promise<void>; /** * Wait for the specified services to become available/registered with this broker. * * @param serviceNames The service, or services, we are waiting for. * @param timeout The total time this call may take. If this time has passed and the service(s) * are not available an error will be thrown. (In milliseconds) * @param interval The time we will wait before once again checking if the service(s) are available (In milliseconds) * @param logger the broker logger instance */ waitForServices(serviceNames: string | Array<string> | Array<ServiceDependency>, timeout?: number, interval?: number, logger?: LoggerInstance): Promise<WaitForServicesResult>; [name: string]: any; static applyMixins(schema: ServiceSchema): ServiceSchema; static mergeSchemas(mixinSchema: ServiceSchema, svcSchema: ServiceSchema): ServiceSchema; static mergeSchemaSettings(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaMetadata(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaMixins(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaDependencies(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaHooks(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaActions(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaMethods(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaEvents(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaLifecycleHandlers(src: GenericObject, target: GenericObject): GenericObject; static mergeSchemaUnknown(src: GenericObject, target: GenericObject): GenericObject; } type CheckRetryable = (err: Error) => boolean; interface BrokerCircuitBreakerOptions { enabled?: boolean, threshold?: number; windowTime?: number; minRequestCount?: number; halfOpenTime?: number; check?: CheckRetryable; } interface RetryPolicyOptions { enabled?: boolean, retries?: number; delay?: number; maxDelay?: number; factor?: number; check?: CheckRetryable; } interface BrokerRegistryOptions { strategy?: Function | string; strategyOptions?: GenericObject; preferLocal?: boolean; discoverer?: RegistryDiscovererOptions | BaseDiscoverer | string; } interface RegistryDiscovererOptions { type: string, options: DiscovererOptions } interface DiscovererOptions extends GenericObject { heartbeatInterval?: number; heartbeatTimeout?: number; disableHeartbeatChecks?: boolean; disableOfflineNodeRemoving?: boolean; cleanOfflineNodesTimeout?: number; } interface BrokerTransitOptions { maxQueueSize?: number; disableReconnect?: boolean; disableVersionCheck?: boolean; maxChunkSize?: number; } interface BrokerTrackingOptions { enabled?: boolean; shutdownTimeout?: number; } interface LogLevelConfig { [module: string]: boolean | LogLevels; } interface LoggerConfig { type: string, options?: GenericObject } interface BrokerOptions { namespace?: string; nodeID?: string; logger?: Loggers.Base | LoggerConfig | Array<LoggerConfig> | boolean; logLevel?: LogLevels | LogLevelConfig; transporter?: Transporter | string | GenericObject; requestTimeout?: number; retryPolicy?: RetryPolicyOptions; contextParamsCloning?: boolean; maxCallLevel?: number; heartbeatInterval?: number; heartbeatTimeout?: number tracking?: BrokerTrackingOptions; disableBalancer?: boolean; registry?: BrokerRegistryOptions; circuitBreaker?: BrokerCircuitBreakerOptions; bulkhead?: BulkheadOptions; transit?: BrokerTransitOptions; uidGenerator?: () => string; errorHandler?: (err: Error, info: any) => void; cacher?: boolean | Cacher | string | GenericObject; serializer?: Serializer | string | GenericObject; validator?: boolean | BaseValidator | ValidatorNames | ValidatorOptions; metrics?: boolean | MetricRegistryOptions; tracing?: boolean | TracerOptions; internalServices?: boolean | { [key: string]: Partial<ServiceSchema> }; internalMiddlewares?: boolean; dependencyInterval?: number; hotReload?: boolean | HotReloadOptions; middlewares?: Array<Middleware | string>; replCommands?: Array<GenericObject>; replDelimiter?: string; metadata?: GenericObject; ServiceFactory?: typeof Service; ContextFactory?: typeof Context; Promise?: PromiseConstructorLike; created?: (broker: ServiceBroker) => void; started?: (broker: ServiceBroker) => void; stopped?: (broker: ServiceBroker) => void; /** * If true, process.on("beforeExit/exit/SIGINT/SIGTERM", ...) handler won't be registered! * You have to register this manually and stop broker in this case! */ skipProcessEventRegistration?: boolean; } interface NodeHealthStatus { cpu: { load1: number; load5: number; load15: number; cores: number; utilization: number; }; mem: { free: number; total: number; percent: number; }; os: { uptime: number; type: string; release: string; hostname: string; arch: string; platform: string; user: string; }; process: { pid: NodeJS.Process["pid"]; memory: NodeJS.MemoryUsage; uptime: number; argv: string[]; }; client: { type: string; version: string; langVersion: NodeJS.Process["version"]; }; net: { ip: string[]; }; time: { now: number; iso: string; utc: string; }; } type FallbackHandler = (ctx: Context, err: Errors.MoleculerError) => Promise<any>; type FallbackResponse = string | number | GenericObject; type FallbackResponseHandler = (ctx: Context, err: Errors.MoleculerError) => Promise<any>; interface CallingOptions { timeout?: number; retries?: number; fallbackResponse?: FallbackResponse | Array<FallbackResponse> | FallbackResponseHandler; nodeID?: string; meta?: GenericObject; parentCtx?: Context; requestID?: string; tracking?: boolean; paramsCloning?: boolean; caller?: string; } interface MCallCallingOptions extends CallingOptions{ settled?: boolean; } interface CallDefinition<P extends GenericObject = GenericObject> { action: string; params: P; } interface MCallDefinition<P extends GenericObject = GenericObject> extends CallDefinition<P> { options?: CallingOptions; } interface Endpoint { broker: ServiceBroker; id: string; node: GenericObject; local: boolean; state: boolean; } interface ActionEndpoint extends Endpoint { service: Service; action: ActionSchema; } interface EventEndpoint extends Endpoint { service: Service; event: EventSchema; } interface PongResponse { nodeID: string; elapsedTime: number; timeDiff: number } interface PongResponses { [name: string]: PongResponse; } interface ServiceSearchObj { name: string; version?: string|number; } interface MoleculerRepl extends Vorpal{ removeIfExist(command:string): void; } namespace Loggers { class Base { constructor(opts?: GenericObject); init(loggerFactory: LoggerFactory): void stop(): void; getLogLevel(mod: string): string getLogHandler(bindings: GenericObject): GenericObject } } class ServiceBroker { constructor(options?: BrokerOptions); options: BrokerOptions; Promise: PromiseConstructorLike; ServiceFactory: typeof Service; ContextFactory: typeof Context; started: boolean; namespace: string; nodeID: string; instanceID: string; logger: LoggerInstance; services: Array<Service>; localBus: EventEmitter2; scope: AsyncStorage; metrics: MetricRegistry; middlewares: MiddlewareHandler; registry: ServiceRegistry; cacher?: Cacher; serializer?: Serializer; validator?: BaseValidator; tracer: Tracer; transit?: Transit; start(): Promise<void>; stop(): Promise<void>; repl(): MoleculerRepl; errorHandler(err: Error, info: GenericObject): void; wrapMethod(method: string, handler: ActionHandler, bindTo: any, opts: MiddlewareCallHandlerOptions): typeof handler; callMiddlewareHookSync(name: string, args: any[], opts: MiddlewareCallHandlerOptions): Promise<void>; callMiddlewareHook(name: string, args: any[], opts: MiddlewareCallHandlerOptions): void; isMetricsEnabled(): boolean; isTracingEnabled(): boolean; getLogger(module: string, props?: GenericObject): LoggerInstance; fatal(message: string, err?: Error, needExit?: boolean): void; loadServices(folder?: string, fileMask?: string): number; loadService(filePath: string): Service; createService(schema: ServiceSchema, schemaMods?: ServiceSchema): Service; destroyService(service: Service | string | ServiceSearchObj): Promise<void>; getLocalService(name: string | ServiceSearchObj): Service; waitForServices(serviceNames: string | Array<string> | Array<ServiceSearchObj>, timeout?: number, interval?: number, logger?: LoggerInstance): Promise<void>; findNextActionEndpoint(actionName: string, opts?: GenericObject, ctx?: Context): ActionEndpoint | Errors.MoleculerRetryableError; call<T>(actionName: string): Promise<T>; call<T, P>(actionName: string, params: P, opts?: CallingOptions): Promise<T>; mcall<T>(def: Record<string, MCallDefinition>, opts?: MCallCallingOptions): Promise<Record<string, T>>; mcall<T>(def: Array<MCallDefinition>, opts?: MCallCallingOptions): Promise<Array<T>>; emit<D>(eventName: string, data: D, opts: GenericObject): Promise<void>; emit<D>(eventName: string, data: D, groups: Array<string>): Promise<void>; emit<D>(eventName: string, data: D, groups: string): Promise<void>; emit<D>(eventName: string, data: D): Promise<void>; emit(eventName: string): Promise<void>; broadcast<D>(eventName: string, data: D, opts: GenericObject): Promise<void>; broadcast<D>(eventName: string, data: D, groups: Array<string>): Promise<void>; broadcast<D>(eventName: string, data: D, groups: string): Promise<void>; broadcast<D>(eventName: string, data: D): Promise<void>; broadcast(eventName: string): Promise<void>; broadcastLocal<D>(eventName: string, data: D, opts: GenericObject): Promise<void>; broadcastLocal<D>(eventName: string, data: D, groups: Array<string>): Promise<void>; broadcastLocal<D>(eventName: string, data: D, groups: string): Promise<void>; broadcastLocal<D>(eventName: string, data: D): Promise<void>; broadcastLocal(eventName: string): Promise<void>; ping(): Promise<PongResponses>; ping(nodeID: string | Array<string>, timeout?: number): Promise<PongResponse>; getHealthStatus(): NodeHealthStatus; getLocalNodeInfo(): BrokerNode; getCpuUsage(): Promise<any>; generateUid(): string; hasEventListener(eventName: string): boolean; getEventListener(eventName: string): Array<EventEndpoint>; getConstructorName(obj: any): string; MOLECULER_VERSION: string; PROTOCOL_VERSION: string; [name: string]: any; static MOLECULER_VERSION: string; static PROTOCOL_VERSION: string; static defaultOptions: BrokerOptions; static Promise: PromiseConstructorLike; } class Packet { constructor(type: string, target: string, payload?: any); } namespace Packets { type PROTOCOL_VERSION = "4"; type PACKET_UNKNOWN = "???"; type PACKET_EVENT = "EVENT"; type PACKET_REQUEST = "REQ"; type PACKET_RESPONSE = "RES"; type PACKET_DISCOVER = "DISCOVER"; type PACKET_INFO = "INFO"; type PACKET_DISCONNECT = "DISCONNECT"; type PACKET_HEARTBEAT = "HEARTBEAT"; type PACKET_PING = "PING"; type PACKET_PONG = "PONG"; type PACKET_GOSSIP_REQ = "GOSSIP_REQ"; type PACKET_GOSSIP_RES = "GOSSIP_RES"; type PACKET_GOSSIP_HELLO = "GOSSIP_HELLO"; const PROTOCOL_VERSION: PROTOCOL_VERSION; const PACKET_UNKNOWN: PACKET_UNKNOWN; const PACKET_EVENT: PACKET_EVENT; const PACKET_REQUEST: PACKET_REQUEST; const PACKET_RESPONSE: PACKET_RESPONSE; const PACKET_DISCOVER: PACKET_DISCOVER; const PACKET_INFO: PACKET_INFO; const PACKET_DISCONNECT: PACKET_DISCONNECT; const PACKET_HEARTBEAT: PACKET_HEARTBEAT; const PACKET_PING: PACKET_PING; const PACKET_PONG: PACKET_PONG; const PACKET_GOSSIP_REQ: PACKET_GOSSIP_REQ; const PACKET_GOSSIP_RES: PACKET_GOSSIP_RES; const PACKET_GOSSIP_HELLO: PACKET_GOSSIP_HELLO; interface PacketPayload { ver: PROTOCOL_VERSION; sender: string | null; } interface Packet { type: PACKET_UNKNOWN | PACKET_EVENT | PACKET_DISCONNECT | PACKET_DISCOVER | PACKET_INFO | PACKET_HEARTBEAT | PACKET_REQUEST | PACKET_PING | PACKET_PONG | PACKET_RESPONSE | PACKET_GOSSIP_REQ | PACKET_GOSSIP_RES | PACKET_GOSSIP_HELLO; target?: string; payload: PacketPayload } } class Transporter { constructor(opts?: GenericObject); hasBuiltInBalancer: boolean; init(transit: Transit, messageHandler: (cmd: string, msg: string) => void, afterConnect: (wasReconnect: boolean) => void): void; connect(): Promise<any>; disconnect(): Promise<any>; onConnected(wasReconnect?: boolean): Promise<any>; makeSubscriptions(topics: Array<GenericObject>): Promise<void>; subscribe(cmd: string, nodeID?: string): Promise<void>; subscribeBalancedRequest(action: string): Promise<void>; subscribeBalancedEvent(event: string, group: string): Promise<void>; unsubscribeFromBalancedCommands(): Promise<void>; incomingMessage(cmd: string, msg: Buffer): Promise<void>; receive(cmd: string, data: Buffer): Promise<void>; prepublish(packet: Packet): Promise<void>; publish(packet: Packet): Promise<void>; publishBalancedEvent(packet: Packet, group: string): Promise<void>; publishBalancedRequest(packet: Packet): Promise<void>; send(topic: string, data: Buffer, meta: GenericObject): Promise<void>; getTopicName(cmd: string, nodeID?: string): string; makeBalancedSubscriptions(): Promise<void>; serialize(packet: Packet): Buffer; deserialize(type: string, data: Buffer): Packet; } interface CacherOptions { ttl?: number; keygen?: Function; maxParamsLength?: number; [key: string]: any; } interface MemoryCacherOptions extends CacherOptions { clone?: boolean; } interface MemoryLRUCacherOptions extends MemoryCacherOptions { max?: number; } interface RedisCacherOptions extends CacherOptions { prefix?: string; redis?: GenericObject; redlock?: GenericObject; monitor?: boolean; pingInterval?: number; } namespace Cachers { class Base { constructor(opts?: CacherOptions); opts: CacherOptions; init(broker: ServiceBroker): void; close(): Promise<any>; get(key: string): Promise<null | GenericObject>; getWithTTL(key: string): Promise<null | GenericObject>; set(key: string, data: any, ttl?: number): Promise<any>; del(key: string|Array<string>): Promise<any>; clean(match?: string|Array<string>): Promise<any>; getCacheKey(actionName: string, params: object, meta: object, keys: Array<string> | null) : string; defaultKeygen(actionName: string, params: object | null, meta: object | null, keys: Array<string> | null): string; } class Memory extends Base { constructor(opts?: MemoryCacherOptions); opts: MemoryCacherOptions; } class MemoryLRU extends Base { constructor(opts?: MemoryLRUCacherOptions); opts: MemoryLRUCacherOptions; } class Redis<C = any> extends Base { constructor(opts?: string | RedisCacherOptions); opts: RedisCacherOptions; client: C; prefix: string | null; } } type Cacher<T extends Cachers.Base = Cachers.Base> = T; class Serializer { constructor(opts?: any); init(broker: ServiceBroker): void; serialize(obj: GenericObject, type: string): Buffer; deserialize(buf: Buffer, type: string): GenericObject; } const Serializers: { Base: typeof Serializer, JSON: typeof Serializer, Avro: typeof Serializer, CBOR: typeof Serializer, MsgPack: typeof Serializer, ProtoBuf: typeof Serializer, Thrift: typeof Serializer, Notepack: typeof Serializer, resolve: (type: string | GenericObject | Serializer) => Serializer, }; class BaseValidator { constructor(); init(broker: ServiceBroker): void; compile(schema: GenericObject): Function; validate(params: GenericObject, schema: GenericObject): boolean; middleware(): ((handler: ActionHandler, action: ActionSchema) => any); convertSchemaToMoleculer(schema: any): GenericObject; } class Validator extends BaseValidator {} // deprecated abstract class BaseStrategy { constructor(registry:ServiceRegistry, broker:ServiceBroker, opts?:object); select(list: any[], ctx?: Context): Endpoint; } type ValidatorNames = "Fastest" class RoundRobinStrategy extends BaseStrategy {} class RandomStrategy extends BaseStrategy {} class CpuUsageStrategy extends BaseStrategy {} class LatencyStrategy extends BaseStrategy {} class ShardStrategy extends BaseStrategy {} namespace Strategies { class Base extends BaseStrategy {} class RoundRobin extends RoundRobinStrategy {} class Random extends RandomStrategy {} class CpuUsage extends CpuUsageStrategy {} class Latency extends LatencyStrategy {} class Shard extends ShardStrategy {} } abstract class BaseDiscoverer { constructor(opts?:DiscovererOptions); transit?: Transit; localNode?: BrokerNode; heartbeatTimer: NodeJS.Timeout; checkNodesTimer: NodeJS.Timeout; offlineTimer: NodeJS.Timeout; init(registry: ServiceRegistry): void; stop(): Promise<void>; startHeartbeatTimers(): void; stopHeartbeatTimers(): void; disableHeartbeat(): void; beat(): Promise<void>; checkRemoteNodes(): void; checkOfflineNodes(): void; heartbeatReceived(nodeID:string, payload:GenericObject): void; processRemoteNodeInfo(nodeID:string, payload:GenericObject): BrokerNode; sendHeartbeat(): Promise<void>; discoverNode(nodeID: string): Promise<BrokerNode | void>; discoverAllNodes(): Promise<BrokerNode[] | void>; localNodeReady(): Promise<void>; sendLocalNodeInfo(nodeID: string): Promise<void>; localNodeDisconnected(): Promise<void>; remoteNodeDisconnected(nodeID:string, isUnexpected:boolean): void; } namespace Discoverers { class Base extends BaseDiscoverer {} class Local extends BaseDiscoverer {} class Redis extends BaseDiscoverer {} class Etcd3 extends BaseDiscoverer {} } interface ValidatorOptions { type: string, options?: GenericObject } namespace Validators { class Base extends BaseValidator {} class Fastest extends BaseValidator {} } namespace Transporters { class Base extends Transporter {} class Fake extends Base { } class NATS extends Base { } class MQTT extends Base { } class Redis extends Base { } class AMQP extends Base { } class Kafka extends Base { } class STAN extends Base { } class TCP extends Base { } } namespace Errors { class MoleculerError extends Error { public code: number; public type: string; public data: any; public retryable: boolean; constructor(message: string, code: number, type: string, data: any); constructor(message: string, code: number, type: string); constructor(message: string, code: number); constructor(message: string); } class MoleculerRetryableError extends MoleculerError { } class MoleculerServerError extends MoleculerRetryableError { } class MoleculerClientError extends MoleculerError { } class ServiceNotFoundError extends MoleculerRetryableError { constructor(data: any); } class ServiceNotAvailableError extends MoleculerRetryableError { constructor(data: any); } class RequestTimeoutError extends MoleculerRetryableError { constructor(data: any); } class RequestSkippedError extends MoleculerError { constructor(data: any); } class RequestRejectedError extends MoleculerRetryableError { constructor(data: any); } class QueueIsFullError extends MoleculerRetryableError { constructor(data: any); } class ValidationError extends MoleculerClientError { constructor(message: string, type: string, data: GenericObject); constructor(message: string, type: string); constructor(message: string); } class MaxCallLevelError extends MoleculerError { constructor(data: any); } class ServiceSchemaError extends MoleculerError { constructor(message: string, data: any); } class BrokerOptionsError extends MoleculerError { constructor(message: string, data: any); } class GracefulStopTimeoutError extends MoleculerError { constructor(data: any); } class ProtocolVersionMismatchError extends MoleculerError { constructor(data: any); } class InvalidPacketDataError extends MoleculerError { constructor(data: any); } } interface TransitRequest { action: string; nodeID: string; ctx: Context; resolve: (value: any) => void; reject: (reason: any) => void; stream: boolean; } interface Transit { pendingRequests: Map<string, TransitRequest> nodeID: string; logger: LoggerInstance; connected: boolean; disconnecting: boolean; isReady: boolean; tx: Transporter afterConnect(wasReconnect: boolean): Promise<void>; connect(): Promise<void>; disconnect(): Promise<void>; ready(): Promise<void>; sendDisconnectPacket(): Promise<void>; makeSubscriptions(): Promise<Array<void>>; messageHandler(cmd: string, msg: GenericObject): boolean | Promise<void> | undefined; request(ctx: Context): Promise<void>; sendEvent(ctx: Context): Promise<void>; removePendingRequest(id: string): void; removePendingRequestByNodeID(nodeID: string): void; sendResponse(nodeID: string, id: string, data: GenericObject, err: Error): Promise<void>; sendResponse(nodeID: string, id: string, data: GenericObject): Promise<void>; discoverNodes(): Promise<void>; discoverNode(nodeID: string): Promise<void>; sendNodeInfo(info: BrokerNode, nodeID?: string): Promise<void | Array<void>>; sendPing(nodeID: string, id?: string): Promise<void>; sendPong(payload: GenericObject): Promise<void>; processPong(payload: GenericObject): void; sendHeartbeat(localNode: BrokerNode): Promise<void>; subscribe(topic: string, nodeID: string): Promise<void>; publish(packet: Packet): Promise<void>; } interface ActionCatalogListOptions { onlyLocal?:boolean; onlyAvailable?:boolean; skipInternal?:boolean; withEndpoints?:boolean; } class ServiceRegistry { broker: ServiceBroker; metrics: MetricRegistry; logger: LoggerInstance; opts: BrokerRegistryOptions; StrategyFactory: BaseStrategy; nodes: any; services: any; actions: any; events: any; getServiceList(opts?: ActionCatalogListOptions): ServiceSchema[] } class AsyncStorage { broker: ServiceBroker; store: Map<string, any>; constructor(broker: ServiceBroker); enable(): void; disable(): void; stop(): void; getAsyncId(): number; setSessionData(data: any): void; getSessionData(): any | null; } const CIRCUIT_CLOSE: string; const CIRCUIT_HALF_OPEN: string; const CIRCUIT_OPEN: string; class Vorpal { parse(argv: ReadonlyArray<string>): this; delimiter(value: string): this; show(): this; hide(): this; find(command: string): Vorpal.Command; exec(command: string): Promise<{}>; execSync(command: string): Promise<{}>; log(value: string, ...values: string[]): this; history(id: string): this; localStorage(id: string): object; help(value: (cmd: string) => string): this; pipe(value: (stdout: string) => string): this; use(extension: Vorpal.Extension): this; catch(command: string, description?: string): Vorpal.Catch; command(command: string, description?: string): Vorpal.Command; version(version: string): this; sigint(value: () => void): this; ui: Vorpal.UI; activeCommand: Vorpal.CommandInstance; } namespace Vorpal { interface Args { [key: string]: any; options: { [key: string]: any; }; } interface PromptObject { [key: string]: any; } type Action = (args: Args) => Promise<void>; type Cancel = () => void; class Command { _name: string; _fn: Action; _cancel: Cancel | undefined; alias(command: string): this; parse(value: (command: string, args: Args) => string): this; option(option: string, description: string, autocomplete?: ReadonlyArray<string>): this; types(types: { string?: ReadonlyArray<string> }): this; hidden(): this; remove(): this; help(value: (args: Args) => void): this; validate(value: (args: Args) => boolean | string): this; autocomplete(values: ReadonlyArray<string> | { data: () => Promise<ReadonlyArray<string>> }): this; action(action: Action): this; cancel(cancel: Cancel): this; allowUnknownOptions(): this; } class Catch extends Command { } class Extension { } class UI { delimiter(text?: string): string; input(text?: string): string; imprint(): void; submit(command: string): string; cancel(): void; redraw: { (text: string, ...texts: string[]): void; clear(): void; done(): void; }; } class CommandInstance { log(value: string, ...values: string[]): void; prompt(prompt: object | ReadonlyArray<object>): Promise<PromptObject>; delimiter(value: string): void; } } namespace Utils { function isFunction(func: unknown): func is Function; function isString(str: unknown): str is string; function isObject(obj: unknown): obj is object; function isPlainObject(obj: unknown): obj is object; function isDate(date: unknown): date is Date; function flatten<T>(arr: readonly T[] | readonly T[][]): T[]; function humanize(millis?: number | null): string; function generateToken(): string; function removeFromArray<T>(arr: T[], item: T): T[]; function getNodeID(): string; function getIpList(): string[]; function isPromise<T>(promise: unknown): promise is Promise<T>; function polyfillPromise(P: typeof Promise): void; function clearRequireCache(filename: string): void; function match(text: string, pattern: string): boolean; function deprecate(prop: unknown, msg?: string): void; function safetyObject(obj: unknown, options?: { maxSafeObjectSize?: number }): any; function dotSet<T extends object>(obj: T, path: string, value: unknown): T; function makeDirs(path: string): void; function parseByteString(value: string): number; } } export = Moleculer;
the_stack
import '@aws-cdk/assert-internal/jest'; import { SynthUtils } from '@aws-cdk/assert-internal'; import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; import * as cdk from '@aws-cdk/core'; import * as fc from 'fast-check'; import * as appscaling from '../lib'; import { arbitrary_input_intervals, createScalableTarget } from './util'; describe('step scaling policy', () => { test('alarm thresholds are valid numbers', () => { fc.assert(fc.property( arbitrary_input_intervals(), (intervals) => { const template = setupStepScaling(intervals); const lowerThreshold = template.lowerThreshold; const upperThreshold = template.upperThreshold; return reportFalse( (lowerThreshold === undefined || (lowerThreshold > 0 && lowerThreshold !== Infinity)) && (upperThreshold === undefined || (upperThreshold > 0 && upperThreshold !== Infinity)), lowerThreshold, upperThreshold); }, )); }); test('generated step intervals are valid intervals', () => { fc.assert(fc.property( arbitrary_input_intervals(), (intervals) => { const template = setupStepScaling(intervals); const steps = template.allStepsAbsolute(); return reportFalse(steps.every(step => { return step.MetricIntervalLowerBound! < step.MetricIntervalUpperBound!; }), steps, 'template', JSON.stringify(template, undefined, 2)); }, )); }); test('generated step intervals are nonoverlapping', () => { fc.assert(fc.property( arbitrary_input_intervals(), (intervals) => { const template = setupStepScaling(intervals); const steps = template.allStepsAbsolute(); for (let i = 0; i < steps.length; i++) { const compareTo = steps.slice(i + 1); if (compareTo.some(x => overlaps(steps[i], x))) { return reportFalse(false, steps); } } return true; }, ), { verbose: true }); }); test('all template intervals occur in input array', () => { fc.assert(fc.property( arbitrary_input_intervals(), (intervals) => { const template = setupStepScaling(intervals); const steps = template.allStepsAbsolute(); return steps.every(step => { return reportFalse(intervals.find(interval => { const acceptableLowerBounds = step.MetricIntervalLowerBound === -Infinity ? [undefined, 0] : [undefined, step.MetricIntervalLowerBound]; // eslint-disable-next-line max-len const acceptableUpperBounds = step.MetricIntervalUpperBound === Infinity ? [undefined, Infinity] : [undefined, step.MetricIntervalUpperBound]; return (acceptableLowerBounds.includes(interval.lower) && acceptableUpperBounds.includes(interval.upper)); }) !== undefined, step, intervals); }); }, )); }); test('lower alarm uses lower policy', () => { fc.assert(fc.property( arbitrary_input_intervals(), (intervals) => { const template = setupStepScaling(intervals); const alarm = template.resource(template.lowerAlarm); fc.pre(alarm !== undefined); return reportFalse(alarm.Properties.AlarmActions[0].Ref === template.lowerPolicy, alarm); }, )); }); test('upper alarm uses upper policy', () => { fc.assert(fc.property( arbitrary_input_intervals(), (intervals) => { const template = setupStepScaling(intervals); const alarm = template.resource(template.upperAlarm); fc.pre(alarm !== undefined); return reportFalse(alarm.Properties.AlarmActions[0].Ref === template.upperPolicy, alarm); }, )); }); test('test step scaling on metric', () => { // GIVEN const stack = new cdk.Stack(); const target = createScalableTarget(stack); // WHEN target.scaleOnMetric('Tracking', { metric: new cloudwatch.Metric({ namespace: 'Test', metricName: 'Metric' }), scalingSteps: [ { upper: 0, change: -1 }, { lower: 100, change: +1 }, { lower: 500, change: +5 }, ], }); // THEN expect(stack).toHaveResource('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'StepScaling', ScalingTargetId: { Ref: 'Target3191CF44', }, StepScalingPolicyConfiguration: { AdjustmentType: 'ChangeInCapacity', MetricAggregationType: 'Average', StepAdjustments: [ { MetricIntervalUpperBound: 0, ScalingAdjustment: -1, }, ], }, }); }); test('step scaling from percentile metric', () => { // GIVEN const stack = new cdk.Stack(); const target = createScalableTarget(stack); // WHEN target.scaleOnMetric('Tracking', { metric: new cloudwatch.Metric({ namespace: 'Test', metricName: 'Metric', statistic: 'p99' }), scalingSteps: [ { upper: 0, change: -1 }, { lower: 100, change: +1 }, { lower: 500, change: +5 }, ], }); // THEN expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'StepScaling', StepScalingPolicyConfiguration: { AdjustmentType: 'ChangeInCapacity', MetricAggregationType: 'Average', }, }); expect(stack).toHaveResource('AWS::CloudWatch::Alarm', { ComparisonOperator: 'GreaterThanOrEqualToThreshold', EvaluationPeriods: 1, AlarmActions: [ { Ref: 'TargetTrackingUpperPolicy72CEFA77' }, ], ExtendedStatistic: 'p99', MetricName: 'Metric', Namespace: 'Test', Threshold: 100, }); }); test('step scaling with evaluation period configured', () => { // GIVEN const stack = new cdk.Stack(); const target = createScalableTarget(stack); // WHEN target.scaleOnMetric('Tracking', { metric: new cloudwatch.Metric({ namespace: 'Test', metricName: 'Metric', statistic: 'p99' }), scalingSteps: [ { upper: 0, change: -1 }, { lower: 100, change: +1 }, { lower: 500, change: +5 }, ], evaluationPeriods: 10, metricAggregationType: appscaling.MetricAggregationType.MAXIMUM, }); // THEN expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'StepScaling', StepScalingPolicyConfiguration: { AdjustmentType: 'ChangeInCapacity', MetricAggregationType: 'Maximum', }, }); expect(stack).toHaveResource('AWS::CloudWatch::Alarm', { ComparisonOperator: 'GreaterThanOrEqualToThreshold', EvaluationPeriods: 10, ExtendedStatistic: 'p99', MetricName: 'Metric', Namespace: 'Test', Threshold: 100, }); }); test('step scaling with evaluation period & data points to alarm configured', () => { // GIVEN const stack = new cdk.Stack(); const target = createScalableTarget(stack); // WHEN target.scaleOnMetric('Tracking', { metric: new cloudwatch.Metric({ namespace: 'Test', metricName: 'Metric', statistic: 'p99' }), scalingSteps: [ { upper: 0, change: -1 }, { lower: 100, change: +1 }, { lower: 500, change: +5 }, ], evaluationPeriods: 10, datapointsToAlarm: 6, metricAggregationType: appscaling.MetricAggregationType.MAXIMUM, }); // THEN expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'StepScaling', StepScalingPolicyConfiguration: { AdjustmentType: 'ChangeInCapacity', MetricAggregationType: 'Maximum', }, }); expect(stack).toHaveResource('AWS::CloudWatch::Alarm', { ComparisonOperator: 'GreaterThanOrEqualToThreshold', EvaluationPeriods: 10, DatapointsToAlarm: 6, ExtendedStatistic: 'p99', MetricName: 'Metric', Namespace: 'Test', Threshold: 100, }); }); test('step scaling with invalid datapointsToAlarm throws error', () => { const stack = new cdk.Stack(); const target = createScalableTarget(stack); expect(() => { target.scaleOnMetric('Tracking', { metric: new cloudwatch.Metric({ namespace: 'Test', metricName: 'Metric', statistic: 'p99' }), scalingSteps: [ { upper: 0, change: -1 }, { lower: 100, change: +1 }, { lower: 500, change: +5 }, ], evaluationPeriods: 10, datapointsToAlarm: 0, metricAggregationType: appscaling.MetricAggregationType.MAXIMUM, }); }).toThrow('datapointsToAlarm cannot be less than 1, got: 0'); }); }); /** * Synthesize the given step scaling setup to a template */ function setupStepScaling(intervals: appscaling.ScalingInterval[]) { const stack = new cdk.Stack(); const target = createScalableTarget(stack); target.scaleOnMetric('ScaleInterval', { metric: new cloudwatch.Metric({ namespace: 'Test', metricName: 'Success' }), scalingSteps: intervals, }); return new ScalingStackTemplate(SynthUtils.synthesize(stack).template); } class ScalingStackTemplate { public readonly lowerPolicy = 'TargetScaleIntervalLowerPolicy6F26D597'; public readonly lowerAlarm = 'TargetScaleIntervalLowerAlarm4B5CE869'; public readonly upperPolicy = 'TargetScaleIntervalUpperPolicy7C751132'; public readonly upperAlarm = 'TargetScaleIntervalUpperAlarm69FD1BBB'; constructor(private readonly template: any) { } public get lowerThreshold() { return this.threshold(this.lowerAlarm); } public get upperThreshold() { return this.threshold(this.upperAlarm); } public get lowerSteps() { return this.steps(this.lowerPolicy); } public get upperSteps() { return this.steps(this.upperPolicy); } public allStepsAbsolute() { const ret = new Array<TemplateStep>(); const lowerThreshold = this.lowerThreshold; if (lowerThreshold !== undefined) { ret.push(...this.lowerSteps!.map(x => makeAbsolute(lowerThreshold, x))); } const upperThreshold = this.upperThreshold; if (upperThreshold !== undefined) { ret.push(...this.upperSteps!.map(x => makeAbsolute(upperThreshold, x))); } return ret; } public resource(id: string): object | any { return this.template.Resources[id]; } private threshold(id: string): number | undefined { return apply(this.resource(id), x => x.Properties.Threshold); } private steps(id: string): TemplateStep[] | undefined { return apply(this.resource(id), x => x.Properties.StepScalingPolicyConfiguration.StepAdjustments); } } interface TemplateStep { MetricIntervalLowerBound?: number; MetricIntervalUpperBound?: number; ScalingAdjustment: number; } function makeAbsolute(threshold: number, step: TemplateStep) { return concrete({ MetricIntervalLowerBound: apply(step.MetricIntervalLowerBound, x => x + threshold), MetricIntervalUpperBound: apply(step.MetricIntervalUpperBound, x => x + threshold), ScalingAdjustment: step.ScalingAdjustment, }); } function overlaps(a: TemplateStep, b: TemplateStep) { return (a.MetricIntervalLowerBound! < b.MetricIntervalUpperBound! && a.MetricIntervalUpperBound! > b.MetricIntervalLowerBound!); } function concrete(step: TemplateStep) { return { MetricIntervalLowerBound: ifUndefined(step.MetricIntervalLowerBound, -Infinity), MetricIntervalUpperBound: ifUndefined(step.MetricIntervalUpperBound, Infinity), ScalingAdjustment: step.ScalingAdjustment, }; } function ifUndefined<T>(x: T | undefined, def: T): T { return x !== undefined ? x : def; } function apply<T, U>(x: T | undefined, f: (x: T) => U | undefined): U | undefined { if (x === undefined) { return undefined; } return f(x); } /** * Helper function to print variables in case of a failing property check */ function reportFalse(cond: boolean, ...repr: any[]) { if (!cond) { // eslint-disable-next-line no-console console.error('PROPERTY FAILS ON:', ...repr); } return cond; }
the_stack
import { when } from 'jest-when'; import { initialState } from '../../src/redux/State'; import { cadLog, convertVersionToNumber, createPartialTabInfo, eventListenerActions, extractMainDomain, getAllCookiesForDomain, getContainerExpressionDefault, getHostname, getMatchedExpressions, getSearchResults, getSetting, getStoreId, globExpressionToRegExp, isAnIP, isAWebpage, isChrome, isFirefox, isFirefoxAndroid, isFirefoxNotAndroid, isFirstPartyIsolate, localFileToRegex, matchIPInExpression, parseCookieStoreId, prepareCleanupDomains, prepareCookieDomain, returnMatchedExpressionObject, returnOptionalCookieAPIAttributes, showNotification, sleep, throwErrorNotification, trimDot, undefinedIsTrue, validateExpressionDomain, } from '../../src/services/Libs'; import ipaddr from 'ipaddr.js'; const mockCookie: browser.cookies.Cookie = { domain: 'domain.com', hostOnly: true, httpOnly: true, name: 'blah', path: '/', sameSite: 'no_restriction', secure: true, session: true, storeId: 'default', value: 'test value', }; describe('Library Functions', () => { describe('cadLog()', () => { beforeAll(() => { when(global.browser.runtime.getManifest) .calledWith() .mockReturnValue({ version: '0.12.34' }); }); const origDebug = console.debug; // eslint-disable-line no-console const origError = console.error; // eslint-disable-line no-console const origInfo = console.info; // eslint-disable-line no-console const origLog = console.log; // eslint-disable-line no-console const origWarn = console.warn; // eslint-disable-line no-console afterEach(() => { console.debug = origDebug; // eslint-disable-line no-console console.error = origError; // eslint-disable-line no-console console.info = origInfo; // eslint-disable-line no-console console.log = origLog; // eslint-disable-line no-console console.warn = origWarn; // eslint-disable-line no-console }); const consoleOutput = [] as { type: string; msg: string }[]; const mockedDebug = (msg: string) => consoleOutput.push({ type: 'debug', msg }); const mockedError = (msg: string) => consoleOutput.push({ type: 'error', msg }); const mockedInfo = (msg: string) => consoleOutput.push({ type: 'info', msg }); const mockedLog = (msg: string) => consoleOutput.push({ type: 'log', msg }); const mockedWarn = (msg: string) => consoleOutput.push({ type: 'warn', msg }); beforeEach(() => { console.debug = mockedDebug; // eslint-disable-line no-console console.error = mockedError; // eslint-disable-line no-console console.info = mockedInfo; // eslint-disable-line no-console console.log = mockedLog; // eslint-disable-line no-console console.warn = mockedWarn; // eslint-disable-line no-console consoleOutput.length = 0; }); it('should do nothing if output=false', () => { expect.assertions(1); cadLog({ msg: 'nothing' }, false); expect(consoleOutput.length).toBe(0); }); it('should format the Log Header with manifest version', () => { expect.assertions(1); cadLog({ msg: 'headerTest' }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - headerTest\n' }, ]); }); it('should output to debug when no type is given', () => { expect.assertions(1); cadLog({ msg: 'noType' }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - noType\n' }, ]); }); it('should output to debug when type is debug', () => { expect.assertions(1); cadLog({ type: 'debug', msg: 'debugType' }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - debugType\n' }, ]); }); it('should output to error when type is error', () => { expect.assertions(1); cadLog({ type: 'error', msg: 'errorType' }, true); expect(consoleOutput).toEqual([ { type: 'error', msg: 'CAD_0.12.34 - error - errorType\n' }, ]); }); it('should output to info when type is info', () => { expect.assertions(1); cadLog({ type: 'info', msg: 'infoType' }, true); expect(consoleOutput).toEqual([ { type: 'info', msg: 'CAD_0.12.34 - info - infoType\n' }, ]); }); it('should output to log when type is log', () => { expect.assertions(1); cadLog({ type: 'log', msg: 'logType' }, true); expect(consoleOutput).toEqual([ { type: 'log', msg: 'CAD_0.12.34 - log - logType\n' }, ]); }); it('should output to warn when type is warn', () => { expect.assertions(1); cadLog({ type: 'warn', msg: 'warnType' }, true); expect(consoleOutput).toEqual([ { type: 'warn', msg: 'CAD_0.12.34 - warn - warnType\n' }, ]); }); it('should default back to debug type when invalid type is given', () => { expect.assertions(1); cadLog({ type: 'invalid', msg: 'invalidType' }, true); expect(consoleOutput).toEqual([ { type: 'error', msg: 'CAD_0.12.34 - Invalid Console Output Type given [ invalid ]. Using [debug] instead.', }, { type: 'debug', msg: 'CAD_0.12.34 - debug - invalidType\n' }, ]); }); it('should display supplied string accordingly', () => { expect.assertions(1); cadLog({ msg: 'withObject', x: 'test.' }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - withObject\ntest.' }, ]); }); it('should attempt to parse function as string for display', () => { expect.assertions(1); cadLog({ msg: 'objectFunction', x: RegExp.toString }, true); expect(consoleOutput).toEqual([ { type: 'warn', msg: 'CAD_0.12.34 - Received unexpected typeof [ function ]. Attempting to display it...', }, { type: 'debug', msg: 'CAD_0.12.34 - debug - objectFunction\nfunction toString() { [native code] }', }, ]); }); it('should parse object for display', () => { expect.assertions(1); cadLog({ msg: 'objectString', x: { a: 'abc' } }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - objectString\n{\n "a": "abc"\n}', }, ]); }); it('should parse number as string.', () => { expect.assertions(1); cadLog({ msg: 'numberString', x: 123 }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - numberString\n123' }, ]); }); it('should parse boolean as string.', () => { expect.assertions(1); cadLog({ msg: 'booleanString', x: true }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - booleanString\ntrue' }, ]); }); it('should parse string as string.', () => { expect.assertions(1); cadLog({ msg: 'stringString', x: 'test' }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - stringString\ntest' }, ]); }); it('should parse undefined as empty string.', () => { expect.assertions(1); cadLog({ msg: 'undefinedString', x: undefined }, true); expect(consoleOutput).toEqual([ { type: 'debug', msg: 'CAD_0.12.34 - debug - undefinedString\n' }, ]); }); it('should not output to console on empty input object (no message), even if output=true', () => { expect.assertions(1); cadLog({}, true); expect(consoleOutput.length).toEqual(0); }); }); describe('convertVersionToNumber()', () => { it('should return 123 from 1.2.3', () => { const results = convertVersionToNumber('1.2.3'); expect(results).toEqual(123); }); it('should return -1 from ()', () => { const results = convertVersionToNumber(); expect(results).toEqual(-1); }); it('should return 300 from 3.0.0', () => { const results = convertVersionToNumber('3.0.0'); expect(results).toEqual(300); }); }); describe('createPartialTabInfo()', () => { const testTab: Partial<browser.tabs.Tab> = { active: true, cookieStoreId: 'firefox-default', discarded: false, height: 123, hidden: false, highlighted: false, id: 1, incognito: false, index: 0, pinned: false, status: 'complete', title: 'TabTitle', url: 'https://test.cad', width: 321, windowId: 1, }; it('should extract information relevant to debug in Firefox', () => { expect(createPartialTabInfo(testTab)).toMatchObject({ cookieStoreId: 'firefox-default', discarded: false, id: 1, incognito: false, status: 'complete', url: 'https://test.cad', windowId: 1, }); }); it('should extract information relevant to debug in Chrome', () => { expect( createPartialTabInfo({ ...testTab, cookieStoreId: undefined }), ).toMatchObject({ discarded: false, id: 1, incognito: false, status: 'complete', url: 'https://test.cad', windowId: 1, }); }); }); describe('eventListenerActions()', () => { it('should do nothing if an event was not passed in', () => { expect(() => { eventListenerActions( undefined as any, Function, EventListenerAction.ADD, ); }).not.toThrowError(); // Unexpected error would be TypeError: "cannot read property 'hasListener' of undefined" }); it('should do nothing if an "event" passed in is not an Event Listener', () => { expect(() => { eventListenerActions({} as any, Function, EventListenerAction.REMOVE); }).not.toThrowError(); }); it('should add the event listener', () => { eventListenerActions( browser.cookies.onChanged, Function, EventListenerAction.ADD, ); expect( global.browser.cookies.onChanged.addListener, ).toHaveBeenCalledTimes(1); }); it('should not add the event listener again if it already exists', () => { when(global.browser.cookies.onChanged.hasListener) .calledWith(expect.any(Function)) .mockReturnValue(true); eventListenerActions( browser.cookies.onChanged, Function, EventListenerAction.ADD, ); expect( global.browser.cookies.onChanged.addListener, ).not.toHaveBeenCalled(); }); it('should remove the listener', () => { when(global.browser.cookies.onChanged.hasListener) .calledWith(expect.any(Function)) .mockReturnValue(true); eventListenerActions( browser.cookies.onChanged, Function, EventListenerAction.REMOVE, ); expect( global.browser.cookies.onChanged.removeListener, ).toHaveBeenCalledTimes(1); }); it('should not remove a non-existent listener', () => { when(global.browser.cookies.onChanged.hasListener) .calledWith(expect.any(Function)) .mockReturnValue(false); eventListenerActions( browser.cookies.onChanged, Function, EventListenerAction.REMOVE, ); expect( global.browser.cookies.onChanged.removeListener, ).not.toHaveBeenCalled(); }); }); describe('extractMainDomain()', () => { it('should return itself from file:///home/user/file.html', () => { expect(extractMainDomain('file:///home/user/file.html')).toEqual( 'file:///home/user/file.html', ); }); it('should return workplace.com from work-12345678.workplace.com', () => { expect(extractMainDomain('work-12345678.workplace.com')).toEqual( 'workplace.com', ); }); it('should return domain.com from domain.com', () => { expect(extractMainDomain('domain.com')).toEqual('domain.com'); }); it('should return domain.com from sub.domain.com', () => { expect(extractMainDomain('sub.domain.com')).toEqual('domain.com'); }); it('should return domain.com from sub.sub.domain.com', () => { expect(extractMainDomain('sub.sub.domain.com')).toEqual('domain.com'); }); it('should return domain.com from sub.sub.sub.domain.com', () => { expect(extractMainDomain('sub.sub.sub.domain.com')).toEqual('domain.com'); }); it('should return example.co.uk from sub.example.co.uk', () => { expect(extractMainDomain('sub.example.co.uk')).toEqual('example.co.uk'); }); it('should return example.co.uk. from sub.example.com.uk.', () => { expect(extractMainDomain('sub.example.co.uk.')).toEqual('example.co.uk.'); }); it('should return example.com.br from sub.example.com.br', () => { expect(extractMainDomain('sub.example.com.br')).toEqual('example.com.br'); }); it('should return the ip address from an ip address', () => { expect(extractMainDomain('127.0.0.1')).toEqual('127.0.0.1'); }); it('should return the srv-test01 from an srv-test01', () => { expect(extractMainDomain('srv-test01')).toEqual('srv-test01'); }); it('should return the test.i2p from an test.i2p', () => { expect(extractMainDomain('test.i2p')).toEqual('test.i2p'); }); it('should return domain.com. from .domain.com.', () => { expect(extractMainDomain('.domain.com.')).toEqual('domain.com.'); }); it('should return domain.com from .domain.com', () => { expect(extractMainDomain('.domain.com')).toEqual('domain.com'); }); it('should return local from local', () => { expect(extractMainDomain('local')).toEqual('local'); }); it('should return nothing on empty string', () => { expect(extractMainDomain('')).toEqual(''); }); }); describe('getAllCookiesForDomain()', () => { beforeAll(() => { when(global.browser.cookies.getAll) .calledWith({ domain: expect.any(String), storeId: 'firefox-default' }) .mockResolvedValue([] as never); when(global.browser.cookies.getAll) .calledWith({ domain: expect.any(String), firstPartyDomain: expect.any(String), storeId: 'firefox-default', }) .mockResolvedValue([] as never); when(global.browser.cookies.getAll) .calledWith({ storeId: 'firefox-default' }) .mockResolvedValue([ testCookie, { ...testCookie, domain: '', path: '/test/' }, ] as never); when(global.browser.cookies.getAll) .calledWith({ storeId: 'firefox-default', firstPartyDomain: undefined }) .mockResolvedValue([ testCookie, { ...testCookie, domain: '', path: '/test/' }, ] as never); when(global.browser.cookies.getAll) .calledWith({ domain: '' }) .mockResolvedValue([] as never); when(global.browser.cookies.getAll) .calledWith({ domain: 'domain.com', storeId: 'firefox-default' }) .mockResolvedValue([testCookie] as never); when(global.browser.cookies.getAll) .calledWith({ domain: '10.1.1.1', firstPartyDomain: '10.1.1.1', storeId: 'firefox-default', }) .mockResolvedValue([testCookie] as never); }); const testCookie: browser.cookies.Cookie = { domain: 'domain.com', hostOnly: true, httpOnly: true, name: 'blah', path: '/', sameSite: 'no_restriction', secure: true, session: true, storeId: 'firefox-default', value: 'test value', }; const sampleTab: browser.tabs.Tab = { active: true, cookieStoreId: 'firefox-default', discarded: false, hidden: false, highlighted: false, incognito: false, index: 0, isArticle: false, isInReaderMode: false, lastAccessed: 12345678, pinned: false, selected: true, url: 'https://www.example.com', windowId: 1, }; const chromeState: State = { ...initialState, cache: { browserDetect: browserName.Chrome, }, }; const firefoxState: State = { ...initialState, cache: { browserDetect: browserName.Firefox, }, }; it('should do nothing if url is an internal page', async () => { const result = await getAllCookiesForDomain(chromeState, { ...sampleTab, url: 'about:home', }); const result2 = await getAllCookiesForDomain(chromeState, { ...sampleTab, url: 'chrome:newtab', }); expect(result).toBeUndefined(); expect(result2).toBeUndefined(); }); it('should do nothing if url is empty string', async () => { const result = await getAllCookiesForDomain(chromeState, { ...sampleTab, url: '', }); expect(result).toBeUndefined(); }); it('should do nothing if url is undefined', async () => { const result = await getAllCookiesForDomain(chromeState, { ...sampleTab, url: undefined, }); expect(result).toBeUndefined(); }); it('should do nothing if url is not valid', async () => { const result = await getAllCookiesForDomain(firefoxState, { ...sampleTab, url: 'bad', }); expect(result).toBeUndefined(); }); // Test in Chrome, though both FF and Chrome should return same thing. it('should work on local files', async () => { const result = await getAllCookiesForDomain(chromeState, { ...sampleTab, url: 'file:///test/file.html', }); expect(result).toStrictEqual( expect.arrayContaining([{ ...testCookie, domain: '', path: '/test/' }]), ); }); it('should fetch additional FPI Cookies (use_site enabled) as needed', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: '', }) .mockRejectedValueOnce(new Error('firstPartyDomain') as never); when(global.browser.cookies.getAll) .calledWith({ domain: 'domain.com', firstPartyDomain: 'domain.com', storeId: 'firefox-default', }) .mockResolvedValue([{ ...testCookie, name: 'old FPI' }] as never); when(global.browser.cookies.getAll) .calledWith({ domain: 'domain.com', firstPartyDomain: '(https,domain.com)', storeId: 'firefox-default', }) .mockResolvedValue([{ ...testCookie, name: 'FPI_use_case' }] as never); const result = await getAllCookiesForDomain(firefoxState, { ...sampleTab, url: 'https://domain.com', }); expect(result).toStrictEqual([ { ...testCookie, name: 'old FPI' }, { ...testCookie, name: 'FPI_use_case' }, ]); }); it('should fetch additional FPI Cookies (use_site enabled) with a port in URL as needed', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: '', }) .mockRejectedValueOnce(new Error('firstPartyDomain') as never); when(global.browser.cookies.getAll) .calledWith({ domain: '10.1.1.1', firstPartyDomain: '10.1.1.1', storeId: 'firefox-default', }) .mockResolvedValue([testCookie] as never); when(global.browser.cookies.getAll) .calledWith({ domain: '10.1.1.1', firstPartyDomain: '(https,10.1.1.1)', storeId: 'firefox-default', }) .mockResolvedValue([] as never); when(global.browser.cookies.getAll) .calledWith({ domain: '10.1.1.1', firstPartyDomain: '(https,10.1.1.1,8080)', storeId: 'firefox-default', }) .mockResolvedValue([ { ...testCookie, name: 'FPI_usecase_port' }, ] as never); const result = await getAllCookiesForDomain(firefoxState, { ...sampleTab, url: 'https://10.1.1.1:8080', }); expect(result).toStrictEqual([ testCookie, { ...testCookie, name: 'FPI_usecase_port' }, ]); }); }); describe('getContainerExpressionDefault()', () => { const mockExpression: Expression = { expression: '', listType: ListType.WHITE, storeId: '', }; it('should return default expression if list does not contain storeId given', () => { expect( getContainerExpressionDefault(initialState, 'default', ListType.WHITE), ).toEqual(mockExpression); }); it('should return default expression if existing list does not contain default expression key', () => { expect( getContainerExpressionDefault( { ...initialState, lists: { default: [mockExpression] } }, 'default', ListType.WHITE, ), ).toEqual(mockExpression); }); it('should return customized default expression if existing list contains default expression key', () => { expect( getContainerExpressionDefault( { ...initialState, lists: { default: [ { expression: `_Default:${ListType.WHITE}`, cleanSiteData: [SiteDataType.PLUGINDATA], listType: ListType.WHITE, storeId: 'default', }, ], }, }, 'default', ListType.WHITE, ), ).toEqual( expect.objectContaining({ cleanSiteData: [SiteDataType.PLUGINDATA] }), ); }); it('should return customized default expression for non-default container from default container if non-default container is missing defaults', () => { expect( getContainerExpressionDefault( { ...initialState, settings: { ...initialState.settings, [SettingID.CONTEXTUAL_IDENTITIES]: { name: SettingID.CONTEXTUAL_IDENTITIES, value: true, }, }, lists: { default: [ { expression: `_Default:${ListType.WHITE}`, cleanSiteData: [SiteDataType.PLUGINDATA], listType: ListType.WHITE, storeId: 'default', }, ], }, }, 'firefox-container-1', ListType.WHITE, ), ).toEqual( expect.objectContaining({ cleanSiteData: [SiteDataType.PLUGINDATA] }), ); }); it('should return default expression for non-default container if non-default and default container is missing defaults', () => { expect( getContainerExpressionDefault( { ...initialState, settings: { ...initialState.settings, [SettingID.CONTEXTUAL_IDENTITIES]: { name: SettingID.CONTEXTUAL_IDENTITIES, value: true, }, }, }, 'firefox-container-1', ListType.WHITE, ), ).toEqual(mockExpression); }); }); describe('getHostname()', () => { it('should return en.wikipedia.org from https://en.wikipedia.org/wiki/Cat', () => { expect(getHostname('https://en.wikipedia.org/wiki/Cat')).toEqual( 'en.wikipedia.org', ); }); it('should return yahoo.com from http://yahoo.com', () => { expect(getHostname('http://yahoo.com')).toEqual('yahoo.com'); }); it('should return scotiaonline.scotiabank.com from https://www1.scotiaonline.scotiabank.com/online/authentication/authentication.bns', () => { expect( getHostname( 'https://www1.scotiaonline.scotiabank.com/online/authentication/authentication.bns', ), ).toEqual('scotiaonline.scotiabank.com'); }); it('should return mint.com from https://wwws.mint.com', () => { expect(getHostname('https://wwws.mint.com')).toEqual('mint.com'); }); it('should return file:///home/user/folder from file:///home/user/folder/file.html', () => { expect(getHostname('file:///home/user/folder/file.html')).toEqual( 'file:///home/user/folder', ); }); it('should return file:///C: from file:///C:/test.html', () => { expect(getHostname('file:///C:/test.html')).toEqual('file:///C:'); }); it('should return an empty string from empty URLs', () => { expect(getHostname('')).toEqual(''); }); it('should return an empty string from invalid URLs', () => { expect(getHostname('test')).toEqual(''); }); }); describe('getMatchedExpressions()', () => { const defaultExpression: Expression = { expression: '*.expression.com', listType: ListType.WHITE, storeId: 'default', }; const lists: StoreIdToExpressionList = { default: [ defaultExpression, { ...defaultExpression, expression: '192.168.1.1', }, { ...defaultExpression, expression: 'fd12:3456:789a:1::1', }, { ...defaultExpression, expression: '192.168.10.0/24', }, { ...defaultExpression, expression: 'fd12:3456:7890:1::/64', }, { ...defaultExpression, expression: '192.168.10.256/22', }, ], }; it('should return empty array if lists have no storeId', () => { expect(getMatchedExpressions(lists, 'test')).toEqual([]); }); it('should return entire storeId list if no input was given.', () => { expect(getMatchedExpressions(lists, 'default')).toEqual([ ...lists['default'], ]); }); it('should return entire storeId list if input was only whitespaces', () => { expect(getMatchedExpressions(lists, 'default', ' ')).toEqual([ ...lists['default'], ]); }); it('should not match 192.168.1.1 with 0xc0.168.1.1 as not valid IPv4 Four-Part Decimal format', () => { // 0xc0 = 192 expect(getMatchedExpressions(lists, 'default', '0xc0.168.1.1')).toEqual( [], ); }); it('should return expressions with matching IPv4 Address', () => { expect(getMatchedExpressions(lists, 'default', '192.168.1.1')).toEqual([ lists['default'][1], ]); }); it('should return expressions with matching IPv6 Address', () => { expect( getMatchedExpressions(lists, 'default', 'fd12:3456:789a:1::1'), ).toEqual([lists['default'][2]]); }); it('should return expressions with matching IPv4 Address with CIDR', () => { expect(getMatchedExpressions(lists, 'default', '192.168.10.5')).toEqual([ lists['default'][3], ]); }); it('should return expressions with matching IPv6 Address with CIDR', () => { expect( getMatchedExpressions(lists, 'default', 'fd12:3456:7890:1:5555::'), ).toEqual([lists['default'][4]]); }); it('should return partial matched expressions when searching', () => { expect(getMatchedExpressions(lists, 'default', 'express', true)).toEqual([ lists['default'][0], ]); }); }); describe('getSearchResults()', () => { it('should return false if string is not matched', () => { expect(getSearchResults('*.expression.com', 'test')).toEqual(false); }); it('should return true if string was partially matched', () => { expect(getSearchResults('*.expression.com', 'express')).toEqual(true); }); it('should return true if string was exactly matched', () => { expect(getSearchResults('test', 'test')).toEqual(true); }); it('should return false if string is invalid regex', () => { expect(getSearchResults('abc(x', 'abc')).toEqual(false); }); }); describe('getSetting()', () => { it('should return value of false for activeMode in default settings', () => { expect(getSetting(initialState, SettingID.ACTIVE_MODE)).toEqual(false); }); }); describe('getStoreId()', () => { const contextualIdentitiesFalseChrome = { ...initialState, cache: { browserDetect: browserName.Chrome, }, settings: { [SettingID.CONTEXTUAL_IDENTITIES]: { id: 7, name: SettingID.CONTEXTUAL_IDENTITIES, value: false, }, }, }; const contextualIdentitiesFalseFF = { ...initialState, cache: { browserDetect: browserName.Firefox, }, settings: { [SettingID.CONTEXTUAL_IDENTITIES]: { id: 7, name: SettingID.CONTEXTUAL_IDENTITIES, value: false, }, }, }; const contextualIdentitiesTrue = { ...initialState, cache: { browserDetect: browserName.Firefox, }, settings: { [SettingID.CONTEXTUAL_IDENTITIES]: { id: 7, name: SettingID.CONTEXTUAL_IDENTITIES, value: true, }, }, }; // Default storeIds it('should return default from firefox-default', () => { expect( getStoreId(contextualIdentitiesFalseFF, 'firefox-default'), ).toEqual('default'); }); it('should return default from Chrome and storeId 0', () => { expect(getStoreId(contextualIdentitiesFalseChrome, '0')).toEqual( 'default', ); }); it('should return default from Chrome and storeId 0', () => { expect( getStoreId( { ...contextualIdentitiesFalseChrome, cache: { browserDetect: browserName.Opera, }, }, '0', ), ).toEqual('default'); }); // Private storeIds it('should return firefox-private from Firefox and storeId firefox-private (private)', () => { expect( getStoreId(contextualIdentitiesFalseFF, 'firefox-private'), ).toEqual('firefox-private'); }); it('should return firefox-private from Firefox and storeId firefox-private (private) with containers', () => { expect(getStoreId(contextualIdentitiesTrue, 'firefox-private')).toEqual( 'firefox-private', ); }); it('should return private from Chrome and storeId 1 (private)', () => { expect(getStoreId(contextualIdentitiesFalseChrome, '1')).toEqual( 'private', ); }); // Containers it('should return firefox-container-1 from Firefox and Containers on', () => { expect( getStoreId(contextualIdentitiesTrue, 'firefox-container-1'), ).toEqual('firefox-container-1'); }); it('should return default from Firefox and storeId firefox-container-1 with Containers off', () => { expect( getStoreId(contextualIdentitiesFalseFF, 'firefox-container-1'), ).toEqual('default'); }); }); describe('globExpressionToRegExp', () => { it('should match example.com for example.com', () => { const regExp = new RegExp(globExpressionToRegExp('example.com')); expect(regExp.test('example.com')).toEqual(true); }); it('should not match badexample.com for example.com', () => { const regExp = new RegExp(globExpressionToRegExp('example.com')); expect(regExp.test('badexample.com')).toEqual(false); }); it('should match example.com for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect(regExp.test('example.com')).toEqual(true); }); it('should match a.example.com for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect(regExp.test('a.example.com')).toEqual(true); }); it('should match a.b.example.com for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect(regExp.test('a.b.example.com')).toEqual(true); }); it('should match a.b-c.example.com for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect(regExp.test('a.b-c.example.com')).toEqual(true); }); it('should match a.b_c.example.com for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect(regExp.test('a.b_c.example.com')).toEqual(true); }); it('should match sub-with-strage_chars.example.another.sub.example.com for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect( regExp.test('sub-with-strage_chars.example.another.sub.example.com'), ).toEqual(true); }); it('should not match badexample.com for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect(regExp.test('badexample.com')).toEqual(false); }); it('should not match bad.example.com.others.org for *.example.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.example.com')); expect(regExp.test('bad.example.com.others.org')).toEqual(false); }); it('should equal ^.*$ for just *', () => { const regExp = new RegExp(globExpressionToRegExp('*')); expect(regExp.toString()).toEqual('/^.*$/'); }); it('should match github.com with git*b.com', () => { const regExp = new RegExp(globExpressionToRegExp('git*b.com')); expect(regExp.test('github.com')).toEqual(true); }); it('should match sub.gitlab.com with *.git*b.com', () => { const regExp = new RegExp(globExpressionToRegExp('*.git*b.com')); expect(regExp.test('sub.gitlab.com')).toEqual(true); }); it('should match [2a03:4000:6:310e:216:3eff:fe53:99b3] with [*]', () => { const regExp = new RegExp(globExpressionToRegExp('[*]')); expect(regExp.test('[2a03:4000:6:310e:216:3eff:fe53:99b3]')).toEqual( true, ); }); it('should match [2a03:4000:6:310e:216:3eff:fe53:99b3] with itself', () => { const regExp = new RegExp( globExpressionToRegExp('[2a03:4000:6:310e:216:3eff:fe53:99b3]'), ); expect(regExp.test('[2a03:4000:6:310e:216:3eff:fe53:99b3]')).toEqual( true, ); }); it('should match github.com with /^git[hub]{3}.com$/', () => { const regExp = new RegExp(globExpressionToRegExp('/^git[hub]{3}.com$/')); expect(regExp.test('github.com')).toEqual(true); }); it('should escape all backslash properly. (should only fail on pre-3.6.0)', () => { expect(globExpressionToRegExp('test\\abc')).toEqual('^test\\\\abc$'); }); it('should parse *. only in the beginning as (^|.). Otherwise as wildcard before dot.', () => { const regExp = new RegExp(globExpressionToRegExp('*.test*.com')); expect(regExp.test('sub.testcom.com')).toEqual(true); expect(regExp.test('tests.com')).toEqual(true); expect(regExp.test('test.com')).toEqual(true); expect(regExp.test('a.test.com')).toEqual(true); }); }); describe('isAnIP()', () => { it('should return false from https://work-12345678.workplace.com', () => { expect(isAnIP('https://work-12345678.workplace.com')).toEqual(false); }); it('should return false from https://en.wikipedia.org/wiki/Cat', () => { expect(isAnIP('https://en.wikipedia.org/wiki/Cat')).toEqual(false); }); it('should return false from http://yahoo.com', () => { expect(isAnIP('http://yahoo.com')).toEqual(false); }); it('should return false from random', () => { expect(isAnIP('random')).toEqual(false); }); it('should return false from extension page', () => { expect(isAnIP('moz-extension://test/settings/settings.html')).toEqual( false, ); }); it('should return true from http ip', () => { expect(isAnIP('http://192.168.1.1/')).toEqual(true); }); it('should return true from https ip', () => { expect(isAnIP('https://192.168.1.1/')).toEqual(true); }); it('should return true from IPv6 Address', () => { expect(isAnIP('https://[2607:f8b0:4006:81a:0:0:0:200e]')).toEqual(true); }); it('should return true from Google DNS IPv6 Address', () => { expect(isAnIP('https://[2001:4860:4860::8888]')).toEqual(true); }); it('should return false from undefined', () => { expect(isAnIP(undefined)).toEqual(false); }); }); describe('isAWebpage()', () => { it('should return true from https://en.wikipedia.org/wiki/Cat', () => { expect(isAWebpage('https://en.wikipedia.org/wiki/Cat')).toEqual(true); }); it('should return true from http://yahoo.com', () => { expect(isAWebpage('http://yahoo.com')).toEqual(true); }); it('should return false from random', () => { expect(isAWebpage('random')).toEqual(false); }); it('should return false from extension page', () => { expect(isAWebpage('moz-extension://test/settings/settings.html')).toEqual( false, ); }); it('should return true from local file file:///home/user/test.html', () => { expect(isAWebpage('file:///home/user/test.html')).toEqual(true); }); it('should return false from undefined', () => { expect(isAWebpage(undefined)).toEqual(false); }); }); describe('isChrome()', () => { it('should return false if browserDetect is undefined', () => { expect(isChrome({})).toBe(false); }); it('should return false if browserDetect is not Chrome', () => { expect(isChrome({ browserDetect: browserName.Unknown })).toBe(false); }); it('should return true if browserDetect is Chrome', () => { expect(isChrome({ browserDetect: browserName.Chrome })).toBe(true); }); }); describe('isFirefox()', () => { it('should return false if browserDetect is undefined', () => { expect(isFirefox({})).toBe(false); }); it('should return false if browserDetect is not Firefox', () => { expect(isFirefox({ browserDetect: browserName.Unknown })).toBe(false); }); it('should return true if browserDetect is Firefox', () => { expect(isFirefox({ browserDetect: browserName.Firefox })).toBe(true); }); }); describe('isFirefoxAndroid()', () => { it('should return false if platformOs is undefined', () => { expect(isFirefoxAndroid({})).toBe(false); }); it('should return false if platformOs is not android', () => { expect( isFirefoxAndroid({ browserDetect: browserName.Unknown, platformOs: 'linux', }), ).toBe(false); }); it('should return true if platformOs is android', () => { expect( isFirefoxAndroid({ browserDetect: browserName.Firefox, platformOs: 'android', }), ).toBe(true); }); }); describe('isFirefoxNotAndroid()', () => { it('should return false if platformOs is undefined', () => { expect(isFirefoxNotAndroid({ browserDetect: browserName.Unknown })).toBe( false, ); }); it('should return true if platformOs is not android', () => { expect( isFirefoxNotAndroid({ browserDetect: browserName.Firefox, platformOs: 'linux', }), ).toBe(true); }); it('should return false if platformOs is android', () => { expect( isFirefoxNotAndroid({ browserDetect: browserName.Firefox, platformOs: 'android', }), ).toBe(false); }); }); describe('isFirstPartyIsolate()', () => { beforeEach(() => { when(global.browser.cookies.getAll) .calledWith({ domain: '' }) .mockResolvedValueOnce([] as never) .mockRejectedValueOnce(new Error('firstPartyDomain') as never) .mockRejectedValueOnce(new Error('Error') as never); }); it('should return false if no error was caught', () => { return expect(isFirstPartyIsolate()).resolves.toEqual(false); }); it('should return true if error was caught and message contained "firstPartyDomain"', () => { return expect(isFirstPartyIsolate()).resolves.toEqual(true); }); it('should return false if error was caught and message did not contain "firstPartyIsolate"', () => { return expect(isFirstPartyIsolate()).resolves.toEqual(false); }); }); describe('localFileToRegex()', () => { it('should return itself if not a local file url (https://example.com)', () => { expect(localFileToRegex('https://example.com')).toEqual( 'https://example.com', ); }); it('should return an escaped file url from url with RegExp special characters', () => { expect(localFileToRegex('file:///home/[u]ser')).toEqual( 'file:///home/\\[u\\]ser', ); }); it('should return empty string from empty hostname', () => { expect(localFileToRegex('')).toEqual(''); }); }); describe('matchIPInExpression()', () => { const ipv4Test = ipaddr.parse('1.1.1.1'); it('should return undefined if Expression is not an IP', () => { expect(matchIPInExpression('test', ipv4Test)).toBeUndefined(); }); it('should return false if IP type is mismatched', () => { expect(matchIPInExpression('fd12:3456:7890:1:5555::', ipv4Test)).toEqual( false, ); }); it('should return undefined if CIDR notation format is not as expected', () => { expect(matchIPInExpression('1.1/1/1', ipv4Test)).toBeUndefined(); }); }); describe('parseCookieStoreId()', () => { it('should return default if contextualIdentities is false', () => { expect(parseCookieStoreId(false, 'abcde')).toEqual('default'); }); it('should return default if contextualIdentities is true and cookieStoreId is "firefox-default"', () => { expect(parseCookieStoreId(true, 'firefox-default')).toEqual('default'); }); it('should return specified cookieStoreId if contextualIdentities is true and cookieStoreId is not "firefox-default"', () => { expect(parseCookieStoreId(true, 'test-container')).toEqual( 'test-container', ); }); it('should return default if contextualIdentities is true but cookieStoreId was undefined', () => { expect(parseCookieStoreId(true, undefined)).toEqual('default'); }); }); describe('prepareCleanupDomains()', () => { it('should return empty array for empty domain', () => { expect(prepareCleanupDomains('', browserName.Firefox)).toEqual([]); }); it('should return empty array for domains with only whitespaces', () => { expect(prepareCleanupDomains(' ', browserName.Firefox)).toEqual([]); }); it('should return cleanup domains from www.example.com', () => { expect( prepareCleanupDomains('www.example.com', browserName.Firefox), ).toEqual(['www.example.com', '.www.example.com']); }); it('should return cleanup domains from .example.com', () => { expect( prepareCleanupDomains('.example.com', browserName.Firefox), ).toEqual([ 'example.com', '.example.com', 'www.example.com', '.www.example.com', ]); }); it('should return cleanup domains from example.com', () => { expect( prepareCleanupDomains('example.com', browserName.Firefox), ).toEqual([ 'example.com', '.example.com', 'www.example.com', '.www.example.com', ]); }); it('should return cleanup domains from example.com for Chrome', () => { expect(prepareCleanupDomains('example.com', browserName.Chrome)).toEqual([ 'http://example.com', 'https://example.com', 'http://.example.com', 'https://.example.com', 'http://www.example.com', 'https://www.example.com', 'http://.www.example.com', 'https://.www.example.com', ]); }); }); describe('prepareCookieDomain()', () => { it('should return https://google.com', () => { expect( prepareCookieDomain({ ...mockCookie, domain: 'google.com', path: '/', secure: true, }), ).toEqual('https://google.com/'); }); it('should return a wrapped ivp6 ip cookie domain in brackets', () => { expect( prepareCookieDomain({ ...mockCookie, domain: '2001:0db8:85a3:0000:0000:8a2e:0370:7334', path: '/', secure: true, }), ).toEqual('https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/'); }); it('should return http://google.com with a removed leading .', () => { expect( prepareCookieDomain({ ...mockCookie, domain: '.google.com', path: '/test', secure: false, }), ).toEqual('http://google.com/test'); }); it('should return local file path for cookie from local file', () => { expect( prepareCookieDomain({ ...mockCookie, domain: '', path: '/home/user' }), ).toEqual('file:///home/user'); }); it('should return domain ending with a dot if supplied', () => { expect( prepareCookieDomain({ ...mockCookie, domain: 'example.com.', secure: true, }), ).toEqual('https://example.com./'); }); }); describe('returnMatchedExpressionObject()', () => { const state: State = { ...initialState, lists: { default: [ { expression: '*.expression.com', listType: ListType.WHITE, storeId: 'default', }, ], }, }; it('should return a matched expression', () => { const results = returnMatchedExpressionObject( state, 'default', 'expression.com', ); expect(results).toEqual( expect.objectContaining({ expression: '*.expression.com' }), ); }); it('should return undefined', () => { const results = returnMatchedExpressionObject( state, 'firefox-container-1', 'expression.com', ); expect(results).toEqual(undefined); }); }); describe('returnOptionalCookieAPIAttributes()', () => { it('should return an object with an undefined firstPartyDomain if browser was Firefox and firstPartyDomain was not already defined.', () => { const state = { ...initialState, cache: { browserDetect: browserName.Firefox, }, }; const cookieAPIAttributes = { ...mockCookie, domain: 'example.com', }; const results = returnOptionalCookieAPIAttributes( state, cookieAPIAttributes, ); expect(results).toEqual( expect.objectContaining({ domain: 'example.com', firstPartyDomain: undefined, }), ); }); it('should return an object the same object with a firstPartyDomain if browser was firefox and firstPartyDomain was given', () => { const state = { ...initialState, cache: { browserDetect: browserName.Firefox, }, }; const cookieAPIAttributes = { ...mockCookie, domain: 'example.com', firstPartyDomain: 'example.com', }; const results = returnOptionalCookieAPIAttributes( state, cookieAPIAttributes, ); expect(results).toEqual( expect.objectContaining({ domain: 'example.com', firstPartyDomain: 'example.com', }), ); }); it('should return an object with no firstPartyDomain (Browser other than FF)', () => { const state = { ...initialState, cache: { browserDetect: browserName.Chrome, }, }; const cookieAPIAttributes = { ...mockCookie, firstPartyDomain: '', }; const results = returnOptionalCookieAPIAttributes( state, cookieAPIAttributes, ); expect(results).not.toHaveProperty('firstPartyDomain'); }); }); describe('showNotification()', () => { beforeAll(() => { when(global.browser.notifications.create) .calledWith(expect.any(String), expect.any(Object)) .mockResolvedValue('testID' as never); when(global.browser.notifications.clear) .calledWith(expect.any(String)) .mockResolvedValue(true as never); when(global.browser.i18n.getMessage) .calledWith('manualActionNotification') .mockReturnValue('manual'); when(global.browser.runtime.getManifest) .calledWith() .mockReturnValue({ version: '3.99.99' }); when(global.browser.runtime.getURL) .calledWith(expect.anything()) .mockReturnValue(''); }); afterAll(() => { global.browser.i18n.getMessage.clearMocks(); global.browser.runtime.getManifest.clearMocks(); global.browser.runtime.getURL.clearMocks(); jest.clearAllTimers(); }); it('should expect one call to browser.notifications.create with default title', async () => { const spyTimeout = jest.spyOn(global, 'setTimeout'); showNotification({ duration: 1, msg: 'Test Notification' }); expect(global.browser.notifications.create).toHaveBeenCalled(); expect(global.browser.notifications.create.mock.calls[0][0]).toEqual( expect.stringContaining('CAD-notification-'), ); expect(global.browser.notifications.create.mock.calls[0][1]).toEqual( expect.objectContaining({ message: 'Test Notification', title: 'CAD 3.99.99 - manual', type: 'basic', }), ); expect(spyTimeout).toHaveBeenCalled(); expect(spyTimeout).toHaveBeenCalledWith(expect.any(Function), 1000); jest.runAllTimers(); expect(browser.notifications.clear).toHaveBeenCalledTimes(1); }); it('should expect one call to browser.notifications.create with custom title', async () => { showNotification({ duration: 1, msg: 'Test Notification', title: 'custom', }); expect(global.browser.notifications.create).toHaveBeenCalled(); expect(global.browser.notifications.create.mock.calls[0][1]).toEqual( expect.objectContaining({ message: 'Test Notification', title: 'CAD 3.99.99 - custom', type: 'basic', }), ); }); it('should not show notification if display was false', async () => { showNotification( { duration: 1, msg: 'Unshown Notification', }, false, ); expect(global.browser.notifications.create).not.toHaveBeenCalled(); }); }); describe('sleep()', () => { jest.useFakeTimers(); const spySetTimeout = jest.spyOn(global, 'setTimeout'); afterEach(() => { spySetTimeout.mockClear(); jest.clearAllTimers(); }); it('should return undefined as result', () => { expect.assertions(1); const result = sleep(1).then((r) => expect(r).toEqual(undefined)); jest.runAllTimers(); return result; }); it('setTimeout in Promise should be set to 250ms if input was 100', () => { expect.assertions(3); const result = sleep(100).then((r) => { expect(r).toEqual(undefined); expect(spySetTimeout).toBeCalledTimes(1); expect(spySetTimeout).toHaveBeenCalledWith(expect.any(Function), 250); }); jest.runAllTimers(); return result; }); it('setTimeout in Promise should be set to 1500ms if input was 1500', () => { expect.assertions(3); const result = sleep(1500).then((r) => { expect(r).toEqual(undefined); expect(spySetTimeout).toBeCalledTimes(1); expect(spySetTimeout).toHaveBeenCalledWith(expect.any(Function), 1500); }); jest.runAllTimers(); return result; }); it('setTimeout in Promise should be set to 2147483500ms if input was greater than 2147483500', () => { expect.assertions(3); const result = sleep(2345678901).then((r) => { expect(r).toEqual(undefined); expect(spySetTimeout).toBeCalledTimes(1); expect(spySetTimeout).toHaveBeenCalledWith( expect.any(Function), 2147483500, ); }); jest.runAllTimers(); return result; }); }); describe('trimDot()', () => { it('should return example.com with no leading dots', () => { const results = trimDot('.example.com'); expect(results).toEqual('example.com'); }); it('should return example.com with no leading and ending dots', () => { const results = trimDot('.example.com.'); expect(results).toEqual('example.com'); }); }); describe('throwErrorNotification()', () => { beforeAll(() => { when(global.browser.notifications.create) .calledWith(expect.any(String), expect.any(Object)) .mockResolvedValue('testID' as never); when(global.browser.notifications.clear) .calledWith(expect.any(String)) .mockResolvedValue(true as never); when(global.browser.i18n.getMessage) .calledWith('errorText') .mockReturnValue('Error!'); when(global.browser.runtime.getManifest) .calledWith() .mockReturnValue({ version: '3.99.99' }); when(global.browser.runtime.getURL) .calledWith(expect.anything()) .mockReturnValue(''); }); beforeEach(() => { jest.spyOn(global, 'setTimeout'); }); afterEach(() => { jest.clearAllTimers(); }); afterAll(() => { global.browser.i18n.getMessage.clearMocks(); global.browser.runtime.getManifest.clearMocks(); global.browser.runtime.getURL.clearMocks(); }); it('should expect one call to browser.notifications.create', () => { throwErrorNotification({ name: 'Test Error', message: 'An ERROR!' }, 1); expect(global.browser.notifications.create).toHaveBeenCalled(); expect(global.browser.notifications.create.mock.calls[0][0]).toEqual( expect.stringContaining('CAD-notification-failed-'), ); expect(global.browser.notifications.create.mock.calls[0][1]).toEqual( expect.objectContaining({ message: 'An ERROR!', title: 'Error!', type: 'basic', }), ); expect(setTimeout).toHaveBeenCalled(); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 1000); jest.runAllTimers(); expect(browser.notifications.clear).toHaveBeenCalledTimes(1); }); }); describe('undefinedIsTrue()', () => { it('should return true for undefined', () => { expect(undefinedIsTrue(undefined)).toEqual(true); }); it('should return true for true', () => { expect(undefinedIsTrue(true)).toEqual(true); }); it('should return false for false', () => { expect(undefinedIsTrue(false)).toEqual(false); }); }); describe('validateExpressionDomain()', () => { when(global.browser.i18n.getMessage) .calledWith(expect.any(String)) .mockReturnValue('message'); when(global.browser.i18n.getMessage) .calledWith(expect.any(String), expect.any(Array)) .mockReturnValue(`message with substitution array`); it('should return invalid message on "" input', () => { validateExpressionDomain(''); expect(global.browser.i18n.getMessage).toHaveBeenCalledWith( 'inputErrorEmpty', ); }); it('should return invalid message on invalid RegExp', () => { validateExpressionDomain('/abc(def]/'); expect( global.browser.i18n.getMessage, ).toHaveBeenCalledWith('inputErrorRegExp', [expect.any(String)]); }); it('should return invalid message on start slash missing end slash', () => { validateExpressionDomain('/abc'); expect(global.browser.i18n.getMessage).toHaveBeenCalledWith( 'inputErrorSlashStartMissingEnd', ); }); it('should return invalid message on end slash missing start slash', () => { validateExpressionDomain('abc/'); expect(global.browser.i18n.getMessage).toHaveBeenCalledWith( 'inputErrorSlashEndMissingStart', ); }); it('should return invalid message on comma usage outside of RegExp', () => { validateExpressionDomain('a,b'); expect(global.browser.i18n.getMessage).toHaveBeenCalledWith( 'inputErrorComma', ); }); it('should return invalid message on spaces between words.', () => { validateExpressionDomain('test expression'); expect(global.browser.i18n.getMessage).toHaveBeenCalledWith( 'inputErrorSpace', ); }); it('should return empty string if valid domain expression', () => { const r = validateExpressionDomain('test'); expect(global.browser.i18n.getMessage).not.toHaveBeenCalled(); expect(r).toEqual(''); }); it('should return empty string if valid RegExp', () => { const r = validateExpressionDomain('/[Rr]eg[Ee]xp.com/'); expect(global.browser.i18n.getMessage).not.toHaveBeenCalled(); expect(r).toEqual(''); }); }); });
the_stack
// A '.tsx' file enables JSX support in the TypeScript compiler, // for more information see the following page on the TypeScript wiki: // https://github.com/Microsoft/TypeScript/wiki/JSX import * as React from 'react'; import * as Utility from '../Utility'; import { AppState, UserInfo } from '../States/AppState'; import * as $ from 'jquery'; import { connect } from 'react-redux'; import { Actions, RootState } from '../Store'; import { Link, withRouter, Route } from 'react-router-dom'; import { refreshCurrentUserInfo } from '../AsyncActions/UserCenter'; import { refreshCurrentMessageCount } from '../AsyncActions/Message'; import { MessageInfo } from '../Reducers/Message'; import { notification } from 'antd'; type props = { isLogOn: boolean; userInfo: UserInfo; logOff: () => void; reLogOn: (userInfo: UserInfo) => void; refreshCurrentMessageCount: () => void; refreshUserInfo: () => void; messageCount: MessageInfo; }; type state = { hoverElement: string; }; class DropDownConnect extends React.Component<props, state> { //顶部条的下拉菜单组件 constructor(props) { super(props); this.state = { hoverElement: null }; } componentDidMount() { /** * 同步不同窗口的登陆信息 */ window.addEventListener('storage', e => { if (e.key === 'userInfo') { if (e.oldValue === e.newValue) return; if (e.newValue) { //如果用户在其他页面重新登陆 this.props.reLogOn(JSON.parse(e.newValue.slice(4))); } else { //如果用户在其他页面注销 this.props.logOff(); } } }); if (Utility.isLogOn()) { this.props.refreshCurrentMessageCount(); } //每天刷新一次用户信息 if ( Utility.isLogOn() && !Utility.getLocalStorage('shouldNotRefreshUserInfo') ) { this.props.refreshUserInfo(); Utility.setLocalStorage('shouldNotRefreshUserInfo', true, 86400); } } logOff() { this.handleMouseEvent('mouseout', 'userName'); Utility.removeLocalStorage('accessToken'); Utility.removeLocalStorage('refresh_token'); Utility.removeLocalStorage('userInfo'); Utility.removeLocalStorage('usePWA'); Utility.removeStorage('all'); Utility.changeTheme(0); this.props.logOff(); //更新redux中的状态 } handleMouseEvent(type, className) { switch (type) { case 'mouseover': { this.setState({ hoverElement: className }); break; } case 'mouseout': { this.setState({ hoverElement: null }); break; } } } render() { if (this.props.isLogOn) { const totalCount = this.props.messageCount.atCount + this.props.messageCount.messageCount + this.props.messageCount.replyCount + this.props.messageCount.systemCount; const style = { display: 'block', transitionDuration: '.2s', height: '0px' }; //全站管理选项 let admin = this.props.userInfo.privilege === '管理员' ? ( <Link to="/sitemanage" style={{ color: '#fff' }}> <li>全站管理</li> </Link> ) : null; //用户中心下拉列表 let userCenterClassName = 'topBarUserCenter'; if (location.pathname === '/') { userCenterClassName = 'topBarUserCenter-mainPage'; } //消息中心下拉列表 let MessageClassName = 'topBarMessageDetails'; if (location.pathname === '/') { MessageClassName = 'topBarMessageDetails-mainPage'; } //获取签到状态 let signinInfo = '签到'; let userInfo = Utility.getLocalStorage('userInfo'); if (userInfo && Utility.getLocalStorage(`signin_${userInfo.id}`)) { signinInfo = '已签到'; } return ( <div className="topBarRight"> <div className="topBarUserInfo"> <div className="topBarMessage" id="userMessage" onMouseOut={e => { this.handleMouseEvent(e.type, 'message'); }} onMouseOver={e => { this.handleMouseEvent(e.type, 'message'); }} > <Link to="/message/response" className="messageTopBar"> <div className="topBarBell"> {' '} <i className="fa fa-bell-o" /> </div> {totalCount ? ( <div className="message-counter" id="unreadCount-totalCount"> {totalCount} </div> ) : null} </Link> </div> <div className="topBarUserImg" onMouseOut={e => { this.handleMouseEvent(e.type, 'userName'); }} onMouseOver={e => { this.handleMouseEvent(e.type, 'userName'); }} > <img src={this.props.userInfo.portraitUrl} /> </div> <div className="topBarUserName" onMouseOut={e => { this.handleMouseEvent(e.type, 'userName'); }} onMouseOver={e => { this.handleMouseEvent(e.type, 'userName'); }} > {this.props.userInfo.name} </div> </div> <div className={userCenterClassName} onMouseOut={e => { this.handleMouseEvent(e.type, 'userName'); }} onMouseOver={e => { this.handleMouseEvent(e.type, 'userName'); }} style={{ ...style, overflow: 'hidden', height: this.state.hoverElement === 'userName' ? '8rem' : '0' }} > <ul style={{ display: 'inherit' }}> <Link to="/usercenter"> {' '} <li>个人中心</li> </Link> {admin} <Link to="/signin"> <li>{signinInfo}</li> </Link> <li onClick={this.logOff.bind(this)}>注销</li> </ul> </div> <div className={MessageClassName} onMouseOut={e => { this.handleMouseEvent(e.type, 'message'); }} onMouseOver={e => { this.handleMouseEvent(e.type, 'message'); }} style={{ ...style, overflow: 'hidden', height: this.state.hoverElement === 'message' ? '8rem' : '0' }} > <ul style={{ display: 'inherit' }}> <Link to="/message/response"> <li> 回复我的 {this.props.messageCount.replyCount ? ( <div className="message-counterLi"> {this.props.messageCount.replyCount} </div> ) : null} </li> </Link> <Link to="/message/attme"> <li> @ 我的 {this.props.messageCount.atCount ? ( <div className="message-counterLi"> {this.props.messageCount.atCount} </div> ) : null} </li> </Link> <Link to="/message/system"> <li> 系统通知 {this.props.messageCount.systemCount ? ( <div className="message-counterLi"> {this.props.messageCount.systemCount} </div> ) : null} </li> </Link> <Link to="/message/message"> <li> 我的私信 {this.props.messageCount.messageCount ? ( <div className="message-counterLi"> {this.props.messageCount.messageCount} </div> ) : null} </li> </Link> </ul> </div> </div> ); } else { return ( <div className="topBarUserInfo"> <div className="topBarText"> {' '} <Link onClick={() => { localStorage.setItem('logOnRedirectUrl', window.location.href); }} to="/logOn" > 登录 </Link> </div> <div className="topBarText"> <a href="https://account.cc98.org/">注册</a> </div> </div> ); } } } // 这里是董松松的修改,加了redux function mapState(state: RootState) { return { userInfo: state.userInfo.currentUserInfo, isLogOn: state.userInfo.isLogOn, messageCount: state.message }; } function mapDispatch(dispatch) { return { logOff: () => { dispatch(Actions.userLogOff()); }, reLogOn: (newInfo: UserInfo) => { Utility.changeTheme(newInfo.theme); dispatch(Actions.changeUserInfo(newInfo)); dispatch(Actions.userLogIn()); }, refreshUserInfo: () => { dispatch(refreshCurrentUserInfo()); }, refreshCurrentMessageCount: () => { dispatch(refreshCurrentMessageCount()); } }; } let DropDown = connect( mapState, mapDispatch )(DropDownConnect); //到此结束 export class SearchBeforeConnent extends React.Component<any, AppState> { //搜索框组件 async componentDidMount() { const searchBoxSelect = $('.searchBoxSelect'); const downArrow = $('.caret-down'); const searchBoxSub = $('.searchBoxSub'); const searchIco = $('.searchIco'); const searchBoxLi = searchBoxSub.find('li'); $(document).click(function() { searchBoxSub.css('display', 'none'); }); searchBoxSelect.click(function() { if (searchBoxSub.css('display') === 'block') searchBoxSub.css('display', 'none'); else searchBoxSub.css('display', 'block'); return false; //阻止事件冒泡 }); downArrow.click(function() { if (searchBoxSub.css('display') === 'block') searchBoxSub.css('display', 'none'); else searchBoxSub.css('display', 'block'); return false; //阻止事件冒泡 }); /*在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序, 如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活), 或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)。*/ searchBoxLi.click(function() { searchBoxSelect.text($(this).text()); }); searchBoxLi.mouseover(function() { this.className = 'hover'; }); searchBoxLi.mouseout(function() { this.className = ''; }); //获取搜索关键词 let self = this; searchIco.click(async () => { let val: any = $('#searchText').val(); if (val && val != '') { if ( searchBoxSelect.text() === '主题' || searchBoxSelect.text() === '全站' ) { // notification.warning({ // message: '非常抱歉', // description: '搜索功能优化中,暂不可用。' // }); this.props.history.push( `/search?boardId=0&keyword=${encodeURI(encodeURI(val))}` ); } else if (searchBoxSelect.text() === '版内') { // notification.warning({ // message: '非常抱歉', // description: '搜索功能优化中,暂不可用。' // }); //查看当前是全站还是某版,如果是某版就查询到某版id let url1 = location.href.match(/\/topic\/(\d+)/); let url2 = location.href.match(/\/board\/(\d+)/); let url3 = location.href.match(/\/search\?boardId=(\d+)&/); let boardId = 0; if (url1) { console.log('版内1'); let topicId = url1[1]; let response = await Utility.getTopicInfo(topicId); boardId = response.boardId; } else if (url2) { console.log('版内2'); boardId = parseInt(url2[1]); } else if (url3) { boardId = parseInt(url3[1]); console.log(url3); console.log(url3[1]); console.log('目前是在版内啊'); } this.props.history.push( `/search?boardId=${boardId}&keyword=${encodeURI(encodeURI(val))}` ); } else if (searchBoxSelect.text() === '用户') { let data = await Utility.getUserInfoByName(val); if (data) { this.props.history.push(`/user/id/${data.id}`); } else { this.props.history.push('/search'); } } else if (searchBoxSelect.text() === '版面') { // notification.warning({ // message: '非常抱歉', // description: '搜索功能优化中,暂不可用。' // }); this.props.history.push( `/searchBoard?keyword=${encodeURI(encodeURI(val))}` ); } } }); } //回车搜索 keypress_submit(e) { var evt = e || window.event; var code = evt.which || evt.keyCode || evt.charCode; //提高浏览器兼容性 if (code === 13) { $('.searchIco').click(); } else if (evt.key === 'Enter') { //提高浏览器兼容性 $('.searchIco').click(); } } render() { //查看当前是全站还是某版 let url1 = location.href.match(/\/topic\/(\d+)/); let url2 = location.href.match(/\/board\/(\d+)/); let url3 = location.href.match(/\/(searchBoard)/); let url4 = location.href.match(/\/search\?boardId=(\d+)/); let flag = 1; if (url1) { flag = 0; } else if (url2) { flag = 0; } else if (url3) { } else if (url4 && parseInt(url4[1]) !== 0) { flag = 0; } if (flag) { return ( <div id="search"> <div className="box"> <div className="searchBoxSelect">主题</div> <div className="caret-down"> <i className="fa fa-caret-down" /> </div> <input id="searchText" type="text" placeholder="请输入搜索内容" onKeyPress={this.keypress_submit} /> <div className="searchIco"> <i className="fa fa-search" /> </div> </div> <ul className="searchBoxSub"> <li>主题</li> <li>用户</li> <li>版面</li> <li style={{ display: 'none' }} /> </ul> </div> ); } else { return ( <div id="search"> <div className="box"> <div className="searchBoxSelect">版内</div> <div className="caret-down"> <i className="fa fa-caret-down" /> </div> <input id="searchText" type="text" placeholder="请输入搜索内容" onKeyPress={this.keypress_submit} /> <div className="searchIco"> <i className="fa fa-search" /> </div> </div> <ul className="searchBoxSub"> <li>版内</li> <li>全站</li> <li>用户</li> <li>版面</li> </ul> </div> ); } } } export const Search = withRouter(SearchBeforeConnent); export class Header extends React.Component<{}, AppState> { render() { let pathname = location.pathname; if (pathname === '/') { return ( <div className="header"> {/*<Redirect />*/} <div className="topBar-mainPage"> <div className="topBarRow"> <div className="row" style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }} > <div className="topBarLogo"> <Link to="/"> <img src="/static/images/98LOGO.ico" /> </Link> </div> <div className="topBarCC98"> <Link to="/">CC98论坛</Link> </div> <div className="topBarText">|</div> <div className="topBarText"> <Link to="/boardList">版面列表</Link> </div> <div className="topBarText"> <Link to="/newTopics">新帖</Link> </div> <div className="topBarText"> <Link to="/focus">关注</Link> </div> <Route component={Search} /> </div> <DropDown /> </div> </div> </div> ); } else { return ( <div className="headerWithoutImage"> {/*<Redirect />*/} <div className="topBar"> <div className="topBarRow"> <div className="row" style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }} > <div className="topBarLogo"> <Link to="/"> <img src="/static/images/98LOGO.ico" /> </Link> </div> <div className="topBarCC98"> <Link to="/">CC98论坛</Link> </div> <div className="topBarText">|</div> <div className="topBarText"> <Link to="/boardList">版面列表</Link> </div> <div className="topBarText"> <Link to="/newTopics">新帖</Link> </div> <div className="topBarText"> <Link to="/focus">关注</Link> </div> <Route component={Search} /> </div> <DropDown /> </div> </div> </div> ); } } } /* class Redirect extends React.Component<{}, { isShowed: boolean }> { constructor(props) { super(props); const isShowed: boolean = !Utility.getLocalStorage('usePWA'); this.state = { isShowed }; } jump = () => { let PWAURL: string = ''; const url = location.href; const basicURL = 'https://m.cc98.org/'; if (url.match(/\/topic\//i)) { //本周热门,本月热门,历史上的今天跳转到pwa热门话题 if (url.match(/(hot-weekly|hot-monthly|hot-history)/i)) { PWAURL = `${basicURL}hotTopics`; } //帖子跳转到pwa相应帖 else { const topicID = url.match(/topic\/\d+/i)[0].match(/\d+/)[0]; PWAURL = `${basicURL}topic/${topicID}`; } } //版面列表跳转到pwa的版面列表 else if (url.match(/boardList/i)) { PWAURL = `${basicURL}boardList`; } //版面跳转到pwa相应版 else if (url.match(/\/board\//i)) { const boardID = url.match(/board\/\d+/i)[0].match(/\d+/)[0]; PWAURL = `${basicURL}board/${boardID}`; } //用户页跳转到pwa相应页 else if (url.match(/\/user\//)) { const userID = url.match(/user\/id\/\d+/i)[0].match(/\d+/)[0]; PWAURL = `${basicURL}user/${userID}`; } //其他页跳转到pwa首页 else { PWAURL = basicURL; } location.href = PWAURL; }; close = () => { this.setState({ isShowed: false }); }; neverShow = () => { Utility.setLocalStorage('usePWA', 'false', 2592000); this.setState({ isShowed: false }); }; render() { if ( this.state.isShowed && navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i) ) { return ( <div className="pwa-redirect-background"> <div className="pwa-redirect-container"> <img className="pwa-redirect-image" src="/static/images/login.png" /> <div className="pwa-redirect-text-container"> <div className="pwa-redirect-text">检测到您正使用移动端访问</div> <div className="pwa-redirect-text"> 建议使用移动版CC98</div> <div className="pwa-redirect-text"> 以获得更好的浏览体验</div> </div> <div className="pwa-redirect-button-container"> <div className="pwa-redirect-button" onClick={this.jump}> 点击跳转 </div> <div className="pwa-redirect-button" onClick={this.close}> 下次再说 </div> <div className="pwa-redirect-button" onClick={this.neverShow}> 不再提示 </div> </div> </div> </div> ); } return <></>; } } */
the_stack
import * as vscode from 'vscode' import * as NodePath from 'path' const KeyVditorOptions = 'vditor.options' function debug(...args: any[]) { console.log(...args) } function showError(msg: string) { vscode.window.showErrorMessage(`[markdown-editor] ${msg}`) } export function activate(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.commands.registerCommand( 'markdown-editor.openEditor', (uri?: vscode.Uri, ...args) => { debug('command', uri, args) EditorPanel.createOrShow(context, uri) } ) ) context.globalState.setKeysForSync([KeyVditorOptions]) } function getWebviewOptions( extensionUri: vscode.Uri ): vscode.WebviewOptions & vscode.WebviewPanelOptions { return { // Enable javascript in the webview enableScripts: true, retainContextWhenHidden: true, } } /** * Manages cat coding webview panels */ class EditorPanel { /** * Track the currently panel. Only allow a single panel to exist at a time. */ public static currentPanel: EditorPanel | undefined public static readonly viewType = 'markdown-editor' private _disposables: vscode.Disposable[] = [] public static async createOrShow( context: vscode.ExtensionContext, uri?: vscode.Uri ) { const { extensionUri } = context const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined if (EditorPanel.currentPanel && uri !== EditorPanel.currentPanel?._uri) { EditorPanel.currentPanel.dispose() } // If we already have a panel, show it. if (EditorPanel.currentPanel) { EditorPanel.currentPanel._panel.reveal(column) return } if (!vscode.window.activeTextEditor && !uri) { showError(`Did not open markdown file!`) return } let doc: undefined | vscode.TextDocument // from context menu : 从当前打开的 textEditor 中寻找 是否有当前 markdown 的 editor, 有的话则绑定 document if (uri) { // 从右键打开文件,先打开文档然后开启自动同步,不然没法保存文件和同步到已经打开的document doc = await vscode.workspace.openTextDocument(uri) } else { doc = vscode.window.activeTextEditor?.document // from command mode if (doc && doc.languageId !== 'markdown') { showError( `Current file language is not markdown, got ${doc.languageId}` ) return } } if (!doc) { showError(`Cannot find markdown file!`) return } // Otherwise, create a new panel. const panel = vscode.window.createWebviewPanel( EditorPanel.viewType, 'markdown-editor', column || vscode.ViewColumn.One, getWebviewOptions(extensionUri) ) EditorPanel.currentPanel = new EditorPanel( context, panel, extensionUri, doc, uri ) } private get _fsPath() { return this._uri.fsPath } private get _config() { return vscode.workspace.getConfiguration('markdown-editor') } private constructor( private readonly _context: vscode.ExtensionContext, private readonly _panel: vscode.WebviewPanel, private readonly _extensionUri: vscode.Uri, public _document: vscode.TextDocument, // 当前有 markdown 编辑器 public _uri = _document.uri // 从资源管理器打开,只有 uri 没有 _document ) { // Set the webview's initial html content this._init() // Listen for when the panel is disposed // This happens when the user closes the panel or when the panel is closed programmatically this._panel.onDidDispose(() => this.dispose(), null, this._disposables) let textEditTimer: NodeJS.Timeout | void // close EditorPanel when vsc editor is close vscode.workspace.onDidCloseTextDocument((e) => { if (e.fileName === this._fsPath) { this.dispose() } }, this._disposables) // update EditorPanel when vsc editor changes vscode.workspace.onDidChangeTextDocument((e) => { if (e.document.fileName !== this._document.fileName) { return } // 当 webview panel 激活时不将由 webview编辑导致的 vsc 编辑器更新同步回 webview // don't change webview panel when webview panel is focus if (this._panel.active) { return } textEditTimer && clearTimeout(textEditTimer) textEditTimer = setTimeout(() => { this._update() this._updateEditTitle() }, 300) }, this._disposables) // Handle messages from the webview this._panel.webview.onDidReceiveMessage( async (message) => { debug('msg from webview review', message, this._panel.active) const syncToEditor = async () => { debug('sync to editor', this._document, this._uri) if (this._document) { const edit = new vscode.WorkspaceEdit() edit.replace( this._document.uri, new vscode.Range(0, 0, this._document.lineCount, 0), message.content ) await vscode.workspace.applyEdit(edit) } else if (this._uri) { await vscode.workspace.fs.writeFile(this._uri, message.content) } else { showError(`Cannot find original file to save!`) } } switch (message.command) { case 'ready': this._update({ type: 'init', options: { useVscodeThemeColor: this._config.get<boolean>( 'useVscodeThemeColor' ), ...this._context.globalState.get(KeyVditorOptions), }, theme: vscode.window.activeColorTheme.kind === vscode.ColorThemeKind.Dark ? 'dark' : 'light', }) break case 'save-options': this._context.globalState.update(KeyVditorOptions, message.options) break case 'info': vscode.window.showInformationMessage(message.content) break case 'error': showError(message.content) break case 'edit': { // 只有当 webview 处于编辑状态时才同步到 vsc 编辑器,避免重复刷新 if (this._panel.active) { await syncToEditor() this._updateEditTitle() } break } case 'reset-config': { await this._context.globalState.update(KeyVditorOptions, {}) break } case 'save': { await syncToEditor() await this._document.save() this._updateEditTitle() break } case 'upload': { const imageSaveFolder = ( this._config.get<string>('imageSaveFolder') || 'assets' ) .replace( '${projectRoot}', vscode.workspace.getWorkspaceFolder(this._uri)?.uri.fsPath || '' ) .replace('${file}', this._fsPath) .replace('${dir}', NodePath.dirname(this._fsPath)) const assetsFolder = NodePath.resolve( NodePath.dirname(this._fsPath), imageSaveFolder ) try { await vscode.workspace.fs.createDirectory(vscode.Uri.file(assetsFolder)) } catch (error) { console.error(error) showError(`Invalid image folder: ${assetsFolder}`) } await Promise.all( message.files.map(async (f: any) => { const content = Buffer.from(f.base64, 'base64') return vscode.workspace.fs.writeFile( vscode.Uri.file(NodePath.join(assetsFolder, f.name)), content ) }) ) const files = message.files.map((f: any) => NodePath.relative( NodePath.dirname(this._fsPath), NodePath.join(assetsFolder, f.name) ).replace(/\\/g, '/') ) this._panel.webview.postMessage({ command: 'uploaded', files, }) break } case 'open-link': { let url = message.href if (!/^http/.test(url)) { url = NodePath.resolve(this._fsPath, '..', url) } vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(url)) break } } }, null, this._disposables ) } public dispose() { EditorPanel.currentPanel = undefined // Clean up our resources this._panel.dispose() while (this._disposables.length) { const x = this._disposables.pop() if (x) { x.dispose() } } } private _init() { const webview = this._panel.webview this._panel.webview.html = this._getHtmlForWebview(webview) this._panel.title = NodePath.basename(this._fsPath) } private _isEdit = false private _updateEditTitle() { const isEdit = this._document.isDirty if (isEdit !== this._isEdit) { this._isEdit = isEdit this._panel.title = `${isEdit ? `[edit]` : ''}${NodePath.basename( this._fsPath )}` } } // private fileToWebviewUri = (f: string) => { // return this._panel.webview.asWebviewUri(vscode.Uri.file(f)).toString() // } private async _update( props: { type?: 'init' | 'update' options?: any theme?: 'dark' | 'light' } = { options: void 0 } ) { const md = this._document ? this._document.getText() : (await vscode.workspace.fs.readFile(this._uri)).toString() // const dir = NodePath.dirname(this._document.fileName) this._panel.webview.postMessage({ command: 'update', content: md, ...props, }) } private _getHtmlForWebview(webview: vscode.Webview) { const toUri = (f: string) => webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, f)) const baseHref = NodePath.dirname( webview.asWebviewUri(vscode.Uri.file(this._fsPath)).toString() ) + '/' const toMediaPath = (f: string) => `media/dist/${f}` const JsFiles = ['main.js'].map(toMediaPath).map(toUri) const CssFiles = ['main.css'].map(toMediaPath).map(toUri) return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <base href="${baseHref}" /> ${CssFiles.map((f) => `<link href="${f}" rel="stylesheet">`).join('\n')} <title>markdown editor</title> </head> <body> <div id="app"></div> ${JsFiles.map((f) => `<script src="${f}"></script>`).join('\n')} </body> </html>` } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Azure recovery vault protection container mapping. A protection container mapping decides how to translate the protection container when a VM is migrated from one region to another. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const primaryResourceGroup = new azure.core.ResourceGroup("primaryResourceGroup", {location: "West US"}); * const secondaryResourceGroup = new azure.core.ResourceGroup("secondaryResourceGroup", {location: "East US"}); * const vault = new azure.recoveryservices.Vault("vault", { * location: secondaryResourceGroup.location, * resourceGroupName: secondaryResourceGroup.name, * sku: "Standard", * }); * const primaryFabric = new azure.siterecovery.Fabric("primaryFabric", { * resourceGroupName: secondaryResourceGroup.name, * recoveryVaultName: vault.name, * location: primaryResourceGroup.location, * }); * const secondaryFabric = new azure.siterecovery.Fabric("secondaryFabric", { * resourceGroupName: secondaryResourceGroup.name, * recoveryVaultName: vault.name, * location: secondaryResourceGroup.location, * }); * const primaryProtectionContainer = new azure.siterecovery.ProtectionContainer("primaryProtectionContainer", { * resourceGroupName: secondaryResourceGroup.name, * recoveryVaultName: vault.name, * recoveryFabricName: primaryFabric.name, * }); * const secondaryProtectionContainer = new azure.siterecovery.ProtectionContainer("secondaryProtectionContainer", { * resourceGroupName: secondaryResourceGroup.name, * recoveryVaultName: vault.name, * recoveryFabricName: secondaryFabric.name, * }); * const policy = new azure.siterecovery.ReplicationPolicy("policy", { * resourceGroupName: secondaryResourceGroup.name, * recoveryVaultName: vault.name, * recoveryPointRetentionInMinutes: 24 * 60, * applicationConsistentSnapshotFrequencyInMinutes: 4 * 60, * }); * const container_mapping = new azure.siterecovery.ProtectionContainerMapping("container-mapping", { * resourceGroupName: secondaryResourceGroup.name, * recoveryVaultName: vault.name, * recoveryFabricName: primaryFabric.name, * recoverySourceProtectionContainerName: primaryProtectionContainer.name, * recoveryTargetProtectionContainerId: secondaryProtectionContainer.id, * recoveryReplicationPolicyId: policy.id, * }); * ``` * * ## Import * * Site Recovery Protection Container Mappings can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:siterecovery/protectionContainerMapping:ProtectionContainerMapping mymapping /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-group-name/providers/Microsoft.RecoveryServices/vaults/recovery-vault-name * ``` */ export class ProtectionContainerMapping extends pulumi.CustomResource { /** * Get an existing ProtectionContainerMapping resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ProtectionContainerMappingState, opts?: pulumi.CustomResourceOptions): ProtectionContainerMapping { return new ProtectionContainerMapping(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:siterecovery/protectionContainerMapping:ProtectionContainerMapping'; /** * Returns true if the given object is an instance of ProtectionContainerMapping. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ProtectionContainerMapping { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ProtectionContainerMapping.__pulumiType; } /** * The name of the network mapping. */ public readonly name!: pulumi.Output<string>; /** * Name of fabric that should contains the protection container to map. */ public readonly recoveryFabricName!: pulumi.Output<string>; /** * Id of the policy to use for this mapping. */ public readonly recoveryReplicationPolicyId!: pulumi.Output<string>; /** * Name of the source protection container to map. */ public readonly recoverySourceProtectionContainerName!: pulumi.Output<string>; /** * Id of target protection container to map to. */ public readonly recoveryTargetProtectionContainerId!: pulumi.Output<string>; /** * The name of the vault that should be updated. */ public readonly recoveryVaultName!: pulumi.Output<string>; /** * Name of the resource group where the vault that should be updated is located. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * Create a ProtectionContainerMapping resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ProtectionContainerMappingArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ProtectionContainerMappingArgs | ProtectionContainerMappingState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ProtectionContainerMappingState | undefined; inputs["name"] = state ? state.name : undefined; inputs["recoveryFabricName"] = state ? state.recoveryFabricName : undefined; inputs["recoveryReplicationPolicyId"] = state ? state.recoveryReplicationPolicyId : undefined; inputs["recoverySourceProtectionContainerName"] = state ? state.recoverySourceProtectionContainerName : undefined; inputs["recoveryTargetProtectionContainerId"] = state ? state.recoveryTargetProtectionContainerId : undefined; inputs["recoveryVaultName"] = state ? state.recoveryVaultName : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; } else { const args = argsOrState as ProtectionContainerMappingArgs | undefined; if ((!args || args.recoveryFabricName === undefined) && !opts.urn) { throw new Error("Missing required property 'recoveryFabricName'"); } if ((!args || args.recoveryReplicationPolicyId === undefined) && !opts.urn) { throw new Error("Missing required property 'recoveryReplicationPolicyId'"); } if ((!args || args.recoverySourceProtectionContainerName === undefined) && !opts.urn) { throw new Error("Missing required property 'recoverySourceProtectionContainerName'"); } if ((!args || args.recoveryTargetProtectionContainerId === undefined) && !opts.urn) { throw new Error("Missing required property 'recoveryTargetProtectionContainerId'"); } if ((!args || args.recoveryVaultName === undefined) && !opts.urn) { throw new Error("Missing required property 'recoveryVaultName'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["name"] = args ? args.name : undefined; inputs["recoveryFabricName"] = args ? args.recoveryFabricName : undefined; inputs["recoveryReplicationPolicyId"] = args ? args.recoveryReplicationPolicyId : undefined; inputs["recoverySourceProtectionContainerName"] = args ? args.recoverySourceProtectionContainerName : undefined; inputs["recoveryTargetProtectionContainerId"] = args ? args.recoveryTargetProtectionContainerId : undefined; inputs["recoveryVaultName"] = args ? args.recoveryVaultName : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ProtectionContainerMapping.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ProtectionContainerMapping resources. */ export interface ProtectionContainerMappingState { /** * The name of the network mapping. */ name?: pulumi.Input<string>; /** * Name of fabric that should contains the protection container to map. */ recoveryFabricName?: pulumi.Input<string>; /** * Id of the policy to use for this mapping. */ recoveryReplicationPolicyId?: pulumi.Input<string>; /** * Name of the source protection container to map. */ recoverySourceProtectionContainerName?: pulumi.Input<string>; /** * Id of target protection container to map to. */ recoveryTargetProtectionContainerId?: pulumi.Input<string>; /** * The name of the vault that should be updated. */ recoveryVaultName?: pulumi.Input<string>; /** * Name of the resource group where the vault that should be updated is located. */ resourceGroupName?: pulumi.Input<string>; } /** * The set of arguments for constructing a ProtectionContainerMapping resource. */ export interface ProtectionContainerMappingArgs { /** * The name of the network mapping. */ name?: pulumi.Input<string>; /** * Name of fabric that should contains the protection container to map. */ recoveryFabricName: pulumi.Input<string>; /** * Id of the policy to use for this mapping. */ recoveryReplicationPolicyId: pulumi.Input<string>; /** * Name of the source protection container to map. */ recoverySourceProtectionContainerName: pulumi.Input<string>; /** * Id of target protection container to map to. */ recoveryTargetProtectionContainerId: pulumi.Input<string>; /** * The name of the vault that should be updated. */ recoveryVaultName: pulumi.Input<string>; /** * Name of the resource group where the vault that should be updated is located. */ resourceGroupName: pulumi.Input<string>; }
the_stack
import type { Context, Plugin } from "graphile-build"; import type { PgType, QueryBuilder, SQL } from "graphile-build-pg"; import type { GraphQLInputFieldConfigMap, GraphQLInputType, GraphQLType, } from "graphql"; import { ConnectionFilterResolver } from "./PgConnectionArgFilterPlugin"; const PgConnectionArgFilterOperatorsPlugin: Plugin = ( builder, { connectionFilterAllowedOperators, connectionFilterOperatorNames } ) => { builder.hook("build", (build) => { const { graphql: { getNamedType, GraphQLBoolean, GraphQLString, GraphQLNonNull, GraphQLList, }, pgGetGqlTypeByTypeIdAndModifier, pgIntrospectionResultsByKind: introspectionResultsByKind, pgSql: sql, gql2pg, escapeLikeWildcards, } = build; const resolveListType = (fieldInputType: GraphQLInputType) => new GraphQLList(new GraphQLNonNull(fieldInputType)); const resolveListSqlValue = ( input: unknown, pgType: PgType, pgTypeModifier: number | null, resolveListItemSqlValue: any ) => (input as unknown[]).length === 0 ? sql.query`(select null::${sql.identifier( pgType.namespaceName )}.${sql.identifier(pgType.name)} limit 0)` : sql.query`(${sql.join( (input as unknown[]).map((i) => resolveListItemSqlValue ? resolveListItemSqlValue(i, pgType, pgTypeModifier) : gql2pg(i, pgType, pgTypeModifier) ), "," )})`; const standardOperators: { [fieldName: string]: OperatorSpec } = { isNull: { description: "Is null (if `true` is specified) or is not null (if `false` is specified).", resolveType: () => GraphQLBoolean, resolveSqlValue: () => null, // do not parse resolve: (i, _v, input) => sql.query`${i} ${ input ? sql.query`IS NULL` : sql.query`IS NOT NULL` }`, }, equalTo: { description: "Equal to the specified value.", resolve: (i, v) => sql.query`${i} = ${v}`, }, notEqualTo: { description: "Not equal to the specified value.", resolve: (i, v) => sql.query`${i} <> ${v}`, }, distinctFrom: { description: "Not equal to the specified value, treating null like an ordinary value.", resolve: (i, v) => sql.query`${i} IS DISTINCT FROM ${v}`, }, notDistinctFrom: { description: "Equal to the specified value, treating null like an ordinary value.", resolve: (i, v) => sql.query`${i} IS NOT DISTINCT FROM ${v}`, }, in: { description: "Included in the specified list.", resolveType: resolveListType, resolveSqlValue: resolveListSqlValue, resolve: (i, v) => sql.query`${i} IN ${v}`, }, notIn: { description: "Not included in the specified list.", resolveType: resolveListType, resolveSqlValue: resolveListSqlValue, resolve: (i, v) => sql.query`${i} NOT IN ${v}`, }, }; const sortOperators: { [fieldName: string]: OperatorSpec } = { lessThan: { description: "Less than the specified value.", resolve: (i, v) => sql.query`${i} < ${v}`, }, lessThanOrEqualTo: { description: "Less than or equal to the specified value.", resolve: (i, v) => sql.query`${i} <= ${v}`, }, greaterThan: { description: "Greater than the specified value.", resolve: (i, v) => sql.query`${i} > ${v}`, }, greaterThanOrEqualTo: { description: "Greater than or equal to the specified value.", resolve: (i, v) => sql.query`${i} >= ${v}`, }, }; const patternMatchingOperators: { [fieldName: string]: OperatorSpec } = { includes: { description: "Contains the specified string (case-sensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}%`, resolve: (i, v) => sql.query`${i} LIKE ${v}`, }, notIncludes: { description: "Does not contain the specified string (case-sensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}%`, resolve: (i, v) => sql.query`${i} NOT LIKE ${v}`, }, includesInsensitive: { description: "Contains the specified string (case-insensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}%`, resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} ILIKE ${v}`, }, notIncludesInsensitive: { description: "Does not contain the specified string (case-insensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}%`, resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} NOT ILIKE ${v}`, }, startsWith: { description: "Starts with the specified string (case-sensitive).", resolveInput: (input) => `${escapeLikeWildcards(input)}%`, resolve: (i, v) => sql.query`${i} LIKE ${v}`, }, notStartsWith: { description: "Does not start with the specified string (case-sensitive).", resolveInput: (input) => `${escapeLikeWildcards(input)}%`, resolve: (i, v) => sql.query`${i} NOT LIKE ${v}`, }, startsWithInsensitive: { description: "Starts with the specified string (case-insensitive).", resolveInput: (input) => `${escapeLikeWildcards(input)}%`, resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} ILIKE ${v}`, }, notStartsWithInsensitive: { description: "Does not start with the specified string (case-insensitive).", resolveInput: (input) => `${escapeLikeWildcards(input)}%`, resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} NOT ILIKE ${v}`, }, endsWith: { description: "Ends with the specified string (case-sensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}`, resolve: (i, v) => sql.query`${i} LIKE ${v}`, }, notEndsWith: { description: "Does not end with the specified string (case-sensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}`, resolve: (i, v) => sql.query`${i} NOT LIKE ${v}`, }, endsWithInsensitive: { description: "Ends with the specified string (case-insensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}`, resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} ILIKE ${v}`, }, notEndsWithInsensitive: { description: "Does not end with the specified string (case-insensitive).", resolveInput: (input) => `%${escapeLikeWildcards(input)}`, resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} NOT ILIKE ${v}`, }, like: { description: "Matches the specified pattern (case-sensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters.", resolve: (i, v) => sql.query`${i} LIKE ${v}`, }, notLike: { description: "Does not match the specified pattern (case-sensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters.", resolve: (i, v) => sql.query`${i} NOT LIKE ${v}`, }, likeInsensitive: { description: "Matches the specified pattern (case-insensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters.", resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} ILIKE ${v}`, }, notLikeInsensitive: { description: "Does not match the specified pattern (case-insensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters.", resolveSqlIdentifier: (i) => i, // avoid casting citext to text resolve: (i, v) => sql.query`${i} NOT ILIKE ${v}`, }, }; const hstoreOperators: { [fieldName: string]: OperatorSpec } = { contains: { description: "Contains the specified KeyValueHash.", resolve: (i, v) => sql.query`${i} @> ${v}`, }, containsKey: { description: "Contains the specified key.", resolveType: () => GraphQLString, resolveSqlValue: (input) => sql.query`${sql.value(input)}::text`, resolve: (i, v) => sql.query`${i} ? ${v}`, }, containsAllKeys: { name: "containsAllKeys", description: "Contains all of the specified keys.", resolveType: () => new GraphQLList(new GraphQLNonNull(GraphQLString)), resolveSqlValue: (input) => sql.value(input), resolve: (i, v) => sql.query`${i} ?& ${v}`, }, containsAnyKeys: { name: "containsAnyKeys", description: "Contains any of the specified keys.", resolveType: () => new GraphQLList(new GraphQLNonNull(GraphQLString)), resolveSqlValue: (input) => sql.value(input), resolve: (i, v) => sql.query`${i} ?| ${v}`, }, containedBy: { description: "Contained by the specified KeyValueHash.", resolve: (i, v) => sql.query`${i} <@ ${v}`, }, }; const jsonbOperators: { [fieldName: string]: OperatorSpec } = { contains: { description: "Contains the specified JSON.", resolve: (i, v) => sql.query`${i} @> ${v}`, }, containsKey: { description: "Contains the specified key.", resolveType: () => GraphQLString, resolveSqlValue: (input) => sql.query`${sql.value(input)}::text`, resolve: (i, v) => sql.query`${i} ? ${v}`, }, containsAllKeys: { name: "containsAllKeys", description: "Contains all of the specified keys.", resolveType: () => new GraphQLList(new GraphQLNonNull(GraphQLString)), resolveSqlValue: (input) => sql.value(input), resolve: (i, v) => sql.query`${i} ?& ${v}`, }, containsAnyKeys: { name: "containsAnyKeys", description: "Contains any of the specified keys.", resolveType: () => new GraphQLList(new GraphQLNonNull(GraphQLString)), resolveSqlValue: (input) => sql.value(input), resolve: (i, v) => sql.query`${i} ?| ${v}`, }, containedBy: { description: "Contained by the specified JSON.", resolve: (i, v) => sql.query`${i} <@ ${v}`, }, }; const inetOperators: { [fieldName: string]: OperatorSpec } = { contains: { description: "Contains the specified internet address.", resolve: (i, v) => sql.query`${i} >> ${v}`, }, containsOrEqualTo: { description: "Contains or equal to the specified internet address.", resolve: (i, v) => sql.query`${i} >>= ${v}`, }, containedBy: { description: "Contained by the specified internet address.", resolve: (i, v) => sql.query`${i} << ${v}`, }, containedByOrEqualTo: { description: "Contained by or equal to the specified internet address.", resolve: (i, v) => sql.query`${i} <<= ${v}`, }, containsOrContainedBy: { description: "Contains or contained by the specified internet address.", resolve: (i, v) => sql.query`${i} && ${v}`, }, }; const gqlTypeNameFromPgTypeName = (pgTypeName: string) => { const pgType = (introspectionResultsByKind.type as PgType[]).find( (t) => t.name === pgTypeName ); if (!pgType) { return null; } const gqlTypeName = pgGetGqlTypeByTypeIdAndModifier(pgType.id, null).name; if (gqlTypeName === "String") { // PostGraphile v4 handles all unknown types as Strings, so we can't trust // that the String operators are appropriate. Just return null so that the // fallback type name defined below is used. return null; } return gqlTypeName; }; const _BigFloat = gqlTypeNameFromPgTypeName("numeric") || "BigFloat"; const _BigInt = gqlTypeNameFromPgTypeName("int8") || "BigInt"; const _BitString = gqlTypeNameFromPgTypeName("varbit") || "BitString"; const _Boolean = gqlTypeNameFromPgTypeName("bool") || "Boolean"; const _CidrAddress = gqlTypeNameFromPgTypeName("cidr") || "CidrAddress"; const _Date = gqlTypeNameFromPgTypeName("date") || "Date"; const _Datetime = gqlTypeNameFromPgTypeName("timestamp") || "Datetime"; const _Float = gqlTypeNameFromPgTypeName("float4") || "Float"; const _Int = gqlTypeNameFromPgTypeName("int2") || "Int"; const _InternetAddress = gqlTypeNameFromPgTypeName("inet") || "InternetAddress"; const _Interval = gqlTypeNameFromPgTypeName("interval") || "Interval"; const _JSON = gqlTypeNameFromPgTypeName("jsonb") || "JSON"; const _KeyValueHash = gqlTypeNameFromPgTypeName("hstore") || "KeyValueHash"; const _MacAddress = gqlTypeNameFromPgTypeName("macaddr") || "MacAddress"; const _MacAddress8 = gqlTypeNameFromPgTypeName("macaddr8") || "MacAddress8"; const _String = gqlTypeNameFromPgTypeName("text") || "String"; const _Time = gqlTypeNameFromPgTypeName("time") || "Time"; const _UUID = gqlTypeNameFromPgTypeName("uuid") || "UUID"; const connectionFilterScalarOperators = { [_BigFloat]: { ...standardOperators, ...sortOperators }, [_BigInt]: { ...standardOperators, ...sortOperators }, [_BitString]: { ...standardOperators, ...sortOperators }, [_Boolean]: { ...standardOperators, ...sortOperators }, [_CidrAddress]: { ...standardOperators, ...sortOperators, ...inetOperators, }, [_Date]: { ...standardOperators, ...sortOperators }, [_Datetime]: { ...standardOperators, ...sortOperators }, [_Float]: { ...standardOperators, ...sortOperators }, [_Int]: { ...standardOperators, ...sortOperators }, [_InternetAddress]: { ...standardOperators, ...sortOperators, ...inetOperators, }, [_Interval]: { ...standardOperators, ...sortOperators }, [_JSON]: { ...standardOperators, ...sortOperators, ...jsonbOperators, }, [_KeyValueHash]: { ...standardOperators, ...hstoreOperators, }, [_MacAddress]: { ...standardOperators, ...sortOperators, }, [_MacAddress8]: { ...standardOperators, ...sortOperators, }, [_String]: { ...standardOperators, ...sortOperators, ...patternMatchingOperators, }, [_Time]: { ...standardOperators, ...sortOperators }, [_UUID]: { ...standardOperators, ...sortOperators }, }; /** * This block adds the following operators: * - distinctFromInsensitive * - equalToInsensitive * - greaterThanInsensitive * - greaterThanOrEqualToInsensitive * - inInsensitive * - lessThanInsensitive * - lessThanOrEqualToInsensitive * - notDistinctFromInsensitive * - notEqualToInsensitive * - notInInsensitive * * The compiled SQL depends on the underlying PostgreSQL column type. * Using case-insensitive operators with `text`/`varchar`/`char` columns * will result in calling `lower()` on the operands. Using case-sensitive * operators with `citext` columns will result in casting the operands to `text`. * * For example, here is how the `equalTo`/`equalToInsensitive` operators compile to SQL: * | GraphQL operator | PostgreSQL column type | Compiled SQL | * | ------------------ | ----------------------- | -------------------------- | * | equalTo | `text`/`varchar`/`char` | `<col> = $1` | * | equalTo | `citext` | `<col>::text = $1::text` | * | equalToInsensitive | `text`/`varchar`/`char` | `lower(<col>) = lower($1)` | * | equalToInsensitive | `citext` | `<col> = $1` | */ for (const [name, spec] of [ ...Object.entries(standardOperators), ...Object.entries(sortOperators), ]) { if (name == "isNull") continue; const description = `${spec.description.substring( 0, spec.description.length - 1 )} (case-insensitive).`; const resolveSqlIdentifier = (sourceAlias: SQL, pgType: PgType) => pgType.name === "citext" ? sourceAlias // already case-insensitive, so no need to call `lower()` : sql.query`lower(${sourceAlias})`; const resolveSimpleSqlValue = ( input: unknown, pgType: PgType, pgTypeModifier: number | null ) => pgType.name === "citext" ? gql2pg(input, pgType, pgTypeModifier) // already case-insensitive, so no need to call `lower()` : sql.query`lower(${gql2pg(input, pgType, pgTypeModifier)})`; const resolveSqlValue = ( input: unknown, pgType: PgType, pgTypeModifier: number | null ) => name === "in" || name === "notIn" ? resolveListSqlValue( input, pgType, pgTypeModifier, resolveSimpleSqlValue ) : resolveSimpleSqlValue(input, pgType, pgTypeModifier); connectionFilterScalarOperators[_String][`${name}Insensitive`] = { ...spec, description, resolveSqlIdentifier, resolveSqlValue, }; } const connectionFilterEnumOperators = { ...standardOperators, ...sortOperators, }; const connectionFilterRangeOperators: { [fieldName: string]: OperatorSpec; } = { ...standardOperators, ...sortOperators, contains: { description: "Contains the specified range.", resolve: (i, v) => sql.query`${i} @> ${v}`, }, containsElement: { description: "Contains the specified value.", resolveType: ( _fieldInputType: GraphQLInputType, rangeElementInputType: GraphQLInputType ) => rangeElementInputType, resolveSqlValue: (input, pgType, pgTypeModifier) => { const rangeSubType = introspectionResultsByKind.typeById[(pgType as any).rangeSubTypeId]; return sql.query`${gql2pg( input, (pgType as any).rangeSubTypeId, pgTypeModifier )}::${sql.identifier(rangeSubType.namespaceName, rangeSubType.name)}`; }, resolve: (i, v) => sql.query`${i} @> ${v}`, }, containedBy: { description: "Contained by the specified range.", resolve: (i, v) => sql.query`${i} <@ ${v}`, }, overlaps: { description: "Overlaps the specified range.", resolve: (i, v) => sql.query`${i} && ${v}`, }, strictlyLeftOf: { description: "Strictly left of the specified range.", resolve: (i, v) => sql.query`${i} << ${v}`, }, strictlyRightOf: { description: "Strictly right of the specified range.", resolve: (i, v) => sql.query`${i} >> ${v}`, }, notExtendsRightOf: { description: "Does not extend right of the specified range.", resolve: (i, v) => sql.query`${i} &< ${v}`, }, notExtendsLeftOf: { description: "Does not extend left of the specified range.", resolve: (i, v) => sql.query`${i} &> ${v}`, }, adjacentTo: { description: "Adjacent to the specified range.", resolve: (i, v) => sql.query`${i} -|- ${v}`, }, }; const resolveArrayItemType = (fieldInputType: GraphQLInputType) => getNamedType(fieldInputType); const resolveArrayItemSqlValue = ( input: unknown, pgType: PgType, pgTypeModifier: number | null ) => gql2pg(input, pgType.arrayItemType, pgTypeModifier); const connectionFilterArrayOperators: { [fieldName: string]: OperatorSpec; } = { isNull: standardOperators.isNull, equalTo: standardOperators.equalTo, notEqualTo: standardOperators.notEqualTo, distinctFrom: standardOperators.distinctFrom, notDistinctFrom: standardOperators.notDistinctFrom, ...sortOperators, contains: { description: "Contains the specified list of values.", resolve: (i, v) => sql.query`${i} @> ${v}`, }, containedBy: { description: "Contained by the specified list of values.", resolve: (i, v) => sql.query`${i} <@ ${v}`, }, overlaps: { description: "Overlaps the specified list of values.", resolve: (i, v) => sql.query`${i} && ${v}`, }, anyEqualTo: { description: "Any array item is equal to the specified value.", resolveType: resolveArrayItemType, resolveSqlValue: resolveArrayItemSqlValue, resolve: (i, v) => sql.query`${v} = ANY (${i})`, }, anyNotEqualTo: { description: "Any array item is not equal to the specified value.", resolveType: resolveArrayItemType, resolveSqlValue: resolveArrayItemSqlValue, resolve: (i, v) => sql.query`${v} <> ANY (${i})`, }, anyLessThan: { description: "Any array item is less than the specified value.", resolveType: resolveArrayItemType, resolveSqlValue: resolveArrayItemSqlValue, resolve: (i, v) => sql.query`${v} > ANY (${i})`, }, anyLessThanOrEqualTo: { description: "Any array item is less than or equal to the specified value.", resolveType: resolveArrayItemType, resolveSqlValue: resolveArrayItemSqlValue, resolve: (i, v) => sql.query`${v} >= ANY (${i})`, }, anyGreaterThan: { description: "Any array item is greater than the specified value.", resolveType: resolveArrayItemType, resolveSqlValue: resolveArrayItemSqlValue, resolve: (i, v) => sql.query`${v} < ANY (${i})`, }, anyGreaterThanOrEqualTo: { description: "Any array item is greater than or equal to the specified value.", resolveType: resolveArrayItemType, resolveSqlValue: resolveArrayItemSqlValue, resolve: (i, v) => sql.query`${v} <= ANY (${i})`, }, }; return build.extend(build, { connectionFilterArrayOperators, connectionFilterEnumOperators, connectionFilterRangeOperators, connectionFilterScalarOperators, }); }); builder.hook("GraphQLInputObjectType:fields", (fields, build, context) => { const { extend, gql2pg, pgIntrospectionResultsByKind: introspectionResultsByKind, pgSql: sql, connectionFilterRegisterResolver, connectionFilterTypesByTypeName, connectionFilterArrayOperators, connectionFilterEnumOperators, connectionFilterRangeOperators, connectionFilterScalarOperators, } = build; const { scope: { isPgConnectionFilterOperators, pgConnectionFilterOperatorsCategory, fieldType, fieldInputType, rangeElementInputType, domainBaseType, }, fieldWithHooks, Self, } = context as Context<GraphQLInputFieldConfigMap> & { scope: { isPgConnectionFilterOperators?: boolean; pgConnectionFilterOperatorsCategory?: | "Array" | "Range" | "Enum" | "Domain" | "Scalar"; }; }; if ( !isPgConnectionFilterOperators || !pgConnectionFilterOperatorsCategory || !fieldType || !fieldInputType ) { return fields; } connectionFilterTypesByTypeName[Self.name] = Self; const operatorSpecsByCategory: { [category: string]: OperatorSpec[] } = { Array: connectionFilterArrayOperators, Range: connectionFilterRangeOperators, Enum: connectionFilterEnumOperators, Domain: domainBaseType ? connectionFilterScalarOperators[domainBaseType.name] : {}, Scalar: connectionFilterScalarOperators[fieldType.name], }; const operatorSpecs = operatorSpecsByCategory[pgConnectionFilterOperatorsCategory]; if (!operatorSpecs) { return fields; } const operatorSpecByFieldName: { [fieldName: string]: OperatorSpec } = {}; const operatorFields = Object.entries(operatorSpecs).reduce( (memo: { [fieldName: string]: any }, [name, spec]) => { const { description, resolveType } = spec; if ( connectionFilterAllowedOperators && !connectionFilterAllowedOperators.includes(name) ) { return memo; } const type = resolveType ? resolveType(fieldInputType, rangeElementInputType) : fieldInputType; const operatorName = (connectionFilterOperatorNames && connectionFilterOperatorNames[name]) || name; operatorSpecByFieldName[operatorName] = spec; memo[operatorName] = fieldWithHooks( operatorName, { description, type, }, { isPgConnectionFilterOperator: true, } ); return memo; }, {} ); const textPgType = (introspectionResultsByKind.type as PgType[]).find( (t) => t.name === "text" ); const textArrayPgType = (introspectionResultsByKind.type as PgType[]).find( (t) => t.name === "_text" ); const resolve: ConnectionFilterResolver = ({ sourceAlias, fieldName, fieldValue, queryBuilder, pgType, pgTypeModifier, parentFieldName, }) => { if (fieldValue == null) return null; const operatorSpec = operatorSpecByFieldName[fieldName]; const { resolveInput, resolveSqlIdentifier, resolveSqlValue, } = operatorSpec; const sqlIdentifier = resolveSqlIdentifier ? resolveSqlIdentifier(sourceAlias, pgType, pgTypeModifier) : pgType.name === "citext" ? sql.query`${sourceAlias}::text` // cast column to text for case-sensitive matching : pgType.name === "_citext" ? sql.query`${sourceAlias}::text[]` // cast column to text[] for case-sensitive matching : sourceAlias; const input = fieldValue; const resolvedInput = resolveInput ? resolveInput(input) : input; const sqlValue = resolveSqlValue ? resolveSqlValue(input, pgType, pgTypeModifier) : pgType.name === "citext" ? gql2pg(resolvedInput, textPgType, null) // cast input to text : pgType.name === "_citext" ? gql2pg(resolvedInput, textArrayPgType, null) // cast input to text[] : gql2pg(resolvedInput, pgType, pgTypeModifier); return operatorSpec.resolve( sqlIdentifier, sqlValue, input, parentFieldName, queryBuilder ); }; for (const fieldName of Object.keys(operatorFields)) { connectionFilterRegisterResolver(Self.name, fieldName, resolve); } return extend(fields, operatorFields); }); }; export interface OperatorSpec { name?: string; description: string; resolveInput?: (input: unknown) => unknown; resolveSql?: any; resolveSqlIdentifier?: ( sqlIdentifier: SQL, pgType: PgType, pgTypeModifier: number | null ) => SQL; resolveSqlValue?: ( input: unknown, pgType: PgType, pgTypeModifier: number | null, resolveListItemSqlValue?: any ) => SQL | null; resolveType?: ( fieldInputType: GraphQLInputType, rangeElementInputType: GraphQLInputType ) => GraphQLType; resolve: ( sqlIdentifier: SQL, sqlValue: SQL, input: unknown, parentFieldName: string, queryBuilder: QueryBuilder ) => SQL | null; } export default PgConnectionArgFilterOperatorsPlugin;
the_stack
// Copyright 2018-2021 the oak authors. All rights reserved. MIT license. import { Context } from "./context.ts"; import { serve as defaultServe, serveTLS as defaultServeTls, Status, STATUS_TEXT, } from "./deps.ts"; import { Key, KeyStack } from "./keyStack.ts"; import { compose, Middleware } from "./middleware.ts"; import type { Serve, Server, ServerRequest, ServerResponse, ServeTls, } from "./types.d.ts"; export interface ListenOptionsBase { hostname?: string; port: number; secure?: false; signal?: AbortSignal; } export interface ListenOptionsTls { certFile: string; hostname?: string; keyFile: string; port: number; secure: true; signal?: AbortSignal; } export type ListenOptions = ListenOptionsTls | ListenOptionsBase; function isOptionsTls(options: ListenOptions): options is ListenOptionsTls { return options.secure === true; } interface ApplicationErrorEventListener<S> { (evt: ApplicationErrorEvent<S>): void | Promise<void>; } interface ApplicationErrorEventListenerObject<S> { handleEvent(evt: ApplicationErrorEvent<S>): void | Promise<void>; } interface ApplicationErrorEventInit<S extends State> extends ErrorEventInit { context?: Context<S>; } type ApplicationErrorEventListenerOrEventListenerObject<S> = | ApplicationErrorEventListener<S> | ApplicationErrorEventListenerObject<S>; interface ApplicationListenEventListener { (evt: ApplicationListenEvent): void | Promise<void>; } interface ApplicationListenEventListenerObject { handleEvent(evt: ApplicationListenEvent): void | Promise<void>; } interface ApplicationListenEventInit extends EventInit { hostname?: string; port: number; secure: boolean; } type ApplicationListenEventListenerOrEventListenerObject = | ApplicationListenEventListener | ApplicationListenEventListenerObject; export interface ApplicationOptions<S> { /** An initial set of keys (or instance of `KeyGrip`) to be used for signing * cookies produced by the application. */ keys?: KeyStack | Key[]; /** If set to `true`, proxy headers will be trusted when processing requests. * This defaults to `false`. */ proxy?: boolean; /** The `server()` function to be used to read requests. * * _Not used generally, as this is just for mocking for test purposes_ */ serve?: Serve; /** The `server()` function to be used to read requests. * * _Not used generally, as this is just for mocking for test purposes_ */ serveTls?: ServeTls; /** The initial state object for the application, of which the type can be * used to infer the type of the state for both the application and any of the * application's context. */ state?: S; } interface RequestState { handling: Set<Promise<void>>; closing: boolean; closed: boolean; server: Server; } // deno-lint-ignore no-explicit-any export type State = Record<string | number | symbol, any>; const ADDR_REGEXP = /^\[?([^\]]*)\]?:([0-9]{1,5})$/; export class ApplicationErrorEvent<S extends State> extends ErrorEvent { context?: Context<S>; constructor(eventInitDict: ApplicationErrorEventInit<S>) { super("error", eventInitDict); this.context = eventInitDict.context; } } export class ApplicationListenEvent extends Event { hostname?: string; port: number; secure: boolean; constructor(eventInitDict: ApplicationListenEventInit) { super("listen", eventInitDict); this.hostname = eventInitDict.hostname; this.port = eventInitDict.port; this.secure = eventInitDict.secure; } } /** A class which registers middleware (via `.use()`) and then processes * inbound requests against that middleware (via `.listen()`). * * The `context.state` can be typed via passing a generic argument when * constructing an instance of `Application`. */ // deno-lint-ignore no-explicit-any export class Application<AS extends State = Record<string, any>> extends EventTarget { #composedMiddleware?: (context: Context<AS>) => Promise<void>; #keys?: KeyStack; #middleware: Middleware<State, Context<State>>[] = []; #serve: Serve; #serveTls: ServeTls; /** A set of keys, or an instance of `KeyStack` which will be used to sign * cookies read and set by the application to avoid tampering with the * cookies. */ get keys(): KeyStack | Key[] | undefined { return this.#keys; } set keys(keys: KeyStack | Key[] | undefined) { if (!keys) { this.#keys = undefined; return; } else if (Array.isArray(keys)) { this.#keys = new KeyStack(keys); } else { this.#keys = keys; } } /** If `true`, proxy headers will be trusted when processing requests. This * defaults to `false`. */ proxy: boolean; /** Generic state of the application, which can be specified by passing the * generic argument when constructing: * * const app = new Application<{ foo: string }>(); * * Or can be contextually inferred based on setting an initial state object: * * const app = new Application({ state: { foo: "bar" } }); * */ state: AS; constructor(options: ApplicationOptions<AS> = {}) { super(); const { state, keys, proxy, serve = defaultServe, serveTls = defaultServeTls, } = options; this.proxy = proxy ?? false; this.keys = keys; this.state = state ?? {} as AS; this.#serve = serve; this.#serveTls = serveTls; } #getComposed = (): ((context: Context<AS>) => Promise<void>) => { if (!this.#composedMiddleware) { this.#composedMiddleware = compose(this.#middleware); } return this.#composedMiddleware; }; /** Deal with uncaught errors in either the middleware or sending the * response. */ // deno-lint-ignore no-explicit-any #handleError = (context: Context<AS>, error: any): void => { if (!(error instanceof Error)) { error = new Error(`non-error thrown: ${JSON.stringify(error)}`); } const { message } = error; this.dispatchEvent(new ApplicationErrorEvent({ context, message, error })); if (!context.response.writable) { return; } for (const key of context.response.headers.keys()) { context.response.headers.delete(key); } if (error.headers && error.headers instanceof Headers) { for (const [key, value] of error.headers) { context.response.headers.set(key, value); } } context.response.type = "text"; const status: Status = context.response.status = error instanceof Deno.errors.NotFound ? 404 : error.status && typeof error.status === "number" ? error.status : 500; context.response.body = error.expose ? error.message : STATUS_TEXT.get(status); }; /** Processing registered middleware on each request. */ #handleRequest = async ( request: ServerRequest, secure: boolean, state: RequestState, ): Promise<void> => { const context = new Context(this, request, secure); let resolve: () => void; const handlingPromise = new Promise<void>((res) => resolve = res); state.handling.add(handlingPromise); if (!state.closing && !state.closed) { try { await this.#getComposed()(context); } catch (err) { this.#handleError(context, err); } } if (context.respond === false) { context.response.destroy(); resolve!(); state.handling.delete(handlingPromise); return; } try { await request.respond(await context.response.toServerResponse()); if (state.closing) { state.server.close(); state.closed = true; } } catch (err) { this.#handleError(context, err); } finally { context.response.destroy(); resolve!(); state.handling.delete(handlingPromise); } }; /** Add an event listener for an `"error"` event which occurs when an * un-caught error occurs when processing the middleware or during processing * of the response. */ addEventListener( type: "error", listener: ApplicationErrorEventListenerOrEventListenerObject<AS> | null, options?: boolean | AddEventListenerOptions, ): void; /** Add an event listener for a `"listen"` event which occurs when the server * has successfully opened but before any requests start being processed. */ addEventListener( type: "listen", listener: ApplicationListenEventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions, ): void; /** Add an event listener for an event. Currently valid event types are * `"error"` and `"listen"`. */ addEventListener( type: "error" | "listen", listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions, ): void { super.addEventListener(type, listener, options); } /** Handle an individual server request, returning the server response. This * is similar to `.listen()`, but opening the connection and retrieving * requests are not the responsibility of the application. If the generated * context gets set to not to respond, then the method resolves with * `undefined`, otherwise it resolves with a request that is compatible with * `std/http/server`. */ handle = async ( request: ServerRequest, secure = false, ): Promise<ServerResponse | undefined> => { if (!this.#middleware.length) { throw new TypeError("There is no middleware to process requests."); } const context = new Context(this, request, secure); try { await this.#getComposed()(context); } catch (err) { this.#handleError(context, err); } if (context.respond === false) { context.response.destroy(); return; } try { const response = await context.response.toServerResponse(); context.response.destroy(); return response; } catch (err) { this.#handleError(context, err); throw err; } }; /** Start listening for requests, processing registered middleware on each * request. If the options `.secure` is undefined or `false`, the listening * will be over HTTP. If the options `.secure` property is `true`, a * `.certFile` and a `.keyFile` property need to be supplied and requests * will be processed over HTTPS. */ async listen(addr: string): Promise<void>; /** Start listening for requests, processing registered middleware on each * request. If the options `.secure` is undefined or `false`, the listening * will be over HTTP. If the options `.secure` property is `true`, a * `.certFile` and a `.keyFile` property need to be supplied and requests * will be processed over HTTPS. */ async listen(options: ListenOptions): Promise<void>; async listen(options: string | ListenOptions): Promise<void> { if (!this.#middleware.length) { throw new TypeError("There is no middleware to process requests."); } if (typeof options === "string") { const match = ADDR_REGEXP.exec(options); if (!match) { throw TypeError(`Invalid address passed: "${options}"`); } const [, hostname, portStr] = match; options = { hostname, port: parseInt(portStr, 10) }; } const server = isOptionsTls(options) ? this.#serveTls(options) : this.#serve(options); const { signal } = options; const state = { closed: false, closing: false, handling: new Set<Promise<void>>(), server, }; if (signal) { signal.addEventListener("abort", () => { if (!state.handling.size) { server.close(); state.closed = true; } state.closing = true; }); } const { hostname, port, secure = false } = options; this.dispatchEvent( new ApplicationListenEvent({ hostname, port, secure }), ); try { for await (const request of server) { this.#handleRequest(request, secure, state); } await Promise.all(state.handling); } catch (error) { const message = error instanceof Error ? error.message : "Application Error"; this.dispatchEvent( new ApplicationErrorEvent({ message, error }), ); } } /** Register middleware to be used with the application. Middleware will * be processed in the order it is added, but middleware can control the flow * of execution via the use of the `next()` function that the middleware * function will be called with. The `context` object provides information * about the current state of the application. * * Basic usage: * * ```ts * const import { Application } from "https://deno.land/x/oak/mod.ts"; * * const app = new Application(); * * app.use((ctx, next) => { * ctx.request; // contains request information * ctx.response; // setups up information to use in the response; * await next(); // manages the flow control of the middleware execution * }); * * await app.listen({ port: 80 }); * ``` */ use<S extends State = AS>( ...middleware: Middleware<S, Context<S>>[] ): Application<S extends AS ? S : (S & AS)> { this.#middleware.push(...middleware); this.#composedMiddleware = undefined; // deno-lint-ignore no-explicit-any return this as Application<any>; } }
the_stack
const iconRegistry = new Map<string, string>(); export function addSVGIcon(path: string | string[], svgDataURL: string) { if (path instanceof Array) { for (const p of path) { iconRegistry.set(p, svgDataURL); } } else { iconRegistry.set(path, svgDataURL); } } export function getSVGIcon(path: string): string { const r = iconRegistry.get(path); if (r) { return r; } else { console.warn(`Icon ${path} is undefined, using default instead`); addSVGIcon(path, getSVGIcon("ChromeClose")); return getSVGIcon("ChromeClose"); } } addSVGIcon("ChevronUp", require("resources/icons/icons_chevron_up.svg")); addSVGIcon("ChevronDown", require("resources/icons/icons_chevron_down.svg")); addSVGIcon("ChevronRight", require("resources/icons/icons_chevron_right.svg")); addSVGIcon("ChevronLeft", require("resources/icons/icons_chevron_left.svg")); // General icons addSVGIcon("ChromeClose", require("resources/icons/icons_cross.svg")); addSVGIcon("general/plus", require("resources/icons/icons_plus.svg")); addSVGIcon("general/minus", require("resources/icons/icons_minus.svg")); addSVGIcon("Copy", require("resources/icons/icons_copy.svg")); addSVGIcon("general/sort", require("resources/icons/icons_sort.svg")); addSVGIcon("Sort", require("resources/icons/icons_reverse-order.svg")); addSVGIcon("general/dropdown", require("resources/icons/icons_dropdown.svg")); addSVGIcon("Edit", require("resources/icons/icons_edit.svg")); addSVGIcon("general/eraser", require("resources/icons/icons_eraser.svg")); addSVGIcon("general/bind-data", require("resources/icons/icons_bind-data.svg")); addSVGIcon("general/confirm", require("resources/icons/icons_confirm.svg")); addSVGIcon( "general/more-horizontal", require("resources/icons/icons_more-horizontal.svg") ); addSVGIcon( "general/more-vertical", require("resources/icons/icons_more-vertical.svg") ); addSVGIcon("general/replace", require("resources/icons/icons_replace.svg")); addSVGIcon("general/eye", require("resources/icons/icons_eye.svg")); addSVGIcon("general/eye-faded", require("resources/icons/icons_eye-faded.svg")); addSVGIcon("general/popout", require("resources/icons/icons_popout.svg")); addSVGIcon("SortLines", require("resources/icons/icons_order.svg")); addSVGIcon("ZoomIn", require("resources/icons/icons_zoom-in.svg")); addSVGIcon("ZoomOut", require("resources/icons/icons_zoom-out.svg")); addSVGIcon("ZoomToFit", require("resources/icons/icons_zoom-auto.svg")); addSVGIcon( "general/triangle-up", require("resources/icons/icons_triangle-up.svg") ); addSVGIcon( "general/triangle-down", require("resources/icons/icons_triangle-down.svg") ); addSVGIcon( "general/triangle-left", require("resources/icons/icons_triangle-left.svg") ); addSVGIcon( "general/triangle-right-bottom", require("resources/icons/icons_triangle-right-bottom.svg") ); addSVGIcon( "general/triangle-right", require("resources/icons/icons_triangle-right.svg") ); addSVGIcon( "general/text-size-up", require("resources/icons/icons_text-size-up.svg") ); addSVGIcon( "general/text-size-down", require("resources/icons/icons_text-size-down.svg") ); addSVGIcon( "general/digits-more", require("resources/icons/icons_digits-more.svg") ); addSVGIcon( "general/digits-less", require("resources/icons/icons_digits-less.svg") ); // Toolbar icons addSVGIcon("toolbar/new", require("resources/icons/icons_toolbar-new.svg")); addSVGIcon("toolbar/open", require("resources/icons/icons_toolbar-open.svg")); addSVGIcon("toolbar/save", require("resources/icons/icons_toolbar-save.svg")); addSVGIcon( "toolbar/save-changes", require("resources/icons/icons_toolbar-save-has-changes.svg") ); addSVGIcon("toolbar/copy", require("resources/icons/icons_toolbar-copy.svg")); addSVGIcon( "toolbar/download", require("resources/icons/icons_toolbar-download.svg") ); addSVGIcon( "toolbar/export-template", require("resources/icons/icons_toolbar-export-template.svg") ); addSVGIcon( "toolbar/export", require("resources/icons/icons_toolbar-export.svg") ); addSVGIcon("Undo", require("resources/icons/icons_toolbar-undo.svg")); addSVGIcon("Redo", require("resources/icons/icons_toolbar-redo.svg")); addSVGIcon("toolbar/help", require("resources/icons/icons_toolbar-help.svg")); addSVGIcon( "toolbar/import", require("resources/icons/icons_toolbar-import.svg") ); addSVGIcon( "toolbar/import-template", require("resources/icons/icons_toolbar-import-template.svg") ); addSVGIcon("toolbar/back", require("resources/icons/icons_toolbar-back.svg")); addSVGIcon("toolbar/trash", require("resources/icons/icons_toolbar-trash.svg")); addSVGIcon("app-icon", require("resources/icons/app_icon.svg")); // Scaffold icons addSVGIcon( "scaffold/cartesian-x", require("resources/icons/icons_scaffold-xline.svg") ); addSVGIcon( "scaffold/cartesian-y", require("resources/icons/icons_scaffold-yline.svg") ); addSVGIcon( "scaffold/circle", require("resources/icons/icons_scaffold-circle.svg") ); addSVGIcon( "scaffold/curve", require("resources/icons/icons_scaffold-curve.svg") ); addSVGIcon( "scaffold/spiral", require("resources/icons/icons_scaffold-spiral.svg") ); addSVGIcon( "GripperBarHorizontal", require("resources/icons/icons_scaffold-xwrap.svg") ); addSVGIcon( "GripperBarVertical", require("resources/icons/icons_scaffold-ywrap.svg") ); addSVGIcon("scaffold/map", require("resources/icons/icons_scaffold-map.svg")); addSVGIcon("Line", require("resources/icons/icons_plot-line.svg")); addSVGIcon("plot/curve", require("resources/icons/icons_plot-curve.svg")); addSVGIcon("BorderDot", require("resources/icons/icons_plot-region.svg")); // Chart & Glyph addSVGIcon("chart", require("resources/icons/icons_chart.svg")); addSVGIcon("glyph", require("resources/icons/icons_glyph.svg")); // Plot segment icons addSVGIcon( "plot-segment/cartesian", require("resources/icons/icons_plot-segment-cartesian.svg") ); addSVGIcon( "plot-segment/polar", require("resources/icons/icons_plot-segment-polar.svg") ); addSVGIcon( "plot-segment/line", require("resources/icons/icons_plot-segment-line.svg") ); addSVGIcon( "plot-segment/curve", require("resources/icons/icons_plot-segment-curve.svg") ); // Guide icons addSVGIcon("guide/x", require("resources/icons/icons_guide-xline.svg")); addSVGIcon("guide/y", require("resources/icons/icons_guide-yline.svg")); addSVGIcon( "guide/coordinator-x", require("resources/icons/icons_guide-coordinator-x.svg") ); addSVGIcon( "guide/coordinator-y", require("resources/icons/icons_guide-coordinator-y.svg") ); addSVGIcon( "guide/coordinator-polar", require("resources/icons/icons_guide-coordinator-polar.svg") ); // Link icons addSVGIcon("CharticulatorLine", require("resources/icons/icons_link-tool.svg")); addSVGIcon("link/line", require("resources/icons/icons_link-line.svg")); addSVGIcon("link/band", require("resources/icons/icons_link-band.svg")); addSVGIcon("link/between", require("resources/icons/icons_link-between.svg")); addSVGIcon("link/table", require("resources/icons/icons_link-table.svg")); addSVGIcon("link/through", require("resources/icons/icons_link-through.svg")); // Mark element icons addSVGIcon("mark/anchor", require("resources/icons/icons_element-anchor.svg")); addSVGIcon("RectangleShape", require("resources/icons/icons_element-rect.svg")); addSVGIcon("Ellipse", require("resources/icons/icons_element-ellipse.svg")); addSVGIcon( "TriangleShape", require("resources/icons/icons_element-triangle.svg") ); addSVGIcon("FileImage", require("resources/icons/icons_element-image.svg")); addSVGIcon("ImagePixel", require("resources/icons/icons_element-icon.svg")); addSVGIcon("Shapes", require("resources/icons/icons_element-symbol.svg")); addSVGIcon("Line", require("resources/icons/icons_element-line.svg")); addSVGIcon("FontColorA", require("resources/icons/icons_element-text.svg")); addSVGIcon("TextField", require("resources/icons/icons_element-textbox.svg")); addSVGIcon("mark/data-axis", require("resources/icons/icons_data-axis.svg")); addSVGIcon("rect-zoom", require("resources/icons/rect-zoom.svg")); addSVGIcon( "BarChartVerticalFilter", require("resources/icons/icons_nested-chart.svg") ); addSVGIcon("stroke/dashed", require("resources/icons/icons_stroke-dashed.svg")); addSVGIcon("stroke/dotted", require("resources/icons/icons_stroke-dotted.svg")); addSVGIcon("stroke/solid", require("resources/icons/icons_stroke-solid.svg")); // Handle icons addSVGIcon("Stack", require("resources/icons/icons_sublayout-overlap.svg")); addSVGIcon( "HorizontalDistributeCenter", require("resources/icons/icons_sublayout-dodge-horizontal.svg") ); addSVGIcon( "VerticalDistributeCenter", require("resources/icons/icons_sublayout-dodge-vertical.svg") ); addSVGIcon( "CharticulatorArrangePolar", require("resources/icons/icons_sublayout-dodge-angular.svg") ); addSVGIcon( "CharticulatorStackRadial", require("resources/icons/icons_sublayout-dodge-radial.svg") ); addSVGIcon( "GridViewSmall", require("resources/icons/icons_sublayout-grid.svg") ); addSVGIcon( "sublayout/polar-grid", require("resources/icons/icons_sublayout-polar-grid.svg") ); addSVGIcon( "sublayout/packing", require("resources/icons/icons_sublayout-packing.svg") ); addSVGIcon( "sublayout/jitter", require("resources/icons/icons_sublayout-jitter.svg") ); addSVGIcon("align/left", require("resources/icons/icons_align-left.svg")); addSVGIcon( "AlignHorizontalLeft", require("resources/icons/icons_align-left.svg") ); addSVGIcon( "AlignHorizontalCenter", require("resources/icons/icons_align-x-middle.svg") ); addSVGIcon( "AlignHorizontalRight", require("resources/icons/icons_align-right.svg") ); addSVGIcon("AlignVerticalTop", require("resources/icons/icons_align-top.svg")); addSVGIcon( "AlignVerticalCenter", require("resources/icons/icons_align-y-middle.svg") ); addSVGIcon( "AlignVerticalBottom", require("resources/icons/icons_align-bottom.svg") ); addSVGIcon( "text-align/left", require("resources/icons/icons_text-align-left.svg") ); addSVGIcon( "text-align/x-middle", require("resources/icons/icons_text-align-x-middle.svg") ); addSVGIcon( "text-align/right", require("resources/icons/icons_text-align-right.svg") ); addSVGIcon( "text-align/top", require("resources/icons/icons_text-align-top.svg") ); addSVGIcon( "text-align/y-middle", require("resources/icons/icons_text-align-y-middle.svg") ); addSVGIcon( "text-align/bottom", require("resources/icons/icons_text-align-bottom.svg") ); // Data type icons addSVGIcon("type/boolean", require("resources/icons/icons_type-boolean.svg")); addSVGIcon( "type/categorical", require("resources/icons/icons_type-categorical.svg") ); addSVGIcon( "type/numerical", require("resources/icons/icons_type-numerical.svg") ); addSVGIcon("type/ordinal", require("resources/icons/icons_type-ordinal.svg")); addSVGIcon("type/temporal", require("resources/icons/icons_type-temporal.svg")); // Checkbox addSVGIcon( "checkbox/empty", require("resources/icons/icons_checkbox-empty.svg") ); addSVGIcon( "checkbox/checked", require("resources/icons/icons_checkbox-checked.svg") ); addSVGIcon("CharticulatorLegend", require("resources/icons/icons_legend.svg")); addSVGIcon("scale/scale", require("resources/icons/icons_scale.svg")); addSVGIcon("scale/color", require("resources/icons/icons_scale-color.svg")); addSVGIcon("loading", require("resources/icons/loading-01.svg"));
the_stack
import Canvas = etch.drawing.Canvas; import DisplayObject = etch.drawing.DisplayObject; import DisplayObjectCollection = etch.drawing.DisplayObjectCollection; import IDisplayObject = etch.drawing.IDisplayObject; import Point = minerva.Point; import {AddressBarManager} from './Core/Visual/AddressBarManager'; import {AnimationsLayer} from './UI/AnimationsLayer'; import {Audio} from './Core/Audio/Audio'; import {BlockSprites} from './Blocks/BlockSprites'; import {ColorManager} from './Core/Visual/ColorManager'; import {CommandHandlerFactory} from './Core/Resources/CommandHandlerFactory'; import {CommandManager} from './Core/Commands/CommandManager'; import {CommandsInputManager} from './Core/Inputs/CommandsInputManager'; import {Commands} from './Commands'; import {CompositionLoadedEventArgs} from './CompositionLoadedEventArgs'; import {CreateBlockCommandHandler} from './CommandHandlers/CreateBlockCommandHandler'; import {DeleteBlockCommandHandler} from './CommandHandlers/DeleteBlockCommandHandler'; import {Effect} from './Blocks/Effect'; import {FocusManagerEventArgs} from './Core/Inputs/FocusManagerEventArgs'; import {FocusManager} from './Core/Inputs/FocusManager'; import {IApp} from './IApp'; import {IBlock} from './Blocks/IBlock'; import {IConfig} from './IConfig'; import {IEffect} from './Blocks/IEffect'; import {IL10n} from './IL10n'; import {IPowerEffect} from './Blocks/Power/IPowerEffect'; import {IPowerSource} from './Blocks/Power/IPowerSource'; import {ISource} from './Blocks/ISource'; import {LoadCommandHandler} from './CommandHandlers/LoadCommandHandler'; import {MainScene} from './MainScene'; import {Metrics} from './Metrics'; import {MoveBlockCommandHandler} from './CommandHandlers/MoveBlockCommandHandler'; import {OperationManager} from './Core/Operations/OperationManager'; import {Particle} from './Particle'; import {PianoKeyboardManager} from './Core/Inputs/PianoKeyboardManager'; import {PointerInputManager} from './Core/Inputs/PointerInputManager'; import {PooledFactoryResource} from './Core/Resources/PooledFactoryResource'; import {PowerEffect} from './Blocks/Power/PowerEffect'; import {PowerSource} from './Blocks/Power/PowerSource'; import {RedoCommandHandler} from './CommandHandlers/RedoCommandHandler'; import {ResourceManager} from './Core/Resources/ResourceManager'; import {SaveAsCommandHandler} from './CommandHandlers/SaveAsCommandHandler'; import {SaveCommandHandler} from './CommandHandlers/SaveCommandHandler'; import {SaveFile} from './SaveFile'; import {Serializer} from './Serializer'; import {SoundCloudAPI} from './Core/Audio/SoundCloud/SoundCloudAPI'; import {Source} from './Blocks/Source'; import {Stage} from './Stage'; import {ThemeChangeEventArgs} from './Core/Visual/ThemeChangeEventArgs'; import {ThemeManager} from './Core/Visual/ThemeManager'; import {TypingManager} from './Core/Inputs/TypingManager'; import {UndoCommandHandler} from './CommandHandlers/UndoCommandHandler'; import {BlockCreator} from './BlockCreator'; import {CommandCategories} from './CommandCategories'; import {Errors} from './Errors'; import {GAVariables} from './GAVariables'; import {CompositionLoadFailedEventArgs} from "./CompositionLoadFailedEventArgs"; //import {DragFileInputManager} from './Core/Inputs/DragFileInputManager'; export default class App implements IApp{ CompositionLoaded = new nullstone.Event<CompositionLoadedEventArgs>(); CompositionLoadFailed = new nullstone.Event<CompositionLoadFailedEventArgs>(); private _FontsLoaded: number; private _SaveFile: SaveFile; private _SessionId: string; public AddressBarManager: AddressBarManager; public Audio: Audio = new Audio(); public Blocks: IBlock[] = []; public BlockCreator: BlockCreator; public BlockSprites: BlockSprites; public Canvas: Canvas; public ColorManager: ColorManager; public CommandManager: CommandManager; public CommandsInputManager: CommandsInputManager; public CompositionId: string; public CompositionName: string; public Config: IConfig; //public DragFileInputManager: DragFileInputManager; public DragOffset: Point = new Point(0, 0); public FocusManager: FocusManager; public GridSize: number; public Height: number; public IsLoadingComposition: boolean = false; public L10n: IL10n; public Metrics: Metrics; public OperationManager: OperationManager; public Palette: string[] = []; public Particles: Particle[] = []; public ParticlesPool: PooledFactoryResource<Particle>; public PianoKeyboardManager: PianoKeyboardManager; public PointerInputManager: PointerInputManager; public ResourceManager: ResourceManager; public ScaledDragOffset: Point; public ScaledGridSize: number; public ScaledUnit: number; public Stage: Stage; public SubCanvas: HTMLCanvasElement[]; public ThemeManager: ThemeManager; public TypingManager: TypingManager; public Unit: number; public Width: number; public ZoomLevel: number; get AnimationsLayer(): AnimationsLayer{ return this.MainScene.AnimationsLayer; } get MainScene(): MainScene { return this.Stage.MainScene; //TODO: trying to reference Stage from one of it's children at init comes back undefined, which is impossible (eg in the init of CreateNew) } get Sources(): ISource[] { return <ISource[]>this.Blocks.en().where(b => b instanceof Source).toArray(); } get Effects(): IEffect[] { return <IEffect[]>this.Blocks.en().where(b => b instanceof Effect).toArray(); } get PowerEffects(): IPowerEffect[] { return <IPowerEffect[]>this.Blocks.en().where(b => b instanceof PowerEffect).toArray(); } get PowerSources(): IPowerSource[] { return <IPowerSource[]>this.Blocks.en().where(b => b instanceof PowerSource).toArray(); } public GetBlockId(): number { // loop through blocks to get max id var max = 0; for (var i = 0; i < this.Blocks.length; i++){ var b = this.Blocks[i]; if (b.Id > max){ max = b.Id; } } return max + 1; } get SessionId(): string { if (this._SessionId) return this._SessionId; var storageItem: Utils.StorageItem = Utils.Storage.get(this.CompositionId, Utils.StorageType.local); if (storageItem) return storageItem.value; } set SessionId(value: string) { this._SessionId = value; Utils.Storage.set(this.CompositionId, this._SessionId, this.Config.StorageTime, Utils.StorageType.local); } get ThemeNo(): number { var storageItem: Utils.StorageItem = Utils.Storage.get("ColorTheme", Utils.StorageType.local); if (storageItem) return storageItem.value; } set ThemeNo(value: number) { Utils.Storage.set("ColorTheme", value, this.Config.StorageTime, Utils.StorageType.local); } get SkipTutorial(): boolean { var storageItem: Utils.StorageItem = Utils.Storage.get("SkipTutorial", Utils.StorageType.local); if (storageItem) return storageItem.value; } set SkipTutorial(value: boolean) { Utils.Storage.set("SkipTutorial", value, this.Config.StorageTime, Utils.StorageType.local); } constructor(config: string, l10n: string) { this.Config = <IConfig>JSON.parse(config); this.L10n = <IL10n>JSON.parse(l10n); } public Setup(){ this.Canvas = new Canvas(); this.Canvas.HTMLElement.id = 'mainCanvas'; document.body.classList.add('app-active'); this.BlockCreator = new BlockCreator(); // METRICS // this.Metrics = new Metrics(); this.BlockSprites = new BlockSprites(); this.SubCanvas = []; this.CreateSubCanvas(0); // optionsPanel window.onresize = () => { this.Resize(); }; // INITIALISE AUDIO // this.Audio.Init(); // LOAD FONTS AND SETUP CALLBACK // this._FontsLoaded = 0; WebFont.load({ custom: { families: ['Merriweather Sans:i3','Dosis:n2,n4']}, fontactive: (font, fvd) => { this.FontsLoaded(font, fvd) }, timeout: 3000 // 3 seconds }); setTimeout(() => { this.FontsNotLoaded(); }, 3020); // CREATE MANAGERS // this.OperationManager = new OperationManager(); this.OperationManager.MaxOperations = this.Config.MaxOperations; this.ResourceManager = new ResourceManager(); this.CommandManager = new CommandManager(this.ResourceManager); this.TypingManager = new TypingManager(); //this.DragFileInputManager = new DragFileInputManager(); this.PianoKeyboardManager = new PianoKeyboardManager(); this.CommandsInputManager = new CommandsInputManager(this.CommandManager); this.PointerInputManager = new PointerInputManager(); this.ColorManager = new ColorManager(); this.ThemeManager = new ThemeManager(); this.FocusManager = new FocusManager(); this.AddressBarManager = new AddressBarManager(); this.FocusManager.FocusChanged.on((s: any, e: FocusManagerEventArgs) => { if (!e.HasFocus){ this.TypingManager.ClearKeysDown(); this.PianoKeyboardManager.ClearKeysDown(); this.CommandsInputManager.ClearKeysDown(); //this.Sources.forEach((s: ISource) => { //s.TriggerRelease('all'); //}) } }, this); // REGISTER COMMAND HANDLERS // this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.CREATE_BLOCK, CreateBlockCommandHandler.prototype)); this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.DELETE_BLOCK, DeleteBlockCommandHandler.prototype)); this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.MOVE_BLOCK, MoveBlockCommandHandler.prototype)); this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.SAVE, SaveCommandHandler.prototype)); this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.SAVE_AS, SaveAsCommandHandler.prototype)); this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.LOAD, LoadCommandHandler.prototype)); this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.UNDO, UndoCommandHandler.prototype)); this.ResourceManager.AddResource(new CommandHandlerFactory(Commands.REDO, RedoCommandHandler.prototype)); // POOLED OBJECTS // this.ParticlesPool = new PooledFactoryResource<Particle>(10, 100, Particle.prototype); // INITIALISE SOUNDCLOUD // var tempClientIDs = ['7258ff07f16ddd167b55b8f9b9a3ed33', '33ebf0c1ffa4e462157606a432bd7b5f', 'ce852127c5413fe70816d488694d7921']; //buffer to deal with initial traffic, will revert to true id after // var tempClientIDs2 = ['3291559d547bd9c545cbf393f522ea68', '3833cf666207c249e9767699a4d22a79', 'cb6c82fd11c903be63bdc4df4c5c7e09', '6c5bafb2050dc09d8f5d738030aa9fed']; this.Config.SoundCloudClientId = tempClientIDs2[Math.floor(Math.random()*tempClientIDs2.length)]; SoundCloudAPI.Initialize(); // INITIALISE THEME // this.ThemeManager.ThemeChanged.on((s: any, e: ThemeChangeEventArgs) => { this.TrackVariable(GAVariables.THEME.toString(), e.Index.toString()); this.TrackEvent(CommandCategories.SETTINGS.toString(), Commands.CHANGE_THEME.toString(), ''+this.ThemeManager.Themes[e.Index].Name); // if first load var firstLoad: boolean = this.Palette.length === 0; this.Palette = e.Palette; if (firstLoad) { this.LoadReady(); } }, this); var themeNo = this.ThemeNo; if (!this.ThemeNo) { themeNo = 0; } this.ThemeManager.LoadTheme(themeNo, true); } // FONT LOAD CALLBACK // FontsLoaded(font, fvd) { this._FontsLoaded += 1; // All fonts are present - load scene if (this._FontsLoaded === 3) { this.LoadReady(); } } // FONT FAILURE TIMEOUT // FontsNotLoaded() { if (this._FontsLoaded !== 3) { console.log("FONTS ARE MISSING"); // proceed anyway for now this._FontsLoaded = 3; this.LoadReady(); } } // PROCEED WHEN ALL SOCKETS LOADED // LoadReady(): void { if (this._FontsLoaded === 3 && this.ThemeManager.Loaded) { this.LoadComposition(); } } // IF LOADING A SHARE URL, GET THE DATA // LoadComposition() { var that = this; this.CompositionId = Utils.Urls.getQuerystringParameter('c'); this.CompositionName = Utils.Urls.getQuerystringParameter('t'); if(this.CompositionId) { this.IsLoadingComposition = true; this.CommandManager.ExecuteCommand(Commands.LOAD, this.CompositionId).then((data) => { that.CompositionLoadComplete(data); }).catch((error: string) => { that.TrackEvent(CommandCategories.COMPOSITIONS.toString(), Errors.LOAD_FAILED.toString(), that.CompositionId); that.CompositionId = null; this.IsLoadingComposition = false; this.CompositionLoadFailed.raise(this, new CompositionLoadFailedEventArgs(that.CompositionId)); }); } this.CreateStage(); } // CREATE Stage & BEGIN DRAWING/ANIMATING // CreateStage() { this.Stage = new Stage(); this.Stage.Init(this.Canvas); this.Stage.Drawn.on((s: any, time: number) => { window.TWEEN.update(time); }, this); this.Resize(); } CompositionLoadComplete(data) { console.log(`Loaded "${this.CompositionName}"`); // get deserialized blocks tree, then "flatten" so that all blocks are in an array this.Deserialize(data); // allow loaded blocks to be alt-duplicable from start for (var i = 0; i < this.Blocks.length; i++) { this.Blocks[i].Duplicable = true; } this.ThemeManager.LoadTheme(this._SaveFile.ColorThemeNo, false, true); this.ZoomLevel = this._SaveFile.ZoomLevel; // bring down volume and validate blocks // this.Audio.Master.volume.value = -100; // Connect the effects chain this.Audio.ConnectionManager.Update(); this.IsLoadingComposition = false; if (!this.SkipTutorial) { this.MainScene.CreateNew.ShowMessage(); } this.CompositionLoaded.raise(this, new CompositionLoadedEventArgs(this._SaveFile)); } Serialize(): string { return Serializer.Serialize(); } Deserialize(json: string): any { this._SaveFile = Serializer.Deserialize(json); this.Blocks = this._SaveFile.Composition.en().traverseUnique(block => (<IBlock>block).Connections).toArray(); this.Blocks.sort((a: IBlock, b: IBlock) => { return a.ZIndex - b.ZIndex; }); } Message(message?: string, options?: any) { if (this.MainScene) { this.MainScene.MessagePanel.Show(); this.MainScene.MessagePanel.NewMessage(message, options); } } CreateSubCanvas(i) { this.SubCanvas[i] = document.createElement("canvas"); document.body.appendChild(this.SubCanvas[i]); } TrackEvent(category: string, action: string, label?: string): void{ window.trackEvent(category, action, label); } TrackVariable(name: string, value: string): void{ window.trackVariable(name, value); } IsLocalhost(): boolean { return document.location.href.indexOf('localhost') != -1; } Resize(): void { this.Metrics.Compute(); this.Stage.Resize(); } // SHORTHAND COLOR SET // FillColor(ctx,col) { this.ColorManager.FillColor(ctx,col); } FillRGBA(ctx,r,g,b,a) { this.ColorManager.FillRGBA(ctx,r,g,b,a); } StrokeColor(ctx,col) { this.ColorManager.StrokeColor(ctx,col); } StrokeRGBA(ctx,r,g,b,a) { this.ColorManager.StrokeRGBA(ctx,r,g,b,a); } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Creates a new Google SQL Database Instance. For more information, see the [official documentation](https://cloud.google.com/sql/), * or the [JSON API](https://cloud.google.com/sql/docs/admin-api/v1beta4/instances). * * > **NOTE on `gcp.sql.DatabaseInstance`:** - Second-generation instances include a * default 'root'@'%' user with no password. This user will be deleted by the provider on * instance creation. You should use `gcp.sql.User` to define a custom user with * a restricted host and strong password. * * > **Note**: On newer versions of the provider, you must explicitly set `deletion_protection=false` * (and run `pulumi update` to write the field to state) in order to destroy an instance. * It is recommended to not set this field (or set it to true) until you're ready to destroy the instance and its databases. * * ## Example Usage * ### SQL Second Generation Instance * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const master = new gcp.sql.DatabaseInstance("master", { * databaseVersion: "POSTGRES_11", * region: "us-central1", * settings: { * // Second-generation instance tiers are based on the machine * // type. See argument reference below. * tier: "db-f1-micro", * }, * }); * ``` * ### Private IP Instance * > **NOTE:** For private IP instance setup, note that the `gcp.sql.DatabaseInstance` does not actually interpolate values from `gcp.servicenetworking.Connection`. You must explicitly add a `dependsOn`reference as shown below. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * import * as random from "@pulumi/random"; * * const privateNetwork = new gcp.compute.Network("privateNetwork", {}, { * provider: google_beta, * }); * const privateIpAddress = new gcp.compute.GlobalAddress("privateIpAddress", { * purpose: "VPC_PEERING", * addressType: "INTERNAL", * prefixLength: 16, * network: privateNetwork.id, * }, { * provider: google_beta, * }); * const privateVpcConnection = new gcp.servicenetworking.Connection("privateVpcConnection", { * network: privateNetwork.id, * service: "servicenetworking.googleapis.com", * reservedPeeringRanges: [privateIpAddress.name], * }, { * provider: google_beta, * }); * const dbNameSuffix = new random.RandomId("dbNameSuffix", {byteLength: 4}); * const instance = new gcp.sql.DatabaseInstance("instance", { * region: "us-central1", * databaseVersion: "MYSQL_5_7", * settings: { * tier: "db-f1-micro", * ipConfiguration: { * ipv4Enabled: false, * privateNetwork: privateNetwork.id, * }, * }, * }, { * provider: google_beta, * dependsOn: [privateVpcConnection], * }); * ``` * * ## Import * * Database instances can be imported using one of any of these accepted formats * * ```sh * $ pulumi import gcp:sql/databaseInstance:DatabaseInstance master projects/{{project}}/instances/{{name}} * ``` * * ```sh * $ pulumi import gcp:sql/databaseInstance:DatabaseInstance master {{project}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:sql/databaseInstance:DatabaseInstance master {{name}} * ``` * * config and set on the server. When importing, double-check that your config has all the fields set that you expect- just seeing no diff isn't sufficient to know that your config could reproduce the imported resource. */ export class DatabaseInstance extends pulumi.CustomResource { /** * Get an existing DatabaseInstance resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: DatabaseInstanceState, opts?: pulumi.CustomResourceOptions): DatabaseInstance { return new DatabaseInstance(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:sql/databaseInstance:DatabaseInstance'; /** * Returns true if the given object is an instance of DatabaseInstance. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is DatabaseInstance { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === DatabaseInstance.__pulumiType; } /** * The context needed to create this instance as a clone of another instance. When this field is set during * resource creation, this provider will attempt to clone another instance as indicated in the context. The * configuration is detailed below. */ public readonly clone!: pulumi.Output<outputs.sql.DatabaseInstanceClone | undefined>; /** * The connection name of the instance to be used in * connection strings. For example, when connecting with [Cloud SQL Proxy](https://cloud.google.com/sql/docs/mysql/connect-admin-proxy). */ public /*out*/ readonly connectionName!: pulumi.Output<string>; /** * The MySQL, PostgreSQL or * SQL Server version to use. Supported values include `MYSQL_5_6`, * `MYSQL_5_7`, `MYSQL_8_0`, `POSTGRES_9_6`,`POSTGRES_10`, `POSTGRES_11`, * `POSTGRES_12`, `POSTGRES_13`, `SQLSERVER_2017_STANDARD`, * `SQLSERVER_2017_ENTERPRISE`, `SQLSERVER_2017_EXPRESS`, `SQLSERVER_2017_WEB`. * `SQLSERVER_2019_STANDARD`, `SQLSERVER_2019_ENTERPRISE`, `SQLSERVER_2019_EXPRESS`, * `SQLSERVER_2019_WEB`. * [Database Version Policies](https://cloud.google.com/sql/docs/db-versions) * includes an up-to-date reference of supported versions. */ public readonly databaseVersion!: pulumi.Output<string>; /** * Whether or not to allow he provider to destroy the instance. Unless this field is set to false * in state, a `destroy` or `update` command that deletes the instance will fail. */ public readonly deletionProtection!: pulumi.Output<boolean | undefined>; /** * The full path to the encryption key used for the CMEK disk encryption. Setting * up disk encryption currently requires manual steps outside of this provider. * The provided key must be in the same region as the SQL instance. In order * to use this feature, a special kind of service account must be created and * granted permission on this key. This step can currently only be done * manually, please see [this step](https://cloud.google.com/sql/docs/mysql/configure-cmek#service-account). * That service account needs the `Cloud KMS > Cloud KMS CryptoKey Encrypter/Decrypter` role on your * key - please see [this step](https://cloud.google.com/sql/docs/mysql/configure-cmek#grantkey). */ public readonly encryptionKeyName!: pulumi.Output<string | undefined>; /** * The first IPv4 address of any type assigned. */ public /*out*/ readonly firstIpAddress!: pulumi.Output<string>; public /*out*/ readonly ipAddresses!: pulumi.Output<outputs.sql.DatabaseInstanceIpAddress[]>; /** * The name of the existing instance that will * act as the master in the replication setup. Note, this requires the master to * have `binaryLogEnabled` set, as well as existing backups. */ public readonly masterInstanceName!: pulumi.Output<string>; /** * A name for this whitelist entry. */ public readonly name!: pulumi.Output<string>; /** * The first private (`PRIVATE`) IPv4 address assigned. */ public /*out*/ readonly privateIpAddress!: pulumi.Output<string>; /** * The full project ID of the source instance.` */ public readonly project!: pulumi.Output<string>; /** * The first public (`PRIMARY`) IPv4 address assigned. */ public /*out*/ readonly publicIpAddress!: pulumi.Output<string>; /** * The region the instance will sit in. Note, Cloud SQL is not * available in all regions - choose from one of the options listed [here](https://cloud.google.com/sql/docs/mysql/instance-locations). * A valid region must be provided to use this resource. If a region is not provided in the resource definition, * the provider region will be used instead, but this will be an apply-time error for instances if the provider * region is not supported with Cloud SQL. If you choose not to provide the `region` argument for this resource, * make sure you understand this. */ public readonly region!: pulumi.Output<string>; /** * The configuration for replication. The * configuration is detailed below. Valid only for MySQL instances. */ public readonly replicaConfiguration!: pulumi.Output<outputs.sql.DatabaseInstanceReplicaConfiguration>; /** * The context needed to restore the database to a backup run. This field will * cause the provider to trigger the database to restore from the backup run indicated. The configuration is detailed below. * **NOTE:** Restoring from a backup is an imperative action and not recommended via this provider. Adding or modifying this * block during resource creation/update will trigger the restore action after the resource is created/updated. */ public readonly restoreBackupContext!: pulumi.Output<outputs.sql.DatabaseInstanceRestoreBackupContext | undefined>; /** * Initial root password. Required for MS SQL Server, ignored by MySQL and PostgreSQL. */ public readonly rootPassword!: pulumi.Output<string | undefined>; /** * The URI of the created resource. */ public /*out*/ readonly selfLink!: pulumi.Output<string>; public /*out*/ readonly serverCaCerts!: pulumi.Output<outputs.sql.DatabaseInstanceServerCaCert[]>; /** * The service account email address assigned to the * instance. */ public /*out*/ readonly serviceAccountEmailAddress!: pulumi.Output<string>; /** * The settings to use for the database. The * configuration is detailed below. Required if `clone` is not set. */ public readonly settings!: pulumi.Output<outputs.sql.DatabaseInstanceSettings>; /** * Create a DatabaseInstance resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: DatabaseInstanceArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: DatabaseInstanceArgs | DatabaseInstanceState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as DatabaseInstanceState | undefined; inputs["clone"] = state ? state.clone : undefined; inputs["connectionName"] = state ? state.connectionName : undefined; inputs["databaseVersion"] = state ? state.databaseVersion : undefined; inputs["deletionProtection"] = state ? state.deletionProtection : undefined; inputs["encryptionKeyName"] = state ? state.encryptionKeyName : undefined; inputs["firstIpAddress"] = state ? state.firstIpAddress : undefined; inputs["ipAddresses"] = state ? state.ipAddresses : undefined; inputs["masterInstanceName"] = state ? state.masterInstanceName : undefined; inputs["name"] = state ? state.name : undefined; inputs["privateIpAddress"] = state ? state.privateIpAddress : undefined; inputs["project"] = state ? state.project : undefined; inputs["publicIpAddress"] = state ? state.publicIpAddress : undefined; inputs["region"] = state ? state.region : undefined; inputs["replicaConfiguration"] = state ? state.replicaConfiguration : undefined; inputs["restoreBackupContext"] = state ? state.restoreBackupContext : undefined; inputs["rootPassword"] = state ? state.rootPassword : undefined; inputs["selfLink"] = state ? state.selfLink : undefined; inputs["serverCaCerts"] = state ? state.serverCaCerts : undefined; inputs["serviceAccountEmailAddress"] = state ? state.serviceAccountEmailAddress : undefined; inputs["settings"] = state ? state.settings : undefined; } else { const args = argsOrState as DatabaseInstanceArgs | undefined; if ((!args || args.databaseVersion === undefined) && !opts.urn) { throw new Error("Missing required property 'databaseVersion'"); } inputs["clone"] = args ? args.clone : undefined; inputs["databaseVersion"] = args ? args.databaseVersion : undefined; inputs["deletionProtection"] = args ? args.deletionProtection : undefined; inputs["encryptionKeyName"] = args ? args.encryptionKeyName : undefined; inputs["masterInstanceName"] = args ? args.masterInstanceName : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["region"] = args ? args.region : undefined; inputs["replicaConfiguration"] = args ? args.replicaConfiguration : undefined; inputs["restoreBackupContext"] = args ? args.restoreBackupContext : undefined; inputs["rootPassword"] = args ? args.rootPassword : undefined; inputs["settings"] = args ? args.settings : undefined; inputs["connectionName"] = undefined /*out*/; inputs["firstIpAddress"] = undefined /*out*/; inputs["ipAddresses"] = undefined /*out*/; inputs["privateIpAddress"] = undefined /*out*/; inputs["publicIpAddress"] = undefined /*out*/; inputs["selfLink"] = undefined /*out*/; inputs["serverCaCerts"] = undefined /*out*/; inputs["serviceAccountEmailAddress"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(DatabaseInstance.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering DatabaseInstance resources. */ export interface DatabaseInstanceState { /** * The context needed to create this instance as a clone of another instance. When this field is set during * resource creation, this provider will attempt to clone another instance as indicated in the context. The * configuration is detailed below. */ clone?: pulumi.Input<inputs.sql.DatabaseInstanceClone>; /** * The connection name of the instance to be used in * connection strings. For example, when connecting with [Cloud SQL Proxy](https://cloud.google.com/sql/docs/mysql/connect-admin-proxy). */ connectionName?: pulumi.Input<string>; /** * The MySQL, PostgreSQL or * SQL Server version to use. Supported values include `MYSQL_5_6`, * `MYSQL_5_7`, `MYSQL_8_0`, `POSTGRES_9_6`,`POSTGRES_10`, `POSTGRES_11`, * `POSTGRES_12`, `POSTGRES_13`, `SQLSERVER_2017_STANDARD`, * `SQLSERVER_2017_ENTERPRISE`, `SQLSERVER_2017_EXPRESS`, `SQLSERVER_2017_WEB`. * `SQLSERVER_2019_STANDARD`, `SQLSERVER_2019_ENTERPRISE`, `SQLSERVER_2019_EXPRESS`, * `SQLSERVER_2019_WEB`. * [Database Version Policies](https://cloud.google.com/sql/docs/db-versions) * includes an up-to-date reference of supported versions. */ databaseVersion?: pulumi.Input<string>; /** * Whether or not to allow he provider to destroy the instance. Unless this field is set to false * in state, a `destroy` or `update` command that deletes the instance will fail. */ deletionProtection?: pulumi.Input<boolean>; /** * The full path to the encryption key used for the CMEK disk encryption. Setting * up disk encryption currently requires manual steps outside of this provider. * The provided key must be in the same region as the SQL instance. In order * to use this feature, a special kind of service account must be created and * granted permission on this key. This step can currently only be done * manually, please see [this step](https://cloud.google.com/sql/docs/mysql/configure-cmek#service-account). * That service account needs the `Cloud KMS > Cloud KMS CryptoKey Encrypter/Decrypter` role on your * key - please see [this step](https://cloud.google.com/sql/docs/mysql/configure-cmek#grantkey). */ encryptionKeyName?: pulumi.Input<string>; /** * The first IPv4 address of any type assigned. */ firstIpAddress?: pulumi.Input<string>; ipAddresses?: pulumi.Input<pulumi.Input<inputs.sql.DatabaseInstanceIpAddress>[]>; /** * The name of the existing instance that will * act as the master in the replication setup. Note, this requires the master to * have `binaryLogEnabled` set, as well as existing backups. */ masterInstanceName?: pulumi.Input<string>; /** * A name for this whitelist entry. */ name?: pulumi.Input<string>; /** * The first private (`PRIVATE`) IPv4 address assigned. */ privateIpAddress?: pulumi.Input<string>; /** * The full project ID of the source instance.` */ project?: pulumi.Input<string>; /** * The first public (`PRIMARY`) IPv4 address assigned. */ publicIpAddress?: pulumi.Input<string>; /** * The region the instance will sit in. Note, Cloud SQL is not * available in all regions - choose from one of the options listed [here](https://cloud.google.com/sql/docs/mysql/instance-locations). * A valid region must be provided to use this resource. If a region is not provided in the resource definition, * the provider region will be used instead, but this will be an apply-time error for instances if the provider * region is not supported with Cloud SQL. If you choose not to provide the `region` argument for this resource, * make sure you understand this. */ region?: pulumi.Input<string>; /** * The configuration for replication. The * configuration is detailed below. Valid only for MySQL instances. */ replicaConfiguration?: pulumi.Input<inputs.sql.DatabaseInstanceReplicaConfiguration>; /** * The context needed to restore the database to a backup run. This field will * cause the provider to trigger the database to restore from the backup run indicated. The configuration is detailed below. * **NOTE:** Restoring from a backup is an imperative action and not recommended via this provider. Adding or modifying this * block during resource creation/update will trigger the restore action after the resource is created/updated. */ restoreBackupContext?: pulumi.Input<inputs.sql.DatabaseInstanceRestoreBackupContext>; /** * Initial root password. Required for MS SQL Server, ignored by MySQL and PostgreSQL. */ rootPassword?: pulumi.Input<string>; /** * The URI of the created resource. */ selfLink?: pulumi.Input<string>; serverCaCerts?: pulumi.Input<pulumi.Input<inputs.sql.DatabaseInstanceServerCaCert>[]>; /** * The service account email address assigned to the * instance. */ serviceAccountEmailAddress?: pulumi.Input<string>; /** * The settings to use for the database. The * configuration is detailed below. Required if `clone` is not set. */ settings?: pulumi.Input<inputs.sql.DatabaseInstanceSettings>; } /** * The set of arguments for constructing a DatabaseInstance resource. */ export interface DatabaseInstanceArgs { /** * The context needed to create this instance as a clone of another instance. When this field is set during * resource creation, this provider will attempt to clone another instance as indicated in the context. The * configuration is detailed below. */ clone?: pulumi.Input<inputs.sql.DatabaseInstanceClone>; /** * The MySQL, PostgreSQL or * SQL Server version to use. Supported values include `MYSQL_5_6`, * `MYSQL_5_7`, `MYSQL_8_0`, `POSTGRES_9_6`,`POSTGRES_10`, `POSTGRES_11`, * `POSTGRES_12`, `POSTGRES_13`, `SQLSERVER_2017_STANDARD`, * `SQLSERVER_2017_ENTERPRISE`, `SQLSERVER_2017_EXPRESS`, `SQLSERVER_2017_WEB`. * `SQLSERVER_2019_STANDARD`, `SQLSERVER_2019_ENTERPRISE`, `SQLSERVER_2019_EXPRESS`, * `SQLSERVER_2019_WEB`. * [Database Version Policies](https://cloud.google.com/sql/docs/db-versions) * includes an up-to-date reference of supported versions. */ databaseVersion: pulumi.Input<string>; /** * Whether or not to allow he provider to destroy the instance. Unless this field is set to false * in state, a `destroy` or `update` command that deletes the instance will fail. */ deletionProtection?: pulumi.Input<boolean>; /** * The full path to the encryption key used for the CMEK disk encryption. Setting * up disk encryption currently requires manual steps outside of this provider. * The provided key must be in the same region as the SQL instance. In order * to use this feature, a special kind of service account must be created and * granted permission on this key. This step can currently only be done * manually, please see [this step](https://cloud.google.com/sql/docs/mysql/configure-cmek#service-account). * That service account needs the `Cloud KMS > Cloud KMS CryptoKey Encrypter/Decrypter` role on your * key - please see [this step](https://cloud.google.com/sql/docs/mysql/configure-cmek#grantkey). */ encryptionKeyName?: pulumi.Input<string>; /** * The name of the existing instance that will * act as the master in the replication setup. Note, this requires the master to * have `binaryLogEnabled` set, as well as existing backups. */ masterInstanceName?: pulumi.Input<string>; /** * A name for this whitelist entry. */ name?: pulumi.Input<string>; /** * The full project ID of the source instance.` */ project?: pulumi.Input<string>; /** * The region the instance will sit in. Note, Cloud SQL is not * available in all regions - choose from one of the options listed [here](https://cloud.google.com/sql/docs/mysql/instance-locations). * A valid region must be provided to use this resource. If a region is not provided in the resource definition, * the provider region will be used instead, but this will be an apply-time error for instances if the provider * region is not supported with Cloud SQL. If you choose not to provide the `region` argument for this resource, * make sure you understand this. */ region?: pulumi.Input<string>; /** * The configuration for replication. The * configuration is detailed below. Valid only for MySQL instances. */ replicaConfiguration?: pulumi.Input<inputs.sql.DatabaseInstanceReplicaConfiguration>; /** * The context needed to restore the database to a backup run. This field will * cause the provider to trigger the database to restore from the backup run indicated. The configuration is detailed below. * **NOTE:** Restoring from a backup is an imperative action and not recommended via this provider. Adding or modifying this * block during resource creation/update will trigger the restore action after the resource is created/updated. */ restoreBackupContext?: pulumi.Input<inputs.sql.DatabaseInstanceRestoreBackupContext>; /** * Initial root password. Required for MS SQL Server, ignored by MySQL and PostgreSQL. */ rootPassword?: pulumi.Input<string>; /** * The settings to use for the database. The * configuration is detailed below. Required if `clone` is not set. */ settings?: pulumi.Input<inputs.sql.DatabaseInstanceSettings>; }
the_stack
import { expect } from '../expect' import { deploy, nuke } from '../../src/infrastructure/index' import { BoosterConfig } from '@boostercloud/framework-types' import { restore, replace, fake } from 'sinon' import { CoreV1Api, KubeConfig, KubernetesObjectApi } from '@kubernetes/client-node' import { DeployManager } from '../../src/infrastructure/deploy-manager' import { internet } from 'faker' describe('During the deploy or nuke of Booster apps:', async () => { const config = new BoosterConfig('production') const errorMsg = 'error!' beforeEach(() => { replace(KubeConfig.prototype, 'makeApiClient', fake.returns(new CoreV1Api())) replace(KubernetesObjectApi, 'makeApiClient', fake.returns(new KubernetesObjectApi())) }) afterEach(() => { restore() }) it('allows finishing deploy correctly', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any const serviceUrl = internet.ip replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureBoosterServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureDaprExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureEventStoreExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadPodExists', fake.resolves(true)) replace(DeployManager.prototype, 'uploadUserCode', fake.resolves(true)) replace(DeployManager.prototype, 'deployBoosterApp', fake.resolves(serviceUrl)) await deploy(config, logger) expect(logger.info.getCalls().length).to.be.equal(8) expect(logger.info).to.have.been.calledWith(`Your app is ready in this url: http://${serviceUrl}/graphql`) }) it('allows deploying but the namespace validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.eventually.be.rejectedWith(errorMsg) }) it('allows deploying but the helms validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.eventually.be.rejectedWith(errorMsg) }) it('allows deploying but the volume claim validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.throws(errorMsg)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows deploying but the upload service validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows deploying but he booster service validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureBoosterServiceExists', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows deploying but the dapr service validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureBoosterServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureDaprExists', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows deploying but the eventStore validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureBoosterServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureDaprExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureEventStoreExists', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows deploying but the Upload pod validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureBoosterServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureDaprExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureEventStoreExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadPodExists', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows deploying but the User code Upload fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureBoosterServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureDaprExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureEventStoreExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadPodExists', fake.resolves(true)) replace(DeployManager.prototype, 'uploadUserCode', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows deploying butthe booster pod validation fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'ensureNamespaceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureHelmIsReady', fake.resolves(true)) replace(DeployManager.prototype, 'ensureVolumeClaimExists', fake.resolves(true)) replace(DeployManager.prototype, 'setServiceType', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureBoosterServiceExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureDaprExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureEventStoreExists', fake.resolves(true)) replace(DeployManager.prototype, 'ensureUploadPodExists', fake.resolves(true)) replace(DeployManager.prototype, 'uploadUserCode', fake.resolves(true)) replace(DeployManager.prototype, 'deployBoosterApp', fake.throws(errorMsg)) await expect(deploy(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows finishing nuke correctly', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'deleteDapr', fake.resolves(true)) replace(DeployManager.prototype, 'deleteRedis', fake.resolves(true)) replace(DeployManager.prototype, 'deleteAllResources', fake.resolves(true)) await nuke(config, logger) expect(logger.info.getCalls().length).to.be.equal(4) expect(logger.info).to.have.been.calledWithMatch(/Your app is terminated and destroyed/) }) it('allows nuking but delete dapr fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'deleteDapr', fake.throws(errorMsg)) await expect(nuke(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows nuking but delete redis fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'deleteDapr', fake.resolves(true)) replace(DeployManager.prototype, 'deleteRedis', fake.throws(errorMsg)) await expect(nuke(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) it('allows nuking but delete resources fails', async () => { const logger = { info: fake(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any replace(DeployManager.prototype, 'deleteDapr', fake.resolves(true)) replace(DeployManager.prototype, 'deleteRedis', fake.resolves(true)) replace(DeployManager.prototype, 'deleteAllResources', fake.throws(errorMsg)) await expect(nuke(config, logger)).to.be.eventually.rejectedWith(errorMsg) }) })
the_stack
import React from 'react' import {Meta} from '@storybook/react' import {BaseStyles, Box, ButtonPrimary, ThemeProvider} from '..' import {useAnchoredPosition} from '../hooks' import styled from 'styled-components' import {get} from '../constants' import type {AnchorSide} from '@primer/behaviors' import Portal, {registerPortalRoot} from '../Portal' import Button from '../Button' export default { title: 'Hooks/useAnchoredPosition', decorators: [ // Note: For some reason, if you use <BaseStyles><Story /></BaseStyles>, // the component gets unmounted from the root every time a control changes! Story => { return ( <ThemeProvider> <BaseStyles>{Story()}</BaseStyles> </ThemeProvider> ) } ], argTypes: { anchorX: { control: {type: 'range', min: 0, max: 500} }, anchorY: { control: {type: 'range', min: 0, max: 500} }, anchorWidth: { control: {type: 'range', min: 50, max: 500} }, anchorHeight: { control: {type: 'range', min: 50, max: 500} }, floatWidth: { control: {type: 'range', min: 50, max: 500} }, floatHeight: { control: {type: 'range', min: 50, max: 500} }, anchorPosition: { control: {type: 'inline-radio', options: ['inside', 'outside']} }, anchorSide: { control: {type: 'inline-radio', options: ['top', 'bottom', 'left', 'right', 'center']}, description: 'note' }, anchorAlignment: { control: {type: 'inline-radio', options: ['first', 'center', 'last']} }, anchorOffset: { control: {type: 'range', min: -100, max: 100} }, alignmentOffset: { control: {type: 'range', min: -100, max: 100} }, allowOutOfBounds: { control: {type: 'boolean'} } } } as Meta const Float = styled(Box)` position: absolute; border: 1px solid ${get('colors.black')}; border-radius: ${get('radii.2')}; background-color: ${get('colors.orange.3')}; display: flex; flex-direction: column; text-align: center; font-size: ${get('fontSizes.3')}; font-weight: ${get('fontWeights.bold')}; padding: ${get('space.3')}; ` const Anchor = styled(Box)` position: absolute; border: 1px solid ${get('colors.black')}; border-radius: ${get('radii.2')}; background-color: ${get('colors.blue.3')}; display: flex; flex-direction: column; text-align: center; font-size: ${get('fontSizes.3')}; font-weight: ${get('fontWeights.bold')}; padding: ${get('space.3')}; ` // eslint-disable-next-line @typescript-eslint/no-explicit-any export const UseAnchoredPosition = (args: any) => { const {floatingElementRef, anchorElementRef, position} = useAnchoredPosition( { side: `${args.anchorPosition ?? 'outside'}-${args.anchorSide ?? 'bottom'}` as AnchorSide, align: args.anchorAlignment ?? 'start', anchorOffset: args.anchorOffset && parseInt(args.anchorOffset, 10), alignmentOffset: args.alignmentOffset && parseInt(args.alignmentOffset, 10), allowOutOfBounds: args.allowOutOfBounds ?? undefined }, [ args.anchorY, args.anchorX, args.anchorPosition, args.anchorSide, args.anchorAlignment, args.anchorOffset, args.alignmentOffset, args.allowOutOfBounds, args.floatHeight, args.floatWidth ] ) return ( <Box position="relative" m={2}> <Anchor top={args.anchorY ?? 0} left={args.anchorX ?? 0} width={args.anchorWidth} height={args.anchorHeight} ref={anchorElementRef as React.RefObject<HTMLDivElement>} > Anchor Element </Anchor> <Float top={position?.top ?? 0} left={position?.left ?? 0} width={args.floatWidth ?? 150} height={args.floatHeight ?? 150} ref={floatingElementRef as React.RefObject<HTMLDivElement>} > Floating element </Float> </Box> ) } export const CenteredOnScreen = () => { const {floatingElementRef, anchorElementRef, position} = useAnchoredPosition({ side: 'inside-center', align: 'center' }) // The outer Position element simply fills all available space return ( <Box ref={anchorElementRef as React.RefObject<HTMLDivElement>} position="absolute" top={0} bottom={0} left={0} right={0} > <Float ref={floatingElementRef as React.RefObject<HTMLDivElement>} top={position?.top ?? 0} left={position?.left ?? 0} > <p>Screen-Centered Floating Element </p> <p> <small> <em>(Controls are ignored for this story)</em> </small> </p> </Float> </Box> ) } export const ComplexAncestry = () => { const [recalculateSignal, setRecalculateSignal] = React.useState(0) const {floatingElementRef, anchorElementRef, position} = useAnchoredPosition( { side: 'outside-bottom', align: 'start' }, [recalculateSignal] ) const onRecalculateClick = React.useCallback(() => { setRecalculateSignal(recalculateSignal + 1) }, [recalculateSignal]) // The outer Position element simply fills all available space const space = 2 return ( <> <Box m={space} p={space} sx={{ border: '1px solid #000', backgroundColor: 'blue.1', height: '440px', overflow: 'auto', position: 'relative' }} > Clipping container - this element has <code>overflow</code> set to something other than <code>visible</code> <Box m={space} p={space} sx={{border: '1px solid #000', backgroundColor: 'blue.2', position: 'relative'}}> Relatively positioned parent, but fluid height, so not the clipping parent. <Box m={space} p={space} sx={{border: '1px solid #000', backgroundColor: 'blue.3', position: 'static', overflow: 'hidden'}} > Floating element container. Position=static and overflow=hidden to show that overflow-hidden on a statically-positioned element will not have any effect. <Float top={position?.top ?? 0} left={position?.left ?? 0} width={150} height={220} ref={floatingElementRef as React.RefObject<HTMLDivElement>} > Floating element </Float> </Box> </Box> <Box m={space} p={space} backgroundColor="blue.3" sx={{border: '1px solid #000', height: '2000px'}}> Anchor element container. This element is really tall to demonstrate behavior within a scrollable clipping container. <Box width="200px" backgroundColor="orange.3" height={60} ref={anchorElementRef as React.RefObject<HTMLDivElement>} sx={{border: '1px solid #000'}} m={space} p={space} > Anchor Element </Box> </Box> </Box> <Button onClick={onRecalculateClick}>Click to recalculate floating position</Button> </> ) } const Nav = styled('nav')` width: 300px; padding: ${get('space.3')}; position: relative; overflow: hidden; border-right: 1px solid ${get('colors.border.gray')}; ` const Main = styled('main')` display: flex; position: absolute; top: 0; left: 0; right: 0; bottom: 0; ` /* There are a few "gotchas" to take note of from this example. See the documentation for more info. 1. The portal's root (<Main> in this example) needs to be large enough to include ANY space that the overlay might need to take. By default, elements are not rendered at full height! Notice how <Main> uses top, left, right, and bottom all set to 0 to achieve a full-size box. 2. The positioning routine needs to know the size of the overlay before calculating its position! Therefore, we use visibility: hidden to prevent showing a single frame of the overlay being positioned at (0, 0). */ export const WithPortal = () => { const [showMenu, setShowMenu] = React.useState(false) const mainRef = React.useRef<HTMLElement>(null) // Calculate the position of the menu const {floatingElementRef, anchorElementRef, position} = useAnchoredPosition( { side: 'outside-bottom', align: 'start' }, [showMenu] ) // Register <Main> as the Portal root React.useEffect(() => { if (mainRef.current) { registerPortalRoot(mainRef.current) } }, [mainRef]) // Toggles rendering the menu when the button is clicked const toggleMenu = React.useCallback(() => { setShowMenu(!showMenu) }, [showMenu]) return ( <Main ref={mainRef}> <Nav> <h2>The nav bar!</h2> <p> This &ldquo;nav bar&rdquo; has a width of 300px and is <code>position:relative</code> with{' '} <code>overflow:hidden</code>, meaning that its children cannot overflow this container. Using &lt;Portal&gt; with <code>useAnchoredPosition</code>, we can break out of this contraint. </p> <Box sx={{textAlign: 'right'}}> <ButtonPrimary onClick={toggleMenu} ref={anchorElementRef as React.RefObject<HTMLButtonElement>}> Show the overlay! </ButtonPrimary> {showMenu ? ( <Portal> <Float ref={floatingElementRef as React.RefObject<HTMLDivElement>} style={{top: `${position?.top ?? 0}px`, left: `${position?.left ?? 0}px`}} width={250} height={400} sx={{visibility: position ? 'visible' : 'hidden'}} > An un-constrained overlay! </Float> </Portal> ) : null} </Box> </Nav> <Box sx={{flexGrow: 1}} p={3}> <h1>The body!</h1> <p> <em>Note: The controls below have no effect in this story.</em> </p> </Box> </Main> ) }
the_stack
import { validateTs } from '@graphql-codegen/testing'; import { parse, GraphQLSchema, buildClientSchema } from 'graphql'; import gql from 'graphql-tag'; import { Types, mergeOutputs } from '@graphql-codegen/plugin-helpers'; import { plugin as tsPlugin } from '@graphql-codegen/typescript'; import { plugin as tsDocumentsPlugin } from '@graphql-codegen/typescript-operations'; import { DocumentMode } from '@graphql-codegen/visitor-plugin-common'; import { extract } from 'jest-docblock'; import { VueApolloSmartOpsRawPluginConfig } from '../src/config'; import { plugin } from '../src/index'; describe('Vue Apollo Operations', () => { let spyConsoleError: jest.SpyInstance; beforeEach(() => { spyConsoleError = jest.spyOn(console, 'warn'); spyConsoleError.mockImplementation(); }); afterEach(() => { spyConsoleError.mockRestore(); }); // eslint-disable-next-line @typescript-eslint/no-var-requires const schema = buildClientSchema(require('../../../../../dev-test/githunt/schema.json')); const basicDoc = parse(/* GraphQL */ ` query test { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } `); const mutationDoc = parse(/* GraphQL */ ` mutation test($name: String) { submitRepository(repoFullName: $name) { id } } `); const subscriptionDoc = parse(/* GraphQL */ ` subscription test($name: String) { commentAdded(repoFullName: $name) { id } } `); const validateTypeScript = async ( output: Types.PluginOutput, testSchema: GraphQLSchema, documents: Types.DocumentFile[], config: any ): Promise<void> => { const tsOutput = await tsPlugin(testSchema, documents, config, { outputFile: '' }); const tsDocumentsOutput = await tsDocumentsPlugin(testSchema, documents, config, { outputFile: '' }); const merged = mergeOutputs([tsOutput, tsDocumentsOutput, output]); validateTs(merged, undefined, true, false); }; describe('Imports', () => { it('should import operation function dependencies', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain( `import { createMutationFunction, createSmartQueryOptionsFunction, createSmartSubscriptionOptionsFunction } from 'vue-apollo-smart-ops';` ); expect(content.prepend).toContain(`import gql from 'graphql-tag';`); await validateTypeScript(content, schema, docs, {}); }); it('should import operation function dependencies from configured packages', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { vueApolloOperationFunctionsImportFrom: 'custom-operation-functions-package', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain( `import { createMutationFunction, createSmartQueryOptionsFunction, createSmartSubscriptionOptionsFunction } from 'custom-operation-functions-package';` ); await validateTypeScript(content, schema, docs, {}); }); it('should import ApolloError type dependency', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import { ApolloError } from 'apollo-client';`); await validateTypeScript(content, schema, docs, {}); }); it('should import ApolloError type dependency from configured package', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { vueApolloErrorType: 'CustomApolloError', vueApolloErrorTypeImportFrom: 'custom-error-package', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import { CustomApolloError } from 'custom-error-package';`); await validateTypeScript(content, schema, docs, {}); }); it('should import error handler function dependency from configured package', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { vueApolloErrorHandlerFunction: 'handleApolloError', vueApolloErrorHandlerFunctionImportFrom: 'custom-error-handler', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import { handleApolloError } from 'custom-error-handler';`); await validateTypeScript(content, schema, docs, {}); }); it('should import Vue app type dependency from configured package', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { vueAppType: 'CustomApp', vueAppTypeImportFrom: 'my-app', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import { CustomApp } from 'my-app';`); await validateTypeScript(content, schema, docs, {}); }); it('should import DocumentNode when using noGraphQLTag', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { noGraphQLTag: true, }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import { DocumentNode } from 'graphql';`); expect(content.prepend).not.toContain(`import gql from 'graphql-tag';`); await validateTypeScript(content, schema, docs, {}); }); it(`should use gql import from gqlImport config option`, async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { gqlImport: 'graphql.macro#gql' }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import { gql } from 'graphql.macro';`); await validateTypeScript(content, schema, docs, {}); }); }); describe('Fragments', () => { it('Should generate basic fragments documents correctly', async () => { const docs = [ { location: 'a.graphql', document: parse(/* GraphQL */ ` fragment MyFragment on Repository { full_name } query { feed { id } } `), }, ]; const result = await plugin(schema, docs, {}, { outputFile: '' }); expect(result.content).toBeSimilarStringTo(` export const MyFragmentFragmentDoc = gql\` fragment MyFragment on Repository { full_name } \`;`); await validateTypeScript(result, schema, docs, {}); }); it('should generate Document variables for inline fragments', async () => { const repositoryWithOwner = gql` fragment RepositoryWithOwner on Repository { full_name html_url owner { avatar_url } } `; const feedWithRepository = gql` fragment FeedWithRepository on Entry { id commentCount repository(search: "phrase") { ...RepositoryWithOwner } } ${repositoryWithOwner} `; const myFeed = gql` query MyFeed { feed { ...FeedWithRepository } } ${feedWithRepository} `; const docs = [{ location: '', document: myFeed }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo(`export const FeedWithRepositoryFragmentDoc = gql\` fragment FeedWithRepository on Entry { id commentCount repository(search: "phrase") { ...RepositoryWithOwner } } \${RepositoryWithOwnerFragmentDoc}\`;`); expect(content.content).toBeSimilarStringTo(`export const RepositoryWithOwnerFragmentDoc = gql\` fragment RepositoryWithOwner on Repository { full_name html_url owner { avatar_url } } \`;`); expect(content.content).toBeSimilarStringTo(`export const MyFeedDocument = gql\` query MyFeed { feed { ...FeedWithRepository } } \${FeedWithRepositoryFragmentDoc}\`;`); await validateTypeScript(content, schema, docs, {}); }); it('should avoid generating duplicate fragments', async () => { const simpleFeed = gql` fragment Item on Entry { id } `; const myFeed = gql` query MyFeed { feed { ...Item } allFeeds: feed { ...Item } } `; const documents = [simpleFeed, myFeed]; const docs = documents.map(document => ({ document, location: '' })); const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo(` export const MyFeedDocument = gql\` query MyFeed { feed { ...Item } allFeeds: feed { ...Item } } \${ItemFragmentDoc}\``); expect(content.content).toBeSimilarStringTo(` export const ItemFragmentDoc = gql\` fragment Item on Entry { id } \`;`); await validateTypeScript(content, schema, docs, {}); }); it('Should generate fragments in proper order (when one depends on other)', async () => { const myFeed = gql` fragment FeedWithRepository on Entry { id repository { ...RepositoryWithOwner } } fragment RepositoryWithOwner on Repository { full_name } query MyFeed { feed { ...FeedWithRepository } } `; const documents = [myFeed]; const docs = documents.map(document => ({ document, location: '' })); const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; const feedWithRepositoryPos = content.content.indexOf('fragment FeedWithRepository'); const repositoryWithOwnerPos = content.content.indexOf('fragment RepositoryWithOwner'); expect(repositoryWithOwnerPos).toBeLessThan(feedWithRepositoryPos); await validateTypeScript(content, schema, docs, {}); }); }); describe('Operation functions', () => { it('Should generate operation functions for query and mutation', async () => { const documents = parse(/* GraphQL */ ` query feed { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } mutation submitRepository($name: String) { submitRepository(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const useFeedQuery = createSmartQueryOptionsFunction< FeedQuery, FeedQueryVariables, ApolloError >(FeedDocument);` ); expect(content.content).toBeSimilarStringTo( `export const submitRepositoryMutation = createMutationFunction< SubmitRepositoryMutation, SubmitRepositoryMutationVariables, ApolloError >(SubmitRepositoryDocument);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should use custom ApolloError type and handler for operation functions', async () => { const documents = parse(/* GraphQL */ ` query feed { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } mutation submitRepository($name: String) { submitRepository(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, { vueApolloErrorType: 'CustomApolloError', vueApolloErrorTypeImportFrom: 'custom-error-type', vueApolloErrorHandlerFunction: 'handleApolloError', vueApolloErrorHandlerFunctionImportFrom: 'custom-error-handler', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const useFeedQuery = createSmartQueryOptionsFunction< FeedQuery, FeedQueryVariables, CustomApolloError >(FeedDocument, handleApolloError);` ); expect(content.content).toBeSimilarStringTo( `export const submitRepositoryMutation = createMutationFunction< SubmitRepositoryMutation, SubmitRepositoryMutationVariables, CustomApolloError >(SubmitRepositoryDocument, handleApolloError);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should use custom Vue app type for operation functions', async () => { const documents = parse(/* GraphQL */ ` query feed { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } mutation submitRepository($name: String) { submitRepository(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, { vueAppType: 'CustomApp', vueAppTypeImportFrom: 'my-app', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const useFeedQuery = createSmartQueryOptionsFunction< FeedQuery, FeedQueryVariables, ApolloError, CustomApp >(FeedDocument);` ); expect(content.content).toBeSimilarStringTo( `export const submitRepositoryMutation = createMutationFunction< SubmitRepositoryMutation, SubmitRepositoryMutationVariables, ApolloError, CustomApp >(SubmitRepositoryDocument);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should generate deduped operation functions for query and mutation', async () => { const documents = parse(/* GraphQL */ ` query FeedQuery { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } mutation SubmitRepositoryMutation($name: String) { submitRepository(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const config = { dedupeOperationSuffix: true }; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const useFeedQuery = createSmartQueryOptionsFunction< FeedQuery, FeedQueryVariables, ApolloError >(FeedQueryDocument);` ); expect(content.content).toBeSimilarStringTo( `export const submitRepositoryMutation = createMutationFunction< SubmitRepositoryMutation, SubmitRepositoryMutationVariables, ApolloError >(SubmitRepositoryMutationDocument);` ); await validateTypeScript(content, schema, docs, config); }); it('Should not generate operation functions for query and mutation', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { withSmartOperationFunctions: false }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).not.toContain(`export const useTestQuery`); await validateTypeScript(content, schema, docs, {}); }); it('Should generate subscription operation functions', async () => { const documents = parse(/* GraphQL */ ` subscription ListenToComments($name: String) { commentAdded(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const useListenToCommentsSubscription = createSmartSubscriptionOptionsFunction< ListenToCommentsSubscription, ListenToCommentsSubscriptionVariables, ApolloError >(ListenToCommentsDocument);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should use custom ApolloError type and handler for subscription operation functions', async () => { const documents = parse(/* GraphQL */ ` subscription ListenToComments($name: String) { commentAdded(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, { vueApolloErrorType: 'CustomApolloError', vueApolloErrorTypeImportFrom: 'custom-error-type', vueApolloErrorHandlerFunction: 'handleApolloError', vueApolloErrorHandlerFunctionImportFrom: 'custom-error-handler', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const useListenToCommentsSubscription = createSmartSubscriptionOptionsFunction< ListenToCommentsSubscription, ListenToCommentsSubscriptionVariables, CustomApolloError >(ListenToCommentsDocument, handleApolloError);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should not add typesPrefix to operation functions', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { typesPrefix: 'I' }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toContain(`export const useTestQuery`); }); it('Should generate a mutation operation function with required variables if required in graphql document', async () => { const documents = parse(/* GraphQL */ ` mutation submitRepository($name: String!) { submitRepository(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const submitRepositoryMutation = createMutationFunction< SubmitRepositoryMutation, SubmitRepositoryMutationVariables, ApolloError >(SubmitRepositoryDocument);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should generate a mutation operation function with no variables if not specified in graphql document', async () => { const documents = parse(/* GraphQL */ ` mutation submitRepository { submitRepository { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const submitRepositoryMutation = createMutationFunction< SubmitRepositoryMutation, SubmitRepositoryMutationVariables, ApolloError >(SubmitRepositoryDocument);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should generate a mutation operation function with optional variables if optional in graphql document', async () => { const documents = parse(/* GraphQL */ ` mutation submitRepository($name: String) { submitRepository(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo( `export const submitRepositoryMutation = createMutationFunction< SubmitRepositoryMutation, SubmitRepositoryMutationVariables, ApolloError >(SubmitRepositoryDocument);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should generate required variables if required in graphql document', async () => { const documents = parse(/* GraphQL */ ` query feed($id: ID!, $name: String, $people: [String]!) { feed(id: $id) { id } } subscription test($name: String!) { commentAdded(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; // query with required variables expect(content.content).toBeSimilarStringTo( `export const useFeedQuery = createSmartQueryOptionsFunction< FeedQuery, FeedQueryVariables, ApolloError >(FeedDocument);` ); // subscription with required variables expect(content.content).toBeSimilarStringTo( `export const useTestSubscription = createSmartSubscriptionOptionsFunction< TestSubscription, TestSubscriptionVariables, ApolloError >(TestDocument);` ); await validateTypeScript(content, schema, docs, {}); }); it('Should generate optional variables if all optional in graphql document', async () => { const documents = parse(/* GraphQL */ ` query feed($id: ID) { feed(id: $id) { id } } subscription test($name: String) { commentAdded(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; // query with optional variables expect(content.content).toBeSimilarStringTo( `export const useFeedQuery = createSmartQueryOptionsFunction< FeedQuery, FeedQueryVariables, ApolloError >(FeedDocument);` ); // subscription with optional variables expect(content.content).toBeSimilarStringTo( `export const useTestSubscription = createSmartSubscriptionOptionsFunction< TestSubscription, TestSubscriptionVariables, ApolloError >(TestDocument);` ); await validateTypeScript(content, schema, docs, {}); }); const queryDocBlockSnapshot = `/** * __useFeedQuery__ * * To use a Smart Query within a Vue component, call \`useFeedQuery\` as the value for a query key * in the component's \`apollo\` config, passing any options required for the query. * * @param options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/core/ApolloClient/#ApolloClient.query * * @example * { * apollo: { * feed: useFeedQuery({ * variables: { * id: // value for 'id' * }, * loadingKey: 'loading', * fetchPolicy: 'no-cache', * }), * } * } */`; const subscriptionDocBlockSnapshot = `/** * __useCommentAddedSubscription__ * * To use a Smart Subscription within a Vue component, call \`useCommentAddedSubscription\` as the value for a \`$subscribe\` key * in the component's \`apollo\` config, passing any options required for the subscription. * * @param options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/core/ApolloClient/#ApolloClient.subscribe * * @example * { * apollo: { * $subscribe: { * commentAdded: useCommentAddedSubscription({ * variables: { * name: // value for 'name' * }, * loadingKey: 'loading', * fetchPolicy: 'no-cache', * }), * }, * } * } */`; const mutationDocBlockSnapshot = `/** * __submitRepositoryMutation__ * * To run a mutation, you call \`submitRepositoryMutation\` within a Vue component and pass it * your Vue app instance along with any options that fit your needs. * * @param app, a reference to your Vue app instance (which must have a \`$apollo\` property) * @param options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/core/ApolloClient/#ApolloClient.mutate * @param client (optional), which can be an instance of \`DollarApollo\` or the \`mutate()\` function provided by an \`<ApolloMutation>\` component * * @example * const { success, data, errors } = submitRepositoryMutation(this, { * variables: { * name: // value for 'name' * }, * }); */`; it('Should generate JSDoc docblocks for operation functions', async () => { const documents = parse(/* GraphQL */ ` query feed($id: ID!) { feed(id: $id) { id } } mutation submitRepository($name: String) { submitRepository(repoFullName: $name) { id } } subscription commentAdded($name: String) { commentAdded(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, {}, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; const queryDocBlock = extract(content.content.substr(content.content.indexOf('/**'))); expect(queryDocBlock).toEqual(queryDocBlockSnapshot); const mutationDocBlock = extract( content.content.substr(content.content.indexOf('/**', content.content.indexOf('/**') + 1)) ); expect(mutationDocBlock).toEqual(mutationDocBlockSnapshot); const subscriptionDocBlock = extract(content.content.substr(content.content.lastIndexOf('/**'))); expect(subscriptionDocBlock).toEqual(subscriptionDocBlockSnapshot); }); it('Should NOT generate JSDoc docblocks for operation functions if addDocBlocks is false', async () => { const documents = parse(/* GraphQL */ ` query feed($id: ID!) { feed(id: $id) { id } } mutation submitRepository($name: String) { submitRepository(repoFullName: $name) { id } } `); const docs = [{ location: '', document: documents }]; const content = (await plugin( schema, docs, { addDocBlocks: false }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; const queryDocBlock = extract(content.content.substr(content.content.indexOf('/**'))); expect(queryDocBlock).not.toEqual(queryDocBlockSnapshot); const mutationDocBlock = extract(content.content.substr(content.content.lastIndexOf('/**'))); expect(mutationDocBlock).not.toEqual(mutationDocBlockSnapshot); }); }); describe('documentMode and importDocumentNodeExternallyFrom', () => { const multipleOperationDoc = parse(/* GraphQL */ ` query testOne { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } mutation testTwo($name: String) { submitRepository(repoFullName: $name) { id } } subscription testThree($name: String) { commentAdded(repoFullName: $name) { id } } `); it('should import DocumentNode when documentMode is "documentNode"', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { documentMode: DocumentMode.documentNode, }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import { DocumentNode } from 'graphql';`); expect(content.prepend).not.toContain(`import gql from 'graphql-tag';`); await validateTypeScript(content, schema, docs, {}); }); it('should generate Document variable when documentMode is "documentNode"', async () => { const docs = [{ location: '', document: basicDoc }]; const content = (await plugin( schema, docs, { documentMode: DocumentMode.documentNode, }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).toBeSimilarStringTo(`export const TestDocument`); // For issue #1599 - make sure there are not `loc` properties expect(content.content).not.toContain(`loc":`); expect(content.content).not.toContain(`loc':`); await validateTypeScript(content, schema, docs, {}); }); it('should NOT generate inline fragment docs for external mode: file with operation using inline fragment', async () => { const docs = [ { location: '', document: parse(/* GraphQL */ ` fragment feedFragment on Entry { id commentCount } query testOne { feed { ...feedFragment } } `), }, ]; const config = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents.tsx', }; const content = (await plugin( schema, docs, { ...config }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).not.toBeSimilarStringTo(`export const FeedFragmentFragmentDoc`); await validateTypeScript(content, schema, docs, {}); }); it('should NOT generate inline fragment docs for external mode: file with operation NOT using inline fragment', async () => { const docs = [ { location: '', document: parse(/* GraphQL */ ` fragment feedFragment on Entry { id commentCount } query testOne { feed { id } } `), }, ]; const config = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents.tsx', }; const content = (await plugin( schema, docs, { ...config, }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).not.toBeSimilarStringTo(`export const FeedFragmentFragmentDoc`); await validateTypeScript(content, schema, docs, {}); }); it('should NOT generate inline fragment docs for external mode: file with just fragment', async () => { const docs = [ { location: '', document: parse(/* GraphQL */ ` fragment feedFragment on Entry { id commentCount } `), }, ]; const config = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents.tsx', }; const content = (await plugin( schema, docs, { ...config, }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.content).not.toBeSimilarStringTo(`export const FeedFragmentFragmentDoc`); await validateTypeScript(content, schema, docs, { ...config }); }); it('should import Operations from one external file and use it in useQuery', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents', }; const docs = [{ location: '', document: basicDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from 'path/to/documents';`); expect(content.content).toBeSimilarStringTo(`export const useTestQuery`); await validateTypeScript(content, schema, docs, {}); }); it('should import Operations from one external file and use it in useMutation', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents.ts', }; const docs = [{ location: '', document: mutationDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from 'path/to/documents';`); expect(content.content).toBeSimilarStringTo(`export const testMutation`); await validateTypeScript(content, schema, docs, {}); }); it('should import Operations from one external file and use it in useSubscription', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents.tsx', }; const docs = [{ location: '', document: subscriptionDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from 'path/to/documents';`); expect(content.content).toBeSimilarStringTo(`export const useTestSubscription`); await validateTypeScript(content, schema, docs, {}); }); it('should import Operations from one external file and use it in multiple operation functions', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents.tsx', }; const docs = [{ location: '', document: multipleOperationDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from 'path/to/documents';`); expect(content.content).toBeSimilarStringTo(`export const useTestOneQuery`); expect(content.content).toBeSimilarStringTo(`export const testTwoMutation`); expect(content.content).toBeSimilarStringTo(`export const useTestThreeSubscription`); await validateTypeScript(content, schema, docs, {}); }); it('should import Operations from near operation file for useQuery', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'near-operation-file', }; const docs = [{ location: 'path/to/document.graphql', document: basicDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from './document.graphql';`); expect(content.content).toBeSimilarStringTo(`export const useTestQuery`); await validateTypeScript(content, schema, docs, {}); }); it('should import Operations from near operation file for useMutation', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'near-operation-file', }; const docs = [{ location: 'path/to/document.graphql', document: mutationDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from './document.graphql';`); expect(content.content).toBeSimilarStringTo(`export const testMutation`); await validateTypeScript(content, schema, docs, {}); }); it('should import Operations from near operation file for useSubscription', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'near-operation-file', }; const docs = [{ location: 'path/to/document.graphql', document: subscriptionDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from './document.graphql';`); expect(content.content).toBeSimilarStringTo(`export const useTestSubscription`); await validateTypeScript(content, schema, docs, {}); }); it('should import Operations from near operation file and use it in multiple operation functions', async () => { const config: VueApolloSmartOpsRawPluginConfig = { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'near-operation-file', }; const docs = [{ location: 'path/to/document.graphql', document: multipleOperationDoc }]; const content = (await plugin(schema, docs, config, { outputFile: 'graphql.ts', })) as Types.ComplexPluginOutput; expect(content.prepend).toContain(`import * as Operations from './document.graphql';`); expect(content.content).toBeSimilarStringTo(`export const useTestOneQuery`); expect(content.content).toBeSimilarStringTo(`export const testTwoMutation`); expect(content.content).toBeSimilarStringTo(`export const useTestThreeSubscription`); await validateTypeScript(content, schema, docs, {}); }); it(`should NOT import Operations if no operation collected: external mode and one file`, async () => { const docs = [ { location: 'path/to/document.graphql', document: parse(/* GraphQL */ ` fragment feedFragment on Entry { id commentCount } `), }, ]; const content = (await plugin( schema, docs, { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'near-operation-file', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).not.toBeSimilarStringTo(`import * as Operations`); await validateTypeScript(content, schema, docs, {}); }); it(`should NOT import Operations if no operation collected: external mode and multiple files`, async () => { const docs = [ { location: 'a.graphql', document: parse(/* GraphQL */ ` fragment feedFragment1 on Entry { id commentCount } `), }, { location: 'b.graphql', document: parse(/* GraphQL */ ` fragment feedFragment2 on Entry { id commentCount } `), }, ]; const content = (await plugin( schema, docs, { documentMode: DocumentMode.external, importDocumentNodeExternallyFrom: 'path/to/documents.tsx', }, { outputFile: 'graphql.ts', } )) as Types.ComplexPluginOutput; expect(content.prepend).not.toBeSimilarStringTo(`import * as Operations`); await validateTypeScript(content, schema, docs, {}); }); }); });
the_stack
import CodeMirror from 'codemirror' import emmet from '@emmetio/codemirror-plugin' import { state } from '@mkenzo_8/puffin' import { EditorClient } from '../../constructors/editorclient' import StaticConfig from 'StaticConfig' import RunningConfig from 'RunningConfig' import isBrowser from '../../utils/is_browser' import path from 'path' import DiffMatchPatch from 'diff-match-patch' import CodeMirrorOptions from 'Types/codemirror_client' import 'lsp-codemirror/lib/codemirror-lsp.css' import 'lsp-codemirror/lib/icons/rect.svg' let LspWsConnection let CodeMirrorAdapter if (!isBrowser) { let CustomWindow: any = window // CodeMirror Merge Addon needs these defined globally CustomWindow.diff_match_patch = DiffMatchPatch CustomWindow.DIFF_EQUAL = 0 CustomWindow.DIFF_INSERT = 1 CustomWindow.DIFF_DELETE = -1 import('lsp-codemirror').then(lspCodemirror => { LspWsConnection = lspCodemirror.LspWsConnection CodeMirrorAdapter = lspCodemirror.CodeMirrorAdapter }) } /* This is the editor client used to edit plain text files */ const CodemirrorClient = new EditorClient( { name: 'codemirror', type: 'editor', }, { getValue: instance => instance.getValue(), getLangFromExt({ extension, fileName }) { switch (fileName) { case '.babelrc': return { fancy: 'json', mode: 'json', name: 'application/json', } } const lowerCasedExtension = extension.toLowerCase() /* * Every case refers to a programming language's file format, * (example: JavaScript -> js). * If it's not supported it will go into the default case, * below yo can see the list of supported by this CodeMirror Client. */ switch (lowerCasedExtension) { case 'html': return { fancy: 'html', mode: 'html', name: 'htmlmixed', } case 'jsx': return { fancy: 'jsx', mode: 'javascript', name: 'text/jsx', } case 'gjs': return { fancy: 'gjs', mode: 'javascript', name: 'text/javascript', } case 'js': return { fancy: 'javascript', mode: 'javascript', name: 'text/jsx', } case 'json': return { fancy: 'json', mode: 'json', name: 'application/json', } case 'css': return { fancy: 'cs', mode: 'css', name: 'css', } case 'php': return { fancy: 'php', mode: 'php', name: 'php', } case 'dart': return { fancy: 'dart', mode: 'dart', name: 'dart', } case 'd': return { fancy: 'd', mode: 'd', name: 'text/x-d', } case 'rs': return { fancy: 'rust', mode: 'rust', name: 'rust', } case 'rb': return { name: 'ruby', } case 'pyw': case 'py': return { fancy: 'python', mode: 'python', name: 'python', } case 'svelte': return { fancy: 'svelte', mode: 'svelte', name: 'text/x-vue', } case 'vue': return { fancy: 'vue', mode: 'vue', name: 'text/x-vue', } case 'svg': case 'xml': return { fancy: 'xml', mode: 'xml', name: 'xml', } case 'ejs': return { fancy: 'ejs', mode: 'javascript', name: 'application/x-ejs', } case 'lua': return { fancy: 'lua', mode: 'lua', name: 'text/x-lua', } case 'yml': case 'yaml': return { fancy: 'yaml', mode: 'yaml', name: 'yaml', } case 'sql': return { fancy: 'sql', mode: 'sql', name: 'sql', } case 'pug': return { fancy: 'pug', mode: 'pug', name: 'pug', } case 'jade': return { fancy: 'jade', mode: 'jade', name: 'pug', } case 'hpp': case 'cpp': case 'h': return { fancy: 'cpp', mode: 'cpp', name: 'text/x-c++src', } case 'c': return { fancy: 'c', mode: 'c', name: 'text/x-csrc', } case 'b': case 'bf': return { fancy: 'Brainfuck', mode: 'brainfuck', name: 'text/x-brainfuck', } case 'java': return { fancy: 'java', mode: 'java', name: 'text/x-java', } case 'scss': return { fancy: 'sass', mode: 'sass', name: 'text/x-scss', } case 'sass': return { fancy: 'sass', mode: 'sass', name: 'text/x-sass', } case 'php': return { fancy: 'php', mode: 'php', name: 'application/x-httpd-php', } case 'md': case 'mdx': return { fancy: 'markdown', mode: 'markdown', name: 'gfm', } case 'tsx': return { fancy: 'tsx', mode: 'typescript', name: 'text/typescript-jsx', } case 'ts': return { fancy: 'typescript', mode: 'typescript', name: 'text/typescript', } case 'sh': return { fancy: 'shell', mode: 'shell', name: 'text/x-sh', } case 'less': return { fancy: 'less', mode: 'less', name: 'text/x-less', } case 'fs': return { fancy: 'fs', mode: 'fs', name: 'text/x-fsharp', } case 'slim': return { fancy: 'slim', mode: 'slim', name: 'application/x-slim', } case 'go': return { fancy: 'golang', mode: 'go', name: 'text/x-go', } case 'cs': return { fancy: 'C#', mode: 'csharp', name: 'text/x-csharp', } case 'hs': return { fancy: 'Haskell', mode: 'text/x-haskell', name: 'text/x-haskell', } default: return { name: extension, unknown: true, } } }, create({ element, language, value, theme, CtrlPlusScroll, directory, options = {} }: CodeMirrorOptions) { let CodeMirrorClient = CodeMirror let extraOptions = {} /* * Only when is in merge mode is enabled use CodeMirror's MergeView to create the instance */ if (options?.merge) { CodeMirrorClient = CodeMirror.MergeView extraOptions = { origRight: options.mirror, orig: value, highlightDifferences: true, conntect: 'align', } } emmet(CodeMirror) let CodemirrorEditor = CodeMirrorClient(element, { mode: language, value: value, ...extraOptions, collpse: false, lineNumbers: true, htmlMode: true, styleActiveLine: { nonEmpty: true, }, styleActiveSelected: true, matchTags: { bothTags: true, }, autoCloseTags: true, autoCloseBrackets: true, matchBrackets: true, theme: theme, tabSize: StaticConfig.data.editorTabSize, indentUnit: StaticConfig.data.editorTabSize, undoDepth: 500, miniMap: false, indentWithTabs: language.name === 'yaml' ? false : StaticConfig.data.editorIndentation == 'tab', lineWrapping: StaticConfig.data.editorWrapLines, extraKeys: { Tab: 'emmetExpandAbbreviation', Esc: 'emmetResetAbbreviation', Enter: 'emmetInsertLineBreak', }, emmet: { preview: false, mark: true, markTagPairs: true, previewOpenTag: false, config: {}, }, foldGutter: StaticConfig.data.editorFold, foldOptions: { widget: (from, to) => { return ' ··· ' }, }, gutters: ['CodeMirror-lsp', 'CodeMirror-foldgutter'], }) /* * Only when is in merge mode is enabled */ if (options?.merge) { setTimeout(() => { // Wait 250ms for lines to be rendered highlightModifiedLines() }, 250) const { edit, right } = CodemirrorEditor // Update lines on changes edit.on('changes', () => { setTimeout(() => { highlightModifiedLines() }, 250) }) // Update lines when scrolling edit.on('scroll', () => { highlightModifiedLines() }) edit.on('optionChange', (cm, option) => { right.orig.setOption(option, edit.getOption(option)) right.orig.refresh() }) edit.on('refresh', () => { right.orig.refresh() setTimeout(() => { highlightModifiedLines() }, 300) }) ;[edit, right.orig].forEach(cm => { // Update lines on cursor activity on both instances cm.on('cursorActivity', () => { setTimeout(() => { highlightModifiedLines() }, 1) }) }) // Reassign the primary CodemirrorEditor to the CM instance CodemirrorEditor = edit } /* * Send a event of clipboard been written on Ctrl+C */ CodemirrorEditor.on('keydown', (cm, ev) => { if (ev.code === 'KeyC' && ev.ctrlKey) { RunningConfig.emit('clipboardHasBeenWritten', { text: CodemirrorEditor.getSelection(), }) } }) /* * Force every CodeMirror instance inside the editor container to have the configured font size */ const editors = element.getElementsByClassName('Codemirror') Object.keys(editors).forEach(cm => { editors[cm].style.fontSize = StaticConfig.data.editorFontSize }) const CtrlUpShortcutEnabled = StaticConfig.data.appShortcuts.IncreaseEditorFontSize.combos.includes('Ctrl+Up') const CtrlDownShortcutEnabled = StaticConfig.data.appShortcuts.DecreaseEditorFontSize.combos.includes('Ctrl+Down') /* * Ctrl+ArrowUp handler */ if (CtrlUpShortcutEnabled) { CodemirrorEditor.addKeyMap({ 'Ctrl-Up': function (instance) { CtrlPlusScroll('up') }, }) } /* * Ctrl+ArrowDown handler */ if (CtrlDownShortcutEnabled) { CodemirrorEditor.addKeyMap({ 'Ctrl-Down': function (instance) { CtrlPlusScroll('down') }, }) } // Ctrl+wheel event handler if (!RunningConfig.data.isBrowser) { element.addEventListener('wheel', (e: any) => { if (!e.ctrlKey) return if (e.wheelDeltaY.toString()[0] == '-') { CtrlPlusScroll('down') } else { CtrlPlusScroll('up') } }) } //Prevent default action of 'keyup' so codemirror doesn't go 1 line up when scrolling on context menus with arrows CodemirrorEditor.on('keyup', (cm, event: KeyboardEvent) => { event.preventDefault() }) let lspServer: string let lspAdapter let lspConnection //Find the first language server that matches the current file's language Object.keys(RunningConfig.data.LSPServers).forEach(server => { if (server == language.mode) { lspServer = `ws://localhost:${RunningConfig.data.LSPPort}/${server}` } }) //Create LSP Client if LSP is enabled if (lspServer && StaticConfig.data.editorAutocomplete) { const lspClient = createLspClient({ lspServer, language, directory, CodemirrorEditor, }) lspAdapter = lspClient.lspAdapter lspConnection = lspClient.lspConnection } //Enable or disable the LSP client if autocompleting is toggled StaticConfig.keyChanged('editorAutocomplete', (value: string) => { if (value) { const lspClient = createLspClient({ lspServer, language, directory, CodemirrorEditor, }) lspAdapter = lspClient.lspAdapter lspConnection = lspClient.lspConnection } else { if (lspAdapter) lspAdapter.remove() if (lspConnection) lspConnection.close() lspAdapter = null lspConnection = null } }) //Assign a puffin state to the CodeMirror instance CodemirrorEditor.pstate = new state({}) CodemirrorEditor.pstate.once('close', () => { if (lspConnection) lspConnection.close() }) CodemirrorEditor.refresh() handleCMAutocomplete(CodemirrorEditor, language) return { instance: CodemirrorEditor, } }, close({ instance }) { instance.pstate.emit('close') }, getMode({ instance }) { return instance.getOption('mode') }, getLinesCount({ instance }) { return instance.lineCount() }, getSelection({ instance }) { return instance.getSelection() }, setIndentation({ instance, indentation }) { instance.setOption('indentWithTabs', indentation === 'tab') }, doRefresh({ instance }) { setTimeout(function () { instance.focus() instance.refresh() }, 1) }, rightclicked({ instance, action }) { instance.on('contextmenu', action) }, clicked({ instance, action }) { instance.on('mousedown', action) }, doIndent({ instance }) { const cursorPos = instance.getCursor() instance.extendSelection( { line: 0, ch: 0 }, { line: instance.lineCount(), }, ) instance.execCommand('indentAuto') instance.setCursor(cursorPos) instance.refresh() }, doChangeValue({ instance, value }) { instance.setValue(value) }, onChanged({ instance, action }) { instance.on('change', (cm, changeObj) => action(instance.getValue(), changeObj)) }, replaceRange({ instance, from, to, text }) { instance.replaceRange(text, from, to, '+move') }, pasteContent({ instance, from, text }) { instance.replaceRange(text, from) }, getRange({ instance, from, to }) { return instance.getRange(from, to) }, getLine({ instance, line }) { return instance.getLine(line) }, executeUndo({ instance, action }) { instance.execCommand('undo') }, executeRedo({ instance, action }) { instance.execCommand('redo') }, onActive({ instance, action }) { instance.on('cursorActivity', action) }, openFind({ instance }) { instance.execCommand('find') }, openReplace({ instance }) { instance.execCommand('replace') }, setTheme({ instance, theme }) { instance.setOption('theme', theme) }, setTabSize({ instance, tabSize }) { instance.setOption('tabSize', tabSize) instance.setOption('indentUnit', tabSize) instance.refresh() }, setFontSize({ instance, element, fontSize }) { const editors = element.getElementsByClassName('Codemirror') Object.keys(editors).forEach(cm => { editors[cm].style.fontSize = fontSize }) instance.refresh() instance.scrollIntoView() }, getCursorPosition({ instance }) { const { line, ch } = instance.getCursor() return { line: line + 1, ch: ch + 1, } }, setBookmark({ instance, line, ch, element }) { const bookmark = instance.setBookmark( { line, ch, }, { widget: element, }, ) const clear = () => bookmark.clear() return { clear, } }, setCursorPosition({ instance, line = 1, ch = 1 }) { instance.setCursor({ line: Number(line) - 1, ch: Number(ch) - 1, }) }, doFocus({ instance }) { instance.focus() }, scrollToCursor({ instance }) { instance.scrollIntoView() }, setLinesWrapping({ instance, status }) { instance.setOption('lineWrapping', status) instance.refresh() instance.scrollIntoView() }, displayContextMenu({ instance, action }) { instance.pstate.on('displayContextMenu', action) }, blur({ instance }) { setTimeout(() => { instance.getInputField().blur() }, 1) }, toggleFold({ instance, value }) { instance.setOption('foldGutter', value) }, }, ) /* * Create a LSP adapter client into a CodeMirror instance */ function createLspClient({ lspServer, language, directory, CodemirrorEditor }) { const fileUri = directory.replace(/\\/gm, '/') const folderUrl = path.dirname(fileUri) const lspConnection = new LspWsConnection({ serverUri: lspServer, languageId: language.fancy, rootUri: `file:///${folderUrl.replace(/\/\//gm, '/')}`, documentUri: `file:///${fileUri.replace(/\/\//gm, '/')}`, documentText: () => CodemirrorEditor.getValue(), }).connect(new WebSocket(lspServer)) const lspAdapter = new CodeMirrorAdapter( lspConnection, { quickSuggestionsDelay: 40, contextMenuProvider(event, buttons) { CodemirrorEditor.pstate.emit('displayContextMenu', { event, buttons }) }, }, CodemirrorEditor, ) return { lspConnection, lspAdapter, } } /* * Handle CodeMirro's built-in autocomplete */ function handleCMAutocomplete(CodemirrorEditor, { fancy }): void { if (fancy === 'html') { CodemirrorEditor.on('change', (cm, change) => { const location = CodemirrorEditor.getDoc().getCursor('end') const line = CodemirrorEditor.getLine(location.line) const typedCharacter = line[location.ch - 1] if (typedCharacter == '<') { CodeMirror.commands.autocomplete(CodemirrorEditor, null, { completeSingle: false, }) } }) } } /* * Append a custom class to every inserted or deleted character's parent */ function highlightModifiedLines(): void { let pastLine = null //Update inserted lines for (const char of document.getElementsByClassName('CodeMirror-merge-r-inserted') as any) { const line = char.parentElement.parentElement if (pastLine !== line) line.classList.add('CodeMirror-merge-line-inserted') pastLine = line } //Update removed lines for (const char of document.getElementsByClassName('CodeMirror-merge-r-deleted') as any) { const line = char.parentElement.parentElement if (pastLine !== line) line.classList.add('CodeMirror-merge-line-deleted') pastLine = line } } export default CodemirrorClient
the_stack
import { TestContext, assert } from '@aurelia/testing'; import { TaskQueuePriority, QueueTaskOptions, ITask, TaskStatus, TaskQueue } from '@aurelia/runtime'; function createExposedPromise() { let resolve: () => void; let reject: (err: any) => void; const promise = new Promise<void>(function ($resolve, $reject) { resolve = $resolve; reject = $reject; }); return { resolve, reject, promise, }; } function round(num: number) { return ((num * 10 + .5) | 0) / 10; } function reportTask(task: any) { const id = task.id; const created = round(task.createdTime); const queue = round(task.queueTime); const preempt = task.preempt; const reusable = task.reusable; const persistent = task.persistent; const status = task._status; return `id=${id} createdTime=${created} queueTime=${queue} preempt=${preempt} reusable=${reusable} persistent=${persistent} status=${status}`; } describe('Scheduler', function () { // There is only ever one global platform, so we might as well store it here instead of initializing all extra boilerplate each test const platform = TestContext.create().platform; function queueRecursive(sut: TaskQueue, opts: QueueTaskOptions, count: number, cb: () => void) { function $queue() { cb(); if (--count > 0) { sut.queueTask($queue, opts); } } sut.queueTask($queue, opts); } function queueRecursiveAsync(sut: TaskQueue, opts: QueueTaskOptions, count: number, cb: () => Promise<void>) { async function $queue() { await cb(); if (--count > 0) { sut.queueTask($queue, opts); } } sut.queueTask($queue, opts); } function queueSequential(sut: TaskQueue, opts: QueueTaskOptions, count: number, cb: () => void) { while (count-- > 0) { sut.queueTask(cb, opts); } } function queueSequentialAsync(sut: TaskQueue, opts: QueueTaskOptions, count: number, cb: () => Promise<void>) { while (count-- > 0) { sut.queueTask(cb, opts); } } const prioritySpecs = [ { sut: platform.domWriteQueue, name: 'domWriteQueue', }, { sut: platform.taskQueue, name: 'taskQueue', }, { sut: platform.domReadQueue, name: 'domReadQueue', }, { sut: platform.domWriteQueue, name: 'domWriteQueue', }, { sut: platform.taskQueue, name: 'taskQueue', }, ]; for (const reusable of [true, false]) { for (const { sut, name } of prioritySpecs) { describe(`can queue ${name}`, function () { it('x1, {preempt: false, delay: 0}', function (done) { sut.queueTask( function () { assert.areTaskQueuesEmpty(); done(); }, { reusable, preempt: false, delay: 0, }, ); }); it('x1, {preempt: true, delay: 0}', function (done) { sut.queueTask( function () { assert.areTaskQueuesEmpty(); done(); }, { reusable, preempt: true, delay: 0, }, ); }); it('x1, {delay: 5}', function (done) { sut.queueTask( function () { assert.areTaskQueuesEmpty(); done(); }, { reusable, delay: 5, }, ); }); it('x1, queue {delay: 5} -> {delay: 0}, invoke {delay: 0} -> {delay: 5}', function (done) { const calls: number[] = []; sut.queueTask( function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); done(); }, { reusable, delay: 5, }, ); sut.queueTask( function () { calls.push(2); }, { reusable, delay: 0, }, ); }); it('x1, queue {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false}', function (done) { const calls: number[] = []; sut.queueTask( function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); done(); }, { reusable, preempt: false, }, ); sut.queueTask( function () { calls.push(2); }, { reusable, preempt: true, }, ); }); it('x1, queue {delay: 5} -> {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false} -> {delay: 5}', function (done) { const calls: number[] = []; sut.queueTask( function () { calls.push(1); assert.deepStrictEqual(calls, [3, 2, 1], 'calls'); assert.areTaskQueuesEmpty(); done(); }, { reusable, delay: 5, }, ); sut.queueTask( function () { calls.push(2); }, { reusable, preempt: false, }, ); sut.queueTask( function () { calls.push(3); }, { reusable, preempt: true, }, ); }); for (const delay of [1, 5]) { for (const expected of [2, 4]) { it(`${name} x${expected} sequential, {delay: ${delay}}`, function (done) { let actual = 0; function increment() { if (++actual === expected) { assert.areTaskQueuesEmpty(); done(); } } queueSequential( sut, { reusable, delay, }, expected, increment, ); }); it(`${name} x${expected} recursive, {delay: ${delay}}`, function (done) { let actual = 0; function increment() { if (++actual === expected) { assert.areTaskQueuesEmpty(); done(); } } queueRecursive( sut, { reusable, delay, }, expected, increment, ); }); } } }); describe(`can await ${name}`, function () { it('x1, {preempt: false, delay: 0}', function () { const task = sut.queueTask( function () { /* */ }, { reusable, preempt: false, delay: 0, }, ); return task.result; }); it('x1, {preempt: true, delay: 0}', function () { const task = sut.queueTask( function () { /* */ }, { reusable, preempt: true, delay: 0, }, ); return task.result; }); it('x1, {delay: 5}', function () { const task = sut.queueTask( function () { /* */ }, { reusable, delay: 5, }, ); return task.result; }); it('x1, queue {delay: 5} -> {delay: 0}, invoke {delay: 0} -> {delay: 5}', function () { const calls: number[] = []; const task = sut.queueTask( function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); }, { reusable, delay: 5, }, ); sut.queueTask( function () { calls.push(2); }, { reusable, delay: 0, }, ); return task.result; }); it('x1, queue {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false}', function () { const calls: number[] = []; const task = sut.queueTask( function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); }, { reusable, preempt: false, }, ); sut.queueTask( function () { calls.push(2); }, { reusable, preempt: true, }, ); return task.result; }); it('x1, queue {delay: 5} -> {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false} -> {delay: 5}', function () { const calls: number[] = []; const task = sut.queueTask( function () { calls.push(1); assert.deepStrictEqual(calls, [3, 2, 1], 'calls'); assert.areTaskQueuesEmpty(); }, { reusable, delay: 5, }, ); sut.queueTask( function () { calls.push(2); }, { reusable, preempt: false, }, ); sut.queueTask( function () { calls.push(3); }, { reusable, preempt: true, }, ); return task.result; }); for (const delay of [1, 5]) { for (const expected of [2, 4]) { it(`x${expected} sequential, {delay: ${delay}}`, async function () { let actual = 0; queueSequential( sut, { reusable, delay, }, expected, function () { ++actual; }, ); await sut.yield(); assert.strictEqual(actual, expected, 'callCount'); assert.areTaskQueuesEmpty(); }); it(`x${expected} recursive, {delay: ${delay}}`, async function () { let actual = 0; queueRecursive( sut, { reusable, delay, }, expected, function () { ++actual; }, ); await sut.yield(); assert.strictEqual(actual, expected, 'callCount'); assert.areTaskQueuesEmpty(); }); } } }); describe(`can persist ${name}`, function () { for (const iterations of [1, 2, 3]) { describe(`runs until canceled after ${iterations} iterations`, function () { it(`from within the running task`, function (done) { let count = 0; const task = sut.queueTask( function () { if (++count === iterations) { assert.strictEqual(task.status, TaskStatus.running, `task.status at count=${count} ${reportTask(task)}`); task.cancel(); assert.areTaskQueuesEmpty(); } }, { persistent: true, reusable, }, ); let thenCount = 0; function callback() { if (++thenCount === iterations) { assert.strictEqual(task.status, TaskStatus.canceled, `task.status at thenCount=${thenCount} ${reportTask(task)}`); assert.areTaskQueuesEmpty(); done(); } else { assert.strictEqual(task.status, TaskStatus.pending, `task.status at thenCount=${thenCount} ${reportTask(task)}`); task.result.then(callback).catch((error) => { throw error; }); } } task.result.then(callback).catch((error) => { throw error; }); }); it(`from within a followup task`, function (done) { let count = 0; const task = sut.queueTask( function () { assert.strictEqual(nextTask.status, TaskStatus.pending, `nextTask.status in task at count=${count} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.running, `task.status in task at count=${count} ${reportTask(task)}`); ++count; }, { persistent: true, reusable, }, ); let nextTask: ITask; function createNextTask() { return sut.queueTask( function () { assert.strictEqual(nextTask.status, TaskStatus.running, `nextTask.status in nextTask at count=${count} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.pending, `task.status in nextTask at count=${count} ${reportTask(task)}`); if (count === iterations) { task.cancel(); assert.areTaskQueuesEmpty(); } else { nextTask = createNextTask(); } }, { reusable, }, ); } nextTask = createNextTask(); let thenCount = 0; function callback() { if (++thenCount === iterations) { assert.strictEqual(nextTask.status, TaskStatus.completed, `nextTask.status at thenCount=${thenCount} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.canceled, `task.status at thenCount=${thenCount} ${reportTask(task)}`); assert.areTaskQueuesEmpty(); done(); } else { assert.strictEqual(nextTask.status, TaskStatus.pending, `nextTask.status at thenCount=${thenCount} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.pending, `task.status at thenCount=${thenCount} ${reportTask(task)}`); nextTask.result.then(callback).catch((error) => { throw error; }); } } nextTask.result.then(callback).catch((error) => { throw error; }); }); it(`yields after the first iteration with no other tasks`, function (done) { let count = 0; let yieldCount = 0; const task = sut.queueTask( function () { assert.strictEqual(task.status, TaskStatus.running, `task.status at count=${count} ${reportTask(task)}`); assert.strictEqual(++count, yieldCount + 1, '++count === yieldCount + 1'); }, { persistent: true, reusable, }, ); function yieldAndVerify() { sut.yield().then(() => { assert.strictEqual(count, ++yieldCount, 'count === ++yieldCount'); if (yieldCount < iterations) { yieldAndVerify(); } else { task.cancel(); assert.areTaskQueuesEmpty(); done(); } }).catch((error) => { throw error; }); } yieldAndVerify(); }); it(`yields after the first iteration with several other tasks`, function (done) { let count = 0; const task = sut.queueTask( function () { assert.strictEqual(task.status, TaskStatus.running, `task.status at count=${count} ${reportTask(task)}`); ++count; }, { persistent: true, reusable, }, ); let otherCount = 0; sut.queueTask( function () { ++otherCount; }, { preempt: true, reusable, }, ); sut.queueTask( function () { ++otherCount; }, { preempt: false, reusable, }, ); sut.queueTask( function () { ++otherCount; }, { preempt: true, reusable, }, ); sut.queueTask( function () { ++otherCount; }, { preempt: false, reusable, }, ); sut.yield().then(() => { assert.strictEqual(count, 1, 'count'); assert.strictEqual(otherCount, 4, 'otherCount'); task.cancel(); assert.areTaskQueuesEmpty(); done(); }).catch((error) => { throw error; }); }); }); } }); } } // TODO(fkleuver): we need async tests with suspend: false. // This is indirectly tested by various integration tests but we need at least a couple of thorough platform-specific tests as well. describe('async', function () { for (const reusable of [true, false]) { const $reusable = reusable ? 'reusable' : 'non-reusable'; for (const { sut, name } of prioritySpecs) { describe(`can queue ${$reusable} ${name}`, function () { it('x1, {preempt: false, delay: 0}', async function () { const { promise, resolve } = createExposedPromise(); sut.queueTask( async function () { assert.areTaskQueuesEmpty(); resolve(); }, { reusable, preempt: false, delay: 0, suspend: true, }, ); await promise; }); it('x1, {preempt: true, delay: 0}', async function () { const { promise, resolve } = createExposedPromise(); sut.queueTask( async function () { assert.areTaskQueuesEmpty(); resolve(); }, { reusable, preempt: true, delay: 0, suspend: true, }, ); await promise; }); it('x1, {delay: 5}', async function () { const { promise, resolve } = createExposedPromise(); sut.queueTask( async function () { assert.areTaskQueuesEmpty(); resolve(); }, { reusable, delay: 5, suspend: true, }, ); await promise; }); it('x1, queue {delay: 5} -> {delay: 0}, invoke {delay: 0} -> {delay: 5}', async function () { const { promise, resolve } = createExposedPromise(); const calls: number[] = []; sut.queueTask( async function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); resolve(); }, { reusable, delay: 5, suspend: true, }, ); sut.queueTask( async function () { calls.push(2); }, { reusable, delay: 0, suspend: true, }, ); await promise; }); it('x1, queue {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false}', async function () { const { promise, resolve } = createExposedPromise(); const calls: number[] = []; sut.queueTask( async function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); resolve(); }, { reusable, preempt: false, suspend: true, }, ); sut.queueTask( async function () { calls.push(2); }, { reusable, preempt: true, suspend: true, }, ); await promise; }); it('x1, queue {delay: 5} -> {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false} -> {delay: 5}', async function () { const { promise, resolve } = createExposedPromise(); const calls: number[] = []; sut.queueTask( async function () { calls.push(1); assert.deepStrictEqual(calls, [3, 2, 1], 'calls'); assert.areTaskQueuesEmpty(); resolve(); }, { reusable, delay: 5, suspend: true, }, ); sut.queueTask( async function () { calls.push(2); }, { reusable, preempt: false, suspend: true, }, ); sut.queueTask( async function () { calls.push(3); }, { reusable, preempt: true, suspend: true, }, ); await promise; }); for (const delay of [1, 5]) { for (const expected of [2, 4]) { it(`${name} x${expected} sequential, {delay: ${delay}}`, async function () { const { promise, resolve } = createExposedPromise(); let actual = 0; async function increment() { if (++actual === expected) { assert.areTaskQueuesEmpty(); resolve(); } } queueSequentialAsync( sut, { reusable, delay, suspend: true, }, expected, increment, ); await promise; }); it(`${name} x${expected} recursive, {delay: ${delay}}`, async function () { const { promise, resolve } = createExposedPromise(); let actual = 0; async function increment() { if (++actual === expected) { assert.areTaskQueuesEmpty(); resolve(); } } queueRecursiveAsync( sut, { reusable, delay, suspend: true, }, expected, increment, ); await promise; }); } } }); describe(`can await ${$reusable} ${name}`, function () { it(`manual 2x recursive`, async function () { const opts = { reusable, preempt: false, delay: 0, suspend: true, }; let count = 0; sut.queueTask( async function () { await Promise.resolve(); ++count; sut.queueTask( async function () { ++count; }, opts, ); }, opts, ); await sut.yield(); assert.strictEqual(count, 2); assert.areTaskQueuesEmpty(); }); it('x1, {preempt: false, delay: 0}', async function () { const task = sut.queueTask( async function () { /* */ }, { reusable, preempt: false, delay: 0, suspend: true, }, ); await task.result; }); it('x1, {preempt: true, delay: 0}', async function () { const task = sut.queueTask( async function () { /* */ }, { reusable, preempt: true, delay: 0, suspend: true, }, ); await task.result; }); it('x1, {delay: 5}', async function () { const task = sut.queueTask( async function () { /* */ }, { reusable, delay: 5, suspend: true, }, ); await task.result; }); it('x1, queue {delay: 5} -> {delay: 0}, invoke {delay: 0} -> {delay: 5}', async function () { const calls: number[] = []; const task = sut.queueTask( async function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); }, { reusable, delay: 5, suspend: true, }, ); sut.queueTask( async function () { calls.push(2); }, { reusable, delay: 0, suspend: true, }, ); await task.result; }); it('x1, queue {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false}', async function () { const calls: number[] = []; const task = sut.queueTask( async function () { calls.push(1); assert.deepStrictEqual(calls, [2, 1], 'calls'); assert.areTaskQueuesEmpty(); }, { reusable, preempt: false, suspend: true, }, ); sut.queueTask( async function () { calls.push(2); }, { reusable, preempt: true, suspend: true, }, ); await task.result; }); it('x1, queue {delay: 5} -> {preempt: false} -> {preempt: true}, invoke {preempt: true} -> {preempt: false} -> {delay: 5}', async function () { const calls: number[] = []; const task = sut.queueTask( async function () { calls.push(1); assert.deepStrictEqual(calls, [3, 2, 1], 'calls'); assert.areTaskQueuesEmpty(); }, { reusable, delay: 5, suspend: true, }, ); sut.queueTask( async function () { calls.push(2); }, { reusable, preempt: false, suspend: true, }, ); sut.queueTask( async function () { calls.push(3); }, { reusable, preempt: true, suspend: true, }, ); await task.result; }); for (const delay of [1, 5]) { for (const expected of [2, 4]) { it(`x${expected} sequential, {delay: ${delay}}`, async function () { let actual = 0; queueSequentialAsync( sut, { reusable, delay, suspend: true, }, expected, async function () { ++actual; }, ); await sut.yield(); assert.strictEqual(actual, expected, 'callCount'); assert.areTaskQueuesEmpty(); }); it(`x${expected} recursive, {delay: ${delay}}`, async function () { let actual = 0; queueRecursiveAsync( sut, { reusable, delay, suspend: true, }, expected, async function () { ++actual; }, ); await sut.yield(); assert.strictEqual(actual, expected, 'callCount'); assert.areTaskQueuesEmpty(); }); } } }); describe(`can persist ${$reusable} ${name}`, function () { for (const iterations of [1, 2, 3]) { describe(`runs until canceled after ${iterations} iterations`, function () { it(`from within the running task`, async function () { const { promise, resolve } = createExposedPromise(); let count = 0; const task = sut.queueTask( async function () { if (++count === iterations) { assert.strictEqual(task.status, TaskStatus.running, `task.status at count=${count} ${reportTask(task)}`); task.cancel(); assert.areTaskQueuesEmpty(); } }, { persistent: true, reusable, suspend: true, }, ); let thenCount = 0; async function callback() { if (++thenCount === iterations) { assert.strictEqual(task.status, TaskStatus.canceled, `task.status at thenCount=${thenCount} ${reportTask(task)}`); assert.areTaskQueuesEmpty(); resolve(); } else { assert.strictEqual(task.status, TaskStatus.pending, `task.status at thenCount=${thenCount} ${reportTask(task)}`); await task.result; await callback(); } } await task.result; await callback(); await promise; }); it(`from within a followup task`, async function () { const { promise, resolve } = createExposedPromise(); let count = 0; const task = sut.queueTask( async function () { assert.strictEqual(nextTask.status, TaskStatus.pending, `nextTask.status in task at count=${count} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.running, `task.status in task at count=${count} ${reportTask(task)}`); ++count; }, { persistent: true, reusable, suspend: true, }, ); let nextTask: ITask; function createNextTask() { return sut.queueTask( async function () { assert.strictEqual(nextTask.status, TaskStatus.running, `nextTask.status in nextTask at count=${count} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.pending, `task.status in nextTask at count=${count} ${reportTask(task)}`); if (count === iterations) { task.cancel(); assert.areTaskQueuesEmpty(); } else { nextTask = createNextTask(); } }, { reusable, suspend: true, }, ); } nextTask = createNextTask(); let thenCount = 0; async function callback() { if (++thenCount === iterations) { assert.strictEqual(nextTask.status, TaskStatus.completed, `nextTask.status at thenCount=${thenCount} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.canceled, `task.status at thenCount=${thenCount} ${reportTask(task)}`); assert.areTaskQueuesEmpty(); resolve(); } else { assert.strictEqual(nextTask.status, TaskStatus.pending, `nextTask.status at thenCount=${thenCount} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.pending, `task.status at thenCount=${thenCount} ${reportTask(task)}`); await nextTask.result; // eslint-disable-next-line @typescript-eslint/no-floating-promises callback(); } } await task.result; assert.strictEqual(nextTask.status, TaskStatus.pending, `nextTask.status after awaiting task.result at thenCount=${thenCount} ${reportTask(nextTask)}`); assert.strictEqual(task.status, TaskStatus.pending, `task.status after awaiting task.result at thenCount=${thenCount} ${reportTask(task)}`); await nextTask.result; await callback(); await promise; }); it(`yields after the first iteration with no other tasks`, async function () { const { promise, resolve } = createExposedPromise(); let count = 0; let yieldCount = 0; const task = sut.queueTask( async function () { assert.strictEqual(task.status, TaskStatus.running, `task.status at count=${count} ${reportTask(task)}`); assert.strictEqual(++count, yieldCount + 1, '++count === yieldCount + 1'); }, { persistent: true, reusable, suspend: true, }, ); async function yieldAndVerify() { await sut.yield(); assert.strictEqual(count, ++yieldCount, 'count === ++yieldCount'); if (yieldCount < iterations) { // eslint-disable-next-line @typescript-eslint/no-floating-promises yieldAndVerify(); } else { task.cancel(); assert.areTaskQueuesEmpty(); resolve(); } } await yieldAndVerify(); await promise; }); it(`yields after the first iteration with several other tasks`, async function () { let count = 0; const task = sut.queueTask( async function () { assert.strictEqual(task.status, TaskStatus.running, `task.status at count=${count} ${reportTask(task)}`); ++count; }, { persistent: true, reusable, suspend: true, }, ); let otherCount = 0; sut.queueTask( async function () { ++otherCount; }, { preempt: true, reusable, suspend: true, }, ); sut.queueTask( async function () { ++otherCount; }, { preempt: false, reusable, suspend: true, }, ); sut.queueTask( async function () { ++otherCount; }, { preempt: true, reusable, suspend: true, }, ); sut.queueTask( async function () { ++otherCount; }, { preempt: false, reusable, suspend: true, }, ); await sut.yield(); assert.strictEqual(count, 1, 'count'); assert.strictEqual(otherCount, 4, 'otherCount'); task.cancel(); assert.areTaskQueuesEmpty(); }); }); } it(`yields after the first iteration with no other tasks, after finishing a persistent task that was canceled from within a followup task`, async function () { const primerTask = sut.queueTask( async function () { assert.strictEqual(primerTask.status, TaskStatus.running, `primerTask.status in primerTask ${reportTask(primerTask)}`); assert.strictEqual(primerCancelTask.status, TaskStatus.pending, `primerCancelTask.status in primerTask ${reportTask(primerCancelTask)}`); }, { persistent: true, reusable, suspend: true, }, ); const primerCancelTask = sut.queueTask( async function () { assert.strictEqual(primerTask.status, TaskStatus.pending, `primerTask.status in primerCancelTask ${reportTask(primerTask)}`); assert.strictEqual(primerCancelTask.status, TaskStatus.running, `primerCancelTask.status in primerCancelTask ${reportTask(primerCancelTask)}`); primerTask.cancel(); assert.areTaskQueuesEmpty(); }, { reusable, suspend: true, }, ); await primerTask.result; assert.strictEqual(primerTask.status, TaskStatus.pending, `primerTask.status after awaiting primerTask.result ${reportTask(primerTask)}`); assert.strictEqual(primerCancelTask.status, TaskStatus.pending, `primerCancelTask.status after awaiting primerTask.result ${reportTask(primerCancelTask)}`); await primerCancelTask.result; assert.strictEqual(primerTask.status, TaskStatus.canceled, `primerTask.status after awaiting primerCancelTask.result ${reportTask(primerTask)}`); assert.strictEqual(primerCancelTask.status, TaskStatus.completed, `primerCancelTask.status after awaiting primerCancelTask.result ${reportTask(primerCancelTask)}`); assert.areTaskQueuesEmpty(); let count = 0; let yieldCount = 0; const persistentTask = sut.queueTask( async function () { assert.strictEqual(persistentTask.status, TaskStatus.running, `persistentTask.status in persistentTask ${reportTask(persistentTask)}`); assert.strictEqual(++count, yieldCount + 1, `++count (${count}) === yieldCount + 1 (${yieldCount + 1}) in persistentTask`); }, { persistent: true, reusable, suspend: true, }, ); await sut.yield(); assert.strictEqual(count, ++yieldCount, `count (${count}) === ++yieldCount (${yieldCount}) after awaiting sut.yield()`); persistentTask.cancel(); assert.areTaskQueuesEmpty(); }); }); } } const enum TaskState { NotStarted = 0, Started = 1, Finished = 2, } it(`awaits the first task before starting the second`, async function () { const states = [ TaskState.NotStarted, TaskState.NotStarted, TaskState.NotStarted, ]; async function callback0() { states[0] = TaskState.Started; assert.deepStrictEqual(states, [TaskState.Started, 0, 0], `state at the start of callback0`); await new Promise(resolve => setTimeout(resolve, 50)); states[0] = TaskState.Finished; assert.deepStrictEqual(states, [TaskState.Finished, 0, 0], `state at the end of callback0`); } async function callback1() { states[1] = TaskState.Started; assert.deepStrictEqual(states, [TaskState.Finished, TaskState.Started, 0], `state at the start of callback1`); await new Promise(resolve => setTimeout(resolve, 50)); states[1] = TaskState.Finished; assert.deepStrictEqual(states, [TaskState.Finished, TaskState.Finished, 0], `state at the end of callback1`); } async function callback2() { states[2] = TaskState.Started; assert.deepStrictEqual(states, [TaskState.Finished, TaskState.Finished, TaskState.Started], `state at the start of callback2`); await new Promise(resolve => setTimeout(resolve, 50)); states[2] = TaskState.Finished; assert.deepStrictEqual(states, [TaskState.Finished, TaskState.Finished, TaskState.Finished], `state at the end of callback2`); } const opts: QueueTaskOptions = { suspend: true, }; const task0 = platform.taskQueue.queueTask(callback0, opts); const task1 = platform.taskQueue.queueTask(callback1, opts); const task2 = platform.taskQueue.queueTask(callback2, opts); assert.deepStrictEqual(states, [TaskState.NotStarted, TaskState.NotStarted, TaskState.NotStarted], `state after queueing 3 tasks`); await task0.result; // Note: the assertion pattern here is to verify that the next task is started on the next 'cycle' rather than immediately after the previous task finished. // If we were to verify the opposite, the expected state would be [Finished, Started, NotStarted] instead of [Finished, NotStarted, NotStarted]. assert.deepStrictEqual(states, [TaskState.Finished, TaskState.NotStarted, TaskState.NotStarted], `state after awaiting task0`); await task1.result; assert.deepStrictEqual(states, [TaskState.Finished, TaskState.Finished, TaskState.NotStarted], `state after awaiting task1`); await task2.result; assert.deepStrictEqual(states, [TaskState.Finished, TaskState.Finished, TaskState.Finished], `state after awaiting task2`); assert.areTaskQueuesEmpty(); }); }); });
the_stack
import { BackendType, ENV } from "../environment"; import * as util from "../util"; import * as axis_util from "./axis_util"; import { MathBackend } from "./backends/backend"; import { BackendEngine, ScopeResult } from "./backends/backend_engine"; import * as broadcast_util from "./broadcast_util"; import * as concat_util from "./concat_util"; import * as conv_util from "./conv_util"; import { Array1D, Array2D, Array3D, Array4D, DataId, DataType, DataTypeMap, IntDType, NDArray, Rank, RankMap, Scalar } from "./ndarray"; import * as slice_util from "./slice_util"; import { MatrixOrientation, SumTypes } from "./types"; export interface LSTMCell { (data: Array2D, c: Array2D, h: Array2D): [Array2D, Array2D]; } export interface NDArrayManager { getNumArrays(): number; register(a: NDArray): void; } export class NDArrayMath implements NDArrayManager { protected backendEngine: BackendEngine; private registeredArrays = new WeakMap<DataId, number>(); private registeredArrayCount = 0; private backend: MathBackend; private customBackend = false; time(query: () => NDArray): Promise<number> { return this.backend.time(query); } getNumArrays() { return this.registeredArrayCount; } register(a: NDArray): void { const refCount = this.registeredArrays.has(a.dataId) ? this.registeredArrays.get(a.dataId) : 0; if (refCount === 0) { this.backend.register(a.dataId, a.shape, a.dtype); this.registeredArrayCount++; } this.registeredArrays.set(a.dataId, refCount + 1); this.backendEngine.track(a); } writePixels( dataId: DataId, pixels: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, numChannels: number): void { this.backend.writePixels(dataId, pixels, numChannels); } write<D extends DataType>(dataId: DataId, values: DataTypeMap[D]): void { this.backend.write(dataId, values); } readSync<D extends DataType>(dataId: DataId): DataTypeMap[D] { return this.backend.readSync(dataId); } read<D extends DataType>(dataId: DataId): Promise<DataTypeMap[D]> { return this.backend.read(dataId); } /** * @param safeMode In safe mode, you must use math operations inside * a math.scope() which will automatically clean up intermediate NDArrays. */ constructor(backend: BackendType | MathBackend) { if (typeof backend === "string") { this.backend = ENV.getBackend(backend); } else { this.customBackend = true; this.backend = backend; } this.backendEngine = new BackendEngine(); } /** * 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: () => T): T { return this.backendEngine.scope("scope", scopeFn); } /** * Start a scope. Use this with endScope() to achieve the same functionality * as scope() without the need for a function closure. */ startScope() { this.backendEngine.startScope(); } /** * End a scope. Use this with startScope() to achieve the same functionality * as scope() without the need for a function closure. */ endScope(result: {}) { this.backendEngine.endScope(result); } dispose() { if (this.customBackend) { this.backend.dispose(); } } /** * 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.backend.matMul(a, b, aOrientation, bOrientation); } private executeOp<T extends NDArray>(name: string, f: () => T): T { // TODO(nsthorat): Do operation logging and performance profiling. return f(); } /** * 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 vector (${v.size}) ` + `must match first dimension of matrix (${matrix.shape[0]})`); return this.matMul(v.as2D(1, -1), 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 matrixTimesVector: second input must rank 1, but got ` + `rank ${v.rank}.`); util.assert( matrix.rank === 2, `Error in matrixTimesVector: first input must be a rank 2, but got ` + `rank ${matrix.rank}.`); util.assert( v.size === matrix.shape[1], `Error in matrixTimesVector: 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(-1, 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, -1), v2.as2D(-1, 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(-1, 1), v2.as2D(1, -1)); } /////////////// // Shape ops // /////////////// /** * Clones an NDArray of any shape. * @param x The NDArray to clone. */ clone<T extends NDArray>(x: T): T { return this.backend.clone(x); } /** Reshapes the array. */ reshape<D extends DataType, R extends Rank, T extends RankMap<D>[R]>( x: NDArray<D>, newShape: number[]): T { newShape = util.inferFromImplicitShape(newShape, x.size); util.assert( x.size === util.sizeFromShape(newShape), "new shape and old shape must have the same number of elements."); return NDArray.make(newShape, {dataId: x.dataId}, x.dtype) as T; } /** * Casts a tensor to a new type. If the new type matches the old type, * this is a no-op. */ cast<D extends DataType, R extends Rank>( x: NDArray<DataType, R>, newDType: D): RankMap<D>[R] { if (!util.hasEncodingLoss(x.dtype, newDType)) { // We don't change the underlying data, since we cast to higher precision. return NDArray.make(x.shape, {dataId: x.dataId}, newDType); } if (newDType === "int32" || newDType === "uint8") { return this.backend.int(x, newDType as IntDType) as NDArray as RankMap<D>[R]; } else if (newDType === "bool") { return this.backend.notEqual(x, Scalar.new(0, x.dtype)) as RankMap<D>[R]; } else { throw new Error(`Error in Cast: unknown dtype argument (${newDType})`); } } gather(x: NDArray, indices: Array1D<"int32">, axis: number): NDArray { return this.backend.gather(x, indices, axis); } pad(x: NDArray, paddings: Array<[number, number]>, padValue: number): NDArray { return this.backend.pad(x, paddings, padValue); } /** * Extracts a 1D slice from 1D array starting at coordinates `begin` and is * of length `size`. * * @param x The input array to slice from. * @param begin The offset to start the slice from. * @param size The size of the slice. */ slice1D(x: Array1D, begin: number, size: number): Array1D { slice_util.assertParamsValid(x, [begin], [size]); return this.backend.slice1D(x, begin, size); } /** * Extracts a 2D slice from a 2D array starting at coordinates `begin` and * is of size `size`. * * @param x The input array to slice from. * @param begin The [row, col] 2d coordinates to start the slice from. * @param size The size of the slice. */ slice2D(x: Array2D, begin: [number, number], size: [number, number]): Array2D { slice_util.assertParamsValid(x, begin, size); return this.backend.slice2D(x, begin, size); } /** * Extracts a 3D slice from a 3D array starting at coordinates `begin` and * is of size `size`. * * @param x The input array to slice from. * @param begin The [row, col, depth] 3d coordinates to start the slice from. * @param size The size of the slice. */ slice3D(x: Array3D, begin: [number, number, number], size: [ number, number, number ]): Array3D { slice_util.assertParamsValid(x, begin, size); return this.backend.slice3D(x, begin, size); } /** * Extracts a 4D slice from a 4D array starting at coordinates `begin` and * is of size `size`. * * @param x The input array to slice from. * @param begin The [row, col, depth, depth2] 4d coordinates to start the * slice from. * @param size The size of the slice. */ slice4D(x: Array4D, begin: [number, number, number, number], size: [ number, number, number, number ]): Array4D { slice_util.assertParamsValid(x, begin, size); return this.backend.slice4D(x, begin, size); } /** * Concatenates two 1D arrays. * * For example, if: * A: shape(3) = |r1, g1, b1| * B: shape(2) = |r2, g2| * C = concat1D(A, B) == |r1, g1, b1, r2, g2| * * @param a The first array. * @param b The second array. * @return The concatenated array. */ concat1D(a: Array1D, b: Array1D): Array1D { concat_util.assertParams(a.shape, b.shape, 0); return this.backend.concat1D(a, b); } /** * Concatenates two 2D arrays along a given axis. * * For example, if: * A: shape(2, 3) = | r1, g1, b1 | * | r2, g2, b2 | * * B: shape(2, 3) = | r3, g3, b3 | * | r4, g4, b4 | * * C = concat2D(A, B, axis) * * if axis = 0: * C: shape(4, 3) = | r1, g1, b1 | * | r2, g2, b2 | * | r3, g3, b3 | * | r4, g4, b4 | * * if axis = 1: * C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 | * | r2, g2, b2, r4, g4, b4 | * * * @param a The first array. * @param b The second array. * @param axis The axis to concatenate along. * @return The concatenated array. */ concat2D(a: Array2D, b: Array2D, axis: number): Array2D { concat_util.assertParams(a.shape, b.shape, axis); return this.backend.concat2D(a, b, axis); } /** * 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 a The first array to concat. * @param b The second array to conat. * @param axis The axis to concate along. * @return The concatenated array. */ concat3D(a: Array3D, b: Array3D, axis: number): Array3D { concat_util.assertParams(a.shape, b.shape, axis); return this.backend.concat3D(a, b, axis); } /** * Concatenates two 4D ndarrays along a given axis. See math.concat2D() for * documentation. * * @param a The first array to concat. * @param b The second array to conat. * @param axis The axis to concate along. * @return The concatenated array. */ concat4D(a: Array4D, b: Array4D, axis: number): Array4D { concat_util.assertParams(a.shape, b.shape, axis); return this.backend.concat4D(a, b, axis); } /////////////////// // Reduction ops // /////////////////// /** * Computes the log(sum(exp(elements across the reduction dimensions)). * * Reduces the input along the dimensions given in `axis`. Unless `keepDims` * is true, the rank of the array is reduced by 1 for each entry in `axis`. * If `keepDims` is true, the reduced dimensions are retained with length 1. * If `axis` has no entries, all dimensions are reduced, and an array with a * single element is returned. * * @param input The input NDArray. * @param axis Optional. The dimension(s) to reduce. If null (the default), * reduces all dimensions. * @param keepDims Optional. If true, retains reduced dimensions with length * of 1. Defaults to false. */ logSumExp<T extends NDArray>( input: NDArray, axis: number | number[] = null, keepDims = false): T { const axes = axis_util.parseAxisParam(axis, input.shape); return this.executeOp("logSumExp", () => { const xMax = this.max(input, axes, true /* keepDims */); const a = this.subtract(input, xMax); const b = this.exp(a); const c = this.sum(b, axes); const d = this.log(c); const res = this.add(xMax.reshape(d.shape), d); if (keepDims) { const newShape = axis_util.expandShapeToKeepDim(res.shape, axes); return res.reshape(newShape); } return res; }) as T; } /** * Computes the sum of elements across dimensions of an array. * * Reduces the input along the dimensions given in `axes`. Unless `keepDims` * is true, the rank of the array is reduced by 1 for each entry in `axes`. * If `keepDims` is true, the reduced dimensions are retained with length 1. * If axes has no entries, all dimensions are reduced, and an array with a * single element is returned. * * @param x The input array to compute the sum over. * @param axis Optional. The dimension(s) to reduce. By default it reduces * all dimensions. * @param keepDims Optional. If true, retains reduced dimensions with size 1. */ sum<D extends DataType, T extends NDArray<SumTypes[D]>>( x: NDArray<D>, axis: number | number[] = null, keepDims = false): T { const origAxes = axis_util.parseAxisParam(axis, x.shape); let axes = origAxes; const permutedAxes = axis_util.getPermutedAxes(axes, x.rank); return this.executeOp("sum", () => { if (permutedAxes != null) { x = this.transpose(x, permutedAxes); axes = axis_util.getInnerMostAxes(axes.length, x.rank); } const res = this.backend.sum(x, axes); if (keepDims) { const newShape = axis_util.expandShapeToKeepDim(res.shape, origAxes); return res.reshape(newShape); } return res; }) as T; } /** * Computes the mean of elements across dimensions of an array. * * Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is * true, the rank of the array is reduced by 1 for each entry in `axis`. * If `keepDims` is true, the reduced dimensions are retained with length 1. * If `axis` has no entries, all dimensions are reduced, and an array with a * single element is returned. * * @param x The input array. * @param axis Optional. The dimension(s) to reduce. By default it reduces * all dimensions. * @param keepDims Optional. If true, retains reduced dimensions with size 1. */ mean(x: NDArray, axis: number | number[] = null, keepDims = false): NDArray<"float32"> { const axes = axis_util.parseAxisParam(axis, x.shape); const shapes = axis_util.computeOutAndReduceShapes(x.shape, axes); const reduceShape = shapes[1]; const reduceSize = util.sizeFromShape(reduceShape); return this.executeOp("mean", () => { return this.scope(() => { const res = this.divide(x, Scalar.new(reduceSize)); return this.sum(res, axis, keepDims); }); }); } /** * Returns the indices of the minimum values along an `axis`. The result has * the same shape as `input` with the dimension along `axis` removed. * * @param x The input array. * @param axis Optional. The dimension to reduce. By default it reduces * across all axes and returns the flat index. * */ argMin<T extends NDArray<"int32">>(x: NDArray, axis: number = null): T { let axes = axis_util.parseAxisParam(axis, x.shape); const permutedAxes = axis_util.getPermutedAxes(axes, x.rank); return this.executeOp("argMin", () => { if (permutedAxes != null) { x = this.transpose(x, permutedAxes); axes = axis_util.getInnerMostAxes(axes.length, x.rank); } return this.backend.argMin(x, axes); }) as T; } /** * Returns the indices of the maximum values along an `axis`. The result has * the same shape as `input` with the dimension along `axis` removed. * * @param x The input array. * @param axis Optional. The dimension to reduce. By default it reduces * across all axes and returns the flat index */ argMax<T extends NDArray<"int32">>(x: NDArray, axis: number = null): T { let axes = axis_util.parseAxisParam(axis, x.shape); const permutedAxes = axis_util.getPermutedAxes(axes, x.rank); return this.executeOp("argMax", () => { if (permutedAxes != null) { x = this.transpose(x, permutedAxes); axes = axis_util.getInnerMostAxes(axes.length, x.rank); } return this.backend.argMax(x, axes); }) as T; } /** * 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<"bool"> { util.assertShapesMatch(x1.shape, x2.shape, "Error in argMaxEquals: "); return this.executeOp("argMaxEquals", () => this.scope(() => { return this.equal(this.argMax(x1), this.argMax(x2)); })); } /** * Returns the truth value of (a == b) element-wise. Supports broadcasting. * For a stricter version without broadcasting use math.equalStrict(). * * @param a The first input `NDArray`. * @param b The second input `NDArray`. Must have the same dtype as `a`. */ equal<D1 extends DataType, D2 extends D1, T extends NDArray<"bool">>( a: NDArray<D1>, b: NDArray<D2>): T { util.assertTypesMatch(a, b); broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.equal(a, b) as T; } equalStrict<T extends NDArray>(a: T, b: T): NDArray<"bool"> { util.assertShapesMatch(a.shape, b.shape, "Error in equalStrict: "); return this.equal(a, b); } /** * Returns the truth value of (a != b) element-wise. Supports broadcasting. * For a stricter version without broadcasting use math.notEqualStrict(). * * @param a The first input `NDArray`. * @param b The second input `NDArray`. Must have the same dtype as `a`. */ notEqual<D1 extends DataType, D2 extends D1, T extends NDArray<"bool">>( a: NDArray<D1>, b: NDArray<D2>): T { util.assertTypesMatch(a, b); broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.notEqual(a, b) as T; } notEqualStrict<R extends Rank, D1 extends DataType, D2 extends D1>( a: NDArray<D1, R>, b: NDArray<D2, R>): RankMap<"bool">[R] { util.assertShapesMatch(a.shape, b.shape, "Error in notEqualStrict: "); return this.notEqual(a, b); } /** * Returns the truth value of (a > b) element-wise. Supports broadcasting. */ greater(a: NDArray, b: NDArray): NDArray<"bool"> { return this.backend.greater(a, b); } /** * Returns the truth value of (a >= b) element-wise. Supports broadcasting. */ greaterEqual(a: NDArray, b: NDArray): NDArray<"bool"> { return this.backend.greaterEqual(a, b); } /** * Returns the truth value of (a < b) element-wise. Supports broadcasting. */ less(a: NDArray, b: NDArray): NDArray<"bool"> { return this.backend.less(a, b); } /** * Returns the truth value of (a <= b) element-wise. Supports broadcasting. */ lessEqual(a: NDArray, b: NDArray): NDArray<"bool"> { return this.backend.lessEqual(a, b); } /** * Selects elements from `a` or `b`, depending on `cond`. */ select(cond: NDArray<"bool">, a: NDArray, b: NDArray): NDArray { return this.backend.select(cond, a, b); } /** * Computes the top K values and flattened indices. * @param x The input NDArray. * @param k How many top values to compute. */ topK(x: NDArray, k: number): {values: Array1D, indices: Array1D<"int32">} { util.assert( k <= x.size, `Error in topK: k value (${k}) must be less than size of input ` + `ndarray, got shape ${x.shape}.`); let values: Array1D; let indices: Array1D<"int32">; this.executeOp("topK", () => { values = this.backend.topKValues(x, k); indices = this.backend.topKIndices(x, k); return values; }); const result = {values, indices}; return result; } /** * Computes the minimum value from the input. * * Reduces the input along the dimensions given in `axes`. Unless `keepDims` * is true, the rank of the array is reduced by 1 for each entry in `axes`. * If `keepDims` is true, the reduced dimensions are retained with length 1. * If `axes` has no entries, all dimensions are reduced, and an array with a * single element is returned. * * @param x The input NDArray. * @param axis Optional. The dimension(s) to reduce. By default it reduces * all dimensions. * @param keepDims Optional. If true, retains reduced dimensions with size 1. */ min<D extends DataType, T extends NDArray<D>>( x: NDArray<D>, axis: number | number[] = null, keepDims = false): T { const origAxes = axis_util.parseAxisParam(axis, x.shape); let axes = origAxes; const permutedAxes = axis_util.getPermutedAxes(axes, x.rank); return this.executeOp("min", () => { if (permutedAxes != null) { x = this.transpose(x, permutedAxes); axes = axis_util.getInnerMostAxes(axes.length, x.rank); } const res = this.backend.min(x, axes) as NDArray<D>; if (keepDims) { const newShape = axis_util.expandShapeToKeepDim(res.shape, origAxes); return res.reshape(newShape); } return res; }) as T; } /** * Returns the min of a and b (`a < b ? a : b`) element-wise. * Supports broadcasting. * * @param a The first ndarray. * @param b The second ndarray. Must have the same type as `a`. */ minimum<D1 extends DataType, D2 extends D1, T extends NDArray<D1>>( a: NDArray<D1>, b: NDArray<D2>): T { util.assertTypesMatch(a, b); broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.minimum(a, b) as T; } /** * Computes the maximum of elements across dimensions of an array. * * Reduces the input along the dimensions given in `axes`. Unless `keepDims` * is true, the rank of the array is reduced by 1 for each entry in `axes`. * If `keepDims` is true, the reduced dimensions are retained with length 1. * If `axes` has no entries, all dimensions are reduced, and an array with a * single element is returned. * * @param x The input array. * @param axis Optional. The dimension(s) to reduce. By default it reduces * all dimensions. * @param keepDims Optional. If true, retains reduced dimensions with size 1. */ max<D extends DataType, T extends NDArray<D>>( x: NDArray<D>, axis: number | number[] = null, keepDims = false): T { const origAxes = axis_util.parseAxisParam(axis, x.shape); let axes = origAxes; const permutedAxes = axis_util.getPermutedAxes(axes, x.rank); return this.executeOp("max", () => { if (permutedAxes != null) { x = this.transpose(x, permutedAxes); axes = axis_util.getInnerMostAxes(axes.length, x.rank); } const res = this.backend.max(x, axes) as NDArray<D>; if (keepDims) { const newShape = axis_util.expandShapeToKeepDim(res.shape, origAxes); return res.reshape(newShape); } return res; }) as T; } /** * Returns the max of a and b (`a > b ? a : b`) element-wise. * Supports broadcasting. * * @param a The first ndarray. * @param b The second ndarray. Must have the same type as `a`. */ maximum<D1 extends DataType, D2 extends D1, T extends NDArray<D1>>( a: NDArray<D1>, b: NDArray<D2>): T { util.assertTypesMatch(a, b); broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.maximum(a, b) as T; } /** * Computes the softmax normalized vector given the logits. * @param logits The logits array. * @param dim The dimension softmax would be performed on. Defaults to -1 * which indicates the last dimension. */ softmax<T extends NDArray>(logits: T, dim = -1): T { if (dim === -1) { dim = logits.rank - 1; } if (dim !== logits.rank - 1) { throw Error( "Softmax along a non-last dimension is not yet supported. " + `Logits was rank ${logits.rank} and dim was ${dim}`); } return this.executeOp("softmax", () => { // Do it in log space for numerical stability. // exp(X - logSumExp(X)) const keepDims = true; const lse = this.logSumExp(logits, [dim], keepDims); const logResult = this.subtract(logits, lse); const value = this.exp(logResult) as T; return value; }); } /** * Computes softmax cross entropy between logits and labels. * * Measures the probability error in discrete classification tasks in which * the classes are mutually exclusive (each entry is in exactly one class). * For example, each CIFAR-10 image is labeled with one and only one label: an * image can be a dog or a truck, but not both. * * NOTE: While the classes are mutually exclusive, their probabilities need * not be. All that is required is that each row of labels is a valid * probability distribution. If they are not, the computation of the gradient * will be incorrect. * * WARNING: This op expects unscaled logits, since it performs a softmax on * logits internally for efficiency. Do not call this op with the output of * softmax, as it will produce incorrect results. * * logits and labels must have the same shape, e.g. [batch_size, num_classes] * and the same dtype. * @param labels The labels array. * @param logits The logits array. * @param dim The dimension softmax would be performed on. Defaults to -1 * which indicates the last dimension. */ softmaxCrossEntropyWithLogits<I extends NDArray<"float32">, O extends NDArray<"float32">>( labels: I, logits: I, dim = -1): O { util.assertShapesMatch( labels.shape, logits.shape, "Error in softmaxCrossEntropyWithLogits: "); if (dim === -1) { dim = logits.rank - 1; } if (dim !== logits.rank - 1) { throw Error( `Softmax cross entropy along a non-last dimension is not yet ` + `supported. Labels / logits was rank ${logits.rank} ` + `and dim was ${dim}`); } return this.executeOp("softmaxCrossEntropyWithLogits", () => { const softmaxLogits = this.softmax(logits, dim); const yPlusEps = this.add(Scalar.new(1e-5), softmaxLogits); const logOutput = this.log(yPlusEps); const tarLogOutput = this.multiply(labels, logOutput); const costVector = this.neg(tarLogOutput); const value = this.sum(costVector, [dim]) as O; return value; }); } ////////////////////// // Element-wise ops // ////////////////////// /** @deprecated Use math.transpose() instead. */ switchDim<T extends NDArray>(a: T, newDim: number[]): T { return this.transpose(a, newDim); } /** * Construct an array by repeating it the number of times given by reps. * * This operation creates a new array by replicating `input` `reps` * times. The output tensor's i'th dimension has `input.shape[i] * * reps[i]` elements, and the values of `input` are replicated * `reps[i]` times along the i'th dimension. For example, tiling * `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`. * * @param x The array to transpose. * @param reps Determines the number of replications per dimension. */ tile<D extends DataType, T extends NDArray<D>>(x: T, reps: number[]): T { util.assert( x.rank === reps.length, `Error in transpose: rank of input ${x.rank} ` + `must match length of reps ${reps}.`); return this.backend.tile(x, reps) as T; } /** * Transposes the array. Permutes the dimensions according to `perm`. * * The returned array's dimension `i` will correspond to the input dimension * `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`, where `n` is * the rank of the input array. Hence by default, this operation performs a * regular matrix transpose on 2-D input arrays. * * @param x The array to transpose. * @param perm Optional. The permutation of the dimensions of a. */ transpose<T extends NDArray>(x: T, perm?: number[]): T { if (perm == null) { perm = x.shape.map((s, i) => i).reverse(); } util.assert( x.rank === perm.length, `Error in transpose: rank of input ${x.rank} ` + `must match length of perm ${perm}.`); return this.backend.transpose(x, perm) as T; } /** @deprecated Use math.add(c, A) instead. */ 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; } /** @deprecated Use math.sub(c, A) instead. */ 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.subtract(c, a) as T; } /** @deprecated Use math.sub(A, c) instead. */ 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.subtract(a, c) as T; } /** * Computes -1 * A element-wise. * @param x The input array. */ neg<T extends NDArray>(x: T): T { return this.backend.neg(x) as 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. * @param b The second `NDArray` to add. Must have the same type as `a`. */ add<D1 extends DataType, D2 extends D1, T extends NDArray<D1>>( a: NDArray<D1>, b: NDArray<D2>): T { util.assertTypesMatch(a, b); broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.add(a, b) as T; } /** * 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`. * @param b The second `NDArray`. Must have the same dtype as `a`. */ subtract<D1 extends DataType, D2 extends D1, T extends NDArray<D1>>( a: NDArray<D1>, b: NDArray<D2>): T { util.assertTypesMatch(a, b); broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.subtract(a, b) as T; } /** * Computes the power of one value to another. * Given a tensor x and a tensor y, this operation computes x^y for * corresponding elements in x and y. For example: * x = tf.constant([[2, 2], [3, 3]]) * y = tf.constant([[8, 16], [2, 3]]) * pow(x, y) # [[256, 65536], [9, 27]] * * @param a The base NDArray to pow element-wise. * @param b The exponent NDArray to pow element-wise. */ pow<D extends DataType, T extends NDArray<D>>( a: NDArray<D>, b: NDArray): T { broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.pow(a, b) as T; } /** * Computes the power of one value to another. Inputs must * be the same shape. For broadcasting support, use math.pow() instead. * * @param a The base NDArray to pow element-wise. * @param b The exponent NDArray to pow element-wise. */ powStrict<D extends DataType>(a: NDArray<D>, b: NDArray): NDArray<D> { util.assertShapesMatch(a.shape, b.shape, "Error in powStrict: "); return this.pow(a, b); } /** @deprecated Use math.subtract instead. */ sub<D1 extends DataType, D2 extends D1, T extends NDArray<D1>>( a: NDArray<D1>, b: NDArray<D2>): T { return this.subtract(a, b); } /** * 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.subtract(a, b); } /** * Multiplies two NDArrays element-wise, A * B. Supports broadcasting. * For a stricter version without broadcasting use math.multiplyStrict(). * * @param a The first `NDArray`. * @param b The second `NDArray`. Must have the same dtype as `a`. */ multiply<D1 extends DataType, D2 extends D1, T extends NDArray<D1>>( a: NDArray<D1>, b: NDArray<D2>): T { util.assertTypesMatch(a, b); broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.multiply(a, b) as 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<T extends NDArray<"float32">>(a: NDArray, b: NDArray): T { broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape); return this.backend.divide(a, b) as T; } /** * 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; } /** @deprecated Use math.divide(c, A) instead. */ 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; } /** @deprecated Use math.divide(A, c) instead. */ 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 ceiling of input NDArray element-wise. y = ceil(x) * TODO(nsthorat): Make this return an int32 when we add rank as a * generic. * @param x The input NDArray. */ ceil<T extends NDArray>(x: T): T { return this.backend.ceil(x) as T; } /** * Computes floor of input NDArray element-wise. y = floor(x). * * @param x The input NDArray. */ floor<T extends NDArray>(x: T): T { return this.backend.floor(x) as T; } /** * Computes exponential of the input NDArray element-wise. y = e ^ x * @param x The input NDArray. */ exp<T extends NDArray>(x: T): T { return this.backend.exp(x) as T; } /** * Computes natural logarithm of the input NDArray element-wise. y = ln(x) * @param x The input NDArray. */ log<T extends NDArray>(x: T): T { return this.backend.log(x) as T; } /** * Computes square root of the input NDArray element-wise. y = sqrt(x) * @param x The input NDArray. */ sqrt<T extends NDArray>(x: T): T { return this.backend.sqrt(x) as T; } /** * Computes square of `x` element-wise. * * @param x The input array. */ square<T extends NDArray>(x: T): T { return this.backend.square(x) as T; } /** * Computes absolute value element-wise. * @param x The input NDArray. */ abs<T extends NDArray>(x: T): T { return this.backend.abs(x) as T; } /** * Clips values element-wise. * @param x The input NDArray. * @param min Lower-bound of range to be clipped to. * @param max Upper-bound of range to be clipped to. */ clip<T extends NDArray>(x: T, min: number, max: number): T { util.assert( (min <= max), `Error in clip: min (${min}) must be` + `less than or equal to max (${max}).`); return this.backend.clip(x, min, max) as T; } /** * Computes rectified linear element-wise, max(x, 0). * @param x The input NDArray. */ relu<T extends NDArray>(x: T): T { return this.backend.relu(x) as T; } /** * Computes exponential linear element-wise * @param {T} x the input NDArray */ elu<T extends NDArray>(x: T): T { return this.backend.elu(x) as T; } /** * Computes the derivative of elu which is used ly * @hidden */ eluDer<T extends NDArray>(x: T): T { return this.backend.eluDer(x) as T; } /** * Computes scaled exponential linear element-wise. * @hidden */ selu<T extends NDArray>(x: T): T { return this.backend.selu(x) as T; } /** * Computes leaky rectified linear element-wise * @param {T} x the input NDArray * @param alpha scaling factor for negative values, defaults to 0.2 * @return {NDArray} */ leakyRelu<T extends NDArray>(x: T, alpha = 0.2): T { return this.backend.leakyRelu(x, alpha) as T; } /** * Computes leaky rectified linear element-wise with parametric alphas * @param {T} x the input NDArray * @param {T} alpha scaling factor NDArray for negative values * @return {NDArray} */ prelu<T extends NDArray>(x: T, alpha: T): T { return this.backend.prelu(x, alpha) as T; } /** * Computes the derivative of PReLU * @param {T} x the input NDArray * @param {T} alpha scaling factor NDArray for negative values * @return {NDArray} */ preluDer<T extends NDArray>(x: T, alpha: T): T { return this.backend.preluDer(x, alpha) as T; } /** * Computes sigmoid element-wise, y = 1 / (1 + exp(-x)). * @param x The input NDArray. */ sigmoid<T extends NDArray>(x: T): T { return this.backend.sigmoid(x) as T; } /** * Computes sin of the input NDArray element-wise, y = sin(x). * @param x The input NDArray. */ sin<T extends NDArray>(x: T): T { return this.backend.sin(x) as T; } /** * Computes cos of the input NDArray element-wise, y = cos(x). * @param x The input NDArray. */ cos<T extends NDArray>(x: T): T { return this.backend.cos(x) as T; } /** * Computes tan of the input NDArray element-wise, y = tan(x). * @param x The input NDArray. */ tan<T extends NDArray>(x: T): T { return this.backend.tan(x) as T; } /** * Computes asin of the input NDArray element-wise, y = asin(x). * @param x The input NDArray. */ asin<T extends NDArray>(x: T): T { return this.backend.asin(x) as T; } /** * Computes acos of the input NDArray element-wise, y = acos(x). * @param x The input NDArray. */ acos<T extends NDArray>(x: T): T { return this.backend.acos(x) as T; } /** * Computes atan of the input NDArray element-wise, y = atan(x). * @param x The input NDArray. */ atan<T extends NDArray>(x: T): T { return this.backend.atan(x) as T; } /** * Computes hyperbolic sin of the input NDArray element-wise, y = sinh(x). * @param x The input NDArray. */ sinh<T extends NDArray>(x: T): T { return this.backend.sinh(x) as T; } /** * Computes hyperbolic cos of the input NDArray element-wise, y = cosh(x). * @param x The input NDArray. */ cosh<T extends NDArray>(x: T): T { return this.backend.cosh(x) as T; } /** * Computes hyperbolic tangent of the input NDArray element-wise. * @param x The input NDArray. */ tanh<T extends NDArray>(x: T): T { return this.backend.tanh(x) as T; } /** * Computes step of the input NDArray element-wise, * y=1 if x>0|alpha*x if x<=0. * * @param x The input NDArray. * @param alpha The gradient when input is negative. */ step<T extends NDArray>(x: T, alpha = 0.0): T { return this.backend.step(x, alpha) as 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.executeOp("scaledArrayAdd", () => { return this.scope(() => { // TODO(nsthorat): Add an SGEMM kernel and then update this. return this.add(this.multiply(c1, a), this.multiply(c2, b)) as T; }); }); } /** @deprecated Use math.multiply(c, A) instead. */ 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 1D convolution over the input x. * @param input The input ndarray, of rank 3 or rank 2, of shape * `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed. * @param filter The filter, rank 3, of shape * [filterWidth, inDepth, outDepth]. * @param bias Optional bias, rank 1 of shape [outDepth]. * @param stride The number of entries by which the filter is moved right at * each step. * @param pad A string from: 'same', 'valid'. The type of padding algorithm. * - 'same' pad and stride 1: output will be of same size as input, * regardless of filter size. * - 'valid' pad: output will be smaller than input if filter is larger * than 1x1. * - For more info, see this guide: * https://www.tensorflow.org/api_guides/python/nn#Convolution */ conv1d<T extends NDArray>( input: T, filter: Array3D, bias: Array1D | null, stride: number, pad: "valid" | "same" | number): T { let input3D = input as NDArray as Array3D; let reshapedTo3D = false; if (input.rank === 2) { reshapedTo3D = true; input3D = input.as3D(1, input.shape[0], input.shape[1]); } util.assert( input3D.rank === 3, `Error in conv1d: input must be rank 3, but got rank ${input3D.rank}.`); util.assert( filter.rank === 3, `Error in conv1d: filter must be rank 3, but got rank ` + `${filter.rank}.`); if (bias != null) { util.assert( bias.rank === 1, `Error in conv1d: bias must be rank 1, but got rank ` + `${bias.rank}.`); } util.assert( input3D.shape[2] === filter.shape[1], `Error in conv1d: depth of input (${input3D.shape[2]}) must match ` + `input depth for filter ${filter.shape[1]}.`); const filter4D = filter.as4D(1, filter.shape[0], filter.shape[1], filter.shape[2]); const input4D = input3D.as4D(input3D.shape[0], 1, input3D.shape[1], input3D.shape[2]); const strides: [number, number] = [1, stride]; return this.executeOp("Conv1D", () => { const res = this.conv2d(input4D, filter4D, bias, strides, pad); if (reshapedTo3D) { return res.as2D(res.shape[2], res.shape[3]) as NDArray as T; } return res.as3D(res.shape[0], res.shape[2], res.shape[3]) as NDArray as T; }); } /** * Computes a 2D convolution over the input x. * * @param input The input ndarray, of rank 4 or rank 3, of shape * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is * assumed. * @param filter The filter, rank 4, of shape * [filterHeight, filterWidth, inDepth, outDepth]. * @param bias Optional bias, rank 1 of shape [outDepth]. * @param strides The strides of the convolution: [strideHeight, * strideWidth]. * @param pad A string from: 'same', 'valid'. The type of padding algorithm. * - 'same' pad and stride 1: output will be of same size as input, * regardless of filter size. * - 'valid' pad: output will be smaller than input if filter is larger * than 1x1. * - For more info, see this guide: * https://www.tensorflow.org/api_guides/python/nn#Convolution */ conv2d<T extends NDArray>( input: T, filter: Array4D, bias: Array1D | null, strides: [number, number] | number, pad: "valid" | "same" | number): T { let input4D = input as NDArray as Array4D; let reshapedTo4D = false; if (input.rank === 3) { reshapedTo4D = true; input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]); } util.assert( input4D.rank === 4, `Error in conv2d: input must be rank 4, but got rank ${input4D.rank}.`); util.assert( filter.rank === 4, `Error in conv2d: filter must be rank 4, but got rank ` + `${filter.rank}.`); if (bias != null) { util.assert( bias.rank === 1, `Error in conv2d: bias must be rank 1, but got rank ` + `${bias.rank}.`); } util.assert( input4D.shape[3] === filter.shape[2], `Error in conv2d: depth of input (${input4D.shape[3]}) must match ` + `input depth for filter ${filter.shape[2]}.`); const convInfo = conv_util.computeConv2DInfo(input4D.shape, filter.shape, strides, pad); return this.executeOp("Conv2D", () => { const res = this.backend.conv2d(input4D, filter, bias, convInfo); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as NDArray as T; } return res as NDArray as T; }); } /** * Computes the derivative of the input of a 2D convolution. * * @param inShape The shape of the input: [batch, height, width, inDepth]. * If length of 3, batch of 1 is assumed. * @param dy The derivative of the output, of rank 4 or rank 3 of shape * [batch, outHeight, outWidth, outDepth]. If rank 3, batch of 1 is * assumed. * @param filter The filter, rank 4, of shape * [filterHeight, filterWidth, inDepth, outDepth]. * @param strides The strides of the convolution: [strideHeight, * strideWidth]. * @param pad A string from: 'same', 'valid'. The type of padding algorithm * used in the forward prop of the op. */ conv2dDerInput<T extends NDArray>( inShape: [number, number, number, number] | [number, number, number], dy: T, filter: Array4D, strides: [number, number] | number, pad: "valid" | "same" | number): T { util.assert( inShape.length === dy.rank, `Length of inShape ` + `(${inShape.length}) and rank of dy (${dy.rank}) must match`); let inShape4D = inShape as [number, number, number, number]; let dy4D = dy as NDArray as Array4D; let reshapedTo4D = false; if (dy.rank === 3) { reshapedTo4D = true; dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]); inShape4D = [1, inShape[0], inShape[1], inShape[2]]; } const inDepth = inShape4D[3]; const outDepth = dy4D.shape[3]; util.assert( inShape4D.length === 4, `Error in conv2dDerInput: inShape must be length 4, but got length ` + `${inShape4D.length}.`); util.assert( dy4D.rank === 4, `Error in conv2dDerInput: dy must be rank 4, but got ` + `rank ${dy4D.rank}`); util.assert( filter.rank === 4, `Error in conv2dDerInput: filter must be rank 4, but got ` + `rank ${filter.rank}`); util.assert( inDepth === filter.shape[2], `Error in conv2dDerInput: depth of input (${inDepth}) must ` + `match input depth for filter ${filter.shape[2]}.`); util.assert( outDepth === filter.shape[3], `Error in conv2dDerInput: depth of output (${outDepth}) must` + `match output depth for filter ${filter.shape[3]}.`); const convInfo = conv_util.computeConv2DInfo(inShape4D, filter.shape, strides, pad); return this.executeOp("conv2dDerInput", () => { const res = this.backend.conv2dDerInput(dy4D, filter, convInfo); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as NDArray as T; } return res as NDArray as T; }); } /** * Computes the derivative of the bias of a 2D convolution. * * @param dy The gradient for the output of this op, of rank 4 or rank 3 of * shape [batch, height, width, outDepth]. If rank 3, batch of 1 is * assumed. */ conv2dDerBias(dy: Array3D | Array4D): Array1D { let dy4D = dy as Array4D; if (dy.rank === 3) { dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]); } return this.backend.conv2dDerBias(dy4D); } /** * Computes the derivative of the filter of a 2D convolution. * * @param input The input ndarray, of rank 4 or rank 3 of shape * [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed. * @param dy The dy image, of rank 4 or rank 3, of shape * [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed. * @param filterShape The shape of the filter, length 4, * [filterHeight, filterWidth, inDepth, outDepth]. * @param strides The strides of the convolution: [strideHeight, * strideWidth]. * @param pad A string from: 'same', 'valid'. The type of padding algorithm * used in the forward prop of the op. */ conv2dDerFilter<T extends NDArray>( input: T, dy: T, filterShape: [number, number, number, number], strides: [number, number] | number, pad: "valid" | "same" | number): Array4D { let input4D = input as NDArray as Array4D; if (input.rank === 3) { input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]); } let dy4D = dy as NDArray as Array4D; if (dy4D.rank === 3) { dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]); } util.assert( input4D.rank === 4, `Error in conv2dDerFilter: input must be rank 4, but got shape ` + `${input4D.shape}.`); util.assert( dy4D.rank === 4, `Error in conv2dDerFilter: dy must be rank 4, but got shape ` + `${dy4D.shape}.`); util.assert( filterShape.length === 4, `Error in conv2dDerFilter: filterShape must be length 4, but got ` + `${filterShape}.`); util.assert( input4D.shape[3] === filterShape[2], `Error in conv2dDerFilter: depth of input ${input4D.shape[3]}) must ` + `match input depth in filter (${filterShape[2]}.`); util.assert( dy4D.shape[3] === filterShape[3], `Error in conv2dDerFilter: depth of dy (${dy4D.shape[3]}) must ` + `match output depth for filter (${filterShape[3]}).`); const convInfo = conv_util.computeConv2DInfo(input4D.shape, filterShape, strides, pad); return this.backend.conv2dDerFilter(input4D, dy4D, convInfo); } /** * Computes the transposed 2D convolution of an image, also known as a * deconvolution. * * @param x The input image, of rank 4 or rank 3, of shape * [batch, height, width, inDepth]. If rank 3, batch of 1 is assumed. * @param filter The filter, rank 4, of shape * `[filterHeight, filterWidth, outDepth, inDepth]`. * `inDepth` must match `inDepth` in `x`. * @param outputShape Output shape, of rank 4 or rank 3: * [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed. * @param strides The strides of the original convolution: * `[strideHeight, strideWidth]`. * @param pad A string from: 'same', 'valid'. The type of padding algorithm * used in the non-transpose version of the op. */ conv2dTranspose<T extends NDArray>( x: T, filter: Array4D, outputShape: [number, number, number, number] | [number, number, number], strides: [number, number] | number, pad: "valid" | "same" | number): T { return this.conv2dDerInput(outputShape, x, filter, strides, pad); } /** * Depthwise 2D convolution. * * Given a 4D `input` array and a `filter` array of shape * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing * `inChannels` convolutional filters of depth 1, this op applies a * different filter to each input channel (expanding from 1 channel to * `channelMultiplier` channels for each), then concatenates the results * together. The output has `inChannels * channelMultiplier` channels. * * See https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d for * more details. * * @param input The input ndarray, of rank 4 or rank 3, of shape * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is * assumed. * @param filter The filter ndarray, rank 4, of shape * `[filterHeight, filterWidth, inChannels, channelMultiplier]`. * @param strides The strides of the convolution: [strideHeight, * strideWidth]. If strides is a single number, then `strideHeight == * strideWidth`. * @param pad A string from: 'same', 'valid'. The type of padding algorithm. * - 'same' pad and stride 1: output will be of same size as input, * regardless of filter size. * - 'valid' pad: output will be smaller than input if filter is larger * than 1x1. * - For more info, see this guide: * https://www.tensorflow.org/api_guides/python/nn#Convolution * @param rates The dilation rates: `[rateHeight, rateWidth]` in which we * sample input values across the height and width dimensions in atrous * convolution. Defaults to `[1, 1]`. If `rate` is a single number, then * `rateHeight == rateWidth`. If it is greater than 1, then all values * of `strides` must be 1. */ depthwiseConv2D<T extends NDArray>( input: T, filter: Array4D, strides: [number, number] | number, pad: "valid" | "same" | number, rates: [number, number] | number = [1, 1]): T { let input4D = input as NDArray as Array4D; let reshapedTo4D = false; if (input.rank === 3) { reshapedTo4D = true; input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]); } util.assert( input4D.rank === 4, `Error in depthwiseConv2D: input must be rank 4, but got ` + `rank ${input4D.rank}.`); util.assert( filter.rank === 4, `Error in depthwiseConv2D: filter must be rank 4, but got rank ` + `${filter.rank}.`); util.assert( input4D.shape[3] === filter.shape[2], `Error in depthwiseConv2D: number of input channels ` + `(${input4D.shape[3]}) must match the inChannels dimension in ` + `filter ${filter.shape[2]}.`); rates = rates || [1, 1]; const [rateHeight, rateWidth] = parseTupleParam(rates); util.assert( rateHeight === 1 && rateWidth === 1, "Error in depthwiseConv2D: rates greater than 1 are not yet " + `supported. Got rates '${rates}'`); const convInfo = conv_util.computeConv2DInfo( input4D.shape, filter.shape, strides, pad, true /* depthwise */); return this.executeOp("depthwiseConv2D", () => { const res = this.backend.depthwiseConv2D(input4D, filter, convInfo); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as NDArray as T; } return res as NDArray as T; }); } /** * Computes the 2D max pooling of an image. * * @param input The input ndarray, of rank 4 or rank 3 of shape * [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed. * @param filterSize The filter size, a tuple [filterHeight, filterWidth]. * @param strides The strides of the pooling: [strideHeight, strideWidth]. * @param pad A string from: 'same', 'valid'. The type of padding algorithm. * - 'same' pad and stride 1: output will be of same size as input, * regardless of filter size. * - 'valid' pad: output will be smaller than input if filter is larger * than 1x1. * - For more info, see this guide: * https://www.tensorflow.org/api_guides/python/nn#Convolution */ maxPool<T extends NDArray>( input: T, filterSize: [number, number] | number, strides: [number, number] | number, pad: "valid" | "same" | number): T { let input4D = input as NDArray as Array4D; let reshapedTo4D = false; if (input.rank === 3) { reshapedTo4D = true; input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]); } util.assert( input4D.rank === 4, `Error in maxPool: input must be rank 4 but got rank ${input4D.rank}.`); const convInfo = conv_util.computePool2DInfo(input4D.shape, filterSize, strides, pad); return this.executeOp("maxPool", () => { const res = this.backend.maxPool(input4D, convInfo); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as NDArray as T; } return res as NDArray as T; }); } /** * Computes the backprop of a max pool. * * @param dy The dy error, of rank 4 or rank 3 of shape * [batchSize, height, width, channels]. If rank 3, batch of 1 is * assumed. * @param input The input image, of rank 4 or rank 3 of shape * [batchSize, height, width, channels]. If rank 3, batch of 1 is * assumed. * @param filterSize The filter size, a tuple [filterHeight, filterWidth]. * @param strides The strides of the pooling: [strideHeight, strideWidth]. * @param pad A string from: 'same', 'valid'. The type of padding algorithm * used in the forward prop of the op. */ maxPoolBackprop<T extends NDArray>( dy: T, input: T, filterSize: [number, number] | number, strides: [number, number] | number, pad: "valid" | "same" | number): T { util.assert( input.rank === dy.rank, `Rank of input (${input.rank}) does not match rank of dy (${dy.rank})`); let input4D = input as NDArray as Array4D; let dy4D = dy as NDArray as Array4D; let reshapedTo4D = false; if (input.rank === 3) { reshapedTo4D = true; input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]); dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]); } util.assert( dy4D.rank === 4, `Error in maxPoolBackprop: dy must be rank 4 but got rank ` + `${dy4D.rank}.`); util.assert( input4D.rank === 4, `Error in maxPoolBackprop: input must be rank 4 but got rank ` + `${input4D.rank}.`); const convInfo = conv_util.computePool2DInfo(input4D.shape, filterSize, strides, pad); return this.executeOp("maxPoolBackprop", () => { const res = this.backend.maxPoolBackprop(dy4D, input4D, convInfo); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as NDArray as T; } return res as NDArray as T; }); } /** * Computes the 2D min pooling of an image. * * @param input The input ndarray, of rank 4 or rank 3 of shape * [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed. * @param filterSize The filter size, a tuple [filterHeight, filterWidth]. * @param strides The strides of the pooling: [strideHeight, strideWidth]. * @param pad A string from: 'same', 'valid'. The type of padding algorithm. * - 'same' pad and stride 1: output will be of same size as input, * regardless of filter size. * - 'valid' pad: output will be smaller than input if filter is larger * than 1x1. * - For more info, see this guide: * https://www.tensorflow.org/api_guides/python/nn#Convolution */ minPool<T extends NDArray>( input: T, filterSize: [number, number] | number, strides: [number, number] | number, pad: "valid" | "same" | number): T { let input4D = input as NDArray as Array4D; let reshapedTo4D = false; if (input.rank === 3) { reshapedTo4D = true; input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]); } util.assert( input4D.rank === 4, `Error in minPool: x must be rank 4 but got rank ${input4D.rank}.`); const convInfo = conv_util.computePool2DInfo(input4D.shape, filterSize, strides, pad); return this.executeOp("minPool", () => { const res = this.backend.minPool(input4D, convInfo); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as NDArray as T; } return res as NDArray as T; }); } /** * Computes the 2D average pooling of an image. * * @param input The input ndarray, of rank 4 or rank 3 of shape * [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed. * @param filterSize The filter size, a tuple [filterHeight, filterWidth]. * @param strides The strides of the pooling: [strideHeight, strideWidth]. * @param pad A string from: 'same', 'valid'. The type of padding algorithm. * - 'same' pad and stride 1: output will be of same size as input, * regardless of filter size. * - 'valid' pad: output will be smaller than input if filter is larger * than 1x1. * - For more info, see this guide: * https://www.tensorflow.org/api_guides/python/nn#Convolution */ avgPool<T extends NDArray>( input: T, filterSize: [number, number] | number, strides: [number, number] | number, pad: "valid" | "same" | number): T { let input4D = input as NDArray as Array4D; let reshapedTo4D = false; if (input.rank === 3) { reshapedTo4D = true; input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]); } util.assert( input4D.rank === 4, `Error in avgPool: x must be rank 4 but got rank ${input4D.rank}.`); const convInfo = conv_util.computePool2DInfo(input4D.shape, filterSize, strides, pad); return this.executeOp("avgPool", () => { const res = this.backend.avgPool(input4D, convInfo); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as NDArray as T; } return res as NDArray as T; }); } /* * 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.backend.resizeBilinear3D(x, newShape2D, alignCorners); } ////////////// // LSTM ops // ////////////// /** * Computes the next states and outputs of a stack of LSTMCells. * Each cell output is used as input to the next cell. * This is only the forward mode. * Derived from tf.contrib.rn.MultiRNNCell. * @param lstmCells Array of LSTMCell functions. * @param data The input to the cell. * @param c Array of previous cell states. * @param h Array of previous cell outputs. * @return Tuple [nextCellStates, cellOutputs] */ multiRNNCell( lstmCells: LSTMCell[], data: Array2D, c: Array2D[], h: Array2D[]): [Array2D[], Array2D[]] { const res = this.scope(() => { let input = data; const newStates = []; for (let i = 0; i < lstmCells.length; i++) { const output = lstmCells[i](input, c[i], h[i]); newStates.push(output[0]); newStates.push(output[1]); input = output[1]; } return newStates; }); const newC: Array2D[] = []; const newH: Array2D[] = []; for (let i = 0; i < res.length; i += 2) { newC.push(res[i]); newH.push(res[i + 1]); } return [newC, newH]; } /** * Computes the next state and output of a BasicLSTMCell. * This is only the forward mode. * Derived from tf.contrib.rnn.BasicLSTMCell. * @param forgetBias Forget bias for the cell. * @param lstmKernel The weights for the cell. * @param lstmBias The bias for the cell. * @param data The input to the cell. * @param c Previous cell state. * @param h Previous cell output. * @return Tuple [nextCellState, cellOutput] */ basicLSTMCell( forgetBias: Scalar, lstmKernel: Array2D, lstmBias: Array1D, data: Array2D, c: Array2D, h: Array2D): [Array2D, Array2D] { const res = this.scope(() => { const combined = this.concat2D(data, h, 1); const weighted = this.matMul(combined, lstmKernel); const res = this.add(weighted, lstmBias) as Array2D; // i = input_gate, j = new_input, f = forget_gate, o = output_gate const batchSize = res.shape[0]; const sliceCols = res.shape[1] / 4; const sliceSize: [number, number] = [batchSize, sliceCols]; const i = this.slice2D(res, [0, 0], sliceSize); const j = this.slice2D(res, [0, sliceCols], sliceSize); const f = this.slice2D(res, [0, sliceCols * 2], sliceSize); const o = this.slice2D(res, [0, sliceCols * 3], sliceSize); const newC = this.addStrict( this.multiplyStrict( c, this.sigmoid(this.scalarPlusArray(forgetBias, f))), this.multiplyStrict(this.sigmoid(i), this.tanh(j))); const newH = this.multiplyStrict(this.tanh(newC), this.sigmoid(o)); return [newC, newH]; }); return [res[0], res[1]]; } /** * Draws samples from a multinomial distribution. * * @param probabilities 1D array with normalized outcome probabilities, or * 2D array of shape `[batchSize, numOutcomes]`. * @param numSamples Number of samples to draw for each row slice. * @param seed Optional. The seed number. * @return 1D array of shape `[numSamples]`, or 2D array of shape * `[batchSize, numSamples]`, depending on the rank of the input. */ multinomial( probabilities: Array1D | Array2D, numSamples: number, seed?: number): Array1D<"int32"> | Array2D<"int32"> { const numOutcomes = probabilities.size; if (numOutcomes < 2) { throw new Error( `Error in multinomial: you need at least 2 outcomes, but got ` + `${numOutcomes}.`); } if (probabilities.rank > 2) { throw new Error( `Rank of probabilities must be 1 or 2, but is ${probabilities.rank}`); } seed = seed || Math.random(); const origRank = probabilities.rank; if (probabilities.rank === 1) { probabilities = probabilities.as2D(1, -1); } return this.executeOp("multinomial", () => { const res = this.backend.multinomial(probabilities as Array2D, numSamples, seed); if (origRank === 1) { return res.as1D(); } return res; }); } /** * Returns a one-hot array. The locations represented by `indices` take * value `onValue` (defaults to 1), while all other locations take value * `offValue` (defaults to 0). * * @param indices 1D Array of indices. * @param depth The depth of the one hot dimension. * @param onValue A number used to fill in output when the index matches the * location. * @param offValue A number used to fill in the output when the index does * not match the location. */ oneHot(indices: Array1D, depth: number, onValue = 1, offValue = 0): Array2D { if (depth < 2) { throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`); } return this.backend.oneHot(indices, depth, onValue, offValue); } /** * Calculates the mean and variance of `x`. The mean and variance are * calculated by aggregating the contents of `x` across `axes`. If `x` is * 1-D and `axes = [0]` this is just the mean and variance of a vector. * * @param x The input array. * @param axis Optional. The dimension(s) along with to compute mean and * variance. By default it reduces all dimensions. * @param keepDims If true, the moments have the same dimensionality as the * input. * @return An object with two keys: `mean` and `variance`. */ moments(x: NDArray, axis: number | number[] = null, keepDims = false): {mean: NDArray<"float32">, variance: NDArray<"float32">} { const axes = axis_util.parseAxisParam(axis, x.shape); const result = this.scope(() => { const mean = this.mean(x, axes, keepDims); let keepDimsShape = mean.shape; if (!keepDims) { keepDimsShape = axis_util.expandShapeToKeepDim(mean.shape, axes); } const devSquared = this.square( this.subtract(x.asType("float32"), mean.reshape(keepDimsShape))); const variance = this.mean(devSquared, axes, keepDims); return {mean, variance}; }); return result; } /** * Computes the norm of scalar, vectors, and matrices. * This function can compute several different vector norms (the 1-norm, the * Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) * and matrix norms (Frobenius, 1-norm, and inf-norm). * * @param x The input array. * @param ord Optional. Order of the norm. Supported norm types are * following: ord norm for matrices norm for vectors * ------------------------------------------------------- * 'euclidean' Frobenius norm 2-norm * ‘fro’ Frobenius norm – * Infinity max(sum(abs(x), axis=1)) max(abs(x)) * -Infinity min(sum(abs(x), axis=1)) min(abs(x)) * 1 max(sum(abs(x), axis=0)) sum(abs(x)) * 2 - sum(abs(x)^2)^1/2* * * @param axis Optional. If axis is null (the default), the input is * considered a vector and a single vector norm is computed over the entire * set of values in the NDArray, i.e. norm(x, ord) is equivalent * to norm(x.reshape([-1]), ord). If axis is a integer, the input * is considered a batch of vectors, and axis determines the axis in x * over which to compute vector norms. If axis is a 2-tuple of integer it is * considered a batch of matrices and axis determines the axes in NDArray * over which to compute a matrix norm. * @param keepDims Optional. If true, the norm have the same dimensionality * as the input. */ norm<D extends DataType>( x: NDArray<D>, ord: number | "euclidean" | "fro" = "euclidean", axis: number | number[] = null, keepDims = false): NDArray<D | SumTypes[D]> { return this.scope(() => { const norm = this.normInternal(x, ord, axis); let keepDimsShape = norm.shape; if (keepDims) { const axes = axis_util.parseAxisParam(axis, x.shape); keepDimsShape = axis_util.expandShapeToKeepDim(norm.shape, axes); } return norm.reshape(keepDimsShape); }); } setDiag(input: Array2D, diag: Array1D): Array2D { return this.backend.setDiag(input, diag); } /** * Calculate the norm for different NDAarray. */ private normInternal<D extends DataType>( x: NDArray<D>, p: number | string, axis: number | number[] = null): NDArray<D | SumTypes[D]> { // scalar if (x.rank === 0) { return this.abs(x); } // consider vector when no axis is specified if (x.rank !== 1 && axis === null) { return this.normInternal(x.reshape([-1]), p, axis); } // vector if (x.rank === 1 || typeof axis === "number" || axis instanceof Array && axis.length === 1) { if (p === 1) { return this.sum(this.abs(x), axis); } if (p === Infinity) { return this.max(this.abs(x), axis); } if (p === -Infinity) { return this.min(this.abs(x), axis); } if (p === "euclidean" || p === 2) { // norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2 return this.sqrt( this.sum(this.pow(this.abs(x), Scalar.new(2, "int32")), axis)); } throw new Error(`Error in norm: invalid ord value: ${p}`); } // matrix (assumption axis[0] < axis[1]) if (axis instanceof Array && axis.length === 2) { if (p === 1) { return this.max(this.sum(this.abs(x), axis[0]), axis[1] - 1); } if (p === Infinity) { return this.max(this.sum(this.abs(x), axis[1]), axis[0]); } if (p === -Infinity) { return this.min(this.sum(this.abs(x), axis[1]), axis[0]); } if (p === "fro" || p === "euclidean") { // norm(x) = sqrt(sum(pow(x, 2))) return this.sqrt(this.sum(this.pow(x, Scalar.new(2, "int32")), axis)); } throw new Error(`Error in norm: invalid ord value: ${p}`); } throw new Error(`Error in norm: invalid axis: ${axis}`); } disposeData(dataId: DataId): void { if (!this.registeredArrays.has(dataId)) { return; } const refCount = this.registeredArrays.get(dataId); if (refCount <= 1) { this.registeredArrays.delete(dataId); this.backend.disposeData(dataId); this.registeredArrayCount--; } else { this.registeredArrays.set(dataId, refCount - 1); } // TODO(nsthorat): Construct an error and save the stack trace for // debugging when in debug mode. Creating a stack trace is too expensive // to do unconditionally. } } function parseTupleParam(param: number | [number, number]): [number, number] { return typeof param === "number" ? [param, param] : param; }
the_stack
class AssemblyDetailPage extends Base.Page { private namespacelistTemplate: HandlebarsTemplateDelegate; private typeBaseListTemplate: HandlebarsTemplateDelegate; private typeBaseTemplates: any = new Object(); private errorsList: Array<any> = new Array<any>(); private popTemplate: string; private popTemplates: any = new Object(); private metaType: Array<string> = new Array("Classes", "Structures", "Interfaces", "Enumerations", "Delegates"); private metaSubType: Array<string> = new Array("Methods", "Constructors", "Properties"); private assemblyData: Array<any> = new Array(); public Ready(): void { toastr.info("Loading data..."); super.Ready(); this.popTemplate = $("#poptemplate").html(); this.namespacelistTemplate = Handlebars.compile($("#namespaces-template").html()); this.typeBaseListTemplate = Handlebars.compile($("#typebaselist-template").html()); for (var j = 0; j < this.metaType.length; j++) { this.typeBaseTemplates[this.metaType[j]] = Handlebars.compile($("#typebase" + this.metaType[j] + "-template").html()); } for (var i: number = 0; i < this.metaSubType.length; i++) { this.popTemplates[this.metaSubType[i] + "-Title"] = Handlebars.compile($("#" + this.metaSubType[i] + "-PopTitle-template").html()); this.popTemplates[this.metaSubType[i] + "-Content"] = Handlebars.compile($("#" + this.metaSubType[i] + "-PopContent-template").html()); } Base.Helpers.AjaxService("POST", this.options.urlGet + "/" + this.options.DllId, null, (data) => { if (data) { // set title $("#h2name").text(data.Name); $("#h2sname").text(data.FullName); // Cout data data.Namespaces.forEach((item) => { item.ClassCount = item.Classes.length; item.StructureCount = item.Structures.length; item.InterfaceCount = item.Interfaces.length; item.EnumerationCount = item.Enumerations.length; item.DelegateCount = item.Delegates.length; }); // copy assembly doc content in cache this.assemblyData = data.Namespaces; // ReSharper disable once AssignedValueIsNeverUsed data = null; // garbage collect this.setNamespaces(this.assemblyData); this.setErrorList(this.assemblyData); this.showErrorsList(); } else { toastr.error("No namespaces", "There is no namespaces to parse : Empty DLL"); } }) .done(() => toastr.success("Data loaded")) .fail(() => toastr.error("Data load failed")); } private setErrorList(data: any): void { var errorTab: Array<any> = new Array<any>(); data.forEach((item) => { if (item.loadError) { errorTab.push(item); } // todo : use .some() & .filter for (let h = 0; h < this.metaType.length; h++) { var tab = item[this.metaType[h]]; if (tab && tab.length > 0) { tab.forEach((itemType) => { if (itemType.LoadError) { errorTab.push(itemType); } for (let k = 0; k < this.metaSubType.length; k++) { var subtab = itemType[this.metaSubType[k]]; if (subtab && subtab.length > 0) { subtab.forEach((subItemType) => { if (subItemType.LoadError) { errorTab.push(subItemType); } }); } } }); } } }); errorTab.forEach((item) => { var map = this.errorsList.map((e) => { return e.message; }); var index: number = map.indexOf(item.Fullname); if (index < 0) { this.errorsList.push({ message: item.Fullname, count: 1 }); } else { this.errorsList[index].count++; } }); this.errorsList.sort((a, b) => { if (a.message > b.message) return 1; if (a.message < b.message) return -1; return 0; }); } private showErrorsList(): void { if (this.errorsList.length > 0) { $("#errorcount").text(this.errorsList.length); $("#errornavmenu").removeClass("hidden").show(); var itemsToAdd: number = Math.min(this.errorsList.length, 10); //var more: boolean = itemsToAdd != this.errorsList.length; var template: HandlebarsTemplateDelegate = Handlebars.compile($("#errorlisttemplate").html()); $("#errornavlist").html(template(this.errorsList.splice(0, itemsToAdd - 1))) .closest("li").removeClass("invisible").addClass("visible"); } } private setNamespaces(namespaces: Array<any>): void { // set namespace list template $("#nmlist").html(this.namespacelistTemplate(namespaces)); // and set event on them var namespacelink: JQuery = $("a[data-type]"); namespacelink.unbind("click") .on("click", (event: JQueryEventObject) => { this.loadTypeBases($(event.currentTarget)); }); // Select the first element for the first namespacelink.first().trigger("click"); } private loadTypeBases(element: JQuery): void { var name: string = element.attr("data-id"); $("#selected-namespace").text(name); var type: string = this.metaType[parseInt(element.attr("data-type"))]; var myArray: any = this.getNameSpaceData(name); if (myArray && myArray[type]) { var data: Array<any> = myArray[type]; if (data) { $("#typebasetitle").text(type); // set namespace list template data.forEach((item) => { item.namespace = name; }); $("#nmsublist").html(this.typeBaseListTemplate(data)); var eventItems: JQuery = $("#nmsublist>.list-group-item"); eventItems.click((event: JQueryEventObject) => { eventItems.removeClass("active"); var item: JQuery = $(event.currentTarget); item.addClass("active"); this.loadType(item); }); eventItems.first().trigger("click"); } else { toastr.error("No classes", "There is no classes to parse : Empty DLL"); } } } private loadType(element: JQuery): void { var name: string = element.attr("data-namespace"); var type: string = $("#typebasetitle").text(); var id: string = element.attr("data-id"); var data = this.getTypeBaseClassData(name, id, type); if (data) { // set namespace list template data.namespace = name; var tmpl = this.typeBaseTemplates[type]; var h = tmpl(data); $("#typebase").html(h); var popoverList = $("a.popoverselect"); this.setPopOver(popoverList); } else { toastr.error("No classes", "There is no classes to parse : Empty DLL"); } } private setPopOver(element: JQuery): void { var self = this; element.popover({ trigger: "focus", html: true, // get the title and content // ReSharper disable SuspiciousThisUsage title: function () { return self.getPopOverElement($(this), "Title"); }, content: function () { return self.getPopOverElement($(this), "Content"); }, // ReSharper restore SuspiciousThisUsage container: "body", placement: "left", template: this.popTemplate }); } private getPopOverElement(element: JQuery, contentType: string): string { var name: string = element.attr("data-namespace"); var subtype: string = this.metaSubType[parseInt(element.attr("data-subtype"))]; var type: string = this.metaType[parseInt(element.attr("data-type"))]; var methodName: string = element.attr("data-id"); var className: string = element.attr("data-parent"); var data = this.getSubTypeBase(name, className, methodName, type, subtype); if (data) { var templ = this.popTemplates[subtype + "-" + contentType]; var html = templ(data); return html; } return "Error"; } private getNameSpaceData(nameSpace: string): any { var myArray: Array<any> = this.assemblyData.filter((item) => { return (item.Name === nameSpace); }); if (myArray && myArray.length === 1) { return myArray[0]; } return null; } private getTypeBaseClassData(nameSpace: string, typeName: string, metaType: string): any { var myArray: any = this.getNameSpaceData(nameSpace); if (myArray && myArray[metaType]) { var data = myArray[metaType].filter((item) => { return item.Id === typeName; })[0]; return data; } return null; } private getSubTypeBase(nameSpace: string, typeName: string, subName: string, metaType: string, metaSubType: string): any { var data = this.getTypeBaseClassData(nameSpace, typeName, metaType); if (data && data[metaSubType]) { var myArray: Array<any> = data[metaSubType].filter((item) => { return (item.Id === subName); }); if (myArray && myArray.length === 1) { return myArray[0]; } } return null; } }
the_stack
import template from "@babel/template"; import type * as t from "@babel/types"; import generated from "./helpers-generated"; interface Helper { minVersion: string; ast: () => t.Program; } const helpers: Record<string, Helper> = { __proto__: null, ...generated }; export default helpers; const helper = (minVersion: string) => (tpl: TemplateStringsArray) => ({ minVersion, ast: () => template.program.ast(tpl), }); helpers.AwaitValue = helper("7.0.0-beta.0")` export default function _AwaitValue(value) { this.wrapped = value; } `; helpers.AsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null, }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg) var value = result.value; var wrappedAwait = value instanceof AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then( function (arg) { if (wrappedAwait) { resume(key === "return" ? "return" : "next", arg); return } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; // Hide "return" method if generator return is not supported if (typeof gen.return !== "function") { this.return = undefined; } } AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }; AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; `; helpers.wrapAsyncGenerator = helper("7.0.0-beta.0")` import AsyncGenerator from "AsyncGenerator"; export default function _wrapAsyncGenerator(fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; } `; helpers.awaitAsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function _awaitAsyncGenerator(value) { return new AwaitValue(value); } `; helpers.asyncGeneratorDelegate = helper("7.0.0-beta.0")` export default function _asyncGeneratorDelegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function (resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value) }; }; iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () { return this; }; iter.next = function (value) { if (waiting) { waiting = false; return value; } return pump("next", value); }; if (typeof inner.throw === "function") { iter.throw = function (value) { if (waiting) { waiting = false; throw value; } return pump("throw", value); }; } if (typeof inner.return === "function") { iter.return = function (value) { if (waiting) { waiting = false; return value; } return pump("return", value); }; } return iter; } `; helpers.asyncToGenerator = helper("7.0.0-beta.0")` function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } export default function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } `; helpers.classCallCheck = helper("7.0.0-beta.0")` export default function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } `; helpers.createClass = helper("7.0.0-beta.0")` function _defineProperties(target, props) { for (var i = 0; i < props.length; i ++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } export default function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } `; helpers.defineEnumerableProperties = helper("7.0.0-beta.0")` export default function _defineEnumerableProperties(obj, descs) { for (var key in descs) { var desc = descs[key]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, key, desc); } // Symbols are not enumerated over by for-in loops. If native // Symbols are available, fetch all of the descs object's own // symbol properties and define them on our target object too. if (Object.getOwnPropertySymbols) { var objectSymbols = Object.getOwnPropertySymbols(descs); for (var i = 0; i < objectSymbols.length; i++) { var sym = objectSymbols[i]; var desc = descs[sym]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, sym, desc); } } return obj; } `; helpers.defaults = helper("7.0.0-beta.0")` export default function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } `; helpers.defineProperty = helper("7.0.0-beta.0")` export default function _defineProperty(obj, key, value) { // Shortcircuit the slow defineProperty path when possible. // We are trying to avoid issues where setters defined on the // prototype cause side effects under the fast path of simple // assignment. By checking for existence of the property with // the in operator, we can optimize most of this overhead away. if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } `; helpers.extends = helper("7.0.0-beta.0")` export default function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } `; // TODO(babel-8): This old helper can be removed in babel v8 helpers.objectSpread = helper("7.0.0-beta.0")` import defineProperty from "defineProperty"; export default function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = (arguments[i] != null) ? Object(arguments[i]) : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { defineProperty(target, key, source[key]); }); } return target; } `; helpers.inherits = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; export default function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } Object.defineProperty(subClass, "prototype", { value: Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }), writable: false, }); if (superClass) setPrototypeOf(subClass, superClass); } `; helpers.inheritsLoose = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; export default function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; setPrototypeOf(subClass, superClass); } `; helpers.getPrototypeOf = helper("7.0.0-beta.0")` export default function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } `; helpers.setPrototypeOf = helper("7.0.0-beta.0")` export default function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } `; helpers.isNativeReflectConstruct = helper("7.9.0")` export default function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; // core-js@3 if (Reflect.construct.sham) return false; // Proxy can't be polyfilled. Every browser implemented // proxies before or at the same time as Reflect.construct, // so if they support Proxy they also support Reflect.construct. if (typeof Proxy === "function") return true; // Since Reflect.construct can't be properly polyfilled, some // implementations (e.g. core-js@2) don't set the correct internal slots. // Those polyfills don't allow us to subclass built-ins, so we need to // use our fallback implementation. try { // If the internal slots aren't set, this throws an error similar to // TypeError: this is not a Boolean object. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})); return true; } catch (e) { return false; } } `; helpers.construct = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; import isNativeReflectConstruct from "isNativeReflectConstruct"; export default function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { // NOTE: If Parent !== Class, the correct __proto__ is set *after* // calling the constructor. _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) setPrototypeOf(instance, Class.prototype); return instance; }; } // Avoid issues with Class being present but undefined when it wasn't // present in the original call. return _construct.apply(null, arguments); } `; helpers.isNativeFunction = helper("7.0.0-beta.0")` export default function _isNativeFunction(fn) { // Note: This function returns "true" for core-js functions. return Function.toString.call(fn).indexOf("[native code]") !== -1; } `; // Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes helpers.wrapNativeSuper = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; import setPrototypeOf from "setPrototypeOf"; import isNativeFunction from "isNativeFunction"; import construct from "construct"; export default function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct(Class, arguments, getPrototypeOf(this).constructor) } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true, } }); return setPrototypeOf(Wrapper, Class); } return _wrapNativeSuper(Class) } `; helpers.instanceof = helper("7.0.0-beta.0")` export default function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } `; helpers.interopRequireDefault = helper("7.0.0-beta.0")` export default function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } `; helpers.interopRequireWildcard = helper("7.14.0")` function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } export default function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) { return { default: obj } } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } `; helpers.newArrowCheck = helper("7.0.0-beta.0")` export default function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } `; helpers.objectDestructuringEmpty = helper("7.0.0-beta.0")` export default function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure undefined"); } `; helpers.objectWithoutPropertiesLoose = helper("7.0.0-beta.0")` export default function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } `; helpers.objectWithoutProperties = helper("7.0.0-beta.0")` import objectWithoutPropertiesLoose from "objectWithoutPropertiesLoose"; export default function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } `; helpers.assertThisInitialized = helper("7.0.0-beta.0")` export default function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } `; helpers.possibleConstructorReturn = helper("7.0.0-beta.0")` import assertThisInitialized from "assertThisInitialized"; export default function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return assertThisInitialized(self); } `; // This is duplicated to packages/babel-plugin-transform-classes/src/inline-createSuper-helpers.js helpers.createSuper = helper("7.9.0")` import getPrototypeOf from "getPrototypeOf"; import isNativeReflectConstruct from "isNativeReflectConstruct"; import possibleConstructorReturn from "possibleConstructorReturn"; export default function _createSuper(Derived) { var hasNativeReflectConstruct = isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { // NOTE: This doesn't work if this.__proto__.constructor has been modified. var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); } } `; helpers.superPropBase = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; export default function _superPropBase(object, property) { // Yes, this throws if object is null to being with, that's on purpose. while (!Object.prototype.hasOwnProperty.call(object, property)) { object = getPrototypeOf(object); if (object === null) break; } return object; } `; // https://tc39.es/ecma262/multipage/reflection.html#sec-reflect.get // // 28.1.5 Reflect.get ( target, propertyKey [ , receiver ] ) // helpers.get = helper("7.0.0-beta.0")` import superPropBase from "superPropBase"; export default function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { // STEP 3. If receiver is not present, then set receiver to target. return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } `; helpers.set = helper("7.0.0-beta.0")` import superPropBase from "superPropBase"; import defineProperty from "defineProperty"; function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { // Both getter and non-writable fall into this. return false; } } // Without a super that defines the property, spec boils down to // "define on receiver" for some reason. desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { // Setter, getter, and non-writable fall into this. return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { // Avoid setters that may be defined on Sub's prototype, but not on // the instance. defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); } export default function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; } `; helpers.taggedTemplateLiteral = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } `; helpers.taggedTemplateLiteralLoose = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; } `; helpers.readOnlyError = helper("7.0.0-beta.0")` export default function _readOnlyError(name) { throw new TypeError("\\"" + name + "\\" is read-only"); } `; helpers.writeOnlyError = helper("7.12.13")` export default function _writeOnlyError(name) { throw new TypeError("\\"" + name + "\\" is write-only"); } `; helpers.classNameTDZError = helper("7.0.0-beta.0")` export default function _classNameTDZError(name) { throw new Error("Class \\"" + name + "\\" cannot be referenced in computed property keys."); } `; helpers.temporalUndefined = helper("7.0.0-beta.0")` // This function isn't mean to be called, but to be used as a reference. // We can't use a normal object because it isn't hoisted. export default function _temporalUndefined() {} `; helpers.tdz = helper("7.5.5")` export default function _tdzError(name) { throw new ReferenceError(name + " is not defined - temporal dead zone"); } `; helpers.temporalRef = helper("7.0.0-beta.0")` import undef from "temporalUndefined"; import err from "tdz"; export default function _temporalRef(val, name) { return val === undef ? err(name) : val; } `; helpers.slicedToArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimit from "iterableToArrayLimit"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArray(arr, i) { return ( arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest() ); } `; helpers.slicedToArrayLoose = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimitLoose from "iterableToArrayLimitLoose"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArrayLoose(arr, i) { return ( arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest() ); } `; helpers.toArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArray from "iterableToArray"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _toArray(arr) { return ( arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest() ); } `; helpers.toConsumableArray = helper("7.0.0-beta.0")` import arrayWithoutHoles from "arrayWithoutHoles"; import iterableToArray from "iterableToArray"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableSpread from "nonIterableSpread"; export default function _toConsumableArray(arr) { return ( arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread() ); } `; helpers.arrayWithoutHoles = helper("7.0.0-beta.0")` import arrayLikeToArray from "arrayLikeToArray"; export default function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return arrayLikeToArray(arr); } `; helpers.arrayWithHoles = helper("7.0.0-beta.0")` export default function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } `; helpers.maybeArrayLike = helper("7.9.0")` import arrayLikeToArray from "arrayLikeToArray"; export default function _maybeArrayLike(next, arr, i) { if (arr && !Array.isArray(arr) && typeof arr.length === "number") { var len = arr.length; return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); } return next(arr, i); } `; helpers.iterableToArray = helper("7.0.0-beta.0")` export default function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } `; helpers.iterableToArrayLimit = helper("7.0.0-beta.0")` export default function _iterableToArrayLimit(arr, i) { // this is an expanded form of \`for...of\` that properly supports abrupt completions of // iterators etc. variable names have been minimised to reduce the size of this massive // helper. sometimes spec compliance is annoying :( // // _n = _iteratorNormalCompletion // _d = _didIteratorError // _e = _iteratorError // _i = _iterator // _s = _step var _i = arr == null ? null : (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } `; helpers.iterableToArrayLimitLoose = helper("7.0.0-beta.0")` export default function _iterableToArrayLimitLoose(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } `; helpers.unsupportedIterableToArray = helper("7.9.0")` import arrayLikeToArray from "arrayLikeToArray"; export default function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } `; helpers.arrayLikeToArray = helper("7.9.0")` export default function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } `; helpers.nonIterableSpread = helper("7.0.0-beta.0")` export default function _nonIterableSpread() { throw new TypeError( "Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." ); } `; helpers.nonIterableRest = helper("7.0.0-beta.0")` export default function _nonIterableRest() { throw new TypeError( "Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." ); } `; helpers.createForOfIteratorHelper = helper("7.9.0")` import unsupportedIterableToArray from "unsupportedIterableToArray"; // s: start (create the iterator) // n: next // e: error (called whenever something throws) // f: finish (always called at the end) export default function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { // Fallback for engines without symbol support if ( Array.isArray(o) || (it = unsupportedIterableToArray(o)) || (allowArrayLike && o && typeof o.length === "number") ) { if (it) o = it; var i = 0; var F = function(){}; return { s: F, n: function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function(e) { throw e; }, f: F, }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function() { it = it.call(o); }, n: function() { var step = it.next(); normalCompletion = step.done; return step; }, e: function(e) { didErr = true; err = e; }, f: function() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } `; helpers.createForOfIteratorHelperLoose = helper("7.9.0")` import unsupportedIterableToArray from "unsupportedIterableToArray"; export default function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); // Fallback for engines without symbol support if ( Array.isArray(o) || (it = unsupportedIterableToArray(o)) || (allowArrayLike && o && typeof o.length === "number") ) { if (it) o = it; var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; } } throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } `; helpers.skipFirstGeneratorNext = helper("7.0.0-beta.0")` export default function _skipFirstGeneratorNext(fn) { return function () { var it = fn.apply(this, arguments); it.next(); return it; } } `; helpers.toPrimitive = helper("7.1.5")` export default function _toPrimitive( input, hint /*: "default" | "string" | "number" | void */ ) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } `; helpers.toPropertyKey = helper("7.1.5")` import toPrimitive from "toPrimitive"; export default function _toPropertyKey(arg) { var key = toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } `; /** * Add a helper that will throw a useful error if the transform fails to detect the class * property assignment, so users know something failed. */ helpers.initializerWarningHelper = helper("7.0.0-beta.0")` export default function _initializerWarningHelper(descriptor, context){ throw new Error( 'Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.' ); } `; /** * Add a helper to call as a replacement for class property definition. */ helpers.initializerDefineProperty = helper("7.0.0-beta.0")` export default function _initializerDefineProperty(target, property, descriptor, context){ if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0, }); } `; /** * Add a helper to take an initial descriptor, apply some decorators to it, and optionally * define the property. */ helpers.applyDecoratedDescriptor = helper("7.0.0-beta.0")` export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context){ var desc = {}; Object.keys(descriptor).forEach(function(key){ desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer){ desc.writable = true; } desc = decorators.slice().reverse().reduce(function(desc, decorator){ return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0){ desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0){ Object.defineProperty(target, property, desc); desc = null; } return desc; } `; helpers.classPrivateFieldLooseKey = helper("7.0.0-beta.0")` var id = 0; export default function _classPrivateFieldKey(name) { return "__private_" + (id++) + "_" + name; } `; helpers.classPrivateFieldLooseBase = helper("7.0.0-beta.0")` export default function _classPrivateFieldBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } `; helpers.classPrivateFieldGet = helper("7.0.0-beta.0")` import classApplyDescriptorGet from "classApplyDescriptorGet"; import classExtractFieldDescriptor from "classExtractFieldDescriptor"; export default function _classPrivateFieldGet(receiver, privateMap) { var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); return classApplyDescriptorGet(receiver, descriptor); } `; helpers.classPrivateFieldSet = helper("7.0.0-beta.0")` import classApplyDescriptorSet from "classApplyDescriptorSet"; import classExtractFieldDescriptor from "classExtractFieldDescriptor"; export default function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); classApplyDescriptorSet(receiver, descriptor, value); return value; } `; helpers.classPrivateFieldDestructureSet = helper("7.4.4")` import classApplyDescriptorDestructureSet from "classApplyDescriptorDestructureSet"; import classExtractFieldDescriptor from "classExtractFieldDescriptor"; export default function _classPrivateFieldDestructureSet(receiver, privateMap) { var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); return classApplyDescriptorDestructureSet(receiver, descriptor); } `; helpers.classExtractFieldDescriptor = helper("7.13.10")` export default function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to " + action + " private field on non-instance"); } return privateMap.get(receiver); } `; helpers.classStaticPrivateFieldSpecGet = helper("7.0.2")` import classApplyDescriptorGet from "classApplyDescriptorGet"; import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; import classCheckPrivateStaticFieldDescriptor from "classCheckPrivateStaticFieldDescriptor"; export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { classCheckPrivateStaticAccess(receiver, classConstructor); classCheckPrivateStaticFieldDescriptor(descriptor, "get"); return classApplyDescriptorGet(receiver, descriptor); } `; helpers.classStaticPrivateFieldSpecSet = helper("7.0.2")` import classApplyDescriptorSet from "classApplyDescriptorSet"; import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; import classCheckPrivateStaticFieldDescriptor from "classCheckPrivateStaticFieldDescriptor"; export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { classCheckPrivateStaticAccess(receiver, classConstructor); classCheckPrivateStaticFieldDescriptor(descriptor, "set"); classApplyDescriptorSet(receiver, descriptor, value); return value; } `; helpers.classStaticPrivateMethodGet = helper("7.3.2")` import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { classCheckPrivateStaticAccess(receiver, classConstructor); return method; } `; helpers.classStaticPrivateMethodSet = helper("7.3.2")` export default function _classStaticPrivateMethodSet() { throw new TypeError("attempted to set read only static private field"); } `; helpers.classApplyDescriptorGet = helper("7.13.10")` export default function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; } `; helpers.classApplyDescriptorSet = helper("7.13.10")` export default function _classApplyDescriptorSet(receiver, descriptor, value) { if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } } `; helpers.classApplyDescriptorDestructureSet = helper("7.13.10")` export default function _classApplyDescriptorDestructureSet(receiver, descriptor) { if (descriptor.set) { if (!("__destrObj" in descriptor)) { descriptor.__destrObj = { set value(v) { descriptor.set.call(receiver, v) }, }; } return descriptor.__destrObj; } else { if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } return descriptor; } } `; helpers.classStaticPrivateFieldDestructureSet = helper("7.13.10")` import classApplyDescriptorDestructureSet from "classApplyDescriptorDestructureSet"; import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; import classCheckPrivateStaticFieldDescriptor from "classCheckPrivateStaticFieldDescriptor"; export default function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { classCheckPrivateStaticAccess(receiver, classConstructor); classCheckPrivateStaticFieldDescriptor(descriptor, "set"); return classApplyDescriptorDestructureSet(receiver, descriptor); } `; helpers.classCheckPrivateStaticAccess = helper("7.13.10")` export default function _classCheckPrivateStaticAccess(receiver, classConstructor) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } } `; helpers.classCheckPrivateStaticFieldDescriptor = helper("7.13.10")` export default function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { if (descriptor === undefined) { throw new TypeError("attempted to " + action + " private static field before its declaration"); } } `; helpers.decorate = helper("7.1.5")` import toArray from "toArray"; import toPropertyKey from "toPropertyKey"; // These comments are stripped by @babel/template /*:: type PropertyDescriptor = | { value: any, writable: boolean, configurable: boolean, enumerable: boolean, } | { get?: () => any, set?: (v: any) => void, configurable: boolean, enumerable: boolean, }; type FieldDescriptor ={ writable: boolean, configurable: boolean, enumerable: boolean, }; type Placement = "static" | "prototype" | "own"; type Key = string | symbol; // PrivateName is not supported yet. type ElementDescriptor = | { kind: "method", key: Key, placement: Placement, descriptor: PropertyDescriptor } | { kind: "field", key: Key, placement: Placement, descriptor: FieldDescriptor, initializer?: () => any, }; // This is exposed to the user code type ElementObjectInput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" }; // This is exposed to the user code type ElementObjectOutput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" extras?: ElementDescriptor[], finisher?: ClassFinisher, }; // This is exposed to the user code type ClassObject = { [@@toStringTag]?: "Descriptor", kind: "class", elements: ElementDescriptor[], }; type ElementDecorator = (descriptor: ElementObjectInput) => ?ElementObjectOutput; type ClassDecorator = (descriptor: ClassObject) => ?ClassObject; type ClassFinisher = <A, B>(cl: Class<A>) => Class<B>; // Only used by Babel in the transform output, not part of the spec. type ElementDefinition = | { kind: "method", value: any, key: Key, static?: boolean, decorators?: ElementDecorator[], } | { kind: "field", value: () => any, key: Key, static?: boolean, decorators?: ElementDecorator[], }; declare function ClassFactory<C>(initialize: (instance: C) => void): { F: Class<C>, d: ElementDefinition[] } */ /*:: // Various combinations with/without extras and with one or many finishers type ElementFinisherExtras = { element: ElementDescriptor, finisher?: ClassFinisher, extras?: ElementDescriptor[], }; type ElementFinishersExtras = { element: ElementDescriptor, finishers: ClassFinisher[], extras: ElementDescriptor[], }; type ElementsFinisher = { elements: ElementDescriptor[], finisher?: ClassFinisher, }; type ElementsFinishers = { elements: ElementDescriptor[], finishers: ClassFinisher[], }; */ /*:: type Placements = { static: Key[], prototype: Key[], own: Key[], }; */ // ClassDefinitionEvaluation (Steps 26-*) export default function _decorate( decorators /*: ClassDecorator[] */, factory /*: ClassFactory */, superClass /*: ?Class<*> */, mixins /*: ?Array<Function> */, ) /*: Class<*> */ { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass( _coalesceClassElements(r.d.map(_createElementDescriptor)), decorators, ); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } function _getDecoratorsApi() { _getDecoratorsApi = function() { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], // InitializeInstanceElements initializeInstanceElements: function( /*::<C>*/ O /*: C */, elements /*: ElementDescriptor[] */, ) { ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, // InitializeClassElements initializeClassElements: function( /*::<C>*/ F /*: Class<C> */, elements /*: ElementDescriptor[] */, ) { var proto = F.prototype; ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { var placement = element.placement; if ( element.kind === kind && (placement === "static" || placement === "prototype") ) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, // DefineClassElement defineClassElement: function( /*::<C>*/ receiver /*: C | Class<C> */, element /*: ElementDescriptor */, ) { var descriptor /*: PropertyDescriptor */ = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver), }; } Object.defineProperty(receiver, element.key, descriptor); }, // DecorateClass decorateClass: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var newElements /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; var placements /*: Placements */ = { static: [], prototype: [], own: [], }; elements.forEach(function(element /*: ElementDescriptor */) { this.addElementPlacement(element, placements); }, this); elements.forEach(function(element /*: ElementDescriptor */) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras /*: ElementFinishersExtras */ = this.decorateElement( element, placements, ); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result /*: ElementsFinishers */ = this.decorateConstructor( newElements, decorators, ); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, // AddElementPlacement addElementPlacement: function( element /*: ElementDescriptor */, placements /*: Placements */, silent /*: boolean */, ) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, // DecorateElement decorateElement: function( element /*: ElementDescriptor */, placements /*: Placements */, ) /*: ElementFinishersExtras */ { var extras /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; for ( var decorators = element.decorators, i = decorators.length - 1; i >= 0; i-- ) { // (inlined) RemoveElementPlacement var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject /*: ElementObjectInput */ = this.fromElementDescriptor( element, ); var elementFinisherExtras /*: ElementFinisherExtras */ = this.toElementFinisherExtras( (0, decorators[i])(elementObject) /*: ElementObjectOutput */ || elementObject, ); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras /*: ElementDescriptor[] | void */ = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, // DecorateConstructor decorateConstructor: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var finishers /*: ClassFinisher[] */ = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj /*: ClassObject */ = this.fromClassDescriptor(elements); var elementsAndFinisher /*: ElementsFinisher */ = this.toClassDescriptor( (0, decorators[i])(obj) /*: ClassObject */ || obj, ); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if ( elements[j].key === elements[k].key && elements[j].placement === elements[k].placement ) { throw new TypeError( "Duplicated element (" + elements[j].key + ")", ); } } } } } return { elements: elements, finishers: finishers }; }, // FromElementDescriptor fromElementDescriptor: function( element /*: ElementDescriptor */, ) /*: ElementObject */ { var obj /*: ElementObject */ = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor, }; var desc = { value: "Descriptor", configurable: true, }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, // ToElementDescriptors toElementDescriptors: function( elementObjects /*: ElementObject[] */, ) /*: ElementDescriptor[] */ { if (elementObjects === undefined) return; return toArray(elementObjects).map(function(elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, // ToElementDescriptor toElementDescriptor: function( elementObject /*: ElementObject */, ) /*: ElementDescriptor */ { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError( 'An element descriptor\\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"', ); } var key = toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if ( placement !== "static" && placement !== "prototype" && placement !== "own" ) { throw new TypeError( 'An element descriptor\\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"', ); } var descriptor /*: PropertyDescriptor */ = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element /*: ElementDescriptor */ = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor), }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty( descriptor, "get", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "set", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "value", "The property descriptor of a field descriptor", ); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function( elementObject /*: ElementObject */, ) /*: ElementFinisherExtras */ { var element /*: ElementDescriptor */ = this.toElementDescriptor( elementObject, ); var finisher /*: ClassFinisher */ = _optionalCallableProperty( elementObject, "finisher", ); var extras /*: ElementDescriptors[] */ = this.toElementDescriptors( elementObject.extras, ); return { element: element, finisher: finisher, extras: extras }; }, // FromClassDescriptor fromClassDescriptor: function( elements /*: ElementDescriptor[] */, ) /*: ClassObject */ { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this), }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, // ToClassDescriptor toClassDescriptor: function( obj /*: ClassObject */, ) /*: ElementsFinisher */ { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError( 'A class descriptor\\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"', ); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, // RunClassFinishers runClassFinishers: function( constructor /*: Class<*> */, finishers /*: ClassFinisher[] */, ) /*: Class<*> */ { for (var i = 0; i < finishers.length; i++) { var newConstructor /*: ?Class<*> */ = (0, finishers[i])(constructor); if (newConstructor !== undefined) { // NOTE: This should check if IsConstructor(newConstructor) is false. if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function(obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; } // ClassElementEvaluation function _createElementDescriptor( def /*: ElementDefinition */, ) /*: ElementDescriptor */ { var key = toPropertyKey(def.key); var descriptor /*: PropertyDescriptor */; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false, }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element /*: ElementDescriptor */ = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor, }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; } // CoalesceGetterSetter function _coalesceGetterSetter( element /*: ElementDescriptor */, other /*: ElementDescriptor */, ) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } // CoalesceClassElements function _coalesceClassElements( elements /*: ElementDescriptor[] */, ) /*: ElementDescriptor[] */ { var newElements /*: ElementDescriptor[] */ = []; var isSameElement = function( other /*: ElementDescriptor */, ) /*: boolean */ { return ( other.kind === "method" && other.key === element.key && other.placement === element.placement ); }; for (var i = 0; i < elements.length; i++) { var element /*: ElementDescriptor */ = elements[i]; var other /*: ElementDescriptor */; if ( element.kind === "method" && (other = newElements.find(isSameElement)) ) { if ( _isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor) ) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError( "Duplicated methods (" + element.key + ") can't be decorated.", ); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError( "Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ").", ); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } function _hasDecorators(element /*: ElementDescriptor */) /*: boolean */ { return element.decorators && element.decorators.length; } function _isDataDescriptor(desc /*: PropertyDescriptor */) /*: boolean */ { return ( desc !== undefined && !(desc.value === undefined && desc.writable === undefined) ); } function _optionalCallableProperty /*::<T>*/( obj /*: T */, name /*: $Keys<T> */, ) /*: ?Function */ { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } `; helpers.classPrivateMethodGet = helper("7.1.6")` export default function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; } `; helpers.checkPrivateRedeclaration = helper("7.14.1")` export default function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } } `; helpers.classPrivateFieldInitSpec = helper("7.14.1")` import checkPrivateRedeclaration from "checkPrivateRedeclaration"; export default function _classPrivateFieldInitSpec(obj, privateMap, value) { checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); } `; helpers.classPrivateMethodInitSpec = helper("7.14.1")` import checkPrivateRedeclaration from "checkPrivateRedeclaration"; export default function _classPrivateMethodInitSpec(obj, privateSet) { checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); } `; if (!process.env.BABEL_8_BREAKING) { // Use readOnlyError instead helpers.classPrivateMethodSet = helper("7.1.6")` export default function _classPrivateMethodSet() { throw new TypeError("attempted to reassign private method"); } `; }
the_stack
import { KeyVaultConnectionsGetParameters, KeyVaultConnectionsCreateParameters, KeyVaultConnectionsDeleteParameters, KeyVaultConnectionsListAllParameters, ClassificationRulesGetParameters, ClassificationRulesCreateOrUpdateParameters, ClassificationRulesDeleteParameters, ClassificationRulesListAllParameters, ClassificationRulesListVersionsByClassificationRuleNameParameters, ClassificationRulesTagClassificationVersionParameters, DataSourcesCreateOrUpdateParameters, DataSourcesGetParameters, DataSourcesDeleteParameters, DataSourcesListAllParameters, FiltersGetParameters, FiltersCreateOrUpdateParameters, ScansCreateOrUpdateParameters, ScansGetParameters, ScansDeleteParameters, ScansListByDataSourceParameters, ScanResultRunScanParameters, ScanResultCancelScanParameters, ScanResultListScanHistoryParameters, ScanRulesetsGetParameters, ScanRulesetsCreateOrUpdateParameters, ScanRulesetsDeleteParameters, ScanRulesetsListAllParameters, SystemScanRulesetsListAllParameters, SystemScanRulesetsGetParameters, SystemScanRulesetsGetByVersionParameters, SystemScanRulesetsGetLatestParameters, SystemScanRulesetsListVersionsByDataSourceParameters, TriggersGetTriggerParameters, TriggersCreateTriggerParameters, TriggersDeleteTriggerParameters, } from "./parameters"; import { KeyVaultConnectionsGet200Response, KeyVaultConnectionsGetdefaultResponse, KeyVaultConnectionsCreate200Response, KeyVaultConnectionsCreatedefaultResponse, KeyVaultConnectionsDelete200Response, KeyVaultConnectionsDelete204Response, KeyVaultConnectionsDeletedefaultResponse, KeyVaultConnectionsListAll200Response, KeyVaultConnectionsListAlldefaultResponse, ClassificationRulesGet200Response, ClassificationRulesGetdefaultResponse, ClassificationRulesCreateOrUpdate200Response, ClassificationRulesCreateOrUpdate201Response, ClassificationRulesCreateOrUpdatedefaultResponse, ClassificationRulesDelete200Response, ClassificationRulesDelete204Response, ClassificationRulesDeletedefaultResponse, ClassificationRulesListAll200Response, ClassificationRulesListAlldefaultResponse, ClassificationRulesListVersionsByClassificationRuleName200Response, ClassificationRulesListVersionsByClassificationRuleNamedefaultResponse, ClassificationRulesTagClassificationVersion202Response, ClassificationRulesTagClassificationVersiondefaultResponse, DataSourcesCreateOrUpdate200Response, DataSourcesCreateOrUpdate201Response, DataSourcesCreateOrUpdatedefaultResponse, DataSourcesGet200Response, DataSourcesGetdefaultResponse, DataSourcesDelete200Response, DataSourcesDelete204Response, DataSourcesDeletedefaultResponse, DataSourcesListAll200Response, DataSourcesListAlldefaultResponse, FiltersGet200Response, FiltersGetdefaultResponse, FiltersCreateOrUpdate200Response, FiltersCreateOrUpdate201Response, FiltersCreateOrUpdatedefaultResponse, ScansCreateOrUpdate200Response, ScansCreateOrUpdate201Response, ScansCreateOrUpdatedefaultResponse, ScansGet200Response, ScansGetdefaultResponse, ScansDelete200Response, ScansDelete204Response, ScansDeletedefaultResponse, ScansListByDataSource200Response, ScansListByDataSourcedefaultResponse, ScanResultRunScan202Response, ScanResultRunScandefaultResponse, ScanResultCancelScan202Response, ScanResultCancelScandefaultResponse, ScanResultListScanHistory200Response, ScanResultListScanHistorydefaultResponse, ScanRulesetsGet200Response, ScanRulesetsGetdefaultResponse, ScanRulesetsCreateOrUpdate200Response, ScanRulesetsCreateOrUpdate201Response, ScanRulesetsCreateOrUpdatedefaultResponse, ScanRulesetsDelete200Response, ScanRulesetsDelete204Response, ScanRulesetsDeletedefaultResponse, ScanRulesetsListAll200Response, ScanRulesetsListAlldefaultResponse, SystemScanRulesetsListAll200Response, SystemScanRulesetsListAlldefaultResponse, SystemScanRulesetsGet200Response, SystemScanRulesetsGetdefaultResponse, SystemScanRulesetsGetByVersion200Response, SystemScanRulesetsGetByVersiondefaultResponse, SystemScanRulesetsGetLatest200Response, SystemScanRulesetsGetLatestdefaultResponse, SystemScanRulesetsListVersionsByDataSource200Response, SystemScanRulesetsListVersionsByDataSourcedefaultResponse, TriggersGetTrigger200Response, TriggersGetTriggerdefaultResponse, TriggersCreateTrigger200Response, TriggersCreateTrigger201Response, TriggersCreateTriggerdefaultResponse, TriggersDeleteTrigger200Response, TriggersDeleteTrigger204Response, TriggersDeleteTriggerdefaultResponse, } from "./responses"; import { getClient, ClientOptions, Client } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; export interface KeyVaultConnectionsGet { /** Gets key vault information */ get( options?: KeyVaultConnectionsGetParameters ): Promise<KeyVaultConnectionsGet200Response | KeyVaultConnectionsGetdefaultResponse>; /** Creates an instance of a key vault connection */ put( options: KeyVaultConnectionsCreateParameters ): Promise<KeyVaultConnectionsCreate200Response | KeyVaultConnectionsCreatedefaultResponse>; /** Deletes the key vault connection associated with the account */ delete( options?: KeyVaultConnectionsDeleteParameters ): Promise< | KeyVaultConnectionsDelete200Response | KeyVaultConnectionsDelete204Response | KeyVaultConnectionsDeletedefaultResponse >; } export interface KeyVaultConnectionsListAll { /** List key vault connections in account */ get( options?: KeyVaultConnectionsListAllParameters ): Promise<KeyVaultConnectionsListAll200Response | KeyVaultConnectionsListAlldefaultResponse>; } export interface ClassificationRulesGet { /** Get a classification rule */ get( options?: ClassificationRulesGetParameters ): Promise<ClassificationRulesGet200Response | ClassificationRulesGetdefaultResponse>; /** Creates or Updates a classification rule */ put( options?: ClassificationRulesCreateOrUpdateParameters ): Promise< | ClassificationRulesCreateOrUpdate200Response | ClassificationRulesCreateOrUpdate201Response | ClassificationRulesCreateOrUpdatedefaultResponse >; /** Deletes a classification rule */ delete( options?: ClassificationRulesDeleteParameters ): Promise< | ClassificationRulesDelete200Response | ClassificationRulesDelete204Response | ClassificationRulesDeletedefaultResponse >; } export interface ClassificationRulesListAll { /** List classification rules in Account */ get( options?: ClassificationRulesListAllParameters ): Promise<ClassificationRulesListAll200Response | ClassificationRulesListAlldefaultResponse>; } export interface ClassificationRulesListVersionsByClassificationRuleName { /** Lists the rule versions of a classification rule */ get( options?: ClassificationRulesListVersionsByClassificationRuleNameParameters ): Promise< | ClassificationRulesListVersionsByClassificationRuleName200Response | ClassificationRulesListVersionsByClassificationRuleNamedefaultResponse >; } export interface ClassificationRulesTagClassificationVersion { /** Sets Classification Action on a specific classification rule version. */ post( options: ClassificationRulesTagClassificationVersionParameters ): Promise< | ClassificationRulesTagClassificationVersion202Response | ClassificationRulesTagClassificationVersiondefaultResponse >; } export interface DataSourcesCreateOrUpdate { /** Creates or Updates a data source */ put( options?: DataSourcesCreateOrUpdateParameters ): Promise< | DataSourcesCreateOrUpdate200Response | DataSourcesCreateOrUpdate201Response | DataSourcesCreateOrUpdatedefaultResponse >; /** Get a data source */ get( options?: DataSourcesGetParameters ): Promise<DataSourcesGet200Response | DataSourcesGetdefaultResponse>; /** Deletes a data source */ delete( options?: DataSourcesDeleteParameters ): Promise< DataSourcesDelete200Response | DataSourcesDelete204Response | DataSourcesDeletedefaultResponse >; } export interface DataSourcesListAll { /** List data sources in Data catalog */ get( options?: DataSourcesListAllParameters ): Promise<DataSourcesListAll200Response | DataSourcesListAlldefaultResponse>; } export interface FiltersGet { /** Get a filter */ get(options?: FiltersGetParameters): Promise<FiltersGet200Response | FiltersGetdefaultResponse>; /** Creates or updates a filter */ put( options?: FiltersCreateOrUpdateParameters ): Promise< | FiltersCreateOrUpdate200Response | FiltersCreateOrUpdate201Response | FiltersCreateOrUpdatedefaultResponse >; } export interface ScansCreateOrUpdate { /** Creates an instance of a scan */ put( options: ScansCreateOrUpdateParameters ): Promise< | ScansCreateOrUpdate200Response | ScansCreateOrUpdate201Response | ScansCreateOrUpdatedefaultResponse >; /** Gets a scan information */ get(options?: ScansGetParameters): Promise<ScansGet200Response | ScansGetdefaultResponse>; /** Deletes the scan associated with the data source */ delete( options?: ScansDeleteParameters ): Promise<ScansDelete200Response | ScansDelete204Response | ScansDeletedefaultResponse>; } export interface ScansListByDataSource { /** List scans in data source */ get( options?: ScansListByDataSourceParameters ): Promise<ScansListByDataSource200Response | ScansListByDataSourcedefaultResponse>; } export interface ScanResultRunScan { /** Runs the scan */ put( options?: ScanResultRunScanParameters ): Promise<ScanResultRunScan202Response | ScanResultRunScandefaultResponse>; } export interface ScanResultCancelScan { /** Cancels a scan */ post( options?: ScanResultCancelScanParameters ): Promise<ScanResultCancelScan202Response | ScanResultCancelScandefaultResponse>; } export interface ScanResultListScanHistory { /** Lists the scan history of a scan */ get( options?: ScanResultListScanHistoryParameters ): Promise<ScanResultListScanHistory200Response | ScanResultListScanHistorydefaultResponse>; } export interface ScanRulesetsGet { /** Get a scan ruleset */ get( options?: ScanRulesetsGetParameters ): Promise<ScanRulesetsGet200Response | ScanRulesetsGetdefaultResponse>; /** Creates or Updates a scan ruleset */ put( options?: ScanRulesetsCreateOrUpdateParameters ): Promise< | ScanRulesetsCreateOrUpdate200Response | ScanRulesetsCreateOrUpdate201Response | ScanRulesetsCreateOrUpdatedefaultResponse >; /** Deletes a scan ruleset */ delete( options?: ScanRulesetsDeleteParameters ): Promise< | ScanRulesetsDelete200Response | ScanRulesetsDelete204Response | ScanRulesetsDeletedefaultResponse >; } export interface ScanRulesetsListAll { /** List scan rulesets in Data catalog */ get( options?: ScanRulesetsListAllParameters ): Promise<ScanRulesetsListAll200Response | ScanRulesetsListAlldefaultResponse>; } export interface SystemScanRulesetsListAll { /** List all system scan rulesets for an account */ get( options?: SystemScanRulesetsListAllParameters ): Promise<SystemScanRulesetsListAll200Response | SystemScanRulesetsListAlldefaultResponse>; } export interface SystemScanRulesetsGet { /** Get a system scan ruleset for a data source */ get( options?: SystemScanRulesetsGetParameters ): Promise<SystemScanRulesetsGet200Response | SystemScanRulesetsGetdefaultResponse>; } export interface SystemScanRulesetsGetByVersion { /** Get a scan ruleset by version */ get( options?: SystemScanRulesetsGetByVersionParameters ): Promise< SystemScanRulesetsGetByVersion200Response | SystemScanRulesetsGetByVersiondefaultResponse >; } export interface SystemScanRulesetsGetLatest { /** Get the latest version of a system scan ruleset */ get( options?: SystemScanRulesetsGetLatestParameters ): Promise<SystemScanRulesetsGetLatest200Response | SystemScanRulesetsGetLatestdefaultResponse>; } export interface SystemScanRulesetsListVersionsByDataSource { /** List system scan ruleset versions in Data catalog */ get( options?: SystemScanRulesetsListVersionsByDataSourceParameters ): Promise< | SystemScanRulesetsListVersionsByDataSource200Response | SystemScanRulesetsListVersionsByDataSourcedefaultResponse >; } export interface TriggersGetTrigger { /** Gets trigger information */ get( options?: TriggersGetTriggerParameters ): Promise<TriggersGetTrigger200Response | TriggersGetTriggerdefaultResponse>; /** Creates an instance of a trigger */ put( options: TriggersCreateTriggerParameters ): Promise< | TriggersCreateTrigger200Response | TriggersCreateTrigger201Response | TriggersCreateTriggerdefaultResponse >; /** Deletes the trigger associated with the scan */ delete( options?: TriggersDeleteTriggerParameters ): Promise< | TriggersDeleteTrigger200Response | TriggersDeleteTrigger204Response | TriggersDeleteTriggerdefaultResponse >; } export interface Routes { /** Resource for '/azureKeyVaults/\{keyVaultName\}' has methods for the following verbs: get, put, delete */ (path: "/azureKeyVaults/{keyVaultName}", keyVaultName: string): KeyVaultConnectionsGet; /** Resource for '/azureKeyVaults' has methods for the following verbs: get */ (path: "/azureKeyVaults"): KeyVaultConnectionsListAll; /** Resource for '/classificationrules/\{classificationRuleName\}' has methods for the following verbs: get, put, delete */ ( path: "/classificationrules/{classificationRuleName}", classificationRuleName: string ): ClassificationRulesGet; /** Resource for '/classificationrules' has methods for the following verbs: get */ (path: "/classificationrules"): ClassificationRulesListAll; /** Resource for '/classificationrules/\{classificationRuleName\}/versions' has methods for the following verbs: get */ ( path: "/classificationrules/{classificationRuleName}/versions", classificationRuleName: string ): ClassificationRulesListVersionsByClassificationRuleName; /** Resource for '/classificationrules/\{classificationRuleName\}/versions/\{classificationRuleVersion\}/:tag' has methods for the following verbs: post */ ( path: "/classificationrules/{classificationRuleName}/versions/{classificationRuleVersion}/:tag", classificationRuleName: string, classificationRuleVersion: string ): ClassificationRulesTagClassificationVersion; /** Resource for '/datasources/\{dataSourceName\}' has methods for the following verbs: put, get, delete */ (path: "/datasources/{dataSourceName}", dataSourceName: string): DataSourcesCreateOrUpdate; /** Resource for '/datasources' has methods for the following verbs: get */ (path: "/datasources"): DataSourcesListAll; /** Resource for '/datasources/\{dataSourceName\}/scans/\{scanName\}/filters/custom' has methods for the following verbs: get, put */ ( path: "/datasources/{dataSourceName}/scans/{scanName}/filters/custom", dataSourceName: string, scanName: string ): FiltersGet; /** Resource for '/datasources/\{dataSourceName\}/scans/\{scanName\}' has methods for the following verbs: put, get, delete */ ( path: "/datasources/{dataSourceName}/scans/{scanName}", dataSourceName: string, scanName: string ): ScansCreateOrUpdate; /** Resource for '/datasources/\{dataSourceName\}/scans' has methods for the following verbs: get */ (path: "/datasources/{dataSourceName}/scans", dataSourceName: string): ScansListByDataSource; /** Resource for '/datasources/\{dataSourceName\}/scans/\{scanName\}/runs/\{runId\}' has methods for the following verbs: put */ ( path: "/datasources/{dataSourceName}/scans/{scanName}/runs/{runId}", dataSourceName: string, scanName: string, runId: string ): ScanResultRunScan; /** Resource for '/datasources/\{dataSourceName\}/scans/\{scanName\}/runs/\{runId\}/:cancel' has methods for the following verbs: post */ ( path: "/datasources/{dataSourceName}/scans/{scanName}/runs/{runId}/:cancel", dataSourceName: string, scanName: string, runId: string ): ScanResultCancelScan; /** Resource for '/datasources/\{dataSourceName\}/scans/\{scanName\}/runs' has methods for the following verbs: get */ ( path: "/datasources/{dataSourceName}/scans/{scanName}/runs", dataSourceName: string, scanName: string ): ScanResultListScanHistory; /** Resource for '/scanrulesets/\{scanRulesetName\}' has methods for the following verbs: get, put, delete */ (path: "/scanrulesets/{scanRulesetName}", scanRulesetName: string): ScanRulesetsGet; /** Resource for '/scanrulesets' has methods for the following verbs: get */ (path: "/scanrulesets"): ScanRulesetsListAll; /** Resource for '/systemScanRulesets' has methods for the following verbs: get */ (path: "/systemScanRulesets"): SystemScanRulesetsListAll; /** Resource for '/systemScanRulesets/datasources/\{dataSourceType\}' has methods for the following verbs: get */ ( path: "/systemScanRulesets/datasources/{dataSourceType}", dataSourceType: string ): SystemScanRulesetsGet; /** Resource for '/systemScanRulesets/versions/\{version\}' has methods for the following verbs: get */ (path: "/systemScanRulesets/versions/{version}", version: string): SystemScanRulesetsGetByVersion; /** Resource for '/systemScanRulesets/versions/latest' has methods for the following verbs: get */ (path: "/systemScanRulesets/versions/latest"): SystemScanRulesetsGetLatest; /** Resource for '/systemScanRulesets/versions' has methods for the following verbs: get */ (path: "/systemScanRulesets/versions"): SystemScanRulesetsListVersionsByDataSource; /** Resource for '/datasources/\{dataSourceName\}/scans/\{scanName\}/triggers/default' has methods for the following verbs: get, put, delete */ ( path: "/datasources/{dataSourceName}/scans/{scanName}/triggers/default", dataSourceName: string, scanName: string ): TriggersGetTrigger; } export type PurviewScanningRestClient = Client & { path: Routes; }; export default function PurviewScanning( Endpoint: string, credentials: TokenCredential, options: ClientOptions = {} ): PurviewScanningRestClient { const baseUrl = options.baseUrl ?? `${Endpoint}`; options.apiVersion = options.apiVersion ?? "2018-12-01-preview"; options = { ...options, credentials: { scopes: ["https://purview.azure.net/.default"], }, }; return getClient(baseUrl, credentials, options) as PurviewScanningRestClient; }
the_stack
import * as React from 'react' import * as _ from 'underscore' import * as mousetrap from 'mousetrap' import { Meteor } from 'meteor/meteor' import { Translated, translateWithTracker } from '../../lib/ReactMeteorData/react-meteor-data' import { withTranslation } from 'react-i18next' import { Rundown, RundownId } from '../../../lib/collections/Rundowns' import { RundownPlaylist } from '../../../lib/collections/RundownPlaylists' import { Segment, DBSegment, SegmentId } from '../../../lib/collections/Segments' import { PartId } from '../../../lib/collections/Parts' import { AdLibPiece, AdLibPieces } from '../../../lib/collections/AdLibPieces' import { AdLibListItem, IAdLibListItem } from './AdLibListItem' import ClassNames from 'classnames' import { mousetrapHelper } from '../../lib/mousetrapHelper' import { faTh, faList, faTimes } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { Spinner } from '../../lib/Spinner' import { MeteorReactComponent } from '../../lib/MeteorReactComponent' import { RundownViewKbdShortcuts } from '../RundownView' import { ShowStyleBase } from '../../../lib/collections/ShowStyleBases' import { IOutputLayer, ISourceLayer, PieceLifespan, IBlueprintActionTriggerMode, SomeTimelineContent, } from '@sofie-automation/blueprints-integration' import { doUserAction, UserAction } from '../../lib/userAction' import { NotificationCenter, Notification, NoticeLevel } from '../../lib/notifications/notifications' import { RundownLayoutFilter, RundownLayoutFilterBase, DashboardLayoutFilter, } from '../../../lib/collections/RundownLayouts' import { RundownBaselineAdLibItem, RundownBaselineAdLibPieces, } from '../../../lib/collections/RundownBaselineAdLibPieces' import { Random } from 'meteor/random' import { literal, normalizeArray, unprotectString, protectString } from '../../../lib/lib' import { RundownAPI } from '../../../lib/api/rundown' import { memoizedIsolatedAutorun } from '../../lib/reactiveData/reactiveDataHelper' import { PartInstance, PartInstances, PartInstanceId, findPartInstanceOrWrapToTemporary, } from '../../../lib/collections/PartInstances' import { MeteorCall } from '../../../lib/api/methods' import { PieceUi } from '../SegmentTimeline/SegmentTimelineContainer' import { AdLibActions, AdLibAction } from '../../../lib/collections/AdLibActions' import { RundownUtils } from '../../lib/rundown' import { ShelfTabs } from './Shelf' import { RundownBaselineAdLibActions, RundownBaselineAdLibAction, } from '../../../lib/collections/RundownBaselineAdLibActions' import { GlobalAdLibHotkeyUseMap } from './GlobalAdLibPanel' import { Studio } from '../../../lib/collections/Studios' import { BucketAdLibActionUi, BucketAdLibUi } from './RundownViewBuckets' import RundownViewEventBus, { RundownViewEvents, RevealInShelfEvent } from '../RundownView/RundownViewEventBus' import { ScanInfoForPackages } from '../../../lib/mediaObjects' import { translateMessage } from '../../../lib/api/TranslatableMessage' import { i18nTranslator } from '../i18n' interface IListViewPropsHeader { uiSegments: Array<AdlibSegmentUi> onSelectAdLib: (piece: IAdLibListItem) => void onToggleAdLib: ( piece: IAdLibListItem, queue: boolean, e: mousetrap.ExtendedKeyboardEvent, mode?: IBlueprintActionTriggerMode ) => void selectedPiece: BucketAdLibActionUi | BucketAdLibUi | IAdLibListItem | PieceUi | undefined selectedSegment: AdlibSegmentUi | undefined searchFilter: string | undefined showStyleBase: ShowStyleBase noSegments: boolean filter: RundownLayoutFilter | undefined rundownAdLibs?: Array<AdLibPieceUi> playlist: RundownPlaylist studio: Studio } interface IListViewStateHeader { outputLayers: { [key: string]: IOutputLayer } sourceLayers: { [key: string]: ISourceLayer } } /** * Applies a filter to an adLib to determine whether it matches filter criteria. * @param item AdLib to test against filter. * @param showStyleBase * @param uiSegments All segments to search for live segment. * @param filter Filter to match against. * @param searchFilter Text to try to match against adLib label. * @param uniquenessIds Set of uniquenessIds, for a given set only one adLib per uniquness Id will be matched by this filter. */ export function matchFilter( item: AdLibPieceUi, showStyleBase: ShowStyleBase, uiSegments: Array<AdlibSegmentUi>, filter?: RundownLayoutFilterBase, searchFilter?: string, uniquenessIds?: Set<string> ) { if (!searchFilter && !filter) return true const liveSegment = uiSegments.find((i) => i.isLive === true) const uppercaseLabel = item.name.toUpperCase() if (filter) { // Filter currentSegment only if ( filter.currentSegment === true && item.partId && ((liveSegment && liveSegment.parts.find((i) => item.partId === i.part._id) === undefined) || !liveSegment) ) { return false } // Filter out items that are not within outputLayerIds filter if ( filter.outputLayerIds !== undefined && filter.outputLayerIds.length && filter.outputLayerIds.indexOf(item.outputLayerId) < 0 ) { return false } // Source layers if ( filter.sourceLayerIds !== undefined && filter.sourceLayerIds.length && filter.sourceLayerIds.indexOf(item.sourceLayerId) < 0 ) { return false } // Source layer types const sourceLayerType = showStyleBase.sourceLayers.find((i) => i._id === item.sourceLayerId) if ( sourceLayerType && filter.sourceLayerTypes !== undefined && filter.sourceLayerTypes.length && filter.sourceLayerTypes.indexOf(sourceLayerType.type) < 0 ) { return false } // Item label needs at least one of the strings in the label array if ( filter.label !== undefined && filter.label.length && filter.label.reduce((p, v) => { return p || uppercaseLabel.indexOf(v.toUpperCase()) >= 0 }, false) === false ) { return false } // Item tags needs to contain all of the strings in the tags array if ( filter.tags !== undefined && filter.tags.length && filter.tags.reduce((p, v) => { return p && item.tags !== undefined && item.tags.indexOf(v) >= 0 }, true) === false ) { return false } // Hide duplicates // Only the first adLib found with a given uniquenessId will be displayed if this option is enabled. // Scope of the filter is determined by the scope of the uniquenessIds set (typically rundown-wide). if (filter.hideDuplicates && uniquenessIds) { const uniquenessId = item.uniquenessId || unprotectString(item._id) if (uniquenessIds.has(uniquenessId)) { return false } else { uniquenessIds.add(uniquenessId) } } } if (searchFilter) { return uppercaseLabel.indexOf(searchFilter.trim().toUpperCase()) >= 0 } else { return true } } export function matchTags(item: AdLibPieceUi, tags?: string[]) { if ( tags !== undefined && tags.reduce((p, v) => { return p && item.tags !== undefined && item.tags.indexOf(v) >= 0 }, true) === false ) { return false } return true } const AdLibListView = withTranslation()( class AdLibListView extends React.Component<Translated<IListViewPropsHeader>, IListViewStateHeader> { table: HTMLTableElement constructor(props: Translated<IListViewPropsHeader>) { super(props) this.state = { outputLayers: {}, sourceLayers: {}, } } static getDerivedStateFromProps(props: IListViewPropsHeader, state) { let tOLayers: { [key: string]: IOutputLayer } = {} let tSLayers: { [key: string]: ISourceLayer } = {} if (props.showStyleBase && props.showStyleBase.outputLayers && props.showStyleBase.sourceLayers) { props.showStyleBase.outputLayers.forEach((outputLayer) => { tOLayers[outputLayer._id] = outputLayer }) props.showStyleBase.sourceLayers.forEach((sourceLayer) => { tSLayers[sourceLayer._id] = sourceLayer }) return { outputLayers: tOLayers, sourceLayers: tSLayers, } } return null } scrollToCurrentSegment() { if (this.table.id && this.props.selectedSegment) { // scroll to selected segment const segmentSelector = `#${this.table.id} .adlib-panel__list-view__item__${this.props.selectedSegment._id}` const segment: HTMLElement | null = document.querySelector(segmentSelector) if (segment) { this.table.scrollTo({ top: segment.offsetTop, behavior: 'smooth', }) } } } componentDidMount() { this.scrollToCurrentSegment() } componentDidUpdate(prevProps: IListViewPropsHeader) { if (prevProps.selectedSegment !== this.props.selectedSegment) { this.scrollToCurrentSegment() } } renderRundownAdLibs(uniquenessIds: Set<string>) { const { t } = this.props return ( <tbody className="adlib-panel__list-view__list__segment adlib-panel__list-view__item__rundown-baseline"> {this.props.rundownAdLibs && this.props.rundownAdLibs .filter( (item) => !item.isHidden && matchFilter( item, this.props.showStyleBase, this.props.uiSegments, this.props.filter, this.props.searchFilter, uniquenessIds ) ) .map((adLibPiece: AdLibPieceUi) => ( <AdLibListItem key={unprotectString(adLibPiece._id)} piece={adLibPiece} layer={adLibPiece.sourceLayer!} studio={this.props.studio} selected={ (this.props.selectedPiece && RundownUtils.isAdLibPiece(this.props.selectedPiece) && this.props.selectedPiece._id === adLibPiece._id) || false } onToggleAdLib={this.props.onToggleAdLib} onSelectAdLib={this.props.onSelectAdLib} playlist={this.props.playlist} /> ))} </tbody> ) } renderSegments(uniquenessIds: Set<string>) { return this.props.uiSegments .filter((a) => (this.props.filter ? (this.props.filter.currentSegment ? a.isLive : true) : true)) .map((segment) => { return ( <tbody key={unprotectString(segment._id)} className={ClassNames( 'adlib-panel__list-view__list__segment', 'adlib-panel__list-view__item__' + segment._id, { live: segment.isLive, next: segment.isNext && !segment.isLive, past: segment.parts.reduce((memo, item) => { return item.timings?.startedPlayback && item.timings?.duration ? memo : false }, true) === true, } )} > <tr className="adlib-panel__list-view__list__seg-header"> <td colSpan={4}>{segment.name}</td> </tr> {segment.pieces && segment.pieces .filter((item) => matchFilter( item, this.props.showStyleBase, this.props.uiSegments, this.props.filter, this.props.searchFilter, uniquenessIds ) ) .map((adLibPiece: AdLibPieceUi) => ( <AdLibListItem key={unprotectString(adLibPiece._id)} piece={adLibPiece} layer={adLibPiece.sourceLayer!} studio={this.props.studio} selected={ (this.props.selectedPiece && RundownUtils.isAdLibPiece(this.props.selectedPiece) && this.props.selectedPiece._id === adLibPiece._id) || false } onToggleAdLib={this.props.onToggleAdLib} onSelectAdLib={this.props.onSelectAdLib} playlist={this.props.playlist} /> ))} </tbody> ) }) } setTableRef = (el) => { this.table = el } render() { const selected = this.props.selectedPiece const uniquenessIds = new Set<string>() return ( <div className={ClassNames('adlib-panel__list-view__list', { 'adlib-panel__list-view__list--no-segments': this.props.noSegments, })} > <table id={'adlib-panel__list-view__table__' + Random.id()} className="adlib-panel__list-view__list__table scroll-sink" ref={this.setTableRef} > {this.renderRundownAdLibs(uniquenessIds)} {this.renderSegments(uniquenessIds)} </table> </div> ) } } ) interface IToolbarPropsHeader { onFilterChange?: (newFilter: string | undefined) => void noSegments?: boolean } interface IToolbarStateHader { searchInputValue: string } export const AdLibPanelToolbar = withTranslation()( class AdLibPanelToolbar extends React.Component<Translated<IToolbarPropsHeader>, IToolbarStateHader> { constructor(props: Translated<IToolbarPropsHeader>) { super(props) this.state = { searchInputValue: '', } } searchInputChanged = (e?: React.ChangeEvent<HTMLInputElement>) => { const newValue = e?.target.value || '' this.setState({ searchInputValue: newValue, }) this.props.onFilterChange && typeof this.props.onFilterChange === 'function' && this.props.onFilterChange(newValue) } searchInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Escape' || e.key === 'Enter') { document.querySelector('button')?.focus() } else if (e.key.match(/^F\d+$/)) { e.preventDefault() } } clearSearchInput = () => { this.searchInputChanged() } render() { const { t } = this.props return ( <div className={ClassNames('adlib-panel__list-view__toolbar', { 'adlib-panel__list-view__toolbar--no-segments': this.props.noSegments, })} > <div className="adlib-panel__list-view__toolbar__filter"> <input className="adlib-panel__list-view__toolbar__filter__input" type="text" placeholder={t('Search...')} onChange={this.searchInputChanged} onKeyDown={this.searchInputKeyDown} value={this.state.searchInputValue} /> {this.state.searchInputValue !== '' && ( <div className="adlib-panel__list-view__toolbar__filter__clear" onClick={this.clearSearchInput}> <FontAwesomeIcon icon={faTimes} /> </div> )} </div> <div className="adlib-panel__list-view__toolbar__buttons" style={{ display: 'none' }}> <button className="action-btn"> <FontAwesomeIcon icon={faList} /> </button> <button className="action-btn"> <FontAwesomeIcon icon={faTh} /> </button> </div> </div> ) } } ) export interface AdLibPieceUi extends AdLibPiece { hotkey?: string sourceLayer?: ISourceLayer outputLayer?: IOutputLayer isGlobal?: boolean isHidden?: boolean isSticky?: boolean isAction?: boolean isClearSourceLayer?: boolean adlibAction?: AdLibAction | RundownBaselineAdLibAction contentMetaData?: any contentPackageInfos?: ScanInfoForPackages message?: string | null } export interface AdlibSegmentUi extends DBSegment { /** Pieces belonging to this part */ parts: Array<PartInstance> pieces: Array<AdLibPieceUi> isLive: boolean isNext: boolean } export interface IAdLibPanelProps { // liveSegment: Segment | undefined visible: boolean playlist: RundownPlaylist studio: Studio showStyleBase: ShowStyleBase studioMode: boolean filter?: RundownLayoutFilterBase includeGlobalAdLibs?: boolean registerHotkeys?: boolean hotkeyGroup: string selectedPiece: BucketAdLibUi | BucketAdLibActionUi | IAdLibListItem | PieceUi | undefined onSelectPiece?: (piece: AdLibPieceUi | PieceUi) => void } interface IState { selectedSegment: AdlibSegmentUi | undefined followLive: boolean searchFilter: string | undefined } type SourceLayerLookup = { [id: string]: ISourceLayer } export interface AdLibFetchAndFilterProps { uiSegments: Array<AdlibSegmentUi> liveSegment: AdlibSegmentUi | undefined sourceLayerLookup: SourceLayerLookup rundownBaselineAdLibs: Array<AdLibPieceUi> } interface IAdLibPanelTrackedProps extends AdLibFetchAndFilterProps { studio: Studio } function actionToAdLibPieceUi( action: AdLibAction | RundownBaselineAdLibAction, sourceLayers: _.Dictionary<ISourceLayer>, outputLayers: _.Dictionary<IOutputLayer> ): AdLibPieceUi { let sourceLayerId = '' let outputLayerId = '' let content: SomeTimelineContent = { timelineObjects: [] } if (RundownUtils.isAdlibActionContent(action.display)) { sourceLayerId = action.display.sourceLayerId outputLayerId = action.display.outputLayerId content = { timelineObjects: [], ...action.display.content, } } return literal<AdLibPieceUi>({ _id: protectString(`function_${action._id}`), name: translateMessage(action.display.label, i18nTranslator), status: RundownAPI.PieceStatusCode.UNKNOWN, isAction: true, expectedDuration: 0, externalId: unprotectString(action._id), rundownId: action.rundownId, partId: action.partId, sourceLayer: sourceLayers[sourceLayerId], outputLayer: outputLayers[outputLayerId], sourceLayerId, outputLayerId, _rank: action.display._rank || 0, content: content, adlibAction: action, tags: action.display.tags, currentPieceTags: action.display.currentPieceTags, nextPieceTags: action.display.nextPieceTags, lifespan: PieceLifespan.WithinPart, // value doesn't matter uniquenessId: action.display.uniquenessId, }) } export function fetchAndFilter(props: Translated<IAdLibPanelProps>): AdLibFetchAndFilterProps { const { t } = props const sourceLayerLookup = normalizeArray(props.showStyleBase && props.showStyleBase.sourceLayers, '_id') const outputLayerLookup = normalizeArray(props.showStyleBase && props.showStyleBase.outputLayers, '_id') // a hash to store various indices of the used hotkey lists let sourceHotKeyUse: { [key: string]: number } = GlobalAdLibHotkeyUseMap.getAll() if (!props.playlist || !props.showStyleBase) { return { uiSegments: [], liveSegment: undefined, sourceLayerLookup, rundownBaselineAdLibs: [], } } const sharedHotkeyList = _.groupBy(props.showStyleBase.sourceLayers, (item) => item.activateKeyboardHotkeys) const segments = props.playlist.getSegments() const { uiSegments, liveSegment, uiPartSegmentMap } = memoizedIsolatedAutorun( (currentPartInstanceId: PartInstanceId | null, nextPartInstanceId: PartInstanceId | null, segments: Segment[]) => { // This is a map of partIds mapped onto segments they are part of const uiPartSegmentMap = new Map<PartId, AdlibSegmentUi>() if (!segments) { return { uiSegments: [], liveSegment: undefined, uiPartSegmentMap, } } let liveSegment: AdlibSegmentUi | undefined const uiSegmentMap = new Map<SegmentId, AdlibSegmentUi>() const uiSegments: Array<AdlibSegmentUi> = segments.map((segment) => { const segmentUi = literal<AdlibSegmentUi>({ ...segment, parts: [], pieces: [], isLive: false, isNext: false, }) uiSegmentMap.set(segmentUi._id, segmentUi) return segmentUi }) const { currentPartInstance, nextPartInstance } = props.playlist.getSelectedPartInstances() const partInstances = props.playlist.getActivePartInstancesMap() props.playlist .getUnorderedParts({ segmentId: { $in: Array.from(uiSegmentMap.keys()), }, }) .forEach((part) => { const segment = uiSegmentMap.get(part.segmentId) if (segment) { const partInstance = findPartInstanceOrWrapToTemporary(partInstances, part) segment.parts.push(partInstance) uiPartSegmentMap.set(part._id, segment) } }) if (currentPartInstance) { const segment = uiSegmentMap.get(currentPartInstance.segmentId) if (segment) { liveSegment = segment segment.isLive = true } } if (nextPartInstance) { const segment = uiSegmentMap.get(nextPartInstance.segmentId) if (segment) { segment.isNext = true } } uiSegmentMap.forEach((segment) => { // Sort parts by rank segment.parts = segment.parts.sort((a, b) => a.part._rank - b.part._rank) }) return { uiSegments, liveSegment, uiPartSegmentMap, } }, 'uiSegments', props.playlist.currentPartInstanceId, props.playlist.nextPartInstanceId, segments ) uiSegments.forEach((segment) => (segment.pieces.length = 0)) const rundownIds = props.playlist.getRundownIDs() const partIds = Array.from(uiPartSegmentMap.keys()) AdLibPieces.find( { rundownId: { $in: rundownIds, }, partId: { $in: partIds, }, }, { sort: { _rank: 1 }, } ) .fetch() .forEach((piece) => { const segment = uiPartSegmentMap.get(piece.partId!) if (segment) { segment.pieces.push({ ...piece, sourceLayer: sourceLayerLookup[piece.sourceLayerId], outputLayer: outputLayerLookup[piece.outputLayerId], }) } }) const adlibActions = memoizedIsolatedAutorun( (rundownIds: RundownId[], partIds: PartId[]) => AdLibActions.find( { rundownId: { $in: rundownIds, }, partId: { $in: partIds, }, }, { // @ts-ignore deep-property sort: { 'display._rank': 1 }, } ).map((action) => { return [action.partId, actionToAdLibPieceUi(action, sourceLayerLookup, outputLayerLookup)] as [ PartId, AdLibPieceUi ] }), 'adLibActions', rundownIds, partIds ) adlibActions.forEach((action) => { const segment = uiPartSegmentMap.get(action[0]) if (segment) { segment.pieces.push(action[1]) } }) uiPartSegmentMap.forEach((segment) => { segment.pieces = segment.pieces.sort((a, b) => a._rank - b._rank) }) if (liveSegment) { liveSegment.pieces = liveSegment.pieces.map((piece) => { let sourceLayer = piece.sourceLayerId && sourceLayerLookup[piece.sourceLayerId] if (sourceLayer && sourceLayer.activateKeyboardHotkeys) { let keyboardHotkeysList = sourceLayer.activateKeyboardHotkeys.split(',') const sourceHotKeyUseLayerId = sharedHotkeyList[sourceLayer.activateKeyboardHotkeys][0]._id || piece.sourceLayerId if ((sourceHotKeyUse[sourceHotKeyUseLayerId] || 0) < keyboardHotkeysList.length) { // clone the AdLibPieceUi object, so that it doesn't affect any memoized autoruns that may have // inserted pieces to this list piece = { ...piece, hotkey: keyboardHotkeysList[sourceHotKeyUse[sourceHotKeyUseLayerId] || 0], } // add one to the usage hash table sourceHotKeyUse[sourceHotKeyUseLayerId] = (sourceHotKeyUse[sourceHotKeyUseLayerId] || 0) + 1 } } return piece }) } let currentRundown: Rundown | undefined = undefined let rundownBaselineAdLibs: Array<AdLibPieceUi> = [] if ( props.playlist && props.filter && props.includeGlobalAdLibs && (props.filter.rundownBaseline === true || props.filter.rundownBaseline === 'only') ) { const { t } = props const rundowns = props.playlist.getRundowns(undefined, { fields: { _id: 1, _rank: 1, name: 1, }, }) const rMap = normalizeArray(rundowns, '_id') currentRundown = rundowns[0] const partInstanceId = props.playlist.currentPartInstanceId || props.playlist.nextPartInstanceId if (partInstanceId) { const partInstance = PartInstances.findOne(partInstanceId) if (partInstance) { currentRundown = rMap[unprotectString(partInstance.rundownId)] } } if (currentRundown) { // memoizedIsolatedAutorun rundownBaselineAdLibs = memoizedIsolatedAutorun( ( currentRundownId: RundownId, sourceLayerLookup: SourceLayerLookup, sourceLayers: ISourceLayer[], sourceHotKeyUse: { [key: string]: number } ) => { let rundownAdLibItems: RundownBaselineAdLibItem[] = RundownBaselineAdLibPieces.find( { rundownId: currentRundownId, }, { sort: { sourceLayerId: 1, _rank: 1, name: 1 }, } ).fetch() rundownBaselineAdLibs = rundownAdLibItems.concat( props.showStyleBase.sourceLayers .filter((i) => i.isSticky && i.activateStickyKeyboardHotkey) .sort((a, b) => a._rank - b._rank) .map((layer) => literal<AdLibPieceUi>({ _id: protectString(`sticky_${layer._id}`), hotkey: layer.activateStickyKeyboardHotkey ? layer.activateStickyKeyboardHotkey.split(',')[0] : '', name: t('Last {{layerName}}', { layerName: layer.abbreviation || layer.name }), status: RundownAPI.PieceStatusCode.UNKNOWN, isSticky: true, isGlobal: true, expectedDuration: 0, lifespan: PieceLifespan.WithinPart, externalId: layer._id, rundownId: protectString(''), sourceLayer: layer, outputLayer: undefined, sourceLayerId: layer._id, outputLayerId: '', _rank: 0, content: { timelineObjects: [] }, }) ) ) const globalAdLibActions = memoizedIsolatedAutorun( (currentRundownId: RundownId) => RundownBaselineAdLibActions.find( { rundownId: currentRundownId, partId: { $exists: false, }, }, { // @ts-ignore deep-property sort: { 'display._rank': 1 }, } ) .fetch() .map((action) => actionToAdLibPieceUi(action, sourceLayerLookup, outputLayerLookup)), 'globalAdLibActions', currentRundownId ) rundownBaselineAdLibs = rundownBaselineAdLibs .concat(globalAdLibActions) .sort((a, b) => a._rank - b._rank) .map((item) => { // automatically assign hotkeys based on adLibItem index const uiAdLib: AdLibPieceUi = _.clone(item) uiAdLib.isGlobal = true let sourceLayer = (uiAdLib.sourceLayer = (item.sourceLayerId && sourceLayerLookup[item.sourceLayerId]) || undefined) uiAdLib.outputLayer = (item.outputLayerId && outputLayerLookup[item.outputLayerId]) || undefined if (sourceLayer && sourceLayer.activateKeyboardHotkeys && sourceLayer.assignHotkeysToGlobalAdlibs) { let keyboardHotkeysList = sourceLayer.activateKeyboardHotkeys.split(',') const sourceHotKeyUseLayerId = sharedHotkeyList[sourceLayer.activateKeyboardHotkeys][0]._id || item.sourceLayerId if ((sourceHotKeyUse[sourceHotKeyUseLayerId] || 0) < keyboardHotkeysList.length) { uiAdLib.hotkey = keyboardHotkeysList[sourceHotKeyUse[sourceHotKeyUseLayerId] || 0] // add one to the usage hash table sourceHotKeyUse[sourceHotKeyUseLayerId] = (sourceHotKeyUse[sourceHotKeyUseLayerId] || 0) + 1 } } if (sourceLayer && sourceLayer.isHidden) { uiAdLib.isHidden = true } // always add them to the list return uiAdLib }) return rundownBaselineAdLibs.sort((a, b) => a._rank - b._rank) }, 'rundownBaselineAdLibs', currentRundown._id, sourceLayerLookup, props.showStyleBase.sourceLayers, sourceHotKeyUse ) } if ((props.filter as DashboardLayoutFilter).includeClearInRundownBaseline) { const rundownBaselineClearAdLibs = memoizedIsolatedAutorun( (sourceLayers: ISourceLayer[]) => { return sourceLayers .filter((i) => !!i.clearKeyboardHotkey) .sort((a, b) => a._rank - b._rank) .map((layer) => literal<AdLibPieceUi>({ _id: protectString(`clear_${layer._id}`), hotkey: layer.clearKeyboardHotkey ? layer.clearKeyboardHotkey.split(',')[0] : '', name: t('Clear {{layerName}}', { layerName: layer.abbreviation || layer.name }), status: RundownAPI.PieceStatusCode.UNKNOWN, isSticky: false, isClearSourceLayer: true, isGlobal: true, expectedDuration: 0, lifespan: PieceLifespan.WithinPart, externalId: layer._id, rundownId: protectString(''), sourceLayer: layer, outputLayer: undefined, sourceLayerId: layer._id, outputLayerId: '', _rank: 0, content: { timelineObjects: [] }, }) ) }, 'rundownBaselineClearAdLibs', props.showStyleBase.sourceLayers ) rundownBaselineAdLibs = rundownBaselineAdLibs.concat(rundownBaselineClearAdLibs) } } return { uiSegments: props.filter && props.filter.rundownBaseline === 'only' ? [] : uiSegments, liveSegment, sourceLayerLookup, rundownBaselineAdLibs, } } export const AdLibPanel = translateWithTracker<IAdLibPanelProps, IState, IAdLibPanelTrackedProps>( (props: Translated<IAdLibPanelProps>) => { const data = fetchAndFilter(props) return { ...data, studio: props.playlist.getStudio(), } }, (data, props: IAdLibPanelProps, nextProps: IAdLibPanelProps) => { return !_.isEqual(props, nextProps) } )( class AdLibPanel extends MeteorReactComponent<Translated<IAdLibPanelProps & IAdLibPanelTrackedProps>, IState> { usedHotkeys: Array<string> = [] constructor(props: Translated<IAdLibPanelProps & AdLibFetchAndFilterProps>) { super(props) this.state = { selectedSegment: undefined, searchFilter: undefined, followLive: true, } } componentDidMount() { if (this.props.liveSegment) { this.setState({ selectedSegment: this.props.liveSegment, }) } this.refreshKeyboardHotkeys() RundownViewEventBus.on(RundownViewEvents.REVEAL_IN_SHELF, this.onRevealInShelf) } componentDidUpdate(prevProps: IAdLibPanelProps & AdLibFetchAndFilterProps) { mousetrapHelper.unbindAll(this.usedHotkeys, 'keyup', this.props.hotkeyGroup) mousetrapHelper.unbindAll(this.usedHotkeys, 'keydown', this.props.hotkeyGroup) this.usedHotkeys.length = 0 if (this.props.liveSegment && this.props.liveSegment !== prevProps.liveSegment && this.state.followLive) { this.setState({ selectedSegment: this.props.liveSegment, }) } this.refreshKeyboardHotkeys() } componentWillUnmount() { this._cleanUp() mousetrapHelper.unbindAll(this.usedHotkeys, 'keyup', this.props.hotkeyGroup) mousetrapHelper.unbindAll(this.usedHotkeys, 'keydown', this.props.hotkeyGroup) this.usedHotkeys.length = 0 RundownViewEventBus.off(RundownViewEvents.REVEAL_IN_SHELF, this.onRevealInShelf) } refreshKeyboardHotkeys() { if (!this.props.studioMode) return if (!this.props.registerHotkeys) return const preventDefault = (e) => { e.preventDefault() } if (this.props.liveSegment && this.props.liveSegment.pieces) { this.props.liveSegment.pieces.forEach((item) => { if (item.hotkey) { mousetrapHelper.bind(item.hotkey, preventDefault, 'keydown', this.props.hotkeyGroup) mousetrapHelper.bind( item.hotkey, (e: mousetrap.ExtendedKeyboardEvent) => { preventDefault(e) this.onToggleAdLib(item, false, e) }, 'keyup', this.props.hotkeyGroup ) this.usedHotkeys.push(item.hotkey) const sourceLayer = this.props.sourceLayerLookup[item.sourceLayerId] if (sourceLayer && sourceLayer.isQueueable) { const queueHotkey = [RundownViewKbdShortcuts.ADLIB_QUEUE_MODIFIER, item.hotkey].join('+') mousetrapHelper.bind(queueHotkey, preventDefault, 'keydown', this.props.hotkeyGroup) mousetrapHelper.bind( queueHotkey, (e: mousetrap.ExtendedKeyboardEvent) => { preventDefault(e) this.onToggleAdLib(item, true, e) }, 'keyup', this.props.hotkeyGroup ) this.usedHotkeys.push(queueHotkey) } } }) } } onRevealInShelf = (e: RevealInShelfEvent) => { const { pieceId } = e let found = false if (pieceId) { const index = this.props.rundownBaselineAdLibs.findIndex((piece) => piece._id === pieceId) if (index >= 0) { found = true } else { this.props.uiSegments.forEach((segment) => { const index = segment.pieces.findIndex((piece) => piece._id === pieceId) if (index >= 0) { found = true } }) } if (found) { RundownViewEventBus.emit(RundownViewEvents.SWITCH_SHELF_TAB, { tab: this.props.filter ? `${ShelfTabs.ADLIB_LAYOUT_FILTER}_${this.props.filter._id}` : ShelfTabs.ADLIB, }) Meteor.setTimeout(() => { const el = document.querySelector(`.adlib-panel__list-view__list__segment__item[data-obj-id="${pieceId}"]`) if (el) { el.scrollIntoView({ behavior: 'smooth', }) } }, 100) } } } onFilterChange = (filter: string) => { this.setState({ searchFilter: filter, }) } onSelectAdLib = (piece: IAdLibListItem) => { this.props.onSelectPiece && this.props.onSelectPiece(piece as AdLibPieceUi) } onToggleAdLib = (adlibPiece: AdLibPieceUi, queue: boolean, e: any, mode?: IBlueprintActionTriggerMode) => { const { t } = this.props if (adlibPiece.invalid) { NotificationCenter.push( new Notification( t('Invalid AdLib'), NoticeLevel.WARNING, t('Cannot play this AdLib because it is marked as Invalid'), 'toggleAdLib' ) ) return } if (adlibPiece.floated) { NotificationCenter.push( new Notification( t('Floated AdLib'), NoticeLevel.WARNING, t('Cannot play this AdLib because it is marked as Floated'), 'toggleAdLib' ) ) return } if ( queue && this.props.sourceLayerLookup && this.props.sourceLayerLookup[adlibPiece.sourceLayerId] && !this.props.sourceLayerLookup[adlibPiece.sourceLayerId].isQueueable ) { console.log(`Item "${adlibPiece._id}" is on sourceLayer "${adlibPiece.sourceLayerId}" that is not queueable.`) return } if (this.props.playlist && this.props.playlist.currentPartInstanceId) { const currentPartInstanceId = this.props.playlist.currentPartInstanceId if (adlibPiece.isAction && adlibPiece.adlibAction) { const action = adlibPiece.adlibAction doUserAction(t, e, adlibPiece.isGlobal ? UserAction.START_GLOBAL_ADLIB : UserAction.START_ADLIB, (e) => MeteorCall.userAction.executeAction( e, this.props.playlist._id, action.actionId, action.userData, mode?.data ) ) } else if (!adlibPiece.isGlobal && !adlibPiece.isAction) { doUserAction(t, e, UserAction.START_ADLIB, (e) => MeteorCall.userAction.segmentAdLibPieceStart( e, this.props.playlist._id, currentPartInstanceId, adlibPiece._id, queue || false ) ) } else if (adlibPiece.isGlobal && !adlibPiece.isSticky) { doUserAction(t, e, UserAction.START_GLOBAL_ADLIB, (e) => MeteorCall.userAction.baselineAdLibPieceStart( e, this.props.playlist._id, currentPartInstanceId, adlibPiece._id, queue || false ) ) } else if (adlibPiece.isSticky) { doUserAction(t, e, UserAction.START_STICKY_PIECE, (e) => MeteorCall.userAction.sourceLayerStickyPieceStart(e, this.props.playlist._id, adlibPiece.sourceLayerId) ) } } } onClearAllSourceLayers = (sourceLayers: ISourceLayer[], e: any) => { const { t } = this.props if (this.props.playlist && this.props.playlist.currentPartInstanceId) { const currentPartInstanceId = this.props.playlist.currentPartInstanceId doUserAction(t, e, UserAction.CLEAR_SOURCELAYER, (e) => MeteorCall.userAction.sourceLayerOnPartStop( e, this.props.playlist._id, currentPartInstanceId, sourceLayers.map((i) => i._id) ) ) } } onSelectSegment = (segment: AdlibSegmentUi) => { this.setState({ selectedSegment: segment, followLive: this.props.liveSegment ? segment._id === this.props.liveSegment._id : true, }) } renderSegmentList() { return this.props.uiSegments.map((item) => { return ( <li className={ClassNames('adlib-panel__segments__segment', { live: item.isLive, next: item.isNext && !item.isLive, past: item.parts.reduce((memo, part) => { return part.timings?.startedPlayback && part.timings?.duration ? memo : false }, true) === true, })} onClick={(e) => this.onSelectSegment(item)} key={unprotectString(item._id)} tabIndex={0} > {item.name} </li> ) }) } renderListView(withSegments?: boolean) { return ( <React.Fragment> <AdLibPanelToolbar onFilterChange={this.onFilterChange} noSegments={!withSegments} /> <AdLibListView uiSegments={this.props.uiSegments} rundownAdLibs={this.props.rundownBaselineAdLibs} onSelectAdLib={this.onSelectAdLib} onToggleAdLib={this.onToggleAdLib} selectedPiece={this.props.selectedPiece} selectedSegment={this.state.selectedSegment} showStyleBase={this.props.showStyleBase} searchFilter={this.state.searchFilter} filter={this.props.filter as RundownLayoutFilter} playlist={this.props.playlist} studio={this.props.studio} noSegments={!withSegments} /> </React.Fragment> ) } render() { if (this.props.visible) { if (!this.props.uiSegments || !this.props.playlist) { return <Spinner /> } else { return ( <div className="adlib-panel super-dark" data-tab-id={ this.props.filter ? `${ShelfTabs.ADLIB_LAYOUT_FILTER}_${this.props.filter._id}` : ShelfTabs.ADLIB } > {this.props.uiSegments.length > 30 && ( <ul className="adlib-panel__segments">{this.renderSegmentList()}</ul> )} {this.renderListView(this.props.uiSegments.length > 30)} </div> ) } } return null } } )
the_stack
import Storex from '@worldbrain/storex' import { StorageModule, StorageModuleConfig, } from '@worldbrain/storex-pattern-modules' import { COLLECTION_NAMES as TAG_COLLECTION_NAMES } from '@worldbrain/memex-storage/lib/tags/constants' import { COLLECTION_NAMES as ANNOT_COLLECTION_NAMES } from '@worldbrain/memex-storage/lib/annotations/constants' import { SearchParams as OldSearchParams, SearchResult as OldSearchResult, } from '../types' import { AnnotSearchParams, AnnotPage, PageUrlsByDay, SocialSearchParams, } from './types' import { PageUrlMapperPlugin } from './page-url-mapper' import { reshapeParamsForOldSearch } from './utils' import { AnnotationsListPlugin } from './annots-list' import { SocialSearchPlugin } from './social-search' import { SocialPage } from 'src/social-integration/types' import { SuggestPlugin, SuggestType } from '../plugins/suggest' import { Annotation } from 'src/annotations/types' export interface SearchStorageProps { storageManager: Storex annotationsColl?: string legacySearch: (params: any) => Promise<any> } export interface Interaction { time: number url: string } export type LegacySearch = ( params: OldSearchParams, ) => Promise<{ ids: OldSearchResult[] totalCount: number }> export default class SearchStorage extends StorageModule { static TAGS_COLL = TAG_COLLECTION_NAMES.tag static BMS_COLL = ANNOT_COLLECTION_NAMES.bookmark private legacySearch constructor({ storageManager, legacySearch }: SearchStorageProps) { super({ storageManager }) this.legacySearch = legacySearch } getConfig = (): StorageModuleConfig => ({ operations: { findAnnotBookmarksByUrl: { collection: SearchStorage.BMS_COLL, operation: 'findObjects', args: { url: { $in: '$annotUrls:string[]' } }, }, findAnnotTagsByUrl: { collection: SearchStorage.TAGS_COLL, operation: 'findObjects', args: [{ url: { $in: '$annotUrls:string[]' } }], }, searchAnnotsByDay: { operation: AnnotationsListPlugin.LIST_BY_DAY_OP_ID, args: ['$params:any'], }, [PageUrlMapperPlugin.MAP_OP_SOCIAL_ID]: { operation: PageUrlMapperPlugin.MAP_OP_SOCIAL_ID, args: [ '$results:any', { base64Img: '$base64Img:boolean', upperTimeBound: '$endDate:number', }, ], }, [SocialSearchPlugin.MAP_POST_IDS_OP_ID]: { operation: SocialSearchPlugin.MAP_POST_IDS_OP_ID, args: ['$postIds:number[]'], }, [SocialSearchPlugin.SEARCH_OP_ID]: { operation: SocialSearchPlugin.SEARCH_OP_ID, args: ['$params:any'], }, [AnnotationsListPlugin.TERMS_SEARCH_OP_ID]: { operation: AnnotationsListPlugin.TERMS_SEARCH_OP_ID, args: ['$params:any'], }, [PageUrlMapperPlugin.MAP_OP_ID]: { operation: PageUrlMapperPlugin.MAP_OP_ID, args: [ '$pageUrls:string[]', { base64Img: '$base64Img:boolean', upperTimeBound: '$upperTimeBound:number', latestTimes: '$latestTimes:number[]', }, ], }, [SuggestPlugin.SUGGEST_OP_ID]: { operation: SuggestPlugin.SUGGEST_OP_ID, args: { query: '$query:string', type: '$type:string', limit: '$limit:number', }, }, [SuggestPlugin.SUGGEST_EXT_OP_ID]: { operation: SuggestPlugin.SUGGEST_EXT_OP_ID, args: { notInclude: '$notInclude:string[]', type: '$type:string', limit: '$limit:number', }, }, }, }) suggest = (args: { query: string; type: SuggestType; limit?: number }) => this.operation(SuggestPlugin.SUGGEST_OP_ID, args) suggestExtended = (args: { notInclude?: string[] type: SuggestType limit?: number }) => this.operation(SuggestPlugin.SUGGEST_EXT_OP_ID, args) private async findAnnotsDisplayData( annotUrls: string[], ): Promise<{ annotsToTags: Map<string, string[]> bmUrls: Set<string> }> { const bookmarks = await this.operation('findAnnotBookmarksByUrl', { annotUrls, }) const bmUrls = new Set<string>(bookmarks.map((bm) => bm.url)) const tags = await this.operation('findAnnotTagsByUrl', { annotUrls }) const annotsToTags = new Map<string, string[]>() tags.forEach(({ name, url }) => { const current = annotsToTags.get(url) || [] annotsToTags.set(url, [...current, name]) }) return { annotsToTags, bmUrls } } async getMergedAnnotsPages( pageUrls: string[], params: AnnotSearchParams, postPrefix = 'socialPosts:', ): Promise<AnnotPage[]> { const results: Map<string, any> = new Map() const pageIds: string[] = [] const postIds: number[] = [] // Split into post and page annots pageUrls.forEach((url) => url.startsWith(postPrefix) ? postIds.push(Number(url.split(postPrefix)[1])) : pageIds.push(url), ) const pages: AnnotPage[] = await this.operation( PageUrlMapperPlugin.MAP_OP_ID, { pageUrls: pageIds, base64Img: params.base64Img, upperTimeBound: params.endDate, }, ) pages.forEach((page) => results.set(page.url, page)) const socialResults: Map< number, Map<string, SocialPage> > = await this.operation(SocialSearchPlugin.MAP_POST_IDS_OP_ID, { postIds, }) const socialPages: SocialPage[] = await this.operation( PageUrlMapperPlugin.MAP_OP_SOCIAL_ID, { results: socialResults, base64Img: params.base64Img, upperTimeBound: params.endDate, }, ) socialPages.forEach((page) => results.set(postPrefix + page.id.toString(), page), ) return pageUrls .map((url) => { const result = results.get(url) if (!result) { return } return { ...result, pageId: url, } }) .filter((page) => page !== undefined) } /** * Searches for annotations which match the passed params and returns * them clustered by day. * @param params Annotation search params * @returns an object containing annotsByDay ( Timestamp as key and AnnotsByPageUrl as values ) * and docs which is of type AnnotPage[]. */ private async searchAnnotsByDay(params: AnnotSearchParams) { const results: Map< number, Map<string, Annotation[]> > = await this.operation('searchAnnotsByDay', { params }) let pageUrls = new Set<string>() for (const [, annotsByPage] of results) { pageUrls = new Set([...pageUrls, ...annotsByPage.keys()]) } const pages: AnnotPage[] = await this.getMergedAnnotsPages( [...pageUrls], params, ) const clusteredResults: PageUrlsByDay = {} // Create reverse annots map pointing from each annot's PK to their data // related to which page, day cluster they belong to + display data. const reverseAnnotMap = new Map<string, [number, string, Annotation]>() for (const [day, annotsByPage] of results) { clusteredResults[day] = {} for (const [pageUrl, annots] of annotsByPage) { annots.forEach((annot) => reverseAnnotMap.set(annot.url, [day, pageUrl, annot]), ) } } // Get display data for all annots then map them back to their clusters const { annotsToTags, bmUrls } = await this.findAnnotsDisplayData([ ...reverseAnnotMap.keys(), ]) reverseAnnotMap.forEach(([day, pageUrl, annot]) => { // Delete any annots containing excluded tags const tags = annotsToTags.get(annot.url) || [] // Skip current annot if contains filtered tags if ( params.tagsExc && params.tagsExc.length && params.tagsExc.some((tag) => tags.includes(tag)) ) { return } const currentAnnots = clusteredResults[day][pageUrl] || [] clusteredResults[day][pageUrl] = [ ...currentAnnots, { ...annot, tags, hasBookmark: bmUrls.has(annot.url), } as any, ] }) // Remove any annots without matching pages (keep data integrity regardless of DB) const validUrls = new Set(pages.map((page) => page.pageId)) for (const day of Object.keys(clusteredResults)) { // Remove any empty days (they might have had all annots filtered out due to excluded tags) if (!Object.keys(clusteredResults[day]).length) { delete clusteredResults[day] continue } for (const url of Object.keys(clusteredResults[day])) { if (!validUrls.has(url)) { delete clusteredResults[day][url] } } } return { annotsByDay: clusteredResults, docs: pages, } } private async searchTermsAnnots(params: AnnotSearchParams) { const results: Map<string, Annotation[]> = await this.operation( AnnotationsListPlugin.TERMS_SEARCH_OP_ID, { params, }, ) const pages: AnnotPage[] = await this.getMergedAnnotsPages( [...results.keys()], params, ) const annotUrls = [] .concat(...results.values()) .map((annot) => annot.url) // Get display data for all annots then map them back to their clusters const { annotsToTags, bmUrls } = await this.findAnnotsDisplayData( annotUrls, ) return { docs: pages.map((page) => { const annotations = results.get(page.pageId).map((annot) => ({ ...annot, tags: annotsToTags.get(annot.url) || [], hasBookmark: bmUrls.has(annot.url), })) return { ...page, annotations } }), } } async searchAnnots( params: AnnotSearchParams, ): Promise<{ docs: AnnotPage[]; annotsByDay?: PageUrlsByDay }> { if (!params.termsInc || !params.termsInc.length) { return this.searchAnnotsByDay(params) } return this.searchTermsAnnots(params) } async searchPages(params: AnnotSearchParams): Promise<AnnotPage[]> { const searchParams = reshapeParamsForOldSearch(params) const { ids } = await this.legacySearch(searchParams) if (!ids.length) { return [] } // Terms search requires lookup of the latest interaction times for scoring, // so it returns triples. The 3rd index is the latest time (to avoid redoing those queries). const latestTimes = ids[0].length === 3 ? ids.map(([, , time]) => time) : undefined return this.operation(PageUrlMapperPlugin.MAP_OP_ID, { pageUrls: ids.map(([url]) => url), upperTimeBound: params.endDate, base64Img: params.base64Img, latestTimes, }) } async searchSocial(params: SocialSearchParams) { const results: Map< number, SocialPage > = await this.operation(SocialSearchPlugin.SEARCH_OP_ID, { params }) if (!results.size) { return [] } return this.operation(PageUrlMapperPlugin.MAP_OP_SOCIAL_ID, { results, base64Img: params.base64Img, upperTimeBound: params.endDate, }) } }
the_stack
// ENFORCED (💪) indicates that the field is enforced by the type system, and it should be impossible for any type // assignable to T to fail JSON validation because of constraints that this field introduces. // For example, the required field on objects is ENFORCED because a type assignable to T is guaranteed to contain all // fields marked required. // PARTIALLY ENFORCED (🔓) indicates that the field is partially enforced by the type system, but it may be possible // to assign a type to T that fails validation against s. // For example, arrays with the additionalItems parameter are PARTIALLY ENFORCED becuase (currently) every element in // the validated type can be assigned to the additionalItems type, when only items after items.length should be // validated against this schema. // NOT ENFORCED (⚠️) indicates that the field is not enforced by the type system. This is either because it's // impossible to do so efficiently given Typescript, or because I haven't figured out how yet. // If the latter, hopefully I've included a comment. // For example, the pattern constraint in a string type is NOT ENFORCED because there's no reasonable way to express a // type that means "a string that matches this regex". // NO ENFORCEMENT NEEDED (🤷) (means that this field does not add any constraints to a JSON schema so is essentially a // comment. // NOT SUPPORTED (❌) means you can't currently define a TsjsonSchema that includes this validation keyword :( // Symbol needed to compile a program that passes typechecking but still fails schema validation. // This would be much nicer as a unique symbol but we run into issues exporting schemas // when we do that. Ideas welcome! export const InternalTypeSymbol = "#__internaltype__#"; export type JsonValue = | { [property: string]: JsonValue } | boolean | readonly JsonValue[] | null | number | string; // Given types T and U, return T transformed such that the fields in U are made required type PartialRequire<T, U extends keyof T> = T & Required<Pick<T, U>>; // Given a union type U, return the intersection of all its component types. // For example, if U = A | B | C, then UnionToIntersection<U> = A & B & C. // UnionToIntersection magic taken from https://stackoverflow.com/a/50375286/2407869 // eslint-disable-next-line @typescript-eslint/no-explicit-any type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( k: infer I ) => void ? I : never; export interface SchemaLike { [InternalTypeSymbol]: unknown; } type SimpleType = | "array" | "boolean" | "integer" | "null" | "number" | "object" | "string"; // If a const field is specified, then the value must be exactly that type. // Otherwise, it can be any valid JSON value. type ConstConstraint< Const extends JsonValue | undefined > = Const extends JsonValue ? Const : unknown; // Could possibly replace all these unknows with JsonValues, but it makes the derived types annoying. type SimpleTypeConstraint< Type extends SimpleType | undefined > = Type extends "array" ? Array<JsonValue> : Type extends "boolean" ? boolean : Type extends "integer" | "number" ? number : Type extends "null" ? null : Type extends "object" ? { [k: string]: unknown } : Type extends "string" ? string : unknown; type EnumConstraint< Enum extends readonly JsonValue[] | undefined > = Enum extends readonly JsonValue[] ? Enum[number] : unknown; // optional by default, unless explicitly in the required list type PropertiesConstraint< Properties extends { [k: string]: SchemaLike } | undefined, Required extends readonly (keyof Properties)[] | undefined > = Properties extends { [k: string]: SchemaLike } ? Required extends readonly (keyof Properties)[] ? PartialRequire< Partial< { [P in keyof Properties]: Properties[P][typeof InternalTypeSymbol] } >, Required[number] > : Partial< // optional by default, unless explicitly in the required list { [P in keyof Properties]: Properties[P][typeof InternalTypeSymbol] } > : unknown; type AdditionalPropertiesConstraint< AdditionalProperties extends SchemaLike | undefined > = AdditionalProperties extends SchemaLike ? { [k: string]: AdditionalProperties[typeof InternalTypeSymbol] } : unknown; // if items is a schema, then every element conforms to it. // If items is a list, then either additionalItems is supplied, in which case every element is either one of items[number] or additionalItems // or additionalItems is not supplied, in which case we just get the union of all item types. // These isn't strict enough; instead of Items[number], it would be better to have [...Items, *AdditionalItems] // since when items are specified in a list, ordering is important. type ItemsConstraint< Items extends (SchemaLike | readonly SchemaLike[]) | undefined, AdditionalItems extends SchemaLike | undefined > = Items extends SchemaLike ? Array<Items[typeof InternalTypeSymbol]> : Items extends readonly SchemaLike[] ? AdditionalItems extends SchemaLike // ? Array< | Items[number][typeof InternalTypeSymbol] | AdditionalItems[typeof InternalTypeSymbol] > : Array<Items[number][typeof InternalTypeSymbol]> : unknown; type AllOfConstraint< AllOf extends readonly SchemaLike[] | undefined > = AllOf extends readonly SchemaLike[] ? UnionToIntersection<AllOf[number][typeof InternalTypeSymbol]> : unknown; type AnyOfConstraint< AnyOf extends readonly SchemaLike[] | undefined > = AnyOf extends readonly SchemaLike[] ? AnyOf[number][typeof InternalTypeSymbol] : unknown; // This isn't strict enough; should be XOR instead of Or type OneOfConstraint< OneOf extends readonly SchemaLike[] | undefined > = AnyOfConstraint<OneOf>; // If both `then` and `else` are specified, then we know that the type must be either Then or Else. // If only one or 0 are specified, we don't know which one the `if` matched, so we don't add any constraints. type IfThenElseConstraint< Then extends SchemaLike | undefined, Else extends SchemaLike | undefined > = Then extends SchemaLike ? Else extends SchemaLike ? Then[typeof InternalTypeSymbol] | Else[typeof InternalTypeSymbol] : unknown : unknown; // Make it impossible to define an invalid schema, and also impossible to define a schema that just doesn't make sense // (e.g. no reason to have a minimum constraint on a string.) export interface Schema< Type extends SimpleType | undefined = undefined, // type can be either a single type or a list of types (TODO allow it to be a list of types) (| readonly SimpleType[]) Properties extends { [k: string]: SchemaLike } | undefined = undefined, Items extends (SchemaLike | readonly SchemaLike[]) | undefined = undefined, AdditionalItems extends SchemaLike | undefined = undefined, AdditionalProperties extends SchemaLike | undefined = undefined, Required extends readonly (keyof Properties)[] | undefined = undefined, Const extends JsonValue | undefined = undefined, Enum extends readonly JsonValue[] | undefined = undefined, AllOf extends readonly SchemaLike[] | undefined = undefined, AnyOf extends readonly SchemaLike[] | undefined = undefined, OneOf extends readonly SchemaLike[] | undefined = undefined, Not extends SchemaLike | undefined = undefined, // not yet enforced If extends SchemaLike | undefined = undefined, Then extends SchemaLike | undefined = undefined, Else extends SchemaLike | undefined = undefined, Definitions extends { [k: string]: SchemaLike } | undefined = undefined, // not yet enforced via refs Ref extends string | undefined = undefined, // ref just gives unknown types for now. TODO: connect with definitions and get proper recursive types here. Dependencies extends | { [k in keyof Properties]: SchemaLike | keyof Properties[] } | undefined = undefined, CalculatedType = ConstConstraint<Const> & SimpleTypeConstraint<Type> & EnumConstraint<Enum> & PropertiesConstraint<Properties, Required> & AdditionalPropertiesConstraint<AdditionalProperties> & ItemsConstraint<Items, AdditionalItems> & AllOfConstraint<AllOf> & AnyOfConstraint<AnyOf> & OneOfConstraint<OneOf> & IfThenElseConstraint<Then, Else> > { $id?: string; // 🤷 adds no constraints, can be in any schema. $schema?: "http://json-schema.org/draft-07/schema#"; // 🤷 if you want to specify the schema, it's got to be draft-07 right now! $ref?: Ref; // ⚠️ not yet enforced. Going to have to try to figure out how to do this without breaking semantics. $comment?: string; // 🤷 adds no constraints, can be in any schema title?: string; // 🤷 adds no constraints, can be in any schema description?: string; // 🤷 adds no constraints, can be in any schema default?: CalculatedType; // 💪 Can only be assigned types that the rest of the schema validates readOnly?: boolean; // 🤷 examples?: JsonValue[]; // 🤷 multipleOf?: Type extends "number" | "integer" ? number : never; // ⚠️ only makes sense for number/integer types maximum?: Type extends "number" | "integer" ? number : never; // ⚠️ only makes sense for number/integer types exclusiveMaximum?: Type extends "number" | "integer" ? number : never; // ⚠️ only makes sense for number/integer types minimum?: Type extends "number" | "integer" ? number : never; // ⚠️ only makes sense for number/integer types exclusiveMinimum?: Type extends "number" | "integer" ? number : never; // ⚠️ only makes sense for number/integer types minLength?: Type extends "string" ? number : never; // ⚠️ only makes sense for string types maxLength?: Type extends "string" ? number : never; // ⚠️ only makes sense for string types pattern?: Type extends "string" ? string : never; // ⚠️ only makes sense for string types additionalItems?: Type extends "array" // 🔓 only makes sense for array types ? Items extends SchemaLike // where the items field is not a single schema ? never : AdditionalItems : never; items?: Type extends "array" ? Items : never; // 🔓 only makes sense for array types maxItems?: Type extends "array" ? number : never; // ⚠️ only makes sense for array types minItems?: Type extends "array" ? number : never; // ⚠️ only makes sense for array types uniqueItems?: Type extends "array" ? boolean : never; // ⚠️ only makes sense for array types contains?: Type extends "array" ? SchemaLike : never; // ⚠️ only makes sense for array types maxProperties?: Type extends "object" ? number : never; // ⚠️ only makes sense for object types minProperties?: Type extends "object" ? number : never; // ⚠️ only makes sense for object types required?: Type extends "object" ? Required : never; // 💪 only makes sense for object types additionalProperties?: Type extends "object" ? AdditionalProperties : never; // 💪 only makes sense for object types definitions?: Definitions; // ⚠️ not yet enforced properties?: Type extends "object" ? Properties : never; // 💪 only makes sense for object types patternProperties?: Type extends "object" ? { [k: string]: SchemaLike } : never; // ⚠️ only makes sense for object types dependencies?: Type extends "object" ? Dependencies : never; // ⚠️ not yet enforced propertyNames?: Type extends "object" ? SchemaLike : never; // ⚠️ only makes sense for object types const?: Const; // 💪 enum?: Enum; // 💪 type?: Type; // 💪 format?: Type extends "string" ? string : never; // ⚠️ only makes sense for string types contentMediaType?: Type extends "string" ? string : never; // 🤷 contentEncoding?: Type extends "string" ? string : never; // 🤷 if?: Then extends SchemaLike // 🤷 ? If : Else extends SchemaLike ? If : never; // If `if` is specified, then at least one of `then` or `else` should be specified. then?: If extends SchemaLike ? Then : never; // 💪 Only matters if `if` is supplied else?: If extends SchemaLike ? Else : never; // 💪 Only matters if `if` is supplied allOf?: AllOf; // 💪 anyOf?: AnyOf; // 💪 oneOf?: OneOf; // 🔓 not?: Not; // ⚠️ [InternalTypeSymbol]?: CalculatedType; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const createSchema = < Type extends SimpleType | undefined = undefined, Properties extends { [k: string]: SchemaLike } | undefined = undefined, Items extends (SchemaLike | readonly SchemaLike[]) | undefined = undefined, AdditionalItems extends SchemaLike | undefined = undefined, AdditionalProperties extends SchemaLike | undefined = undefined, Required extends readonly (keyof Properties)[] | undefined = undefined, Const extends JsonValue | undefined = undefined, Enum extends readonly JsonValue[] | undefined = undefined, AllOf extends readonly SchemaLike[] | undefined = undefined, AnyOf extends readonly SchemaLike[] | undefined = undefined, OneOf extends readonly SchemaLike[] | undefined = undefined, Not extends SchemaLike | undefined = undefined, If extends SchemaLike | undefined = undefined, Then extends SchemaLike | undefined = undefined, Else extends SchemaLike | undefined = undefined, Definitions extends { [k: string]: SchemaLike } | undefined = undefined, Ref extends string | undefined = undefined, Dependencies extends | { [k in keyof Properties]: SchemaLike | keyof Properties[] } | undefined = undefined, BooleanValue extends boolean | undefined = undefined >( schema: | Schema< Type, Properties, Items, AdditionalItems, AdditionalProperties, Required, Const, Enum, AllOf, AnyOf, OneOf, Not, If, Then, Else, Definitions, Ref, Dependencies > | BooleanValue ) => { type schemaType = Exclude<typeof schema, BooleanValue>; type InternalType = BooleanValue extends true ? { "#__internaltype__#": JsonValue } : BooleanValue extends false ? { "#__internaltype__#": never } : { "#__internaltype__#": NonNullable< schemaType[typeof InternalTypeSymbol] >; }; return schema as schemaType & InternalType; };
the_stack
import * as converter from "./converter"; import { printQuickInfo } from "./inspect"; let conv: converter.Converter; beforeAll(() => { conv = converter.createConverter(); }); afterAll(() => { if (conv) { conv.close(); } }); describe("inspect", () => { it("no info", () => { const src = ""; const info = conv.inspect(``, src, 0); expect(info).toBeUndefined(); }); it("let number", () => { const src = "/** xys is a great variable */\nlet xyz = 10;"; const position = src.indexOf("xyz ="); const info = conv.inspect(``, src, position); expect(info).toEqual({ displayParts: [ { kind: "keyword", text: "let", }, { kind: "space", text: " ", }, { kind: "localName", text: "xyz", }, { kind: "punctuation", text: ":", }, { kind: "space", text: " ", }, { kind: "keyword", text: "number", }, ], documentation: [ { kind: "text", text: "xys is a great variable", }, ], kind: "let", kindModifiers: "", tags: undefined, textSpan: { length: 3, // TODO: Cancel the length of prefix. start: position, }, }); expect(printQuickInfo(info)).toEqual( ["let xyz: number", "", "xys is a great variable"].join("\n") ); }); it("var boolean", () => { const src = "/** klm is a great boolean */\nvar klm = true;"; const position = src.indexOf("klm ="); const info = conv.inspect(``, src, position); expect(info).toEqual({ displayParts: [ { kind: "keyword", text: "var", }, { kind: "space", text: " ", }, { kind: "localName", text: "klm", }, { kind: "punctuation", text: ":", }, { kind: "space", text: " ", }, { kind: "keyword", text: "boolean", }, ], documentation: [ { kind: "text", text: "klm is a great boolean", }, ], kind: "var", kindModifiers: "", tags: undefined, textSpan: { length: 3, // TODO: Cancel the length of prefix. start: position, }, }); expect(printQuickInfo(info)).toEqual( ["var klm: boolean", "", "klm is a great boolean"].join("\n") ); }); it("const string", () => { const src = "/** abc is a great string */\nconst abc = 'hello';"; const position = src.indexOf("abc ="); const info = conv.inspect(``, src, position); expect(info).toEqual({ displayParts: [ { kind: "keyword", text: "const", }, { kind: "space", text: " ", }, { kind: "localName", text: "abc", }, { kind: "punctuation", text: ":", }, { kind: "space", text: " ", }, { kind: "stringLiteral", text: '"hello"', }, ], documentation: [ { kind: "text", text: "abc is a great string", }, ], kind: "const", kindModifiers: "", tags: undefined, textSpan: { length: 3, // TODO: Cancel the length of prefix. start: position, }, }); expect(printQuickInfo(info)).toEqual( ['const abc: "hello"', "", "abc is a great string"].join("\n") ); }); it("std method", () => { const src = 'let s = "abc"; s.indexOf("b");'; const position = src.indexOf("indexOf("); const info = conv.inspect(``, src, position); expect(info).toEqual({ kind: "method", kindModifiers: "declare", textSpan: { start: 17, length: 7 }, displayParts: [ { text: "(", kind: "punctuation" }, { text: "method", kind: "text" }, { text: ")", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "String", kind: "localName" }, { text: ".", kind: "punctuation" }, { text: "indexOf", kind: "methodName" }, { text: "(", kind: "punctuation" }, { text: "searchString", kind: "parameterName" }, { text: ":", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "string", kind: "keyword" }, { text: ",", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "position", kind: "parameterName" }, { text: "?", kind: "punctuation" }, { text: ":", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "number", kind: "keyword" }, { text: ")", kind: "punctuation" }, { text: ":", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "number", kind: "keyword" }, ], documentation: [ { text: "Returns the position of the first occurrence of a substring.", kind: "text", }, ], tags: [ { name: "param", text: "searchString The substring to search for in the string", }, { name: "param", text: "position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.", }, ], }); expect(printQuickInfo(info)).toEqual( [ "(method) String.indexOf(searchString: string, position?: number): number", "", "Returns the position of the first occurrence of a substring.", "@param searchString The substring to search for in the string", "@param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.", ].join("\n") ); }); it("std constructor with override", () => { const src = "let m = new Map();"; const position = src.indexOf("Map("); const info = conv.inspect(``, src, position); expect(info).toEqual({ kind: "var", kindModifiers: "declare", textSpan: { start: 12, length: 3 }, displayParts: [ { text: "var", kind: "keyword" }, { text: " ", kind: "space" }, { text: "Map", kind: "localName" }, { text: ":", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "MapConstructor", kind: "interfaceName" }, { text: "\n", kind: "lineBreak" }, { text: "new", kind: "keyword" }, { text: " ", kind: "space" }, { text: "(", kind: "punctuation" }, { text: ")", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "=>", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "Map", kind: "localName" }, { text: "<", kind: "punctuation" }, { text: "any", kind: "keyword" }, { text: ",", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "any", kind: "keyword" }, { text: ">", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "(", kind: "punctuation" }, { text: "+", kind: "operator" }, { text: "2", kind: "numericLiteral" }, { text: " ", kind: "space" }, { text: "overloads", kind: "text" }, { text: ")", kind: "punctuation" }, ], documentation: [], }); expect(printQuickInfo(info)).toEqual( [ "var Map: MapConstructor", "new () => Map<any, any> (+2 overloads)", ].join("\n") ); }); it("let interface", () => { const src = "let m: Map<string, number>;"; const position = src.indexOf("m:"); const info = conv.inspect(``, src, position); expect(info).toEqual({ kind: "let", kindModifiers: "", textSpan: { start: 4, length: 1 }, displayParts: [ { text: "let", kind: "keyword" }, { text: " ", kind: "space" }, { text: "m", kind: "localName" }, { text: ":", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "Map", kind: "localName" }, { text: "<", kind: "punctuation" }, { text: "string", kind: "keyword" }, { text: ",", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "number", kind: "keyword" }, { text: ">", kind: "punctuation" }, ], documentation: [], }); expect(printQuickInfo(info)).toEqual("let m: Map<string, number>"); }); it("std interface", () => { const src = "let m: Map<string, number>;"; const position = src.indexOf("Map<"); const info = conv.inspect(``, src, position); expect(info).toEqual({ kind: "var", kindModifiers: "declare", textSpan: { start: 7, length: 3 }, displayParts: [ { text: "interface", kind: "keyword" }, { text: " ", kind: "space" }, { text: "Map", kind: "localName" }, { text: "<", kind: "punctuation" }, { text: "K", kind: "typeParameterName" }, { text: ",", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "V", kind: "typeParameterName" }, { text: ">", kind: "punctuation" }, ], documentation: [], }); expect(printQuickInfo(info)).toEqual("interface Map<K, V>"); }); it("enum member", () => { const src = "enum myenum {key1, key2} myenum.key1;"; const position = src.indexOf("key1;"); const info = conv.inspect(``, src, position); expect(info).toEqual({ kind: "enum member", kindModifiers: "", textSpan: { start: 32, length: 4 }, displayParts: [ { text: "(", kind: "punctuation" }, { text: "enum member", kind: "text" }, { text: ")", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "myenum", kind: "enumName" }, { text: ".", kind: "punctuation" }, { text: "key1", kind: "enumMemberName" }, { text: " ", kind: "space" }, { text: "=", kind: "operator" }, { text: " ", kind: "space" }, { text: "0", kind: "numericLiteral" }, ], documentation: [], }); expect(printQuickInfo(info)).toEqual("(enum member) myenum.key1 = 0"); }); });
the_stack
import * as rp from 'request-promise'; import { flattenDeploymentOperationError } from './Utils'; interface ManagedService { producerProjectId?: string; serviceName?: string; } interface ListServicesResponse { services?: ManagedService[]; } interface EnableServiceRequest { consumerId?: string; } export default class Gapi { public static sautil = class { /** * Returns a list of services that are needed but not enabled for the given project. */ public static async getServicesToEnable(project: string, token: string, enableAttempts: number) { const consumerId = encodeURIComponent(`project:${project}`); const enabledServices = await rp( { headers: { 'Authorization': `Bearer ${token}`, 'content-type': 'application/json' }, method: 'GET', uri: `https://servicemanagement.googleapis.com/v1/services?pageSize=100&consumerId=${consumerId}`, } ).then( response => JSON.parse(response) as ListServicesResponse, badResult => { if (enableAttempts > 10) { throw new Error('Errors listing services: ' + badResult); } else { return [] as ListServicesResponse; } }); const servicesToEnable = new Set([ 'deploymentmanager.googleapis.com', 'container.googleapis.com', 'cloudresourcemanager.googleapis.com', 'endpoints.googleapis.com', 'iam.googleapis.com', 'sourcerepo.googleapis.com', 'ml.googleapis.com', 'file.googleapis.com', 'sqladmin.googleapis.com', ]); if (enabledServices.services !== undefined) { for (const k of Array.from(servicesToEnable.keys())) { if (enabledServices!.services!.find(s => s.serviceName === k)) { servicesToEnable.delete(k); } } } return Array.from(servicesToEnable); } public static async enableServices(project: string, token: string, serviceName: string) { return rp( { body: JSON.stringify({ consumerId: `project:${project}` }), headers: { 'Authorization': `Bearer ${token}`, 'content-type': 'application/json' }, method: 'POST', uri: `https://servicemanagement.googleapis.com/v1/services/${serviceName}:enable`, } ).then(response => JSON.parse(response) as EnableServiceRequest, badResult => { throw new Error('Errors enabling service: ' + badResult); }); } }; public static deploymentmanager = class { public static async insert(project: string, resource: {}) { await this._load(); return this._deploymentManager.insert({ project, resource } as any) .then(r => r.result, badResult => { throw new Error( 'Errors creating new deployment: ' + flattenDeploymentOperationError(badResult.result)); }); } public static async get(project: string, deploymentName: string) { await this._load(); return this._deploymentManager.get({ project, deployment: deploymentName }) .then(r => r.result, badResult => { throw new Error( 'Errors creating new deployment: ' + flattenDeploymentOperationError(badResult.result)); }); } private static _deploymentManager: gapi.client.deploymentmanager.DeploymentsResource; private static async _load() { await Gapi.load(); return new Promise(resolve => gapi.client.load('deploymentmanager', 'v2', () => resolve())) .then(() => { this._deploymentManager = (gapi.client as any).deploymentmanager.deployments; }); } }; public static cloudresourcemanager = class { public static async getProjectNumber(projectId: string) { await Gapi.load(); return gapi.client.request({ headers: {'X-Goog-User-Project': projectId}, path: `https://cloudresourcemanager.googleapis.com/v1/projects/${projectId}` }).then(response => (response.result as any).projectNumber as number, badResult => { throw new Error('Error trying to get the project number: ' + JSON.stringify(badResult)); }); } public static async getIamPolicy(projectId: string) { await Gapi.load(); return gapi.client.request({ headers: {'X-Goog-User-Project': projectId}, method: 'POST', path: `https://cloudresourcemanager.googleapis.com/v1/projects/${projectId}:getIamPolicy` }).then(response => response.result, badResult => { throw new Error('Error trying to get iam policy: ' + JSON.stringify(badResult)); }); } public static async setIamPolicy(projectId: string, policy: object) { await Gapi.load(); return gapi.client.request({ body: { 'policy': policy }, headers: {'X-Goog-User-Project': projectId}, method: 'POST', path: `https://cloudresourcemanager.googleapis.com/v1/projects/${projectId}:setIamPolicy` }).then(response => (response.result as any).bindings, badResult => { throw new Error('Error trying to set iam policy: ' + JSON.stringify(badResult)); }); } }; public static iam = class { public static async getServiceAccountId(projectId: string, saEmail: string) { await Gapi.load(); return gapi.client.request({ headers: {'X-Goog-User-Project': projectId}, path: `https://iam.googleapis.com/v1/projects/${projectId}/serviceAccounts/${saEmail}` }).then(response => (response.result as any).uniqueId, badResult => null); } public static async createServiceAccount(projectId: string, accountId: string) { await Gapi.load(); return gapi.client.request({ body: { 'accountId': accountId, 'serviceAccount': { 'displayName': 'kubeflow service account' } }, headers: {'X-Goog-User-Project': projectId}, method: 'POST', path: `https://iam.googleapis.com/v1/projects/${projectId}/serviceAccounts` }).then(response => (response.result as any).uniqueId, badResult => { throw new Error('Error trying to create service account: ' + JSON.stringify(badResult)); }); } public static async getServiceAccountIAM(projectId: string, saEmail: string) { await Gapi.load(); return gapi.client.request({ headers: {'X-Goog-User-Project': projectId}, method: 'POST', path: `https://iam.googleapis.com/v1/projects/${projectId}/serviceAccounts/${saEmail}:getIamPolicy` }).then(response => response.result, badResult => { throw new Error('Error trying to get service account iam policy: ' + JSON.stringify(badResult)); }); } public static async setServiceAccountIAM(projectId: string, saEmail: string, policy: object) { await Gapi.load(); return gapi.client.request({ body: { 'policy': policy }, headers: {'X-Goog-User-Project': projectId}, method: 'POST', path: `https://iam.googleapis.com/v1/projects/${projectId}/serviceAccounts/${saEmail}:setIamPolicy` }).then(response => (response.result as any).bindings, badResult => { throw new Error('Error trying to set service account iam policy: ' + JSON.stringify(badResult)); }); } public static async getServiceAccountToken(projectId: string, saEmail: string) { await Gapi.load(); return gapi.client.request({ body: { 'delegates': [], 'lifetime': '900s', 'scope': [ 'https://www.googleapis.com/auth/cloud-platform' ] }, headers: {'X-Goog-User-Project': projectId}, method: 'POST', path: `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${saEmail}:generateAccessToken` }).then(response => (response.result as any).accessToken, badResult => { throw new Error('Error trying to generate service account token: ' + JSON.stringify(badResult)); }); } }; public static async signIn(doPrompt?: boolean): Promise<void> { const rePromptOptions = 'login consent select_account'; const promptFlags = doPrompt ? rePromptOptions : ''; const options = { prompt: promptFlags, }; await this.load(); await gapi.auth2.getAuthInstance().signIn(options); } public static async signOut(): Promise<void> { return this.load() .then(() => gapi.auth2.getAuthInstance().signOut()); } public static async getSignedInEmail(): Promise<string | null> { await this.load(); const user = await this._getCurrentUser(); return user ? user.getBasicProfile().getEmail() : null; } public static async loadSigninButton(buttonId: string): Promise<any> { await this.load(); return this._loadPromise.then(() => new Promise((resolve, reject) => { gapi.load('signin2', { callback: resolve, onerror: (e: string) => reject(e) }); })).then(() => gapi.signin2.render(buttonId, { height: 50, longtitle: true, scope: this._SCOPE, theme: 'dark', width: 250, })); } public static load(): Promise<void> { if (!this._loadPromise) { this._loadPromise = window.gapiPromise .then(() => new Promise((resolve, reject) => gapi.load('client:auth2', { callback: resolve, onerror: (e: string) => reject(e) }))) .then(() => this._loadClient()); } return this._loadPromise; } public static async listenForSignInChanges(signInChangedCallback: (isSignedIn: boolean) => void): Promise<void> { await this.load(); // Initialize the callback now signInChangedCallback(gapi.auth2.getAuthInstance().isSignedIn.get()); // Listen for auth changes gapi.auth2.getAuthInstance().isSignedIn.listen(() => { signInChangedCallback(gapi.auth2.getAuthInstance().isSignedIn.get()); }); } private static _loadPromise: Promise<void>; // TODO(jlewi): ClientId for project cloud-ml-dev we should change this. private static readonly _CLIENT_ID = '848270605882-24q1l9p37opq3i0ououumpts6rv5s0mb.apps.googleusercontent.com'; private static readonly _SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; private static _currentUser: null | gapi.auth2.GoogleUser = null; // Gets set by _loadClientId private static async _updateSigninStatus() { await this.load(); if (gapi.auth2.getAuthInstance().isSignedIn.get()) { this._currentUser = gapi.auth2.getAuthInstance().currentUser.get(); } else { this._currentUser = null; } } private static _loadClient(): Promise<void> { return gapi.auth2.init({ client_id: this._CLIENT_ID, fetch_basic_profile: true, scope: this._SCOPE, ux_mode: 'popup', }).then(() => { const auth2 = gapi.auth2.getAuthInstance(); auth2.isSignedIn.listen(() => this._updateSigninStatus()); auth2.then(() => this._updateSigninStatus()); }, (errorReason: any) => { throw new Error('Error in gapi auth: ' + errorReason.details); }); } private static async _getCurrentUser(): Promise<null | gapi.auth2.GoogleUser> { await this.load(); return this._currentUser; } }
the_stack
import '../../../styles/gr-a11y-styles'; import '../../../styles/shared-styles'; import '../gr-comment/gr-comment'; import '../../diff/gr-diff/gr-diff'; import '../gr-copy-clipboard/gr-copy-clipboard'; import {css, html, LitElement, PropertyValues} from 'lit'; import {customElement, property, query, queryAll, state} from 'lit/decorators'; import { computeDiffFromContext, isDraft, isRobot, Comment, CommentThread, getLastComment, UnsavedInfo, isDraftOrUnsaved, createUnsavedComment, getFirstComment, createUnsavedReply, isUnsaved, } from '../../../utils/comment-util'; import {ChangeMessageId} from '../../../api/rest-api'; import {GerritNav} from '../../core/gr-navigation/gr-navigation'; import {getAppContext} from '../../../services/app-context'; import { createDefaultDiffPrefs, SpecialFilePath, } from '../../../constants/constants'; import {computeDisplayPath} from '../../../utils/path-list-util'; import { AccountDetailInfo, CommentRange, NumericChangeId, RepoName, UrlEncodedCommentId, } from '../../../types/common'; import {GrComment} from '../gr-comment/gr-comment'; import {FILE} from '../../diff/gr-diff/gr-diff-line'; import {GrButton} from '../gr-button/gr-button'; import {DiffInfo, DiffPreferencesInfo} from '../../../types/diff'; import {DiffLayer, RenderPreferences} from '../../../api/diff'; import {assertIsDefined} from '../../../utils/common-util'; import {fire, fireAlert, waitForEventOnce} from '../../../utils/event-util'; import {GrSyntaxLayer} from '../../diff/gr-syntax-layer/gr-syntax-layer'; import {TokenHighlightLayer} from '../../diff/gr-diff-builder/token-highlight-layer'; import {anyLineTooLong} from '../../diff/gr-diff/gr-diff-utils'; import {getUserName} from '../../../utils/display-name-util'; import {generateAbsoluteUrl} from '../../../utils/url-util'; import {sharedStyles} from '../../../styles/shared-styles'; import {a11yStyles} from '../../../styles/gr-a11y-styles'; import {subscribe} from '../../lit/subscription-controller'; import {repeat} from 'lit/directives/repeat'; import {classMap} from 'lit/directives/class-map'; import {ShortcutController} from '../../lit/shortcut-controller'; import {ValueChangedEvent} from '../../../types/events'; import {notDeepEqual} from '../../../utils/deep-util'; import {resolve} from '../../../models/dependency'; import {commentsModelToken} from '../../../models/comments/comments-model'; const NEWLINE_PATTERN = /\n/g; declare global { interface HTMLElementEventMap { 'comment-thread-editing-changed': ValueChangedEvent<boolean>; } } /** * gr-comment-thread exposes the following attributes that allow a * diff widget like gr-diff to show the thread in the right location: * * line-num: * 1-based line number or 'FILE' if it refers to the entire file. * * diff-side: * "left" or "right". These indicate which of the two diffed versions * the comment relates to. In the case of unified diff, the left * version is the one whose line number column is further to the left. * * range: * The range of text that the comment refers to (start_line, * start_character, end_line, end_character), serialized as JSON. If * set, range's end_line will have the same value as line-num. Line * numbers are 1-based, char numbers are 0-based. The start position * (start_line, start_character) is inclusive, and the end position * (end_line, end_character) is exclusive. */ @customElement('gr-comment-thread') export class GrCommentThread extends LitElement { @query('#replyBtn') replyBtn?: GrButton; @query('#quoteBtn') quoteBtn?: GrButton; @query('.comment-box') commentBox?: HTMLElement; @queryAll('gr-comment') commentElements?: NodeList; /** * Required to be set by parent. * * Lit's `hasChanged` change detection defaults to just checking strict * equality (===). Here it makes sense to install a proper `deepEqual` * check, because of how the comments-model and ChangeComments are setup: * Each thread object is recreated on the slightest model change. So when you * have 100 comment threads and there is an update to one thread, then you * want to avoid re-rendering the other 99 threads. */ @property({hasChanged: notDeepEqual}) thread?: CommentThread; /** * Id of the first comment and thus must not change. Will be derived from * the `thread` property in the first willUpdate() cycle. * * The `rootId` property is also used in gr-diff for maintaining lists and * maps of threads and their associated elements. * * Only stays `undefined` for new threads that only have an unsaved comment. */ @property({type: String}) rootId?: UrlEncodedCommentId; // TODO: Is this attribute needed for querySelector() or css rules? // We don't need this internally for the component. @property({type: Boolean, reflect: true, attribute: 'has-draft'}) hasDraft?: boolean; /** Will be inspected on firstUpdated() only. */ @property({type: Boolean, attribute: 'should-scroll-into-view'}) shouldScrollIntoView = false; /** * Should the file path and line number be rendered above the comment thread * widget? Typically true in <gr-thread-list> and false in <gr-diff>. */ @property({type: Boolean, attribute: 'show-file-path'}) showFilePath = false; /** * Only relevant when `showFilePath` is set. * If false, then only the line number is rendered. */ @property({type: Boolean, attribute: 'show-file-name'}) showFileName = false; @property({type: Boolean, attribute: 'show-ported-comment'}) showPortedComment = false; /** This is set to false by <gr-diff>. */ @property({type: Boolean, attribute: false}) showPatchset = true; @property({type: Boolean, attribute: 'show-comment-context'}) showCommentContext = false; /** * Optional context information when a thread is being displayed for a * specific change message. That influences which comments are expanded or * collapsed by default. */ @property({type: String, attribute: 'message-id'}) messageId?: ChangeMessageId; /** * We are reflecting the editing state of the draft comment here. This is not * an input property, but can be inspected from the parent component. * * Changes to this property are fired as 'comment-thread-editing-changed' * events. */ @property({type: Boolean, attribute: 'false'}) editing = false; /** * This can either be an unsaved reply to the last comment or the unsaved * content of a brand new comment thread (then `comments` is empty). * If set, then `thread.comments` must not contain a draft. A thread can only * contain *either* an unsaved comment *or* a draft, not both. */ @state() unsavedComment?: UnsavedInfo; @state() changeNum?: NumericChangeId; @state() prefs: DiffPreferencesInfo = createDefaultDiffPrefs(); @state() renderPrefs: RenderPreferences = { hide_left_side: true, disable_context_control_buttons: true, show_file_comment_button: false, hide_line_length_indicator: true, }; @state() repoName?: RepoName; @state() account?: AccountDetailInfo; @state() layers: DiffLayer[] = []; /** Computed during willUpdate(). */ @state() diff?: DiffInfo; /** Computed during willUpdate(). */ @state() highlightRange?: CommentRange; /** * Reflects the *dirty* state of whether the thread is currently unresolved. * We are listening on the <gr-comment> of the draft, so we even know when the * checkbox is checked, even if not yet saved. */ @state() unresolved = true; /** * Normally drafts are saved within the <gr-comment> child component and we * don't care about that. But when creating 'Done.' replies we are actually * saving from this component. True while the REST API call is inflight. */ @state() saving = false; // Private but used in tests. readonly getCommentsModel = resolve(this, commentsModelToken); private readonly changeModel = getAppContext().changeModel; private readonly userModel = getAppContext().userModel; private readonly shortcuts = new ShortcutController(this); private readonly syntaxLayer = new GrSyntaxLayer(); constructor() { super(); subscribe(this, this.changeModel.changeNum$, x => (this.changeNum = x)); subscribe(this, this.userModel.account$, x => (this.account = x)); subscribe(this, this.changeModel.repo$, x => (this.repoName = x)); subscribe(this, this.userModel.diffPreferences$, x => this.syntaxLayer.setEnabled(!!x.syntax_highlighting) ); subscribe(this, this.userModel.preferences$, prefs => { const layers: DiffLayer[] = [this.syntaxLayer]; if (!prefs.disable_token_highlighting) { layers.push(new TokenHighlightLayer(this)); } this.layers = layers; }); subscribe(this, this.userModel.diffPreferences$, prefs => { this.prefs = { ...prefs, // set line_wrapping to true so that the context can take all the // remaining space after comment card has rendered line_wrapping: true, }; }); this.shortcuts.addGlobal({key: 'e'}, () => this.handleExpandShortcut()); this.shortcuts.addGlobal({key: 'E'}, () => this.handleCollapseShortcut()); } static override get styles() { return [ a11yStyles, sharedStyles, css` :host { font-family: var(--font-family); font-size: var(--font-size-normal); font-weight: var(--font-weight-normal); line-height: var(--line-height-normal); /* Explicitly set the background color of the diff. We * cannot use the diff content type ab because of the skip chunk preceding * it, diff processor assumes the chunk of type skip/ab can be collapsed * and hides our diff behind context control buttons. * */ --dark-add-highlight-color: var(--background-color-primary); } gr-button { margin-left: var(--spacing-m); } gr-comment { border-bottom: 1px solid var(--comment-separator-color); } #actions { margin-left: auto; padding: var(--spacing-s) var(--spacing-m); } .comment-box { width: 80ch; max-width: 100%; background-color: var(--comment-background-color); color: var(--comment-text-color); box-shadow: var(--elevation-level-2); border-radius: var(--border-radius); flex-shrink: 0; } #container { display: var(--gr-comment-thread-display, flex); align-items: flex-start; margin: 0 var(--spacing-s) var(--spacing-s); white-space: normal; /** This is required for firefox to continue the inheritance */ -webkit-user-select: inherit; -moz-user-select: inherit; -ms-user-select: inherit; user-select: inherit; } .comment-box.unresolved { background-color: var(--unresolved-comment-background-color); } .comment-box.robotComment { background-color: var(--robot-comment-background-color); } #actionsContainer { display: flex; } .comment-box.saving #actionsContainer { opacity: 0.5; } #unresolvedLabel { font-family: var(--font-family); margin: auto 0; padding: var(--spacing-m); } .pathInfo { display: flex; align-items: baseline; justify-content: space-between; padding: 0 var(--spacing-s) var(--spacing-s); } .fileName { padding: var(--spacing-m) var(--spacing-s) var(--spacing-m); } @media only screen and (max-width: 1200px) { .diff-container { display: none; } } .diff-container { margin-left: var(--spacing-l); border: 1px solid var(--border-color); flex-grow: 1; flex-shrink: 1; max-width: 1200px; } .view-diff-button { margin: var(--spacing-s) var(--spacing-m); } .view-diff-container { border-top: 1px solid var(--border-color); background-color: var(--background-color-primary); } /* In saved state the "reply" and "quote" buttons are 28px height. * top:4px positions the 20px icon vertically centered. * Currently in draft state the "save" and "cancel" buttons are 20px * height, so the link icon does not need a top:4px in gr-comment_html. */ .link-icon { position: relative; top: 4px; cursor: pointer; } .fileName gr-copy-clipboard { display: inline-block; visibility: hidden; vertical-align: top; --gr-button-padding: 0px; } .fileName:focus-within gr-copy-clipboard, .fileName:hover gr-copy-clipboard { visibility: visible; } `, ]; } override render() { if (!this.thread) return; const dynamicBoxClasses = { robotComment: this.isRobotComment(), unresolved: this.unresolved, saving: this.saving, }; return html` ${this.renderFilePath()} <div id="container"> <h3 class="assistive-tech-only">${this.computeAriaHeading()}</h3> <div class="comment-box ${classMap(dynamicBoxClasses)}" tabindex="0"> ${this.renderComments()} ${this.renderActions()} </div> ${this.renderContextualDiff()} </div> `; } renderFilePath() { if (!this.showFilePath) return; const href = this.getUrlForFileComment(); const line = this.computeDisplayLine(); return html` ${this.renderFileName()} <div class="pathInfo"> ${href ? html`<a href="${href}">${line}</a>` : html`<span>${line}</span>`} </div> `; } renderFileName() { if (!this.showFileName) return; if (this.isPatchsetLevel()) { return html`<div class="fileName"><span>Patchset</span></div>`; } const href = this.getDiffUrlForPath(); const displayPath = this.getDisplayPath(); return html` <div class="fileName"> ${href ? html`<a href="${href}">${displayPath}</a>` : html`<span>${displayPath}</span>`} <gr-copy-clipboard hideInput .text="${displayPath}"></gr-copy-clipboard> </div> `; } renderComments() { assertIsDefined(this.thread, 'thread'); const robotButtonDisabled = !this.account || this.isDraftOrUnsaved(); const comments: Comment[] = [...this.thread.comments]; if (this.unsavedComment && !this.isDraft()) { comments.push(this.unsavedComment); } return repeat( comments, // We want to reuse <gr-comment> when unsaved changes to draft. comment => (isDraftOrUnsaved(comment) ? 'unsaved' : comment.id), comment => { const initiallyCollapsed = !isDraftOrUnsaved(comment) && (this.messageId ? comment.change_message_id !== this.messageId : !this.unresolved); return html` <gr-comment .comment="${comment}" .comments="${this.thread!.comments}" .patchNum="${this.thread?.patchNum}" ?initially-collapsed="${initiallyCollapsed}" ?robot-button-disabled="${robotButtonDisabled}" ?show-patchset="${this.showPatchset}" ?show-ported-comment="${this.showPortedComment && comment.id === this.rootId}" @create-fix-comment="${this.handleCommentFix}" @copy-comment-link="${this.handleCopyLink}" @comment-editing-changed="${(e: CustomEvent) => { if (isDraftOrUnsaved(comment)) this.editing = e.detail; }}" @comment-unresolved-changed="${(e: CustomEvent) => { if (isDraftOrUnsaved(comment)) this.unresolved = e.detail; }}" ></gr-comment> `; } ); } renderActions() { if (!this.account || this.isDraftOrUnsaved() || this.isRobotComment()) return; return html` <div id="actionsContainer"> <span id="unresolvedLabel">${ this.unresolved ? 'Unresolved' : 'Resolved' }</span> <div id="actions"> <iron-icon class="link-icon copy" @click="${this.handleCopyLink}" title="Copy link to this comment" icon="gr-icons:link" role="button" tabindex="0" > </iron-icon> <gr-button id="replyBtn" link class="action reply" ?disabled="${this.saving}" @click="${() => this.handleCommentReply(false)}" >Reply</gr-button > <gr-button id="quoteBtn" link class="action quote" ?disabled="${this.saving}" @click="${() => this.handleCommentReply(true)}" >Quote</gr-button > ${ this.unresolved ? html` <gr-button id="ackBtn" link class="action ack" ?disabled="${this.saving}" @click="${this.handleCommentAck}" >Ack</gr-button > <gr-button id="doneBtn" link class="action done" ?disabled="${this.saving}" @click="${this.handleCommentDone}" >Done</gr-button > ` : '' } </div> </div> </div> `; } renderContextualDiff() { if (!this.changeNum || !this.showCommentContext || !this.diff) return; if (!this.thread?.path) return; const href = this.getUrlForFileComment(); return html` <div class="diff-container"> <gr-diff id="diff" .changeNum="${this.changeNum}" .diff="${this.diff}" .layers="${this.layers}" .path="${this.thread.path}" .prefs="${this.prefs}" .renderPrefs="${this.renderPrefs}" .highlightRange="${this.highlightRange}" > </gr-diff> <div class="view-diff-container"> <a href="${href}"> <gr-button link class="view-diff-button">View Diff</gr-button> </a> </div> </div> `; } private firstWillUpdateDone = false; firstWillUpdate() { if (!this.thread) return; if (this.firstWillUpdateDone) return; this.firstWillUpdateDone = true; if (this.getFirstComment() === undefined) { this.unsavedComment = createUnsavedComment(this.thread); } this.unresolved = this.getLastComment()?.unresolved ?? true; this.diff = this.computeDiff(); this.highlightRange = this.computeHighlightRange(); } override willUpdate(changed: PropertyValues) { this.firstWillUpdate(); if (changed.has('thread')) { if (!this.isDraftOrUnsaved()) { // We can only do this for threads without draft, because otherwise we // are relying on the <gr-comment> component for the draft to fire // events about the *dirty* `unresolved` state. this.unresolved = this.getLastComment()?.unresolved ?? true; } this.hasDraft = this.isDraftOrUnsaved(); this.rootId = this.getFirstComment()?.id; if (this.isDraft()) { this.unsavedComment = undefined; } } if (changed.has('editing')) { // changed.get('editing') contains the old value. We only want to trigger // when changing from editing to non-editing (user has cancelled/saved). // We do *not* want to trigger on first render (old value is `null`) if (!this.editing && changed.get('editing') === true) { this.unsavedComment = undefined; if (this.thread?.comments.length === 0) { this.remove(); } } fire(this, 'comment-thread-editing-changed', {value: this.editing}); } } override firstUpdated() { if (this.shouldScrollIntoView) { this.commentBox?.focus(); this.scrollIntoView(); } } private isDraft() { return isDraft(this.getLastComment()); } private isDraftOrUnsaved(): boolean { return this.isDraft() || this.isUnsaved(); } private isNewThread(): boolean { return this.thread?.comments.length === 0; } private isUnsaved(): boolean { return !!this.unsavedComment || this.thread?.comments.length === 0; } private isPatchsetLevel() { return this.thread?.path === SpecialFilePath.PATCHSET_LEVEL_COMMENTS; } private computeDiff() { if (!this.showCommentContext) return; if (!this.thread?.path) return; const firstComment = this.getFirstComment(); if (!firstComment?.context_lines?.length) return; const diff = computeDiffFromContext( firstComment.context_lines, this.thread?.path, firstComment.source_content_type ); // Do we really have to re-compute (and re-render) the diff? if (this.diff && JSON.stringify(this.diff) === JSON.stringify(diff)) { return this.diff; } if (!anyLineTooLong(diff)) { this.syntaxLayer.init(diff); waitForEventOnce(this, 'render').then(() => { this.syntaxLayer.process(); }); } return diff; } private getDiffUrlForPath() { if (!this.changeNum || !this.repoName || !this.thread?.path) { return undefined; } if (this.isNewThread()) return undefined; return GerritNav.getUrlForDiffById( this.changeNum, this.repoName, this.thread.path, this.thread.patchNum ); } private computeHighlightRange() { const comment = this.getFirstComment(); if (!comment) return undefined; if (comment.range) return comment.range; if (comment.line) { return { start_line: comment.line, start_character: 0, end_line: comment.line, end_character: 0, }; } return undefined; } // Does not work for patchset level comments private getUrlForFileComment() { if (!this.repoName || !this.changeNum || this.isNewThread()) { return undefined; } assertIsDefined(this.rootId, 'rootId of comment thread'); return GerritNav.getUrlForComment( this.changeNum, this.repoName, this.rootId ); } private handleCopyLink() { const comment = this.getFirstComment(); if (!comment) return; assertIsDefined(this.changeNum, 'changeNum'); assertIsDefined(this.repoName, 'repoName'); const url = generateAbsoluteUrl( GerritNav.getUrlForCommentsTab( this.changeNum!, this.repoName!, comment.id ) ); assertIsDefined(url, 'url for comment'); navigator.clipboard.writeText(generateAbsoluteUrl(url)).then(() => { fireAlert(this, 'Link copied to clipboard'); }); } private getDisplayPath() { if (this.isPatchsetLevel()) return 'Patchset'; return computeDisplayPath(this.thread?.path); } private computeDisplayLine() { assertIsDefined(this.thread, 'thread'); if (this.thread.line === FILE) return this.isPatchsetLevel() ? '' : FILE; if (this.thread.line) return `#${this.thread.line}`; // If range is set, then lineNum equals the end line of the range. if (this.thread.range) return `#${this.thread.range.end_line}`; return ''; } private isRobotComment() { return isRobot(this.getLastComment()); } private getFirstComment() { assertIsDefined(this.thread); return getFirstComment(this.thread); } private getLastComment() { assertIsDefined(this.thread); return getLastComment(this.thread); } private handleExpandShortcut() { this.expandCollapseComments(false); } private handleCollapseShortcut() { this.expandCollapseComments(true); } private expandCollapseComments(actionIsCollapse: boolean) { for (const comment of this.commentElements ?? []) { (comment as GrComment).collapsed = actionIsCollapse; } } private async createReplyComment( content: string, userWantsToEdit: boolean, unresolved: boolean ) { const replyingTo = this.getLastComment(); assertIsDefined(this.thread, 'thread'); assertIsDefined(replyingTo, 'the comment that the user wants to reply to'); if (isDraft(replyingTo)) { throw new Error('cannot reply to draft'); } if (isUnsaved(replyingTo)) { throw new Error('cannot reply to unsaved comment'); } const unsaved = createUnsavedReply(replyingTo, content, unresolved); if (userWantsToEdit) { this.unsavedComment = unsaved; } else { try { this.saving = true; await this.getCommentsModel().saveDraft(unsaved); } finally { this.saving = false; } } } private handleCommentReply(quote: boolean) { const comment = this.getLastComment(); if (!comment) throw new Error('Failed to find last comment.'); let content = ''; if (quote) { const msg = comment.message; if (!msg) throw new Error('Quoting empty comment.'); content = '> ' + msg.replace(NEWLINE_PATTERN, '\n> ') + '\n\n'; } this.createReplyComment(content, true, comment.unresolved ?? true); } private handleCommentAck() { this.createReplyComment('Ack', false, false); } private handleCommentDone() { this.createReplyComment('Done', false, false); } private handleCommentFix(e: CustomEvent) { const comment = e.detail.comment; const msg = comment.message; const quoted = msg.replace(NEWLINE_PATTERN, '\n> ') as string; const quoteStr = '> ' + quoted + '\n\n'; const response = quoteStr + 'Please fix.'; this.createReplyComment(response, false, true); } private computeAriaHeading() { const author = this.getFirstComment()?.author ?? this.account; const user = getUserName(undefined, author); const unresolvedStatus = this.unresolved ? 'Unresolved ' : ''; const draftStatus = this.isDraftOrUnsaved() ? 'Draft ' : ''; return `${unresolvedStatus}${draftStatus}Comment thread by ${user}`; } } declare global { interface HTMLElementTagNameMap { 'gr-comment-thread': GrCommentThread; } }
the_stack
function mode(diffmeta?:diffmeta):string { "use strict"; const pdcomment = function mode_pdcomment():void { const ops:any = prettydiff.sparser.options; let sindex:number = options.source.search(/((\/(\*|\/))|<!--*)\s*prettydiff\.com/), dindex:number = options.diff.search(/((\/(\*|\/))|<!--*)\s*prettydiff\.com/), a:number = 0, b:number = 0, keys:string[], def:any, len:number; // parses the prettydiff settings comment // // - Source Priorities: // * the prettydiff comment is only accepted if it occurs before non-comments (near the top) // * options.source is the priority material for reading the comment // * the prettydiff comment will be processed from options.diff only if it present there, missing from options.source, and options.mode is diff // // - Examples: // /*prettydiff.com width:80 preserve:4*/ // /* prettydiff.com width:80 preserve:4 */ // /*prettydiff.com width=80 preserve=4 */ // // prettydiff.com width=80 preserve:4 // <!-- prettydiff.com width:80 preserve=4 --> // <!--prettydiff.com width:40 preserve:2--> // // - Parsing Considerations: // * there may be any amount of space at the start or end of the comment // * "prettydiff.com" must exist at the start of the comment // * comment must exist prior to non-comment tokens (near top of code) // * parameters are name value pairs separated by white space // * the delimiter separating name and value is either ":" or "=" characters if ((sindex > -1 && (sindex === 0 || "\"':".indexOf(options.source.charAt(sindex - 1)) < 0)) || (options.mode === "diff" && dindex > -1 && (dindex === 0 || "\"':".indexOf(options.diff.charAt(dindex - 1)) < 0))) { let pdcom:number = sindex, a:number = (pdcom > -1) ? pdcom : dindex, b:number = 0, quote:string = "", item:string = "", lang:string = "", lex:string = "", valkey:string[] = [], op:string[] = []; const ops:string[] = [], source:string = (pdcom > -1) ? options.source : options.diff, len:number = source.length, comment:string = (source.charAt(a) === "<") ? "<!--" : (source.charAt(a + 1) === "/") ? "//" : "/\u002a", esc = function mode_pdcomment_esc():boolean { if (source.charAt(a - 1) !== "\\") { return false; } let x:number = a; do { x = x - 1; } while (x > 0 && source.charAt(x) === "\\"); if ((a - x) % 2 === 0) { return true; } return false; }; do { if (source.slice(a - 3, a) === "com") { break; } a = a + 1; } while (a < len); do { if (esc() === false) { if (quote === "") { if (source.charAt(a) === "\"") { quote = "\""; if (ops.length > 0 && (ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === ":" || ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === "=")) { b = a; } } else if (source.charAt(a) === "'") { quote = "'"; if (ops.length > 0 && (ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === ":" || ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === "=")) { b = a; } } else if (source.charAt(a) === "`") { quote = "`"; if (ops.length > 0 && (ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === ":" || ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === "=")) { b = a; } } else if ((/\s/).test(source.charAt(a)) === false && b === 0) { b = a; } else if (source.charAt(a) === "," || ((/\s/).test(source.charAt(a)) === true && b > 0)) { item = source.slice(b, a); if (ops.length > 0) { if (ops.length > 0 && (item === ":" || item === "=") && ops[ops.length - 1].indexOf("=") < 0 && ops[ops.length - 1].indexOf(":") < 0) { // for cases where white space is between option name and assignment operator ops[ops.length - 1] = ops[ops.length - 1] + item; b = a; } else if (ops.length > 0 && (ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === ":" || ops[ops.length - 1].charAt(ops[ops.length - 1].length - 1) === "=")) { // for cases where white space is between assignment operator and value ops[ops.length - 1] = ops[ops.length - 1] + item; b = 0; } else { ops.push(item); b = 0; } } else { ops.push(item); b = 0; } } if (comment === "<!--" && source.slice(a - 2, a + 1) === "-->") { break; } if (comment === "//" && source.charAt(a) === "\n") { break; } if (comment === "/\u002a" && source.slice(a - 1, a + 1) === "\u002a/") { break; } } else if (source.charAt(a) === quote && quote !== "${") { quote = ""; } else if (quote === "`" && source.slice(a, a + 2) === "${") { quote = "${"; } else if (quote === "${" && source.charAt(a) === "}") { quote = "`"; } } a = a + 1; } while (a < len); if (b > 0) { quote = source.slice(b, a + 1); if (comment === "<!--") { quote = quote.replace(/\s*-+>$/, ""); } else if (comment === "//") { quote = quote.replace(/\s+$/, ""); } else { quote = quote.replace(/\s*\u002a\/$/, ""); } ops.push(quote); } a = ops.length; if (a > 0) { do { a = a - 1; if (ops[a].indexOf("=") > 0 && ops[a].indexOf(":") > 0) { if (ops[a].indexOf("=") < ops[a].indexOf(":")) { op = [ops[a].slice(0, ops[a].indexOf("=")), ops[a].slice(ops[a].indexOf("=") + 1)]; } } else if (ops[a].indexOf("=") > 0) { op = [ops[a].slice(0, ops[a].indexOf("=")), ops[a].slice(ops[a].indexOf("=") + 1)]; } else if (ops[a].indexOf(":") > 0) { op = [ops[a].slice(0, ops[a].indexOf(":")), ops[a].slice(ops[a].indexOf(":") + 1)]; } else if (prettydiff.api.optionDef[ops[a]] !== undefined && prettydiff.api.optionDef[ops[a]].type === "boolean") { options[ops[a]] = true; } if (op.length === 2 && prettydiff.api.optionDef[op[0]] !== undefined) { if ((op[1].charAt(0) === "\"" || op[1].charAt(0) === "'" || op[1].charAt(0) === "`") && op[1].charAt(op[1].length - 1) === op[1].charAt(0)) { op[1] = op[1].slice(1, op[1].length - 1); } if (prettydiff.api.optionDef[op[0]].type === "number" && isNaN(Number(op[1])) === false) { options[op[0]] = Number(op[1]); } else if (prettydiff.api.optionDef[op[0]].type === "boolean") { if (op[1] === "true") { options[op[0]] = true; } else if (op[1] === "false") { options[op[0]] = false; } } else { if (prettydiff.api.optionDef[op[0]].values !== undefined) { valkey = Object.keys(prettydiff.api.optionDef[op[0]].values); b = valkey.length; do { b = b - 1; if (valkey[b] === op[1]) { options[op[0]] = op[1]; break; } } while (b > 0); } else { if (op[0] === "language") { lang = op[1]; } else if (op[0] === "lexer") { lex = op[1]; } options[op[0]] = op[1]; } } } } while (a > 0); if (lex === "" && lang !== "") { lex = prettydiff.api.language.setlexer(lang); } } } if (options.mode === "diff") { modeValue = "beautify"; } if (options.mode === "minify" && options.minify_wrap === false) { options.wrap = -1; } if (options.lexer === "script") { let styleguide = { airbnb: function mode_pdcomment_styleairbnb() { options.brace_padding = true; options.correct = true; options.lexerOptions.script.end_comma = "always"; options.indent_char = " "; options.indent_size = 2; options.preserve = 1; options.quote_convert = "single"; options.variable_list = "each"; options.wrap = 80; }, crockford: function mode_pdcomment_stylecrockford() { options.brace_padding = false; options.correct = true; options.else_line = false; options.lexerOptions.script.end_comma = "never"; options.indent_char = " "; options.indent_size = 4; options.no_case_indent = true; options.space = true; options.variable_list = "each"; options.vertical = false; }, google: function mode_pdcomment_stylegoogle() { options.correct = true; options.indent_char = " "; options.indent_size = 4; options.preserve = 1; options.quote_convert = "single"; options.vertical = false; options.wrap = -1; }, jquery: function mode_pdcomment_stylejquery() { options.brace_padding = true; options.correct = true; options.indent_char = "\u0009"; options.indent_size = 1; options.quote_convert = "double"; options.variable_list = "each"; options.wrap = 80; }, jslint: function mode_pdcomment_stylejslint() { options.brace_padding = false; options.correct = true; options.else_line = false; options.lexerOptions.script.end_comma = "never"; options.indent_char = " "; options.indent_size = 4; options.no_case_indent = true; options.space = true; options.variable_list = "each"; options.vertical = false; }, mrdoobs: function mode_pdcomment_stylemrdoobs() { options.brace_line = true; options.brace_padding = true; options.correct = true; options.indent_char = "\u0009"; options.indent_size = 1; options.vertical = false; }, mediawiki: function mode_pdcomment_stylemediawiki() { options.brace_padding = true; options.correct = true; options.indent_char = "\u0009"; options.indent_size = 1; options.preserve = 1; options.quote_convert = "single"; options.space = false; options.wrap = 80; }, meteor: function mode_pdcomment_stylemeteor() { options.correct = true; options.indent_char = " "; options.indent_size = 2; options.wrap = 80; }, semistandard: function mode_pdcomment_stylessemistandard() { options.brace_line = false; options.brace_padding = false; options.braces = false; options.correct = true; options.end_comma = "never"; options.indent_char = " "; options.indent_size = 2; options.new_line = false; options.no_semicolon = false; options.preserve = 1; options.quote_convert = "single"; options.space = true; options.ternary_line = false; options.variable_list = "each"; options.vertical = false; options.wrap = 0; }, standard: function mode_pdcomment_stylestandard() { options.brace_line = false; options.brace_padding = false; options.braces = false; options.correct = true; options.end_comma = "never"; options.indent_char = " "; options.indent_size = 2; options.new_line = false; options.no_semicolon = true; options.preserve = 1; options.quote_convert = "single"; options.space = true; options.ternary_line = false; options.variable_list = "each"; options.vertical = false; options.wrap = 0; }, yandex: function mode_pdcomment_styleyandex() { options.brace_padding = false; options.correct = true; options.quote_convert = "single"; options.variable_list = "each"; options.vertical = false; } }, brace_style = { collapse: function mode_pdcomment_collapse() { options.brace_line = false; options.brace_padding = false; options.braces = false; options.format_object = "indent"; options.never_flatten = true; }, "collapse-preserve-inline": function mode_pdcomment_collapseInline() { options.brace_line = false; options.brace_padding = true; options.braces = false; options.format_object = "inline"; options.never_flatten = false; }, expand: function mode_pdcomment_expand() { options.brace_line = false; options.brace_padding = false; options.braces = true; options.format_object = "indent"; options.never_flatten = true; } }; if (styleguide[options.styleguide] !== undefined) { styleguide[options.styleguide](); } if (brace_style[options.brace_style] !== undefined) { brace_style[options.brace_style](); } if (options.language === "json") { options.wrap = 0; } else if (options.language === "titanium") { options.correct = false; } if (options.language !== "javascript" && options.language !== "typescript" && options.language !== "jsx") { options.jsscope = "none"; } } if (options.lexer !== "markup" || options.language === "text") { options.diff_rendered_html = false; } else if (options.api === "node" && options.read_method !== "file") { options.diff_rendered_html = false; } def = prettydiff.sparser.libs.optionDef; keys = Object.keys(def); len = keys.length; do { if (options[keys[a]] !== undefined) { if (def[keys[a]].lexer[0] === "all") { ops[keys[a]] = options[keys[a]]; } else { b = def[keys[a]].lexer.length; do { b = b - 1; if (keys[a] !== "parse_space" || (options.mode === "parse" && keys[a] === "parse_space" && options[keys[a]] === true)) { ops.lexer_options[def[keys[a]].lexer[b]][keys[a]] = options[keys[a]]; } } while (b > 0); } } a = a + 1; } while (a < len); }, options:any = prettydiff.options, lf:string = (options.crlf === true) ? "\r\n" : "\n"; let modeValue:"beautify"|"minify" = options.mode, result:string = ""; if (options.api === "node" && (options.read_method === "directory" || options.read_method === "subdirectory")) { if (options.mode === "parse" && options.parse_format === "table") { return "Error: option parse_format with value 'table' is not available with read_method directory or subdirectory."; } } if (options.language === "text" && options.mode !== "diff") { options.language = "auto"; } if (options.lexer === "text" && options.mode !== "diff") { options.lexer = "auto"; } if (options.language === "text" || options.lexer === "text") { options.language = "text"; options.language_name = "Plain Text"; options.lexer = "text"; } else if (options.language === "auto" || options.lexer === "auto") { const def:string = (options.language_default === "" || options.language_default === null || options.language_default === undefined) ? "javascript" : options.language_default; let lang:[string, string, string] = prettydiff.api.language.auto(options.source, def); if (lang[0] === "text") { if (options.mode === "diff") { lang[2] = "Plain Text"; } else { lang = ["javascript", "script", "JavaScript"]; } } else if (lang[0] === "csv") { lang[2] = "CSV"; } if (options.language === "auto") { options.language = lang[0]; options.language_name = lang[2]; } if (options.lexer === "auto") { options.lexer = lang[1]; } } pdcomment(); if (options.mode === "parse") { const parse_format = (options.parse_format === "htmltable") ? "table" : options.parse_format, api = (options.parse_format === "htmltable") ? "dom" : options.api; options.parsed = prettydiff.sparser.parser(); if (parse_format === "table") { if (api === "dom") { const parsLen:number = options.parsed.token.length, keys = Object.keys(options.parsed), keylen:number = keys.length, headingString:string = (function mode_parseHeading():string { const hout:string[] = ["<tr><th>index</th>"]; let b:number = 0; do { if (keys[b] !== "token") { hout.push(`<th>${keys[b]}</th>`); } b = b + 1; } while (b < keylen); hout.push("<th>token</th></tr>"); return hout.join(""); }()), row = function mode_parseRow():string { const hout:string[] = ["<tr>"]; let b = 0; hout.push(`<td>${a}</td>`); do { if (keys[b] !== "token") { hout.push(`<td>${options.parsed[keys[b]][a].toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</td>`); } b = b + 1; } while (b < keylen); hout.push(`<td>${options.parsed.token[a].replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</td></tr>`); return hout.join(""); }, parsOut:string[] = []; parsOut.push(`<p><strong>${parsLen}</strong> total parsed tokens</p>`); parsOut.push("<table><thead>"); parsOut.push(headingString); parsOut.push("</thead><tbody>"); let a:number = 0; do { if (a % 100 === 0 && a > 0) { parsOut.push(headingString); } parsOut.push(row()); a = a + 1; } while (a < parsLen); parsOut.push("</tbody></table>"); result = parsOut.join(""); } else { let a:number = 0, str:string[] = []; const outputArrays:data = options.parsed, nodeText:any = { angry : "\u001b[1m\u001b[31m", blue : "\u001b[34m", bold : "\u001b[1m", cyan : "\u001b[36m", green : "\u001b[32m", nocolor : "\u001b[39m", none : "\u001b[0m", purple : "\u001b[35m", red : "\u001b[31m", underline: "\u001b[4m", yellow : "\u001b[33m" }, output:string[] = [], b:number = outputArrays.token.length, pad = function mode_parsePad(x:string, y:number):void { const cc:string = x .toString() .replace(/\s/g, " "); let dd:number = y - cc.length; str.push(cc); if (dd > 0) { do { str.push(" "); dd = dd - 1; } while (dd > 0); } str.push(" | "); }, heading:string = "index | begin | ender | lexer | lines | stack | types | token", bar:string = "------|-------|-------|--------|-------|-------------|-------------|------"; output.push(""); output.push(heading); output.push(bar); do { if (a % 100 === 0 && a > 0) { output.push(""); output.push(heading); output.push(bar); } str = []; if (outputArrays.lexer[a] === "markup") { str.push(nodeText.red); } else if (outputArrays.lexer[a] === "script") { str.push(nodeText.green); } else if (outputArrays.lexer[a] === "style") { str.push(nodeText.yellow); } pad(a.toString(), 5); pad(outputArrays.begin[a].toString(), 5); pad(outputArrays.ender[a].toString(), 5); pad(outputArrays.lexer[a].toString(), 5); pad(outputArrays.lines[a].toString(), 5); pad(outputArrays.stack[a].toString(), 11); pad(outputArrays.types[a].toString(), 11); str.push(outputArrays.token[a].replace(/\s/g, " ")); str.push(nodeText.none); output.push(str.join("")); a = a + 1; } while (a < b); result = output.join(lf); } } else { result = JSON.stringify(options.parsed); } } else { if (prettydiff[modeValue][options.lexer] === undefined && ((options.mode !== "diff" && options.language === "text") || options.language !== "text")) { result = `Error: Library prettydiff.${modeValue}.${options.lexer} does not exist.`; } else if (options.mode === "diff") { let diffoutput:[string, number, number]; if (options.diff_format === "json") { options.complete_document = false; } if (options.language === "text") { diffoutput = prettydiff.api.diffview(options); result = diffoutput[0]; } else { const ind:number = options.indent; if (options.diff_rendered_html === true) { const lexers:any = { del: 0, insert: 0, replace: 0 }, typeIgnore:string[] = [ "attribute", "cdata", "comment", "conditional", "ignore", "jsx_attribute_end", "jsx_attribute_start", "script", "sgml", "style", "xml" ], tab = function mode_diffhtmlTab(indentation:number):string { const tabout:string[] = (options.crlf === true) ? ["\r\n"] : ["\n"]; let a:number = 0, b:number = options.indent_size * indentation; if (b > 1) { do { tabout.push(options.indent_char); a = a + 1; } while (a < b); } else { tabout.push(options.indent_char); tabout.push(options.indent_char); } return tabout.join(""); }, css:string[] = [ `${tab(2)}<style type="text/css">`, "#prettydiff_summary{background:#eef8ff;border:2px solid #069}", ".prettydiff_rendered{border-style:solid;border-width:2px;display:inline-block}", ".prettydiff_delete{background:#ffd8d8;border-color:#c44}", ".prettydiff_insert{background:#d8ffd8;border-color:#090}", ".prettydiff_replace{background:#fec;border-color:#a86}" ], insert = function mode_insert():void { const inject:string[] = [`<span class="prettydiff_rendered prettydiff_insert">`]; if (json[a + 1][0] === "+") { do { inject.push(json[a][1]); count[1] = count[1] + 1; a = a + 1; } while (json[a + 1][0] === "+"); } inject.push(json[a][1]); inject.push("</span>"); options.parsed.token[count[0]] = `${inject.join("")} ${options.parsed.token[count[0]]}`; lexers.insert = lexers.insert + 1; }, del = function mode_del():void { const symb:string = json[a][0], change:string = (symb === "-") ? "delete" : "replace"; options.parsed.token[count[0]] = `<span class="prettydiff_rendered prettydiff_${change}">${options.parsed.token[count[0]]}`; if (json[a + 1][0] === symb) { do { count[0] = count[0] + 1; if (change === "replace") { count[1] = count[1] + 1; } a = a + 1; } while (json[a + 1][0] === symb); } options.parsed.token[count[0]] = `${options.parsed.token[count[0]]}</span>`; if (change === "delete") { lexers.del = lexers.del + 1; } else { lexers.replace = lexers.replace + 1; } }, summary = function mode_summary():void { const keys:string[] = Object.keys(lexers), len:number = keys.length, output:string[] = [], lex:string[] = []; let a:number = 0, lextest:boolean = false; output.push(`<div id="prettydiff_summary"><h1>Pretty Diff - Summary</h1>`); output.push("<p>This is the count of identified differences starting with visual differences colored in the document first.</p><ul>"); output.push(`<li>Deletions - <strong>${lexers.del}</strong></li>`); output.push(`<li>Insertions - <strong>${lexers.insert}</strong></li>`); output.push(`<li>Replacements - <strong>${lexers.replace}</strong></li>`); output.push("</ul>"); if (len > 3) { lexers.del = 0; lexers.insert = 0; lexers.replace = 0; lex.push("<hr/><p>This list of differences is not visible in the rendered HTML.</p><ul>"); do { if (lexers[keys[a]] > 0) { lextest = true; lex.push(`<li>${keys[a]} - ${lexers[keys[a]]}</li>`); } a = a + 1; } while (a < len); lex.push("</ul>"); } if (lextest === true) { output.push(lex.join("")); } output.push("</div>"); options.parsed.token[body] = `${options.parsed.token[body]} ${output.join("")}`; }; let diff_parsed:data, json:any, a:number = 0, count:[number, number] = [0, 0], len:number = 0, body:number = 0, head:boolean = false; options.diff_format = "json"; options.parsed = prettydiff.sparser.parser(); options.source = options.parsed.token; prettydiff.start = 0; prettydiff.end = 0; options.indent_level = ind; prettydiff.sparser.options.source = options.diff; diff_parsed = prettydiff.sparser.parser(); options.diff = diff_parsed.token; diffoutput = prettydiff.api.diffview(options); json = JSON.parse(diffoutput[0]).diff; len = json.length; do { if (head === false && options.parsed.types[count[0]] === "start" && options.parsed.lexer[count[0]] === "markup" && json[a][1].toLowerCase().indexOf("<head") === 0) { options.parsed.token[count[0]] = `${options.parsed.token[count[0]] + css.join(tab(3)) + tab(2)}</style>${tab(0)}`; head = true; } else if (body < 1 && options.parsed.types[count[0]] === "start" && options.parsed.lexer[count[0]] === "markup" && options.parsed.token[count[0]].toLowerCase().indexOf("<body") === 0) { body = count[0]; } if (json[a][0] === "=") { count[0] = count[0] + 1; count[1] = count[1] + 1; } else if ( body > 1 && options.parsed.lexer[count[0]] === "markup" && options.parsed.token[count[0]].indexOf(`<span class="prettydiff_`) !== 0 && ((json[a][0] === "+" && typeIgnore.indexOf(diff_parsed.types[count[1]]) < 0) || (json[a][0] !== "+" && typeIgnore.indexOf(options.parsed.types[count[0]]) < 0)) ) { if (json[a][0] === "+") { insert(); } else { del(); } } else { if (json[a][0] === "-") { count[0] = count[0] + 1; } else if (json[a][0] === "+") { count[1] = count[1] + 1; } else { count[0] = count[0] + 1; count[1] = count[1] + 1; } if (lexers[options.parsed.lexer[count[0]]] === undefined) { lexers[options.parsed.lexer[count[0]]] = 1; } else { lexers[options.parsed.lexer[count[0]]] = lexers[options.parsed.lexer[count[0]]] + 1; } } a = a + 1; } while (a < len); summary(); result = prettydiff.beautify.markup(options); } else { options.parsed = prettydiff.sparser.parser(); options.source = prettydiff.beautify[options.lexer](options); prettydiff.start = 0; prettydiff.end = 0; options.indent_level = ind; // diff text formatting prettydiff.sparser.options.source = options.diff; options.parsed = prettydiff.sparser.parser(); options.diff = prettydiff.beautify[options.lexer](options); // comparison diffoutput = prettydiff.api.diffview(options); result = diffoutput[0]; } } if (diffmeta !== undefined) { diffmeta.differences = diffoutput[1]; diffmeta.lines = diffoutput[2]; } } else { options.parsed = prettydiff.sparser.parser(); result = prettydiff[modeValue][options.lexer](options); } } if (options.new_line === true) { result = result.replace(/\s*$/, lf); } else { result = result.replace(/\s+$/, ""); } if (options.complete_document === true && options.jsscope !== "report") { let finalFile:finalFile = prettydiff.api.finalFile; finalFile.order[7] = options.color; finalFile.order[10] = result; if (options.crlf === true) { finalFile.order[12] = "\r\n"; finalFile.order[15] = "\r\n"; } if (options.mode === "diff") { finalFile.order[13] = finalFile.script.diff; } else if (options.mode === "beautify" && options.language === "javascript" && options.jsscope !== "none") { finalFile.order[13] = finalFile.script.beautify; } else { finalFile.order[13] = finalFile.script.minimal; } // escape changes characters that result in xml wellformedness errors prettydiff.end = 0; prettydiff.start = 0; return finalFile.order.join(""); } prettydiff.end = 0; prettydiff.start = 0; return result; } mode();
the_stack
import React, { useState, useContext, useEffect } from 'react'; import DeploymentCenterContainerSource from './DeploymentCenterContainerSource'; import { ContainerRegistrySources, DeploymentCenterFieldProps, DeploymentCenterContainerFormData, WorkflowOption, AppType, PublishType, } from '../DeploymentCenter.types'; import { ScmType } from '../../../../models/site/config'; import DeploymentCenterContainerRegistrySettings from './DeploymentCenterContainerRegistrySettings'; import DeploymentCenterContainerDockerHubSettings from './DeploymentCenterContainerDockerHubSettings'; import DeploymentCenterContainerPrivateRegistrySettings from './DeploymentCenterContainerPrivateRegistrySettings'; import DeploymentCenterGitHubDataLoader from '../github-provider/DeploymentCenterGitHubDataLoader'; import DeploymentCenterContainerAcrDataLoader from './DeploymentCenterContainerAcrDataLoader'; import DeploymentCenterGitHubWorkflowConfigSelector from '../github-provider/DeploymentCenterGitHubWorkflowConfigSelector'; import DeploymentCenterGitHubWorkflowConfigPreview from '../github-provider/DeploymentCenterGitHubWorkflowConfigPreview'; import { DeploymentCenterContext } from '../DeploymentCenterContext'; import { useTranslation } from 'react-i18next'; import { getTelemetryInfo, getWorkflowFileName } from '../utility/DeploymentCenterUtility'; import { Guid } from '../../../../utils/Guid'; import DeploymentCenterContainerContinuousDeploymentSettings from './DeploymentCenterContainerContinuousDeploymentSettings'; import { DeploymentCenterConstants } from '../DeploymentCenterConstants'; import DeploymentCenterGitHubConfiguredView from '../github-provider/DeploymentCenterGitHubConfiguredView'; import DeploymentCenterContainerSettingsReadOnlyView from './DeploymentCenterContainerSettingsReadOnlyView'; import { SiteStateContext } from '../../../../SiteState'; import DeploymentCenterVstsBuildProvider from '../devops-provider/DeploymentCenterVstsBuildProvider'; import { ProgressIndicator } from 'office-ui-fabric-react'; import { AppOs } from '../../../../models/site/site'; import DeploymentCenterData from '../DeploymentCenter.data'; import { PortalContext } from '../../../../PortalContext'; import { CommonConstants } from '../../../../utils/CommonConstants'; const DeploymentCenterContainerSettings: React.FC<DeploymentCenterFieldProps<DeploymentCenterContainerFormData>> = props => { const { formProps, isDataRefreshing } = props; const { t } = useTranslation(); const [githubActionExistingWorkflowContents, setGithubActionExistingWorkflowContents] = useState<string>(''); const [workflowFilePath, setWorkflowFilePath] = useState<string>(''); const [isPreviewFileButtonDisabled, setIsPreviewFileButtonDisabled] = useState(false); const [panelMessage, setPanelMessage] = useState(''); const [showGitHubActionReadOnlyView, setShowGitHubActionReadOnlyView] = useState(false); const [showSourceSelectionOption, setShowSourceSelectionOption] = useState(false); // NOTE(michinoy): The serverUrl, image, username, and password are retrieved from one of three sources: // acr, dockerHub, or privateRegistry. // These values are used in combination with GitHub Action workflow selection to show the preview panel for the // workflow file. Using useState hooks here to aggregate each property from their respective sources. const [serverUrl, setServerUrl] = useState(''); const [image, setImage] = useState(''); const [username, setUsername] = useState(''); const [password, SetPassword] = useState(''); const deploymentCenterContext = useContext(DeploymentCenterContext); const siteStateContext = useContext(SiteStateContext); const portalContext = useContext(PortalContext); const deploymentCenterData = new DeploymentCenterData(); const isGitHubActionSelected = formProps.values.scmType === ScmType.GitHubAction; const isVstsSelected = formProps.values.scmType === ScmType.Vsts; const isAcrConfigured = formProps.values.registrySource === ContainerRegistrySources.acr && !formProps.values.privateRegistryUsername; const isDockerHubConfigured = formProps.values.registrySource === ContainerRegistrySources.docker; const isPrivateRegistryConfigured = formProps.values.registrySource === ContainerRegistrySources.privateRegistry; const getWorkflowFileVariables = () => { const slotName = !!deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.slot : ''; const siteName = !!deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.site : ''; const loginServer = serverUrl.toLocaleLowerCase(); // NOTE(stpelleg): For dockerHub the server URL contains /v1 at the end. // The server used in the image should not have that part. const server = loginServer.indexOf(DeploymentCenterConstants.dockerHubServerUrlHost) > -1 ? DeploymentCenterConstants.dockerHubServerUrlHost : loginServer.replace(CommonConstants.DeploymentCenterConstants.https, ''); return { siteName: slotName ? `${siteName}(${slotName})` : siteName, slotName: slotName || CommonConstants.production, branch: formProps.values.branch || CommonConstants.master, publishingProfileSecretName: `AzureAppService_PublishProfile_${formProps.values.gitHubPublishProfileSecretGuid}`, loginServer: loginServer, publishServer: server, image: image, containerUserSecretName: `AzureAppService_ContainerUsername_${formProps.values.gitHubContainerUsernameSecretGuid}`, containerPasswordSecretName: `AzureAppService_ContainerPassword_${formProps.values.gitHubContainerPasswordSecretGuid}`, }; }; const getWorkflowFileContent = async () => { if (deploymentCenterContext.siteDescriptor) { if (formProps.values.workflowOption === WorkflowOption.UseExistingWorkflowConfig) { return githubActionExistingWorkflowContents; } else if (formProps.values.workflowOption === WorkflowOption.Add || formProps.values.workflowOption === WorkflowOption.Overwrite) { const variables = getWorkflowFileVariables(); const appType = siteStateContext.isFunctionApp ? AppType.FunctionApp : AppType.WebApp; const os = siteStateContext.isLinuxApp ? AppOs.linux : AppOs.windows; const getWorkflowFile = await deploymentCenterData.getWorkflowFile(appType, PublishType.Container, os, variables); if (getWorkflowFile.metadata.success) { return getWorkflowFile.data; } else { portalContext.log( getTelemetryInfo('error', 'getWorkflowFile', 'failed', { appType: appType, publishType: PublishType.Code, os: os, branch: variables.branch, }) ); return t('deploymentCenterWorkflowError'); } } } return ''; }; useEffect(() => { if (formProps.values.workflowOption === WorkflowOption.UseExistingWorkflowConfig) { setPanelMessage(t('githubActionWorkflowOptionUseExistingMessage')); } else if (formProps.values.workflowOption === WorkflowOption.UseAvailableWorkflowConfigs) { setPanelMessage(t('githubActionWorkflowOptionUseExistingMessageWithoutPreview')); } else if (formProps.values.workflowOption === WorkflowOption.Add || formProps.values.workflowOption === WorkflowOption.Overwrite) { setPanelMessage(t('githubActionWorkflowOptionOverwriteIfConfigExists')); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formProps.values.workflowOption]); useEffect(() => { const useAvailableOrExisting = formProps.values.workflowOption === WorkflowOption.UseAvailableWorkflowConfigs || (formProps.values.workflowOption === WorkflowOption.UseExistingWorkflowConfig && githubActionExistingWorkflowContents); const formFilled = (formProps.values.workflowOption !== WorkflowOption.None && serverUrl && username && password && image) || useAvailableOrExisting; setIsPreviewFileButtonDisabled(formProps.values.workflowOption === WorkflowOption.None || !formFilled); // eslint-disable-next-line react-hooks/exhaustive-deps }, [formProps.values.workflowOption, githubActionExistingWorkflowContents, serverUrl, image, username, password]); useEffect(() => { if (formProps.values.registrySource === ContainerRegistrySources.acr) { setServerUrl(`https://${formProps.values.acrLoginServer}`); } else if (formProps.values.registrySource === ContainerRegistrySources.privateRegistry) { setServerUrl(formProps.values.privateRegistryServerUrl); } else { setServerUrl(DeploymentCenterConstants.dockerHubServerUrl); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formProps.values.registrySource, formProps.values.acrLoginServer, formProps.values.privateRegistryServerUrl]); useEffect(() => { if (formProps.values.registrySource === ContainerRegistrySources.acr && formProps.values.acrImage) { setImage(formProps.values.acrImage); } else if ( formProps.values.registrySource === ContainerRegistrySources.privateRegistry && formProps.values.privateRegistryImageAndTag ) { const imageAndTagParts = formProps.values.privateRegistryImageAndTag.split(':'); setImage(imageAndTagParts[0]); } else if (formProps.values.dockerHubImageAndTag) { const imageAndTagParts = formProps.values.dockerHubImageAndTag.split(':'); setImage(imageAndTagParts[0]); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ formProps.values.registrySource, formProps.values.acrImage, formProps.values.dockerHubImageAndTag, formProps.values.privateRegistryImageAndTag, ]); useEffect(() => { if (formProps.values.registrySource === ContainerRegistrySources.acr) { setUsername(formProps.values.acrUsername); } else if (formProps.values.registrySource === ContainerRegistrySources.privateRegistry) { setUsername(formProps.values.privateRegistryUsername); } else { setUsername(formProps.values.dockerHubUsername); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ formProps.values.registrySource, formProps.values.acrUsername, formProps.values.dockerHubUsername, formProps.values.privateRegistryUsername, ]); useEffect(() => { if (formProps.values.registrySource === ContainerRegistrySources.acr) { SetPassword(formProps.values.acrPassword); } else if (formProps.values.registrySource === ContainerRegistrySources.privateRegistry) { SetPassword(formProps.values.privateRegistryPassword); } else { SetPassword(formProps.values.dockerHubPassword); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ formProps.values.registrySource, formProps.values.acrPassword, formProps.values.dockerHubPassword, formProps.values.privateRegistryPassword, ]); useEffect(() => { if ( deploymentCenterContext.siteDescriptor && (formProps.values.workflowOption === WorkflowOption.UseExistingWorkflowConfig || formProps.values.workflowOption === WorkflowOption.Add || formProps.values.workflowOption === WorkflowOption.Overwrite) ) { const workflowFileName = getWorkflowFileName( formProps.values.branch, deploymentCenterContext.siteDescriptor.site, deploymentCenterContext.siteDescriptor.slot ); setWorkflowFilePath(`.github/workflows/${workflowFileName}`); } else { setWorkflowFilePath(''); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formProps.values.workflowOption]); useEffect(() => { // NOTE(michinoy): In case of having GitHub Action based integrate for containers // the container registry username and password need to be added as secrets on // the GitHub repo. if (formProps.values.scmType === ScmType.GitHubAction) { formProps.setFieldValue( 'gitHubPublishProfileSecretGuid', Guid.newGuid() .toLowerCase() .replace(/[-]/g, '') ); formProps.setFieldValue( 'gitHubContainerUsernameSecretGuid', Guid.newGuid() .toLowerCase() .replace(/[-]/g, '') ); formProps.setFieldValue( 'gitHubContainerPasswordSecretGuid', Guid.newGuid() .toLowerCase() .replace(/[-]/g, '') ); } else { formProps.setFieldValue('gitHubPublishProfileSecretGuid', ''); formProps.setFieldValue('gitHubContainerUsernameSecretGuid', ''); formProps.setFieldValue('gitHubContainerPasswordSecretGuid', ''); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formProps.values.scmType]); useEffect(() => { const showReadOnlyView = !!deploymentCenterContext && !!deploymentCenterContext.siteConfig && deploymentCenterContext.siteConfig.properties.scmType === ScmType.GitHubAction; setShowGitHubActionReadOnlyView(showReadOnlyView); // eslint-disable-next-line react-hooks/exhaustive-deps }, [deploymentCenterContext.siteConfig]); useEffect(() => { setShowSourceSelectionOption(siteStateContext && siteStateContext.isLinuxApp); // eslint-disable-next-line react-hooks/exhaustive-deps }, [siteStateContext.isLinuxApp]); const renderSetupView = () => { return ( <> {showSourceSelectionOption && <DeploymentCenterContainerSource formProps={formProps} />} {isGitHubActionSelected && ( <> <DeploymentCenterGitHubDataLoader isGitHubActions={isGitHubActionSelected} formProps={formProps} />{' '} <DeploymentCenterGitHubWorkflowConfigSelector formProps={formProps} setGithubActionExistingWorkflowContents={setGithubActionExistingWorkflowContents} /> </> )} {isVstsSelected && <DeploymentCenterVstsBuildProvider />} {!isVstsSelected && ( <> <DeploymentCenterContainerRegistrySettings {...props} /> {isAcrConfigured && <DeploymentCenterContainerAcrDataLoader {...props} />} {isDockerHubConfigured && <DeploymentCenterContainerDockerHubSettings {...props} />} {isPrivateRegistryConfigured && <DeploymentCenterContainerPrivateRegistrySettings {...props} />} {!isGitHubActionSelected && <DeploymentCenterContainerContinuousDeploymentSettings {...props} />} </> )} {isGitHubActionSelected && ( <DeploymentCenterGitHubWorkflowConfigPreview isPreviewFileButtonDisabled={isPreviewFileButtonDisabled} getWorkflowFileContent={getWorkflowFileContent} workflowFilePath={workflowFilePath} panelMessage={panelMessage} /> )} </> ); }; const renderGitHubActionReadOnlyView = () => { return ( <> <DeploymentCenterGitHubConfiguredView formProps={formProps} /> <DeploymentCenterContainerSettingsReadOnlyView /> </> ); }; const getSettingsControls = () => (showGitHubActionReadOnlyView ? renderGitHubActionReadOnlyView() : renderSetupView()); const getProgressIndicator = () => ( <ProgressIndicator description={t('deploymentCenterSettingsLoading')} ariaValueText={t('deploymentCenterSettingsLoadingAriaValue')} /> ); return isDataRefreshing ? getProgressIndicator() : getSettingsControls(); }; export default DeploymentCenterContainerSettings;
the_stack
import { RuleTester } from "eslint" import path from "path" import rule from "../../../lib/rules/prefer-result-array-groups" const tester = new RuleTester({ parserOptions: { ecmaVersion: 2020, sourceType: "module", }, }) tester.run("prefer-result-array-groups", rule as any, { valid: [ ` const regex = /regexp/ let match while (match = regex.exec(foo)) { const match = match[0] // ... } `, ` const regex = /a(b)c/ let match while (match = regex.exec(foo)) { const p1 = match[1] // ... } `, ` const regex = /a(b)c/ let match while (match = regex.exec(foo)) { const p1 = match?.[1] // ... } `, ` const regex = /a(b)c/ let match while (match = regex.exec(foo)) { const p1 = match.unknown // ... } `, ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match.unknown // ... } `, // String.prototype.match() ` const arr = "str".match(/regexp/) const p1 = arr[1] `, ` const arr = "str".match(/a(b)c/) const p1 = arr[1] `, ` const arr = "str".match(/a(?<foo>b)c/) const p1 = arr.groups.foo `, ` const arr = "str".match(/a(?<foo>b)c/) const p1 = arr.unknown `, ` const arr = unknown.match(/a(?<foo>b)c/) const p1 = arr[1] `, ` const arr = "str".match(/a(?<foo>b)c/g) const p1 = arr[1] `, // String.prototype.matchAll() ` const matches = "str".matchAll(/a(?<foo>b)c/); for (const match of matches) { const p1 = match.groups.foo // .. } `, ` const matches = "str".matchAll(/a(b)c/); for (const match of matches) { const p1 = match[1] // .. } `, ` const matches = unknown.matchAll(/a(?<foo>b)c/); for (const match of matches) { const p1 = match.groups.foo // .. } `, ], invalid: [ { code: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match[1] // ... } `, output: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match.groups.foo // ... } `, errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 5, column: 28, }, ], }, { code: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match?.[1] // ... } `, output: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match?.groups.foo // ... } `, errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 5, column: 28, }, ], }, { code: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match?.[(1)] // ... } `, output: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match?.groups.foo // ... } `, errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 5, column: 28, }, ], }, { code: ` const regex = /(a)(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match[1] const p2 = match[2] // ... } `, output: ` const regex = /(a)(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match[1] const p2 = match.groups.foo // ... } `, errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 6, column: 28, }, ], }, { code: ` const regex = /(?<foo>a)(?<bar>b)c/ let match while (match = regex.exec(foo)) { const [,p1,p2] = match // ... } `, output: null, errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 5, column: 25, }, { message: "Unexpected indexed access for the named capturing group 'bar' from regexp result array.", line: 5, column: 28, }, ], }, // String.prototype.match() { code: ` const arr = "str".match(/a(?<foo>b)c/) const p1 = arr[1] `, output: ` const arr = "str".match(/a(?<foo>b)c/) const p1 = arr.groups.foo `, errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 3, column: 24, }, ], }, { code: ` const arr = unknown.match(/a(?<foo>b)c/) const p1 = arr[1] `, output: ` const arr = unknown.match(/a(?<foo>b)c/) const p1 = arr.groups.foo `, options: [{ strictTypes: false }], errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 3, column: 24, }, ], }, // String.prototype.matchAll() { code: ` const matches = "str".matchAll(/a(?<foo>b)c/); for (const match of matches) { const p1 = match[1] // .. } `, output: ` const matches = "str".matchAll(/a(?<foo>b)c/); for (const match of matches) { const p1 = match.groups.foo // .. } `, errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 4, column: 28, }, ], }, { code: ` const matches = unknown.matchAll(/a(?<foo>b)c/); for (const match of matches) { const p1 = match[1] // .. } `, output: ` const matches = unknown.matchAll(/a(?<foo>b)c/); for (const match of matches) { const p1 = match.groups.foo // .. } `, options: [{ strictTypes: false }], errors: [ { message: "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", line: 4, column: 28, }, ], }, // with TypeScript { filename: path.join(__dirname, "prefer-result-array-groups.ts"), code: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match[1] // ... } `, output: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match.groups!.foo // ... } `, parser: require.resolve("@typescript-eslint/parser"), parserOptions: { project: require.resolve("../../../tsconfig.json"), }, errors: [ "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", ], }, { // If don't give type information. code: ` const regex = /a(?<foo>b)c/ let match while (match = regex.exec(foo)) { const p1 = match[1] // ... } `, output: null, parser: require.resolve("@typescript-eslint/parser"), errors: [ "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", ], }, { // Not using RegExpExecArray filename: path.join(__dirname, "prefer-result-array-groups.ts"), code: ` const regex = /a(?<foo>b)c/ let match: any[] | null while (match = regex.exec(foo)) { const p1 = match[1] // ... } `, output: null, parser: require.resolve("@typescript-eslint/parser"), parserOptions: { project: require.resolve("../../../tsconfig.json"), }, errors: [ "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", ], }, { // Using `any` type. filename: path.join(__dirname, "prefer-result-array-groups.ts"), code: ` const regex = /a(?<foo>b)c/ let match: any while (match = regex.exec(foo)) { const p1 = match[1] // ... } `, output: ` const regex = /a(?<foo>b)c/ let match: any while (match = regex.exec(foo)) { const p1 = match.groups.foo // ... } `, parser: require.resolve("@typescript-eslint/parser"), parserOptions: { project: require.resolve("../../../tsconfig.json"), }, errors: [ "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", ], }, { // https://github.com/ota-meshi/eslint-plugin-regexp/issues/355 filename: path.join(__dirname, "prefer-result-array-groups.ts"), code: ` const match = /(?<foo>foo)/u.exec(str)! match[1]; // <- /(?<bar>bar)/u.exec(str)?.[1]; // <- const match2 = /(?<baz>baz)/u.exec(str) match2?.[1] // <- const match3 = /(?<qux>qux)/u.exec(str) as RegExpExecArray match3[1] // <- `, output: ` const match = /(?<foo>foo)/u.exec(str)! match.groups!.foo; // <- /(?<bar>bar)/u.exec(str)?.groups!.bar; // <- const match2 = /(?<baz>baz)/u.exec(str) match2?.groups!.baz // <- const match3 = /(?<qux>qux)/u.exec(str) as RegExpExecArray match3.groups!.qux // <- `, parser: require.resolve("@typescript-eslint/parser"), parserOptions: { project: require.resolve("../../../tsconfig.json"), }, errors: [ "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", "Unexpected indexed access for the named capturing group 'bar' from regexp result array.", "Unexpected indexed access for the named capturing group 'baz' from regexp result array.", "Unexpected indexed access for the named capturing group 'qux' from regexp result array.", ], }, { code: ` const match = /(?<foo>foo)/u.exec(str) if (match) { match[1] // <- } const match2 = /(?<bar>bar)/u.exec(str) match2 ? match2[1] // <- : null; const match3 = /(?<baz>baz)/u.exec(str) match3 && match3[1] // <- const match4 = /(?<qux>qux)/u.exec(str) if (!match4) { } else { match4[1] // <- } `, output: ` const match = /(?<foo>foo)/u.exec(str) if (match) { match.groups.foo // <- } const match2 = /(?<bar>bar)/u.exec(str) match2 ? match2.groups.bar // <- : null; const match3 = /(?<baz>baz)/u.exec(str) match3 && match3.groups.baz // <- const match4 = /(?<qux>qux)/u.exec(str) if (!match4) { } else { match4.groups.qux // <- } `, errors: [ "Unexpected indexed access for the named capturing group 'foo' from regexp result array.", "Unexpected indexed access for the named capturing group 'bar' from regexp result array.", "Unexpected indexed access for the named capturing group 'baz' from regexp result array.", "Unexpected indexed access for the named capturing group 'qux' from regexp result array.", ], }, ], })
the_stack
import { Injectable, Inject, NgZone, EventEmitter } from '@angular/core' import { Observable, Subject } from 'rxjs' import { HotkeyDescription, HotkeyProvider } from '../api/hotkeyProvider' import { KeyEventData, getKeyName, Keystroke, KeyName, getKeystrokeName, metaKeyName, altKeyName } from './hotkeys.util' import { ConfigService } from './config.service' import { HostAppService, Platform } from '../api/hostApp' import { deprecate } from 'util' export interface PartialHotkeyMatch { id: string strokes: string[] matchedLength: number } interface PastKeystroke { keystroke: Keystroke time: number } @Injectable({ providedIn: 'root' }) export class HotkeysService { /** @hidden @deprecated */ key = new EventEmitter<KeyboardEvent>() /** @hidden @deprecated */ matchedHotkey = new EventEmitter<string>() /** * Fired for each recognized hotkey */ get hotkey$ (): Observable<string> { return this._hotkey } /** * Fired for once hotkey is released */ get hotkeyOff$ (): Observable<string> { return this._hotkeyOff } /** * Fired for each singular key */ get key$ (): Observable<KeyName> { return this._key } /** * Fired for each key event */ get keyEvent$ (): Observable<KeyboardEvent> { return this._keyEvent } /** * Fired for each singular key combination */ get keystroke$ (): Observable<Keystroke> { return this._keystroke } private _hotkey = new Subject<string>() private _hotkeyOff = new Subject<string>() private _keyEvent = new Subject<KeyboardEvent>() private _key = new Subject<KeyName>() private _keystroke = new Subject<Keystroke>() private disabledLevel = 0 private hotkeyDescriptions: HotkeyDescription[] = [] private pressedKeys = new Set<KeyName>() private pressedKeyTimestamps = new Map<KeyName, number>() private pressedHotkey: string|null = null private pressedKeystroke: Keystroke|null = null private lastKeystrokes: PastKeystroke[] = [] private recognitionPhase = true private lastEventTimestamp = 0 private constructor ( private zone: NgZone, private config: ConfigService, @Inject(HotkeyProvider) private hotkeyProviders: HotkeyProvider[], hostApp: HostAppService, ) { this.config.ready$.toPromise().then(async () => { const hotkeys = await this.getHotkeyDescriptions() this.hotkeyDescriptions = hotkeys const events = ['keydown', 'keyup'] events.forEach(eventType => { document.addEventListener(eventType, (nativeEvent: KeyboardEvent) => { this._keyEvent.next(nativeEvent) this.pushKeyEvent(eventType, nativeEvent) if (hostApp.platform === Platform.Web && this.matchActiveHotkey(true) !== null) { nativeEvent.preventDefault() nativeEvent.stopPropagation() } }) }) }) // deprecated this.hotkey$.subscribe(h => this.matchedHotkey.emit(h)) this.matchedHotkey.subscribe = deprecate(s => this.hotkey$.subscribe(s), 'matchedHotkey is deprecated, use hotkey$') this.keyEvent$.subscribe(h => this.key.next(h)) this.key.subscribe = deprecate(s => this.keyEvent$.subscribe(s), 'key is deprecated, use keyEvent$') } /** * Adds a new key event to the buffer * * @param eventName DOM event name * @param nativeEvent event object */ pushKeyEvent (eventName: string, nativeEvent: KeyboardEvent): void { if (nativeEvent.timeStamp === this.lastEventTimestamp) { return } nativeEvent['event'] = eventName const eventData = { ctrlKey: nativeEvent.ctrlKey, metaKey: nativeEvent.metaKey, altKey: nativeEvent.altKey, shiftKey: nativeEvent.shiftKey, code: nativeEvent.code, key: nativeEvent.key, eventName, time: nativeEvent.timeStamp, registrationTime: performance.now(), } for (const [key, time] of this.pressedKeyTimestamps.entries()) { if (time < performance.now() - 2000) { this.removePressedKey(key) } } const keyName = getKeyName(eventData) if (eventName === 'keydown') { this.addPressedKey(keyName, eventData) if (!nativeEvent.repeat) { this.recognitionPhase = true } this.updateModifiers(eventData) } if (eventName === 'keyup') { const keystroke = getKeystrokeName([...this.pressedKeys]) if (this.recognitionPhase) { this._keystroke.next(keystroke) this.lastKeystrokes.push({ keystroke, time: performance.now(), }) this.recognitionPhase = false } this.pressedKeys.clear() this.pressedKeyTimestamps.clear() this.removePressedKey(keyName) } if (this.pressedKeys.size) { this.pressedKeystroke = getKeystrokeName([...this.pressedKeys]) } else { this.pressedKeystroke = null } const matched = this.matchActiveHotkey() this.zone.run(() => { if (matched && this.recognitionPhase) { this.emitHotkeyOn(matched) } else if (this.pressedHotkey) { this.emitHotkeyOff(this.pressedHotkey) } }) this.zone.run(() => { this._key.next(getKeyName(eventData)) }) if (process.platform === 'darwin' && eventData.metaKey && eventName === 'keydown' && !['Ctrl', 'Shift', altKeyName, metaKeyName].includes(keyName)) { // macOS will swallow non-modified keyups if Cmd is held down this.pushKeyEvent('keyup', nativeEvent) } this.lastEventTimestamp = nativeEvent.timeStamp } getCurrentKeystrokes (): Keystroke[] { if (!this.pressedKeystroke) { return [] } return [...this.lastKeystrokes.map(x => x.keystroke), this.pressedKeystroke] } matchActiveHotkey (partial = false): string|null { if (!this.isEnabled() || !this.pressedKeystroke) { return null } const matches: { id: string, sequence: string[], }[] = [] const currentSequence = this.getCurrentKeystrokes() const config = this.getHotkeysConfig() for (const id in config) { for (const sequence of config[id]) { if (currentSequence.length < sequence.length) { continue } if (sequence[sequence.length - 1] !== this.pressedKeystroke) { continue } let lastIndex = 0 let matched = true for (const item of sequence) { const nextOffset = currentSequence.slice(lastIndex).findIndex( x => x.toLowerCase() === item.toLowerCase() ) if (nextOffset === -1) { matched = false break } lastIndex += nextOffset } if (partial ? lastIndex > 0 : matched) { matches.push({ id, sequence, }) } } } matches.sort((a, b) => b.sequence.length - a.sequence.length) if (!matches.length) { return null } if (matches[0].sequence.length > 1) { this.clearCurrentKeystrokes() } return matches[0].id } clearCurrentKeystrokes (): void { this.lastKeystrokes = [] this.pressedKeys.clear() this.pressedKeyTimestamps.clear() this.pressedKeystroke = null this.pressedHotkey = null } getHotkeyDescription (id: string): HotkeyDescription { return this.hotkeyDescriptions.filter((x) => x.id === id)[0] } enable (): void { this.disabledLevel-- } disable (): void { this.disabledLevel++ } isEnabled (): boolean { return this.disabledLevel === 0 } async getHotkeyDescriptions (): Promise<HotkeyDescription[]> { return ( await Promise.all( this.config.enabledServices(this.hotkeyProviders) .map(async x => x.provide()) ) ).reduce((a, b) => a.concat(b)) } private updateModifiers (event: KeyEventData) { for (const [prop, key] of Object.entries({ ctrlKey: 'Ctrl', metaKey: metaKeyName, altKey: altKeyName, shiftKey: 'Shift', })) { if (!event[prop] && this.pressedKeys.has(key)) { this.removePressedKey(key) } if (event[prop] && !this.pressedKeys.has(key)) { this.addPressedKey(key, event) } } } private emitHotkeyOn (hotkey: string) { if (this.pressedHotkey) { if (this.pressedHotkey === hotkey) { return } this.emitHotkeyOff(this.pressedHotkey) } if (document.querySelectorAll('input:focus').length === 0) { console.debug('Matched hotkey', hotkey) this._hotkey.next(hotkey) this.pressedHotkey = hotkey } this.recognitionPhase = false } private emitHotkeyOff (hotkey: string) { console.debug('Unmatched hotkey', hotkey) this._hotkeyOff.next(hotkey) this.pressedHotkey = null } private getHotkeysConfig () { return this.getHotkeysConfigRecursive(this.config.store.hotkeys) } private getHotkeysConfigRecursive (branch: any) { const keys = {} for (const key in branch) { let value = branch[key] if (value instanceof Object && !(value instanceof Array)) { const subkeys = this.getHotkeysConfigRecursive(value) for (const subkey in subkeys) { keys[key + '.' + subkey] = subkeys[subkey] } } else { if (typeof value === 'string') { value = [value] } if (!(value instanceof Array)) { continue } if (value.length > 0) { value = value.map((item: string | string[]) => typeof item === 'string' ? [item] : item) keys[key] = value } } } return keys } private addPressedKey (keyName: KeyName, eventData: KeyEventData) { this.pressedKeys.add(keyName) this.pressedKeyTimestamps.set(keyName, eventData.registrationTime) } private removePressedKey (key: KeyName) { this.pressedKeys.delete(key) this.pressedKeyTimestamps.delete(key) } }
the_stack
import RamlWrapper = require('../artifacts/raml08parserapi') import RamlWrapperImpl = require('../artifacts/raml08parser') import factory = require('../artifacts/raml08factory') import core=require("./parserCore"); import ramlPathMatch = require("../../util/raml-path-match") import hl = require('../highLevelAST'); import ll = require("../lowLevelAST"); import hlimpl = require('../highLevelImpl'); import defs = require('raml-definition-system'); import universes=require("../tools/universe") import expanderLL=require("../ast.core/expanderLL") import lowLevelProxy=require("../ast.core/LowLevelASTProxy") import linter=require("../ast.core/linter") import util = require('../../util/index'); import search=require("../../search/search-interface") import universeHelpers = require("../tools/universeHelpers"); import jsyaml=require("../jsyaml/jsyaml2lowLevel"); import path=require("path") import _ = require("underscore"); //export function resolveType(p:RamlWrapper.TypeDeclaration):hl.ITypeDefinition{ // var tpe=typeexpression.typeFromNode(p.highLevel()); // return tpe.toRuntime(); //} let messageRegistry = require("../../../resources/errorMessages"); export function load(pth: string):core.BasicNode{ var m=new jsyaml.Project(path.dirname(pth)); var unit=m.unit(path.basename(pth)); if (unit){ if (unit.isRAMLUnit()){ return (<hlimpl.ASTNodeImpl>hlimpl.fromUnit(unit)).wrapperNode(); } } return null; } /** * __$helperMethod__ * Equivalent API with traits and resource types expanded * __$meta__={"name":"expand"} **/ export function expandTraitsAndResourceTypes(api:RamlWrapper.Api):RamlWrapper.Api{ var lowLevelNode = api.highLevel().lowLevel(); if(lowLevelProxy.LowLevelProxyNode.isInstance(lowLevelNode)){ return api; } return expanderLL.expandTraitsAndResourceTypes(api); } //__$helperMethod__ Path relative to API root export function completeRelativeUri(res:RamlWrapper.Resource):string{ var uri = ''; var parent:any = res; do{ res = <RamlWrapper.Resource>parent;//(parent instanceof RamlWrapper.ResourceImpl) ? <RamlWrapper.Resource>parent : null; uri = res.relativeUri().value() + uri; parent = res.parent(); } while (parent.definition().key().name==universes.Universe08.Resource.name); return uri; } //__$helperMethod__ baseUri of owning Api concatenated with completeRelativeUri export function absoluteUri(res:RamlWrapper.Resource):string{ var uri = ''; var parent:any = res; do{ res = <RamlWrapper.Resource>parent;//(parent instanceof RamlWrapper.ResourceImpl) ? <RamlWrapper.Resource>parent : null; uri = res.relativeUri().value() + uri; parent = res.parent(); } while (parent.definition().key().name==universes.Universe08.Resource.name); var buri=(<RamlWrapper.Api>parent).baseUri(); var base =buri?buri.value():""; base = base ? base : ''; if(res){ base = base.replace(/\/+$/,""); } uri = base + uri; return uri; } export function qName(c:core.BasicNode):string{ return hlimpl.qName(c.highLevel(),c.highLevel().root()); } /** * __$helperMethod__ * __$meta__{"name":"traits","override":true} **/ export function traitsPrimary(a:RamlWrapper.Api):RamlWrapper.Trait[]{ return allTraits(a); } /** * __$helperMethod__ Retrieve all traits including those defined in libraries * * __$meta__{"deprecated":true} */ export function allTraits(a:RamlWrapper.Api):RamlWrapper.Trait[]{ return <any>findTemplates(a,d=>universeHelpers.isTraitType(d)); } /** *__$helperMethod__ *__$meta__{"name":"resourceTypes","override":true} **/ export function resourceTypesPrimary(a:RamlWrapper.Api):RamlWrapper.ResourceType[]{ return allResourceTypes(a); } /** * __$helperMethod__ Retrieve all resource types including those defined in libraries * __$meta__{"deprecated":true} */ export function allResourceTypes(a:RamlWrapper.Api):RamlWrapper.ResourceType[]{ return <any>findTemplates(a,d=>universeHelpers.isResourceTypeType(d)); } function findTemplates(a:core.BasicNode,filter) { var arr = search.globalDeclarations(a.highLevel()).filter(x=>filter(x.definition())); var ll = a.highLevel().lowLevel(); if(!ll) { return []; } var nodePath = ll.includePath(); if(!nodePath){ nodePath = ll.unit().path(); } var topLevelArr = arr.map(x=>{ var topLevelNode:core.BasicNode; var p = x.lowLevel().unit().path(); if(p!=nodePath){ topLevelNode = factory.buildWrapperNode(x,false); (<core.NodeMetadataImpl>topLevelNode.meta()).setCalculated(); } else{ topLevelNode = x.wrapperNode(); } return topLevelNode; }); return topLevelArr; }; export function relativeUriSegments(res:RamlWrapper.Resource):string[]{ var result:string[] = []; var parent:any = res; do{ res = <RamlWrapper.Resource>parent;//(parent instanceof RamlWrapper.ResourceImpl) ? <RamlWrapper.Resource>parent : null; result.push(res.relativeUri().value()); parent = res.parent(); } while (parent.definition().key().name==universes.Universe08.Resource.name); return result.reverse(); } //__$helperMethod__ For methods of Resources returns parent resource. For methods of ResourceTypes returns null. export function parentResource(method:RamlWrapper.Method):RamlWrapper.Resource{ if(RamlWrapperImpl.ResourceImpl.isInstance(method.parent())) { return <RamlWrapper.Resource>method.parent(); } return null; } //__$helperMethod__ Parent resource for non top level resources __$meta__={"name":"parentResource"} export function parent(resource:RamlWrapper.Resource):RamlWrapper.Resource{ var parent = resource.parent(); if(parent.definition().key().name==universes.Universe08.Resource.name){ <RamlWrapper.Resource>parent } return null; } //__$helperMethod__ Get child resource by its relative path export function childResource(container:RamlWrapper.Resource|RamlWrapper.Api, relPath:string):RamlWrapper.Resource{ if(container==null){ return null; } var resources:RamlWrapper.Resource[] = container.resources(); if(!resources){ return null; } resources = resources.filter(x=>x.relativeUri().value()==relPath); if(resources.length==0){ return null; } return resources[0]; } export function getResource(container:RamlWrapper.Api|RamlWrapper.Resource, path:string[]):RamlWrapper.Resource{ if(!container){ return null; } var res:RamlWrapper.Resource = null; for (var i = 0; i < path.length; i++) { res = childResource(container, path[i]); if(!res){ return null; } container = res; } return res; } //__$helperMethod__ Get child method by its name export function childMethod(resource:RamlWrapper.Resource, method:string):RamlWrapper.Method[]{ if(!resource){ return null; } return resource.methods().filter(x=>x.method()==method); } export function getMethod(container:RamlWrapper.Resource|RamlWrapper.Api, path:string[],method:string):RamlWrapper.Method[]{ var resource = getResource(container,path); if(resource==null){ return null; } return childMethod(resource,method); } function isApi(obj) { return (obj.definition().key().name==universes.Universe08.Api.name); }; //__$helperMethod__ Api owning the resource as a sibling export function ownerApi(method:RamlWrapper.Method|RamlWrapper.Resource):RamlWrapper.Api{ var obj:core.BasicNode = method; while(!isApi(obj)){ obj = obj.parent(); } return <RamlWrapper.Api>obj; } /** * __$helperMethod__ * For methods of Resources: `{parent Resource relative path} {methodName}`. * For methods of ResourceTypes: `{parent ResourceType name} {methodName}`. * For other methods throws Exception. **/ export function methodId(method:RamlWrapper.Method):string{ var parent = method.parent(); if(RamlWrapperImpl.ResourceImpl.isInstance(parent)){ return completeRelativeUri(<RamlWrapper.Resource>parent) + ' ' + method.method().toLowerCase(); } else if(RamlWrapperImpl.ResourceTypeImpl.isInstance(parent)){ return (<RamlWrapper.ResourceType>parent).name() + ' ' + method.method().toLowerCase(); } throw new Error(linter.applyTemplate(messageRegistry.METHOD_OWNED_BY, {owner:method.definition().key().name})); } //__$helperMethod__ true for codes < 400 and false otherwise export function isOkRange(response:RamlWrapper.Response):boolean{ var str:string = response.code().value(); var err = linter.validateResponseString(str); if(err!=null){ return false; } try{ if(parseInt(str.charAt(0)) < 4){ return true; } } catch(e){} return false; } //__$helperMethod__ Retrieve all resources of the Api export function allResources(api:RamlWrapper.Api):RamlWrapper.Resource[]{ var resources:RamlWrapper.Resource[] = [] var visitor = (res:RamlWrapper.Resource) => { resources.push(res); res.resources().forEach(x=>visitor(x)); } api.resources().forEach(x=>visitor(x)); return resources; } //export function matchUri(apiRootRelativeUri:string, resource:RamlWrapper.Resource):Opt<ParamValue[]>{ // // var allParameters:Raml08Parser.NamedParameterMap = {} // var opt:Opt<RamlWrapper.Resource> = new Opt<RamlWrapper.Resource>(resource); // while(opt.isDefined()){ // var res:RamlWrapper.Resource = opt.getOrThrow(); // uriParameters(res).forEach(x=>allParameters[x.name()]=new ParamWrapper(x)); // opt = parent(res); // } // var result = ramlPathMatch(completeRelativeUri(resource), allParameters, {})(apiRootRelativeUri); // if (result) { // return new Opt<ParamValue[]>(Object.keys((<any>result).params) // .map(x=>new ParamValue(x, result['params'][x]))); // } // return Opt.empty<ParamValue[]>(); //} var schemaContentChars:string[] = [ '{', '<' ]; //export function schema(body:RamlWrapper.TypeDeclaration, api:RamlWrapper.Api):Opt<SchemaDef>{ // // var schemaNode = body.schema(); // if(!schemaNode){ // return Opt.empty<SchemaDef>(); // } // var schemaString = schemaNode; // var isContent:boolean = false; // schemaContentChars.forEach(x=>{try{ isContent = isContent||schemaString.indexOf(x)>=0}catch(e){}}); // var schDef:SchemaDef; // if(isContent) { // schDef = new SchemaDef(schemaString); // } // else{ // var globalSchemes = api.schemas().filter(x=>x.key()==schemaString); // if(globalSchemes.length>0){ // schDef = new SchemaDef(globalSchemes[0].value().value(),globalSchemes[0].key()); // } // else{ // return Opt.empty<SchemaDef>(); // } // } // return new Opt<SchemaDef>(schDef); //} /** * __$helperMethod__ * Retrieve an ordered list of all uri parameters including those which are not described in the `uriParameters` node. * Consider a fragment of RAML specification: * ```yaml * /resource/{objectId}/{propertyId}: * uriParameters: * objectId: * ``` * Here `propertyId` uri parameter is not described in the `uriParameters` node, * but it is among Resource.uriParameters(). * __$meta__={"name":"uriParameters","override": true} **/ export function uriParametersPrimary(resource:RamlWrapper.Resource):RamlWrapper.Parameter[]{ return uriParameters(resource); } /** * __$helperMethod__ * Retrieve an ordered list of all uri parameters including those which are not described in the `uriParameters` node. * Consider a fragment of RAML specification: * ```yaml * /resource/{objectId}/{propertyId}: * uriParameters: * objectId: * ``` * Here `propertyId` uri parameter is not described in the `uriParameters` node, * Thus, it is not among Resource.uriParameters(), but it is among Resource.allUriParameters(). * __$meta__={"name":"allUriParameters","deprecated":true} **/ export function uriParameters(resource:RamlWrapper.Resource):RamlWrapper.Parameter[]{ let uriNode = resource.relativeUri(); var uri = uriNode.value(); var params = (<RamlWrapperImpl.ResourceImpl>resource).uriParameters_original(); var propName = universes.Universe08.Resource.properties.uriParameters.name; let llNode = uriNode.highLevel().lowLevel(); return extractParams(params, uri, resource, propName, llNode); } /** * __$helperMethod__ * Retrieve an ordered list of all base uri parameters regardless of whether they are described in `baseUriParameters` or not * Consider a fragment of RAML specification: * ```yaml * version: v1 * baseUri: https://{organization}.example.com/{version}/{service} * baseUriParameters: * service: * ``` * Here `version` and `organization` are base uri parameters which are not described in the `baseUriParameters` node, * but they are among `Api.baseUriParameters()`. * __$meta__={"name":"baseUriParameters","override":true} **/ export function baseUriParametersPrimary(api:RamlWrapper.Api):RamlWrapper.Parameter[]{ return baseUriParameters(api); } /** * __$helperMethod__ * Retrieve an ordered list of all base uri parameters regardless of whether they are described in `baseUriParameters` or not * Consider a fragment of RAML specification: * ```yaml * version: v1 * baseUri: https://{organization}.example.com/{version}/{service} * baseUriParameters: * service: * ``` * Here `version` and `organization` are base uri parameters which are not described in the `baseUriParameters` node, * Thus, they are not among `Api.baseUriParameters()`, but they are among `Api.allBaseUriParameters()`. * __$meta__={"name":"allBaseUriParameters","deprecated":true} **/ export function baseUriParameters(api:RamlWrapper.Api):RamlWrapper.Parameter[]{ let uriNode = api.baseUri(); var uri = uriNode ? uriNode.value() : ''; var params = (<RamlWrapperImpl.ApiImpl>api).baseUriParameters_original(); var propName = universes.Universe08.Api.properties.baseUriParameters.name; let llNode = uriNode && uriNode.highLevel().lowLevel(); return extractParams(params, uri, api, propName,llNode); } /** * __$helperMethod__ * Retrieve an ordered list of all absolute uri parameters. Returns a union of `Api.allBaseUriParameters()` * for `Api` owning the `Resource` and `Resource.allUriParameters()`. **/ export function absoluteUriParameters(res:RamlWrapper.Resource):RamlWrapper.Parameter[]{ var params:RamlWrapper.Parameter[] = []; var parent:any = res; do{ res = <RamlWrapper.Resource>parent; params = uriParameters(res).concat(params); parent = res.parent(); } while (parent.definition().key().name==universes.Universe10.Resource.name); var api = <RamlWrapper.Api>parent; var baseUriParams = api.baseUriParameters(); params = baseUriParameters(api).concat(params); return params; } /** * _//_$helperMethod__ * Protocols used by the API. Returns the `protocols` property value if it is specified. * Otherwise, returns protocol, specified in the base URI. * __$meta__={"name":"protocols","override":true} **/ export function protocolsPrimary(api:RamlWrapper.Api):string[]{ return allProtocols(api); } /** * __$helperMethod__ * Protocols used by the API. Returns the `protocols` property value if it is specified. * Otherwise, returns protocol, specified in the base URI. * __$meta__{"deprecated":true} **/ export function allProtocols(api:RamlWrapper.Api):string[]{ return api.protocols().map(x=>x.toUpperCase()); //var attributeDefaults = (<RamlWrapper.ApiImpl>api).attributeDefaults(); //var result = (<RamlWrapper.ApiImpl>api).protocols_original(); //if(result.length!=0||!attributeDefaults){ // return result; //} //var baseUriAttr = api.baseUri(); //if(baseUriAttr) { // var baseUri = baseUriAttr.value(); // if (baseUri) { // var ind = baseUri.indexOf('://'); // if (ind >= 0) { // result = [baseUri.substring(0, ind)]; // } // if(result.length==0){ // result = [ 'HTTP' ]; // } // } //} //return result; } /** * _//_$helperMethod__ * Returns security schemes, resource or method is secured with. If no security schemes are set at resource or method level, * returns schemes defined with `securedBy` at API level. * __$meta__={"name":"securedBy","override":true} **/ export function securedByPrimary(resourceOrMethod : RamlWrapper.Resource | RamlWrapper.Method):RamlWrapper.SecuritySchemeRef[] { return allSecuredBy(resourceOrMethod); } /** * __$helperMethod__ * Returns security schemes, resource or method is secured with. If no security schemes are set at resource or method level, * returns schemes defined with `securedBy` at API level. * __$meta__{"deprecated":true} **/ export function allSecuredBy(resourceOrMethod : RamlWrapper.Resource | RamlWrapper.Method):RamlWrapper.SecuritySchemeRef[] { //var currentSecuredBy = (<RamlWrapper.ResourceImpl|RamlWrapper.MethodImpl>resourceOrMethod).securedBy_original(); //if (currentSecuredBy && currentSecuredBy.length > 0) { // return currentSecuredBy; //} // ////instanceof, but have to avoid direct usage of instanceof in JS. //if (resourceOrMethod.highLevel().definition().key() == universes.Universe08.Method) { // var resource = <RamlWrapper.ResourceImpl>(<RamlWrapper.Method>resourceOrMethod).parentResource(); // if (resource && resource.securedBy_original() && resource.securedBy_original().length > 0) { // return resource.securedBy(); // } //} return resourceOrMethod.securedBy(); } /** * __$helperMethod__ * __$meta__={"primary":true} **/ export function securitySchemeName(schemeReference : RamlWrapper.SecuritySchemeRef) : string { var highLevel = schemeReference.highLevel(); if (!highLevel) return ""; var attributeValue = highLevel.value(); if (!attributeValue) return ""; return attributeValue.toString(); } /** * __$helperMethod__ * __$meta__={"primary":true} **/ export function securityScheme(schemeReference : RamlWrapper.SecuritySchemeRef) : RamlWrapper.AbstractSecurityScheme { var highLevel = schemeReference.highLevel(); if (!highLevel) return null; var declaration = search.findDeclarationByNode(highLevel, search.LocationKind.VALUE_COMPLETION); if (!declaration) return null; if (!(<any>declaration).getKind || (<hl.IHighLevelNode>declaration).getKind() != hl.NodeKind.NODE) { return null; } var result = (<hl.IHighLevelNode> declaration).wrapperNode(); if (!(RamlWrapperImpl.AbstractSecuritySchemeImpl.isInstance(result))) { //I do not see how to avoid instanceof here return null; } return <RamlWrapper.AbstractSecurityScheme> result; } /** * __$helperMethod__ * __$meta__={"primary":true} **/ export function RAMLVersion(api:RamlWrapper.Api):string{ return api.highLevel().definition().universe().version(); } /** * __$helperMethod__ * __$meta__={"primary":true} **/ export function structuredValue(reference:RamlWrapper.Reference):RamlWrapper.TypeInstance{ var hl = reference.value().lowLevel(); return <RamlWrapper.TypeInstance><any>new core.TypeInstanceImpl(hl); } /** * __$helperMethod__ * __$meta__={"name":"name","primary":true} **/ export function referenceName(reference:RamlWrapper.Reference):string{ var val = reference.highLevel().value(); return (typeof val == 'string') || val == null ? val : val.valueName(); } /** * __$helperMethod__ * __$meta__={"name":"trait","primary":true} **/ export function referencedTrait(ref:RamlWrapper.TraitRef):RamlWrapper.Trait{ return <RamlWrapper.Trait>referencedObject(ref); } /** * __$helperMethod__ * __$meta__={"name":"resourceType","primary":true} **/ export function referencedResourceType(ref:RamlWrapper.ResourceTypeRef):RamlWrapper.ResourceType{ return <RamlWrapper.ResourceType>referencedObject(ref); } function referencedObject(ref:RamlWrapper.Reference):core.BasicNode{ var attr = ref.highLevel(); var parent = attr.parent(); var vn = ref.name(); var cands = search.referenceTargets(attr.property(),parent).filter(x=>hlimpl.qName(x,parent)==vn); if(cands.length==0){ return null; } return cands[0].wrapperNode(); } function extractParams( params:RamlWrapper.Parameter[], uri:string, owner:core.BasicNode, propName:string, propNode:ll.ILowLevelASTNode):RamlWrapper.Parameter[] { let ownerHl = owner.highLevel(); let prop = ownerHl.definition().property(propName); if(typeof(uri)!='string'){ uri = ""; } let describedParams = {}; params.forEach(x=>{ let arr = describedParams[x.name()]; if(!arr){ arr = []; describedParams[x.name()] = arr; } arr.push(x); }); let allParams:RamlWrapper.Parameter[] = []; let prev = 0; let mentionedParams = {}; for (let i = uri.indexOf('{'); i >= 0; i = uri.indexOf('{', prev)) { prev = uri.indexOf('}', ++i); if(prev<0){ break; } let paramName = uri.substring(i, prev); mentionedParams[paramName] = true; if (describedParams[paramName]) { describedParams[paramName].forEach(x=>allParams.push(x)); } else { let propUnit = propNode && hlimpl.actualUnit(propNode); let uriParameter = new RamlWrapperImpl.StringTypeDeclarationImpl(paramName); uriParameter.setName(paramName); let hlNode = uriParameter.highLevel(); (<jsyaml.ASTNode>hlNode.lowLevel()).setUnit(propUnit); hlNode.setParent(ownerHl); (<core.NodeMetadataImpl>uriParameter.meta()).setCalculated(); (<hlimpl.ASTNodeImpl>hlNode).patchProp(prop); allParams.push(uriParameter); } } Object.keys(describedParams).filter(x=>!mentionedParams[x]) .forEach(x=>describedParams[x].forEach(y=>allParams.push(y))); return allParams; } /** * __$helperMethod__ * __$meta__={"primary":true} **/ export function schemaContent(bodyDeclaration : RamlWrapper.BodyLike) : string { var schemaDecl = bodyDeclaration.schema(); if (schemaDecl == null) { return null; } var schemaString = schemaDecl.value(); if(!schemaString){ return null; } if(util.stringStartsWith(schemaString,"{") ||util.stringStartsWith(schemaString,"[") ||util.stringStartsWith(schemaString,"<")){ return schemaString; } var hlNode = bodyDeclaration.highLevel(); var root = hlNode.root(); var globalSchemas = root.elementsOfKind(universes.Universe08.Api.properties.schemas.name); var declaration = _.find(globalSchemas,x=>x.name()==schemaString); if (!declaration) return schemaString; if (!(<any>declaration).getKind || (<any>declaration).getKind() != hl.NodeKind.NODE) { return schemaString; } //we found the schema declaration and should get its contents if ((<hl.IHighLevelNode>declaration).definition().key() != universes.Universe08.GlobalSchema) { return schemaString; } var valueAttribute = (<hl.IHighLevelNode>declaration).attr(universes.Universe08.GlobalSchema.properties.value.name); if (valueAttribute == null) { return null; } return valueAttribute.value(); } /** * __$helperMethod__ * __$meta__={"name":"parametrizedProperties","primary":true} **/ export function getTemplateParametrizedProperties( node:RamlWrapper.Trait|RamlWrapper.ResourceType|RamlWrapper.Response|RamlWrapper.Method|RamlWrapper.Parameter|RamlWrapper.BodyLike):RamlWrapper.TypeInstance{ var highLevelNode = node.highLevel(); if(highLevelNode==null){ return null; } var lowLevelNode = highLevelNode.lowLevel(); if(lowLevelNode==null){ return null; } var children = lowLevelNode.children().filter(x=>x.key().indexOf("<<")>=0); if(children.length==0){ return null; } var result = new core.TypeInstanceImpl(children); return result; } // //export class SchemaDef{ // // constructor(private _content:string, private _name?:string){} // // name():string{return this._name} // // content(): string{return this._content} //} // // //export class ParamValue{ // key:string // value:any // // constructor(key:string, value:any) { // this.key = key; // this.value = value; // } //} // // //class ParamWrapper implements Raml08Parser.BasicNamedParameter{ // // constructor(private _param:RamlWrapper.TypeDeclaration){ // // this.description = _param.description() ? _param.description().value() : this.description; // // this.displayName = _param.displayName(); // //// this.enum = _param.enum(); // // this.type = _param.type().length > 0 ? _param.type()[0] : "string"; // // this.example = _param.example(); // // this.repeat = _param.repeat(); // // this.required = _param.required(); // // this.default = _param.default(); // } // // description: Raml08Parser.MarkdownString // // displayName: string // // 'enum': any[] // // type: string // // example: any // // repeat: boolean // // required: boolean // // 'default': any // //}
the_stack
import { Agent } from "https"; import axios from 'axios'; import type {AxiosResponse, AxiosError} from "axios"; import randomIpv6 from "random-ipv6"; import { hasProperty } from "./utils"; import { randomize } from '../config'; import { AlertLevel, isAlert, logAlert, TestingConfig } from "../config.model"; interface GetRequest { queryKey: string; queryValue: string | number | boolean; replace: string | number; route: string; } export interface IDData extends Record<string | number, unknown> { getRequest?: Array<GetRequest>; route?: string; } interface APIDataData extends Record<PropertyKey, unknown>, IDData { id?: unknown; } export interface APIData { action: string; data: Array<APIDataData>; method: string; route: string; } /** * Checks if an object is an AxiosError, usually useful in `try`/`catch` blocks * around axios calls. * * @param e The object to check. * @returns Whether or not `e` is an AxiosError. */ function isAxiosError(e: unknown): e is AxiosError { if (typeof(e) !== "object" || e === null) { return false; } if (!hasProperty(e, "isAxiosError", "boolean")) { return false; } return e.isAxiosError; } export class API { private cookie = ""; /** * This controls the alert levels that get logged - levels not in this set * are not logged */ private readonly alertLevels = new Set<AlertLevel>(["warning", "error", "info"]); /** * Stores login information for the admin-level user. */ private readonly loginInfo: { password: string; username: string; }; /** * The URL base used for the Traffic Ops API. * * Trailing `/` is guaranteed. * * @example * "https://localhost:6443/api/4.0/" */ private readonly apiURL: string; /** * @param cfg The testing configuration. */ constructor(cfg: TestingConfig) { axios.defaults.headers.common['Accept'] = 'application/json' axios.defaults.headers.common['Authorization'] = 'No-Auth' axios.defaults.headers.common['Content-Type'] = 'application/json' axios.defaults.httpsAgent = new Agent({ rejectUnauthorized: false }) if (cfg.alertLevels) { this.alertLevels = new Set(cfg.alertLevels); } this.loginInfo = cfg.login; this.apiURL = cfg.apiUrl.endsWith("/") ? cfg.apiUrl : `${cfg.apiUrl}/`; } /** * Logs the API client into Traffic Ops. * * @returns The API response from logging in. * @throws {Error} when login fails, or when Traffic Ops doesn't return a cookie. */ public async Login(): Promise<AxiosResponse<unknown>> { const data = { p: this.loginInfo.password, u: this.loginInfo.username, } const response = await this.getResponse("post", "/user/login", data); const h = response.headers as object; if (!hasProperty(h, "set-cookie", "Array") || h["set-cookie"].length < 1) { throw new Error("Traffic Ops response did not set a cookie"); } const cookie = await h["set-cookie"][0]; if (typeof(cookie) !== "string") { throw new Error(`non-string cookie: ${cookie}`); } this.cookie = cookie; return response } /** * Retrieves a response from the API. * * Alerts will be logged if they are found - even if an error occurs and is * thrown. * * @param method The request method to use. * @param path The path to request, relative to the configured TO API URL. * @returns The server's response. * @throws {unknown} when the request fails for any reason. If an error * response was returned from the API, it was logged, so there's no need to * dig into the properties of these errors, really. */ private async getResponse(method: "get" | "delete", path: string): Promise<AxiosResponse>; /** * Retrieves a response from the API. * * Alerts will be logged if they are found - even if an error occurs and is * thrown. * * @param method The request method to use. * @param path The path to request, relative to the configured TO API URL. * @param data Data to send in the body of the POST request. * @returns The server's response. * @throws {unknown} when the request fails for any reason. If an error * response was returned from the API, it was logged, so there's no need to * dig into the properties of these errors, really. */ private async getResponse(method: "post", path: string, data: unknown): Promise<AxiosResponse>; private async getResponse(method: "post" | "get" | "delete", path: string, data?: unknown): Promise<AxiosResponse> { if (method === "post" && data === undefined) { throw new TypeError("request body must be given for POST requests"); } const url = `${this.apiURL}${path.replace(/^\/+/g, "")}`; const conf = { method, url, headers: { Cookie: this.cookie }, data } let throwable; let resp: AxiosResponse<unknown>; try { resp = await axios(conf); } catch(e) { if (!isAxiosError(e) || !e.response) { console.debug("non-axios error or axios error with no response thrown"); throw e; } resp = e.response; throwable = e; } if (typeof(resp.data) === "object" && resp.data !== null && hasProperty(resp.data, "alerts", "Array")) { for (const a of resp.data.alerts) { if (isAlert(a) && this.alertLevels.has(a.level)) { logAlert(a, `${method.toUpperCase()} ${url} (${resp.status} ${resp.statusText}):`); } } } if (throwable) { throw throwable; } return resp; } public async SendRequest<T extends IDData>(route: string, method: string, data: T): Promise<void> { let response this.Randomize(data) if(data.hasOwnProperty('getRequest')){ let response; try { response = await this.GetId(data); } catch (e) { let msg = e instanceof Error ? e.message : String(e); if (response) { msg = `response status: ${response.statusText}, response data: ${response.data} - ${msg}`; } throw new Error(`Failed to get id: ${msg}`); } } switch (method) { case "post": response = await this.getResponse("post", route, data); break; case "get": response = await this.getResponse("get", route); break; case "delete": if (!data.route) { throw new Error("DELETE requests must include a 'route' data property") } if ((data.route).includes('?name')){ data.route = data.route + randomize } if ((data.route).includes('?id')){ if (!hasProperty(data, "id")) { throw new Error("route specified an 'id' query parameter, but data had no 'id' property"); } data.route = data.route + data.id; } if((data.route).includes('/service_categories/')){ data.route = data.route + randomize } response = await this.getResponse("delete", data.route); break; default: throw new Error(`unrecognized request method: '${method}'`); } if (response.status == 200 || response.status == 201) { return; } else { console.log("Reponse Data: " , response.data); console.log("Response: " , response); throw new Error(`request failed: response status: '${response.statusText}' response data: '${response.data}'`); } } public async GetId(data: IDData): Promise<null | AxiosResponse<unknown>> { if (!data.getRequest) { return null; } for (const request of data.getRequest) { let query = `?${encodeURIComponent(request.queryKey)}=`; if (request.queryValue === 'admin' || request.queryValue === 'operations' || request.queryValue === 'read-only'){ query += encodeURIComponent(request.queryValue); }else{ query += encodeURIComponent(request.queryValue+randomize); } const response = await this.getResponse("get", request.route + query) if (response.status == 200) { if(request.hasOwnProperty('isArray')){ data[request.replace] = [await response.data.response[0].id]; } else if (request.replace === "route") { data.route = data.route + response.data.response[0].id; } else { data[request.replace] = await response.data.response[0].id; } } else { // todo: should this be getting cut short like this? return response } } return null } public Randomize(data: object): void { if (hasProperty(data, "fullName")) { if (hasProperty(data, "email")) { data.email = data.fullName + randomize + data.email; } data.fullName = data.fullName + randomize; } if (hasProperty(data, "hostName")) { data.hostName = data.hostName + randomize; } if (hasProperty(data, "ipAddress")) { const rand = () => Math.floor(Math.random()*255)+1; data.ipAddress = `${rand()}.${rand()}.${rand()}.${rand()}`; } if(hasProperty(data, 'name')) { data.name = data.name + randomize; } if(hasProperty(data, 'requiredCapability')) { data.requiredCapability = data.requiredCapability + randomize; } if(hasProperty(data, 'serverCapability')) { data.serverCapability = data.serverCapability + randomize; } if(hasProperty(data, 'username')) { data.username = data.username + randomize; } if(hasProperty(data, 'xmlId')) { data.xmlId = data.xmlId + randomize; } if(hasProperty(data, 'shortName')) { data.shortName = data.shortName + randomize; } if(hasProperty(data, 'divisionName')) { data.divisionName = data.divisionName + randomize; } if(hasProperty(data, 'domainName')) { data.domainName = data.domainName + randomize; } if(hasProperty(data, 'nodes', "Array")){ data.nodes.map(i => { if (typeof(i) === "object" && i !== null && hasProperty(i, "cachegroup")) { i.cachegroup = i.cachegroup + randomize; } }); } if(hasProperty(data, 'interfaces', "Array")){ const ipv6 = randomIpv6(); for (const inf of data.interfaces) { if (typeof(inf) === "object" && inf !== null && hasProperty(inf, "ipAddresses", "Array")) { for (const ip of inf.ipAddresses) { (ip as Record<"address", string>).address = ipv6.toString(); } } } } } public async UseAPI(data: Array<APIData>): Promise<void> { const response = await this.Login(); if (response.status === 200) { for(let i = 0; i < data.length; i++){ for(let j = 0; j < data[i].data.length; j++){ const route = data[i].data[j].route ?? data[i].route; try { await this.SendRequest(route, data[i].method, data[i].data[j]); } catch (output) { if (output instanceof Error) { output = output.message; } console.debug(`${data[i].method} ${route}`); console.debug("DATA:", data[i].data[j]); throw new Error(`UseAPI failed on Action ${data[i].action} with index ${i}, and Data index ${j}: ${output}`); } } } } else if (response.status == undefined) { throw new Error(`Error requesting ${this.apiURL}: ${response}`); } else { throw new Error(`Login failed: Response Status: '${response.statusText}'' Response Data: '${response.data}'`); } } }
the_stack
import Vue from 'vue'; import VueRouter from 'vue-router'; // Style import './style.styl'; import init from '../init'; import fuckAdBlock from '../common/scripts/fuck-ad-block'; import composeNotification from '../common/scripts/compose-notification'; import MkHome from './views/home/home.vue'; import MkSelectDrive from './views/pages/selectdrive.vue'; import MkDrive from './views/pages/drive.vue'; import MkMessagingRoom from './views/pages/messaging-room.vue'; import MkReversi from './views/pages/games/reversi.vue'; import MkShare from '../common/views/pages/share.vue'; import MkFollow from '../common/views/pages/follow.vue'; import MkNotFound from '../common/views/pages/not-found.vue'; import MkSettings from './views/pages/settings.vue'; import DeckColumn from '../common/views/deck/deck.column-template.vue'; import Ctx from './views/components/context-menu.vue'; import RenoteFormWindow from './views/components/renote-form-window.vue'; import MkChooseFileFromDriveWindow from './views/components/choose-file-from-drive-window.vue'; import MkChooseFolderFromDriveWindow from './views/components/choose-folder-from-drive-window.vue'; import MkHomeTimeline from './views/home/timeline.vue'; import Notification from './views/components/ui-notification.vue'; import { url } from '../config'; import MiOS from '../mios'; /** * init */ init(async (launch, os) => { Vue.mixin({ methods: { $contextmenu(e, menu, opts?) { const o = opts || {}; const vm = this.$root.new(Ctx, { menu, x: e.pageX - window.pageXOffset, y: e.pageY - window.pageYOffset, }); vm.$once('closed', () => { if (o.closed) o.closed(); }); }, $post(opts) { const o = opts || {}; if (o.renote) { const vm = this.$root.new(RenoteFormWindow, { note: o.renote, animation: o.animation == null ? true : o.animation }); if (o.cb) vm.$once('closed', o.cb); } else { this.$root.newAsync(() => import('./views/components/post-form-window.vue').then(m => m.default), { reply: o.reply, mention: o.mention, animation: o.animation == null ? true : o.animation }).then(vm => { if (o.cb) vm.$once('closed', o.cb); }); } }, $chooseDriveFile(opts) { return new Promise((res, rej) => { const o = opts || {}; if (document.body.clientWidth > 800) { const w = this.$root.new(MkChooseFileFromDriveWindow, { title: o.title, multiple: o.multiple, initFolder: o.currentFolder }); w.$once('selected', file => { res(file); }); } else { window['cb'] = file => { res(file); }; window.open(url + `/selectdrive?multiple=${o.multiple}`, 'choose_drive_window', 'height=500, width=800'); } }); }, $chooseDriveFolder(opts) { return new Promise((res, rej) => { const o = opts || {}; const w = this.$root.new(MkChooseFolderFromDriveWindow, { title: o.title, initFolder: o.currentFolder }); w.$once('selected', folder => { res(folder); }); }); }, $notify(message) { this.$root.new(Notification, { message }); } } }); // Register directives require('./views/directives'); // Register components require('./views/components'); require('./views/widgets'); // Init router const router = new VueRouter({ mode: 'history', routes: [ os.store.state.device.inDeckMode ? { path: '/', name: 'index', component: () => import('../common/views/deck/deck.vue').then(m => m.default), children: [ { path: '/@:user', component: () => import('../common/views/deck/deck.user-column.vue').then(m => m.default), children: [ { path: '', name: 'user', component: () => import('../common/views/deck/deck.user-column.home.vue').then(m => m.default) }, { path: 'following', component: () => import('../common/views/pages/following.vue').then(m => m.default) }, { path: 'followers', component: () => import('../common/views/pages/followers.vue').then(m => m.default) }, ]}, { path: '/notes/:note', name: 'note', component: () => import('../common/views/deck/deck.note-column.vue').then(m => m.default) }, { path: '/search', component: () => import('../common/views/deck/deck.search-column.vue').then(m => m.default) }, { path: '/tags/:tag', name: 'tag', component: () => import('../common/views/deck/deck.hashtag-column.vue').then(m => m.default) }, { path: '/featured', name: 'featured', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/featured.vue').then(m => m.default), platform: 'deck' }) }, { path: '/explore', name: 'explore', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/explore.vue').then(m => m.default) }) }, { path: '/explore/tags/:tag', name: 'explore-tag', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/explore.vue').then(m => m.default), tag: route.params.tag }) }, { path: '/i/favorites', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/favorites.vue').then(m => m.default), platform: 'deck' }) }, { path: '/i/pages', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/pages.vue').then(m => m.default) }) }, { path: '/i/lists', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/user-lists.vue').then(m => m.default) }) }, { path: '/i/lists/:listId', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/user-list-editor.vue').then(m => m.default), listId: route.params.listId }) }, { path: '/i/groups', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/user-groups.vue').then(m => m.default) }) }, { path: '/i/groups/:groupId', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/user-group-editor.vue').then(m => m.default), groupId: route.params.groupId }) }, { path: '/i/follow-requests', component: DeckColumn, props: route => ({ component: () => import('../common/views/pages/follow-requests.vue').then(m => m.default) }) }, ]} : { path: '/', component: MkHome, children: [ { path: '', name: 'index', component: MkHomeTimeline }, { path: '/@:user', component: () => import('./views/home/user/index.vue').then(m => m.default), children: [ { path: '', name: 'user', component: () => import('./views/home/user/user.home.vue').then(m => m.default) }, { path: 'following', component: () => import('../common/views/pages/following.vue').then(m => m.default) }, { path: 'followers', component: () => import('../common/views/pages/followers.vue').then(m => m.default) }, ]}, { path: '/notes/:note', name: 'note', component: () => import('./views/home/note.vue').then(m => m.default) }, { path: '/search', component: () => import('./views/home/search.vue').then(m => m.default) }, { path: '/tags/:tag', name: 'tag', component: () => import('./views/home/tag.vue').then(m => m.default) }, { path: '/featured', name: 'featured', component: () => import('../common/views/pages/featured.vue').then(m => m.default), props: { platform: 'desktop' } }, { path: '/explore', name: 'explore', component: () => import('../common/views/pages/explore.vue').then(m => m.default) }, { path: '/explore/tags/:tag', name: 'explore-tag', props: true, component: () => import('../common/views/pages/explore.vue').then(m => m.default) }, { path: '/i/favorites', component: () => import('../common/views/pages/favorites.vue').then(m => m.default), props: { platform: 'desktop' } }, { path: '/i/pages', component: () => import('../common/views/pages/pages.vue').then(m => m.default) }, { path: '/i/lists', component: () => import('../common/views/pages/user-lists.vue').then(m => m.default) }, { path: '/i/lists/:listId', props: true, component: () => import('../common/views/pages/user-list-editor.vue').then(m => m.default) }, { path: '/i/groups', component: () => import('../common/views/pages/user-groups.vue').then(m => m.default) }, { path: '/i/groups/:groupId', props: true, component: () => import('../common/views/pages/user-group-editor.vue').then(m => m.default) }, { path: '/i/follow-requests', component: () => import('../common/views/pages/follow-requests.vue').then(m => m.default) }, { path: '/i/pages/new', component: () => import('../common/views/pages/page-editor/page-editor.vue').then(m => m.default) }, { path: '/i/pages/edit/:pageId', component: () => import('../common/views/pages/page-editor/page-editor.vue').then(m => m.default), props: route => ({ initPageId: route.params.pageId }) }, { path: '/@:user/pages/:page', component: () => import('../common/views/pages/page/page.vue').then(m => m.default), props: route => ({ pageName: route.params.page, username: route.params.user }) }, { path: '/@:user/pages/:pageName/view-source', component: () => import('../common/views/pages/page-editor/page-editor.vue').then(m => m.default), props: route => ({ initUser: route.params.user, initPageName: route.params.pageName }) }, ]}, { path: '/i/pages/new', component: () => import('../common/views/pages/page-editor/page-editor.vue').then(m => m.default) }, { path: '/i/pages/edit/:pageId', component: () => import('../common/views/pages/page-editor/page-editor.vue').then(m => m.default), props: route => ({ initPageId: route.params.pageId }) }, { path: '/@:user/pages/:page', component: () => import('../common/views/pages/page/page.vue').then(m => m.default), props: route => ({ pageName: route.params.page, username: route.params.user }) }, { path: '/@:user/pages/:pageName/view-source', component: () => import('../common/views/pages/page-editor/page-editor.vue').then(m => m.default), props: route => ({ initUser: route.params.user, initPageName: route.params.pageName }) }, { path: '/i/messaging/group/:group', component: MkMessagingRoom }, { path: '/i/messaging/:user', component: MkMessagingRoom }, { path: '/i/drive', component: MkDrive }, { path: '/i/drive/folder/:folder', component: MkDrive }, { path: '/i/settings', component: MkSettings }, { path: '/selectdrive', component: MkSelectDrive }, { path: '/share', component: MkShare }, { path: '/games/reversi/:game?', component: MkReversi }, { path: '/authorize-follow', component: MkFollow }, { path: '/deck', redirect: '/' }, { path: '*', component: MkNotFound } ], scrollBehavior(to, from, savedPosition) { return { x: 0, y: 0 }; } }); // Launch the app const [app, _] = launch(router); if (os.store.getters.isSignedIn) { /** * Fuck AD Block */ fuckAdBlock(app); } /** * Init Notification */ if ('Notification' in window && os.store.getters.isSignedIn) { // 許可を得ていなかったらリクエスト if ((Notification as any).permission == 'default') { await Notification.requestPermission(); } if ((Notification as any).permission == 'granted') { registerNotifications(os); } } }, true); function registerNotifications(os: MiOS) { const stream = os.stream; if (stream == null) return; const connection = stream.useSharedConnection('main'); connection.on('notification', notification => { const _n = composeNotification('notification', notification); const n = new Notification(_n.title, { body: _n.body, icon: _n.icon }); setTimeout(n.close.bind(n), 6000); }); connection.on('driveFileCreated', file => { const _n = composeNotification('driveFileCreated', file); const n = new Notification(_n.title, { body: _n.body, icon: _n.icon }); setTimeout(n.close.bind(n), 5000); }); connection.on('unreadMessagingMessage', message => { const _n = composeNotification('unreadMessagingMessage', message); const n = new Notification(_n.title, { body: _n.body, icon: _n.icon }); n.onclick = () => { n.close(); /*(riot as any).mount(document.body.appendChild(document.createElement('mk-messaging-room-window')), { user: message.user });*/ }; setTimeout(n.close.bind(n), 7000); }); connection.on('reversiInvited', matching => { const _n = composeNotification('reversiInvited', matching); const n = new Notification(_n.title, { body: _n.body, icon: _n.icon }); }); }
the_stack
declare module 'moleculer-elasticsearch' { export const actions: { bulk: { handler: any; params: { body: { type: string; }; index: { optional: boolean; type: string; }; type: { optional: boolean; type: string; }; }; }; call: { handler: any; params: { api: { type: string; }; params: { type: string; }; }; }; count: { handler: any; params: { body: { optional: boolean; type: string; }; q: { optional: boolean; type: string; }; }; }; create: { handler: any; params: { body: { type: string; }; id: { type: string; }; index: { type: string; }; type: { type: string; }; }; }; delete: { handler: any; params: { id: { type: string; }; index: { type: string; }; type: { type: string; }; }; }; get: { handler: any; params: { id: { type: string; }; index: { type: string; }; type: { type: string; }; }; }; search: { handler: any; params: { body: { optional: boolean; type: string; }; q: { optional: boolean; type: string; }; }; }; update: { handler: any; params: { body: { type: string; }; id: { type: string; }; index: { type: string; }; type: { type: string; }; }; }; }; export const methods: {}; export const name: string; export const settings: { elasticsearch: { apiVersion: string; host: string; }; }; } export interface ConfigOptions { host?: any; hosts?: any; httpAuth?: string; log?: any; apiVersion?: string; plugins?: any; sniffOnStart?: boolean; sniffInterval?: number; sniffOnConnectionFault?: boolean; maxRetries?: number; requestTimeout?: number; deadTimeout?: number; pingTimeout?: number; keepAlive?: boolean; maxSockets?: number; suggestCompression?: boolean; connectionClass?: string; sniffedNodesProtocol?: string; ssl?: object; selector?: any; defer?: () => void; nodesToHostCallback?: any; createNodeAgent?: any; } export interface Explanation { value: number; description: string; details: Explanation[]; } export interface GenericParams { requestTimeout?: number; maxRetries?: number; method?: string; body?: any; ignore?: number | number[]; filterPath?: string | string[]; } export interface ShardsResponse { total: number; successful: number; failed: number; skipped: number; } /** * A string of a number and a time unit. A time unit is one of * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. */ export type TimeSpan = string; export type NameList = string | string[] | boolean; export type Refresh = boolean | 'true' | 'false' | 'wait_for' | ''; export type VersionType = 'internal' | 'external' | 'external_gte' | 'force'; export type ExpandWildcards = 'open' | 'closed' | 'none' | 'all'; export type DefaultOperator = 'AND' | 'OR'; export type Conflicts = 'abort' | 'proceed'; export interface BulkIndexDocumentsParams extends GenericParams { waitForActiveShards?: string; refresh?: Refresh; routing?: string; timeout?: TimeSpan; type?: string; fields?: NameList; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; pipeline?: string; index?: string; } export interface ClearScrollParams extends GenericParams { scrollId: NameList; } export interface CountParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; minScore?: number; preference?: string; routing?: string; q?: string; analyzer?: string; analyzeWildcard?: boolean; defaultOperator?: DefaultOperator; df?: string; lenient?: boolean; lowercaseExpandedTerms?: boolean; index?: NameList; type?: NameList; } export interface CountResponse { count: number; _shards: ShardsResponse; } export interface CreateDocumentParams extends GenericParams { waitForActiveShards?: string; parent?: string; refresh?: Refresh; routing?: string; timeout?: TimeSpan; timestamp?: Date | number; ttl?: TimeSpan; version?: number; versionType?: VersionType; pipeline?: string; id?: string; index: string; type: string; } export interface CreateDocumentResponse { _shards: ShardsResponse; _index: string; _type: string; _id: string; _version: number; created: boolean; result: string; } export interface DeleteDocumentParams extends GenericParams { waitForActiveShards?: string; parent?: string; refresh?: Refresh; routing?: string; timeout?: TimeSpan; version?: number; versionType?: VersionType; index: string; type: string; id: string; } export interface DeleteDocumentResponse { _shards: ShardsResponse; found: boolean; _index: string; _type: string; _id: string; _version: number; result: string; } export interface DeleteDocumentByQueryParams extends GenericParams { analyzer?: string; analyzeWildcard?: boolean; defaultOperator?: DefaultOperator; df?: string; from?: number; ignoreUnavailable?: boolean; allowNoIndices?: boolean; conflicts?: Conflicts; expandWildcards?: ExpandWildcards; lenient?: boolean; lowercaseExpandedTerms?: boolean; preference?: string; q?: string; routing?: string | string[] | boolean; scroll?: string; searchType?: 'query_then_fetch' | 'dfs_query_then_fetch'; searchTimeout?: TimeSpan; size?: number; sort?: NameList; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; terminateAfter?: number; stats?: string | string[] | boolean; version?: number; requestCache?: boolean; refresh?: Refresh; timeout?: TimeSpan; waitForActiveShards?: string; scrollSize?: number; waitForCompletion?: boolean; requestsPerSecond?: number; slices?: number; index?: string; type?: string; } export interface DeleteDocumentByQueryResponse extends ReindexResponse { // DeleteDocumentByQueryResponse, UpdateDocumentByQueryResponse and ReindexResponse are identical } export interface DeleteScriptParams extends GenericParams { id: string; lang: string; } export interface DeleteTemplateParams extends GenericParams { id: string; } export interface ExistsParams extends GenericParams { parent?: string; preference?: string; realtime?: boolean; refresh?: boolean; routing?: string; id: string; index: string; type: string; } export interface ExplainParams extends GenericParams { analyzeWildcard?: boolean; analyzer?: string; defaultOperator?: DefaultOperator; df?: string; storedFields?: NameList; lenient?: boolean; lowercaseExpandedTerms?: boolean; parent?: string; preference?: string; q?: string; routing?: string; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; id?: string; index?: string; type?: string; } export interface ExplainResponse { _index: string; _type: string; _id: string; matched: boolean; explanation: ExplainResponseDetails; } export interface ExplainResponseDetails { value: number; description: string; details: ExplainResponseDetails[]; } export interface FieldStatsParams extends GenericParams { fields?: NameList; level?: 'indices' | 'cluster'; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index?: NameList; } export interface FieldStatsResponse { _shards: ShardsResponse; indices: { [indexName: string]: FieldStatsResponseIndex }; conflicts?: { [fieldName: string]: string }; } export interface FieldStatsResponseIndex { fields: { [fieldName: string]: FieldStatsResponseField }; } export interface FieldStatsResponseField { max_doc: number; doc_count: number; density: number; sum_doc_freq: number; sum_total_term_freq: number; min_value: any; max_value: any; is_searchable: string; is_aggregatable: string; } export interface GetParams extends GenericParams { storedFields?: NameList; parent?: string; preference?: string; realtime?: boolean; refresh?: boolean; routing?: string; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; version?: number; versionType?: VersionType; id: string; index: string; type: string; } export interface GetResponse<T> { _index: string; _type: string; _id: string; _version: number; _routing?: string; found: boolean; _source: T; } export interface GetScriptParams extends GenericParams { id: string; lang: string; } export interface GetSourceParams extends GenericParams { preference?: string; realtime?: boolean; refresh?: boolean; routing?: string; _source: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; version?: number; versionType?: VersionType; id: string; index: string; type: string; } export interface GetTemplateParams extends GenericParams { id: string; } export interface IndexDocumentParams<T> extends GenericParams { waitForActiveShards?: string; opType?: 'index' | 'create'; parent?: string; refresh?: Refresh; routing?: string; timeout?: TimeSpan; timestamp?: Date | number; ttl?: TimeSpan; version?: number; versionType?: VersionType; pipeline?: string; id?: string; index: string; type: string; body: T; } export interface InfoParams extends GenericParams {} export interface MGetParams extends GenericParams { storedFields?: NameList; preference?: string; realtime?: boolean; refresh?: boolean; routing?: string; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; index?: string; type?: string; } export interface MGetResponse<T> { docs?: Array<GetResponse<T>>; } export interface MSearchParams extends GenericParams { search_type?: | 'query_then_fetch' | 'query_and_fetch' | 'dfs_query_then_fetch' | 'dfs_query_and_fetch'; maxConcurrentSearches?: number; index?: NameList; type?: NameList; } export interface MSearchResponse<T> { responses?: Array<SearchResponse<T>>; } export interface MSearchTemplateParams extends GenericParams { search_type?: | 'query_then_fetch' | 'query_and_fetch' | 'dfs_query_then_fetch' | 'dfs_query_and_fetch'; index?: NameList; type?: NameList; } export interface MTermVectorsParams extends GenericParams { ids?: NameList; termStatistics?: boolean; fieldStatistics?: boolean; fields?: NameList; offsets?: boolean; positions?: boolean; payloads?: boolean; preference?: string; routing?: string; parent?: string; realtime?: boolean; version?: number; versionType?: VersionType; index: string; type: string; } export interface PingParams extends GenericParams {} export interface PutScriptParams extends GenericParams { id: string; lang: string; body: any; } export interface PutTemplateParams extends GenericParams { id: string; body: any; } export interface ReindexParams extends GenericParams { refresh?: boolean; timeout?: TimeSpan; waitForActiveShards?: string; waitForCompletion?: boolean; requestsPerSecond?: number; slices?: number; body: { conflicts?: string; source: { index: string | string[]; type?: string | string[]; query?: any; sort?: any; size?: number; remote?: { host: string; username?: string; password?: string; }; }; dest: { index: string; version_type?: string; op_type?: string; routing?: string; pipeline?: string; }; script?: { inline: string; lang: string; }; }; } export interface ReindexRethrottleParams extends GenericParams { requestsPerSecond: number; taskId: string; } export interface RenderSearchTemplateParams extends GenericParams { id: string; } export interface ScrollParams extends GenericParams { scroll: TimeSpan; scrollId: string; } export interface SearchParams extends GenericParams { analyzer?: string; analyzeWildcard?: boolean; defaultOperator?: DefaultOperator; df?: string; explain?: boolean; storedFields?: NameList; docvalueFields?: NameList; fielddataFields?: NameList; from?: number; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; lenient?: boolean; lowercaseExpandedTerms?: boolean; preference?: string; q?: string; routing?: NameList; scroll?: TimeSpan; searchType?: 'query_then_fetch' | 'dfs_query_then_fetch'; size?: number; sort?: NameList; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; terminateAfter?: number; stats?: NameList; suggestField?: string; suggestMode?: 'missing' | 'popular' | 'always'; suggestSize?: number; suggestText?: string; timeout?: TimeSpan; trackScores?: boolean; version?: boolean; requestCache?: boolean; index?: NameList; type?: NameList; } export interface SearchResponse<T> { took: number; timed_out: boolean; _scroll_id?: string; _shards: ShardsResponse; hits: { total: number; max_score: number; hits: Array<{ _index: string; _type: string; _id: string; _score: number; _source: T; _version?: number; _explanation?: Explanation; fields?: any; highlight?: any; inner_hits?: any; matched_queries?: string[]; sort?: string[]; }>; }; aggregations?: any; } export interface SearchShardsParams extends GenericParams { preference?: string; routing?: string; local?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index: NameList; type: NameList; } export interface SearchShardsResponse { nodes: any; shards: SearchShardsResponseShard[][]; } export interface SearchShardsResponseShard { index: string; node: string; primary: boolean; share: number; state: string; allocation_id: { id: string; }; relocating_node: any; } export interface SearchTemplateParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; preference?: string; routing?: NameList; scroll?: TimeSpan; searchType?: | 'query_then_fetch' | 'query_and_fetch' | 'dfs_query_then_fetch' | 'dfs_query_and_fetch'; index: NameList; type: NameList; } export interface SuggestParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; preference?: string; routing?: string; index: NameList; } export interface TermvectorsParams extends GenericParams { termStatistics?: boolean; fieldStatistics?: boolean; fields?: NameList; offsets?: boolean; positions?: boolean; payloads?: boolean; preference?: string; routing?: string; parent?: string; realtime?: boolean; version?: number; versionType?: VersionType; index: string; type: string; id?: string; } export interface UpdateDocumentParams extends GenericParams { waitForActiveShards?: string; fields?: NameList; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; lang?: string; parent?: string; refresh?: Refresh; retryOnConflict?: number; routing?: string; timeout?: TimeSpan; timestamp?: Date | number; ttl?: TimeSpan; version?: number; versionType?: 'internal' | 'force'; id: string; index: string; type: string; } export interface UpdateDocumentByQueryParams extends GenericParams { analyzer?: string; analyzeWildcard?: boolean; defaultOperator?: DefaultOperator; df?: string; explain?: boolean; storedFields?: NameList; docvalueFields?: NameList; fielddataFields?: NameList; from?: number; ignoreUnavailable?: boolean; allowNoIndices?: boolean; conflicts?: Conflicts; expandWildcards?: ExpandWildcards; lenient?: boolean; lowercaseExpandedTerms?: boolean; pipeline?: string; preference?: string; q?: string; routing?: NameList; scroll?: TimeSpan; searchType?: 'query_then_fetch' | 'dfs_query_then_fetch'; searchTimeout?: TimeSpan; size?: number; sort?: NameList; _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; terminateAfter?: number; stats?: NameList; suggestField?: string; suggestMode?: 'missing' | 'popular' | 'always'; suggestSize?: number; suggestText?: string; timeout?: TimeSpan; trackScores?: boolean; version?: boolean; versionType?: boolean; requestCache?: boolean; refresh?: boolean; waitForActiveShards?: string; scrollSize?: number; waitForCompletion?: boolean; requestsPerSecond?: number; slices?: number; index: NameList; type: NameList; } export interface UpdateDocumentByQueryResponse extends ReindexResponse { // DeleteDocumentByQueryResponse, UpdateDocumentByQueryResponse and ReindexResponse are identical } export interface ReindexResponse extends ReindexResponseBase { took: number; timed_out: boolean; failures: any[]; slices?: ReindexOrByQueryResponseSlice[]; } export interface ReindexOrByQueryResponseSlice extends ReindexResponseBase { slice_id: number; } export interface ReindexResponseBase { total: number; updated: number; deleted: number; batches: number; version_conflicts: number; noops: number; retries: { bulk: number; search: number; }; throttled_millis: number; requests_per_second: number; throttled_until_millis: number; } export interface Cat { aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; aliases(params: CatAliasesParams): Promise<any>; allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; allocation(params: CatAllocationParams): Promise<any>; count(params: CatCountParams, callback: (error: any, response: any) => void): void; count(params: CatAllocationParams): Promise<any>; fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; fielddata(params: CatFielddataParams): Promise<any>; health(params: CatHealthParams, callback: (error: any, response: any) => void): void; health(params: CatHealthParams): Promise<any>; help(params: CatHelpParams, callback: (error: any, response: any) => void): void; help(params: CatHelpParams): Promise<any>; indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; indices(params: CatIndicesParams): Promise<any>; master(params: CatCommonParams, callback: (error: any, response: any) => void): void; master(params: CatCommonParams): Promise<any>; nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; nodeattrs(params: CatCommonParams): Promise<any>; nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; nodes(params: CatCommonParams): Promise<any>; pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; pendingTasks(params: CatCommonParams): Promise<any>; plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; plugins(params: CatCommonParams): Promise<any>; recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; recovery(params: CatRecoveryParams): Promise<any>; repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; repositories(params: CatCommonParams): Promise<any>; segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; segments(params: CatSegmentsParams): Promise<any>; shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; shards(params: CatShardsParams): Promise<any>; snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; snapshots(params: CatSnapshotsParams): Promise<any>; tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; tasks(params: CatTasksParams): Promise<any>; threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; threadPool(params: CatThreadPoolParams): Promise<any>; } export type CatBytes = 'b' | 'k' | 'kb' | 'm' | 'mb' | 'g' | 'gb' | 't' | 'tb' | 'p' | 'pb'; export interface CatCommonParams extends GenericParams { format: string; local?: boolean; masterTimeout?: TimeSpan; h?: NameList; help?: boolean; v?: boolean; } export interface CatAliasesParams extends CatCommonParams { name?: NameList; } export interface CatAllocationParams extends CatCommonParams { bytes?: CatBytes; nodeId?: NameList; } export interface CatCountParams extends CatCommonParams { index?: NameList; } export interface CatFielddataParams extends CatCommonParams { bytes?: CatBytes; fields?: NameList; } export interface CatHealthParams extends CatCommonParams { ts?: boolean; } export interface CatHelpParams extends GenericParams { help?: boolean; } export interface CatIndicesParams extends CatCommonParams { bytes?: CatBytes; health?: 'green' | 'yellow' | 'red'; pri?: boolean; index?: NameList; } export interface CatRecoveryParams extends GenericParams { format: string; bytes?: CatBytes; masterTimeout?: TimeSpan; h?: NameList; help?: boolean; v?: boolean; } export interface CatSegmentsParams extends GenericParams { format: string; h?: NameList; help?: boolean; v?: boolean; index?: NameList; } export interface CatShardsParams extends CatCommonParams { index?: NameList; } export interface CatSnapshotsParams extends GenericParams { format: string; ignoreUnavailable?: boolean; masterTimeout?: TimeSpan; h?: NameList; help?: boolean; v?: boolean; repository?: NameList; } export interface CatTasksParams extends GenericParams { format: string; nodeId?: NameList; actions?: NameList; detailed?: boolean; parentNode?: string; parentTask?: number; h?: NameList; help?: boolean; v?: boolean; } export interface CatThreadPoolParams extends CatCommonParams { size?: '' | 'k' | 'm' | 'g' | 't' | 'p'; threadPoolPatterns?: NameList; } export interface Cluster { allocationExplain( params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void ): void; allocationExplain(params: ClusterAllocationExplainParams): Promise<any>; getSettings( params: ClusterGetSettingsParams, callback: (error: any, response: any) => void ): void; getSettings(params: ClusterGetSettingsParams): Promise<any>; health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; health(params: ClusterHealthParams): Promise<any>; pendingTasks( params: ClusterPendingTasksParams, callback: (error: any, response: any) => void ): void; pendingTasks(params: ClusterPendingTasksParams): Promise<any>; putSettings( params: ClusterPutSettingsParams, callback: (error: any, response: any) => void ): void; putSettings(params: ClusterPutSettingsParams): Promise<any>; reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; reroute(params: ClusterRerouteParams): Promise<any>; state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; state(params: ClusterStateParams): Promise<any>; stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; stats(params: ClusterStatsParams): Promise<any>; } export interface ClusterAllocationExplainParams extends GenericParams { includeYesDecisions?: boolean; includeDiskInfo?: boolean; } export interface ClusterGetSettingsParams extends GenericParams { flatSettings?: boolean; masterTimeout?: TimeSpan; timeout?: TimeSpan; includeDefaults?: boolean; } export interface ClusterHealthParams extends GenericParams { level?: 'cluster' | 'indices' | 'shards'; local?: boolean; masterTimeout?: TimeSpan; waitForActiveShards?: string; waitForNodes?: string; waitForEvents?: 'immediate' | 'urgent' | 'high' | 'normal' | 'low' | 'languid'; waitForRelocatingShards?: boolean; waitForStatus?: 'green' | 'yellow' | 'red'; index?: NameList; } export interface ClusterPendingTasksParams extends GenericParams { local?: boolean; masterTimeout?: TimeSpan; } export interface ClusterPutSettingsParams extends GenericParams { flatSettings?: boolean; masterTimeout?: TimeSpan; timeout?: TimeSpan; } export interface ClusterRerouteParams extends GenericParams { dryRun?: boolean; explain?: boolean; retryFailed?: boolean; metric?: NameList; masterTimeout?: TimeSpan; timeout?: TimeSpan; } export interface ClusterStateParams extends GenericParams { local?: boolean; masterTimeout?: TimeSpan; flatSettings?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index?: NameList; metric?: NameList; } export interface ClusterStatsParams extends GenericParams { flatSettings?: boolean; human?: boolean; timeout?: TimeSpan; nodeId?: NameList; } export class Indices { analyze( params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void ): void; analyze(params: IndicesAnalyzeParams): Promise<any>; clearCache( params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void ): void; clearCache(params: IndicesClearCacheParams): Promise<any>; close( params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void ): void; close(params: IndicesCloseParams): Promise<any>; create( params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void ): void; create(params: IndicesCreateParams): Promise<any>; delete( params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void ): void; delete(params: IndicesDeleteParams): Promise<any>; deleteAlias( params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void ): void; deleteAlias(params: IndicesDeleteAliasParams): Promise<any>; deleteTemplate( params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void ): void; deleteTemplate(params: IndicesDeleteTemplateParams): Promise<any>; exists( params: IndicesExistsParams, callback: (error: any, response: boolean, status: any) => void ): void; exists(params: IndicesExistsParams): Promise<boolean>; existsAlias( params: IndicesExistsAliasParams, callback: (error: any, response: boolean, status: any) => void ): void; existsAlias(params: IndicesExistsAliasParams): Promise<boolean>; existsTemplate( params: IndicesExistsTemplateParams, callback: (error: any, response: boolean, status: any) => void ): void; existsTemplate(params: IndicesExistsTemplateParams): Promise<boolean>; existsType( params: IndicesExistsTypeParams, callback: (error: any, response: boolean, status: any) => void ): void; existsType(params: IndicesExistsTypeParams): Promise<boolean>; flush( params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void ): void; flush(params: IndicesFlushParams): Promise<any>; flushSynced( params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void ): void; flushSynced(params: IndicesFlushSyncedParams): Promise<any>; forcemerge( params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void ): void; forcemerge(params: IndicesForcemergeParams): Promise<any>; get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; get(params: IndicesGetParams): Promise<any>; getAlias( params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void ): void; getAlias(params: IndicesGetAliasParams): Promise<any>; getFieldMapping( params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void ): void; getFieldMapping(params: IndicesGetFieldMappingParams): Promise<any>; getMapping( params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void ): void; getMapping(params: IndicesGetMappingParams): Promise<any>; getSettings( params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void ): void; getSettings(params: IndicesGetSettingsParams): Promise<any>; getTemplate( params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void ): void; getTemplate(params: IndicesGetTemplateParams): Promise<any>; getUpgrade( params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void ): void; getUpgrade(params: IndicesGetUpgradeParams): Promise<any>; open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; open(params: IndicesOpenParams): Promise<any>; putAlias( params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void ): void; putAlias(params: IndicesPutAliasParams): Promise<any>; putMapping( params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void ): void; putMapping(params: IndicesPutMappingParams): Promise<any>; putSettings( params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void ): void; putSettings(params: IndicesPutSettingsParams): Promise<any>; putTemplate( params: IndicesPutTemplateParams, callback: (error: any, response: any) => void ): void; putTemplate(params: IndicesPutTemplateParams): Promise<any>; recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; recovery(params: IndicesRecoveryParams): Promise<any>; refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; refresh(params: IndicesRefreshParams): Promise<any>; rollover( params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void ): void; rollover(params: IndicesRolloverParams): Promise<IndicesRolloverResponse>; segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; segments(params: IndicesSegmentsParams): Promise<any>; shardStores( params: IndicesShardStoresParams, callback: (error: any, response: any) => void ): void; shardStores(params: IndicesShardStoresParams): Promise<any>; shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; shrink(params: IndicesShrinkParams): Promise<any>; stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; stats(params: IndicesStatsParams): Promise<any>; updateAliases( params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void ): void; updateAliases(params: IndicesUpdateAliasesParams): Promise<any>; upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; upgrade(params: IndicesUpgradeParams): Promise<any>; validateQuery( params: IndicesValidateQueryParams, callback: (error: any, response: any) => void ): void; validateQuery(params: IndicesValidateQueryParams): Promise<any>; } export interface IndicesAnalyzeParams extends GenericParams { analyzer?: string; charFilter?: NameList; field?: string; filter?: NameList; index?: string; perferLocal?: boolean; text?: NameList; tokenizer?: string; explain?: boolean; attributes?: NameList; format?: ''; } export interface IndicesClearCacheParams extends GenericParams { fieldData?: boolean; fielddata?: boolean; // yes the docs really have both fields?: NameList; query?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index?: NameList; recycler?: boolean; request?: boolean; } export interface IndicesCloseParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index: NameList; } export interface IndicesCreateParams extends GenericParams { waitForActiveShards?: string; timeout?: TimeSpan; masterTimeout?: TimeSpan; updateAllTypes?: boolean; index: string; } export interface IndicesDeleteParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; index: NameList; ignoreUnavailable?: boolean; } export interface IndicesDeleteAliasParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; index: NameList; name: NameList; } export interface IndicesDeleteTemplateParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; name: string; } export interface IndicesExistsParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; local?: boolean; index: NameList; } export interface IndicesExistsAliasParams extends IndicesExistsParams { name: NameList; } export interface IndicesExistsTemplateParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; name: NameList; } export interface IndicesExistsTypeParams extends IndicesExistsParams { type: NameList; } export interface IndicesFlushParams extends GenericParams { force?: boolean; waitIfOngoing?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index: NameList; } export interface IndicesFlushSyncedParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index: NameList; } export interface IndicesForcemergeParams extends GenericParams { flush?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; maxNumSegments?: number; onlyExpungeDeletes?: boolean; operationThreading?: any; // even the docs don't know what this does waitForMerge?: boolean; index: NameList; } export interface IndicesGetParams extends GenericParams { local?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; flatSettings?: boolean; human?: boolean; includeDefaults?: boolean; index?: NameList; feature?: NameList; } export interface IndicesGetAliasParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; local?: boolean; index?: NameList; name?: NameList; } export interface IndicesGetFieldMappingParams extends GenericParams { includeDefaults?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; local?: boolean; index?: NameList; type?: NameList; fields?: NameList; } export interface IndicesGetMappingParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; local?: boolean; index?: NameList; type?: NameList; } export interface IndicesGetSettingsParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; flatSettings?: boolean; local?: boolean; human?: boolean; includeDefaults?: boolean; index?: NameList; name?: NameList; } export interface IndicesGetTemplateParams extends GenericParams { flatSettings?: boolean; masterTimeout?: TimeSpan; local?: boolean; name?: NameList; } export interface IndicesGetUpgradeParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; human?: boolean; index?: NameList; } export interface IndicesOpenParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; index?: NameList; } export interface IndicesPutAliasParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; index?: NameList; name: NameList; } export interface IndicesPutMappingParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; updateAllTypes?: boolean; index: NameList; type: string; body: any; } export interface IndicesPutSettingsParams extends GenericParams { masterTimeout?: TimeSpan; preserveExisting?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; flatSettings?: boolean; index: NameList; body: any; } export interface IndicesPutTemplateParams extends GenericParams { order?: number; create?: boolean; timeout?: TimeSpan; masterTimeout?: TimeSpan; flatSettings?: boolean; name: string; body: any; } export interface IndicesRecoveryParams extends GenericParams { detailed?: boolean; activeOnly?: boolean; human?: boolean; index: NameList; } export interface IndicesRefreshParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; force?: boolean; operationThreading?: any; // even the docs don't know what this does index: NameList; } export interface IndicesRolloverParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; waitForActiveShards?: number | string; alias?: string; newIndex?: string; } export interface IndicesRolloverResponse { acknowledged: boolean; shards_acknowledged: boolean; old_index: string; new_index: string; rolled_over: boolean; dry_run: boolean; conditions: { [condition: string]: boolean }; } export interface IndicesSegmentsParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; human?: boolean; operationThreading?: any; // even the docs don't know what this does verbose?: boolean; index: NameList; } export interface IndicesShardStoresParams extends GenericParams { status?: NameList; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; operationThreading?: any; // even the docs don't know what this does index: NameList; } export interface IndicesShrinkParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; waitForActiveShards?: string | number; index: string; target: string; } export interface IndicesStatsParams extends GenericParams { completionFields?: NameList; fielddataFields?: NameList; fields?: NameList; groups?: NameList; human?: boolean; level?: 'cluster' | 'indices' | 'shards'; types?: NameList; index: NameList; metric?: NameList; } export interface IndicesUpdateAliasesParams extends GenericParams { timeout?: TimeSpan; masterTimeout?: TimeSpan; body: { actions: IndicesUpdateAliasesParamsAction[]; }; } export interface IndicesUpdateAliasesParamsAction { add?: { index?: string; indices?: string[]; alias: string; routing?: string; filter?: object; }; remove?: { index?: string; indices?: string[]; alias: string; }; remove_index?: { index: string; }; } export interface IndicesUpgradeParams extends GenericParams { expandWildcards?: ExpandWildcards; ignoreUnavailable?: boolean; waitForCompletion?: boolean; onlyAncientSegments?: boolean; index: NameList; } export interface IndicesValidateQueryParams extends GenericParams { explain?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; operationThreading?: any; // even the docs don't know what this does q?: string; analyzer?: string; analyzeWildcard?: boolean; defaultOperator?: DefaultOperator; df?: string; lenient?: boolean; lowercaseExpandedTerms?: boolean; rewrite?: boolean; index: NameList; type?: NameList; } export class Ingest { deletePipeline( params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void ): void; deletePipeline(params: IngestDeletePipelineParams): Promise<any>; getPipeline( params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void ): void; getPipeline(params: IngestGetPipelineParams): Promise<any>; putPipeline( params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void ): void; putPipeline(params: IngestPutPipelineParams): Promise<any>; simulate( params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void ): void; simulate(params: IngestSimulateParams): Promise<any>; } export interface IngestDeletePipelineParams extends GenericParams { masterTimeout?: number; timeout?: number; id: string; } export interface IngestGetPipelineParams extends GenericParams { masterTimeout?: number; id: string; } export interface IngestPutPipelineParams extends GenericParams { masterTimeout?: number; timeout?: number; id: string; body: any; } export interface IngestSimulateParams extends GenericParams { verbose?: boolean; id: string; } export class Nodes { hotThreads( params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void ): void; hotThreads(params: NodesHotThreadsParams): Promise<any>; info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; info(params: NodesInfoParams): Promise<any>; stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; stats(params: NodesStatsParams): Promise<any>; } export interface NodesHotThreadsParams extends GenericParams { interval?: TimeSpan; snapshots?: number; threads?: number; ignoreIdleThreads?: boolean; type?: 'cpu' | 'wait' | 'blocked'; timeout?: TimeSpan; nodeId: NameList; } export interface NodesInfoParams extends GenericParams { flatSettings?: boolean; human?: boolean; timeout?: TimeSpan; nodeId: NameList; metric?: NameList; } export interface NodesStatsParams extends GenericParams { completionFields?: NameList; fielddataFields?: NameList; fields?: NameList; groups?: boolean; human?: boolean; level?: 'indices' | 'node' | 'shards'; types?: NameList; timeout?: TimeSpan; metric?: NameList; indexMetric?: NameList; nodeId?: NameList; } export class Snapshot { create( params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void ): void; create(params: SnapshotCreateParams): Promise<any>; createRepository( params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void ): void; createRepository(params: SnapshotCreateRepositoryParams): Promise<any>; delete( params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void ): void; delete(params: SnapshotDeleteParams): Promise<any>; deleteRepository( params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void ): void; deleteRepository(params: SnapshotDeleteRepositoryParams): Promise<any>; get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; get(params: SnapshotGetParams): Promise<any>; getRepository( params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void ): void; getRepository(params: SnapshotGetRepositoryParams): Promise<any>; restore( params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void ): void; restore(params: SnapshotRestoreParams): Promise<any>; status( params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void ): void; status(params: SnapshotStatusParams): Promise<any>; verifyRepository( params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void ): void; verifyRepository(params: SnapshotVerifyRepositoryParams): Promise<any>; } export interface SnapshotCreateParams extends GenericParams { masterTimeout?: TimeSpan; waitForCompletion?: boolean; repository: string; snapshot: string; } export interface SnapshotCreateRepositoryParams extends GenericParams { masterTimeout?: TimeSpan; timeout?: TimeSpan; verify?: boolean; repository: string; } export interface SnapshotDeleteParams extends GenericParams { masterTimeout?: TimeSpan; repository: string; snapshot: string; } export interface SnapshotDeleteRepositoryParams extends GenericParams { masterTimeout?: TimeSpan; timeout?: TimeSpan; repository: string; } export interface SnapshotGetParams extends GenericParams { masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; repository: string; snapshot: NameList; } export interface SnapshotGetRepositoryParams extends GenericParams { masterTimeout?: TimeSpan; local?: boolean; repository: NameList; } export interface SnapshotRestoreParams extends GenericParams { masterTimeout?: TimeSpan; waitForCompletion?: boolean; repository: string; snapshot: string; } export interface SnapshotStatusParams extends GenericParams { masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; repository: string; snapshot: NameList; } export interface SnapshotVerifyRepositoryParams extends GenericParams { masterTimeout?: TimeSpan; timeout?: TimeSpan; repository: string; } export class Tasks { cancel( params: TasksCancelParams, callback: (error: any, response: any, status: any) => void ): void; cancel(params: TasksCancelParams): Promise<any>; get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; get(params: TasksGetParams): Promise<any>; list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; list(params: TasksListParams): Promise<any>; } export interface TasksCancelParams extends GenericParams { nodeId?: NameList; actions?: NameList; parentNode?: string; parentTask?: string; taskId?: string; } export interface TasksGetParams extends GenericParams { waitForCompletion?: boolean; taskId?: string; } export interface TasksListParams extends GenericParams { nodeId?: NameList; actions?: NameList; detailed?: boolean; parentNode?: string; parentTask?: string; waitForCompletion?: boolean; groupBy?: 'nodes' | 'parents'; } export namespace errors { class _Abstract extends Error {} class Generic extends _Abstract {} class ConnectionFault extends _Abstract {} class NoConnections extends _Abstract {} class Serialization extends _Abstract {} class RequestTypeError extends _Abstract {} class AuthenticationException extends _Abstract {} class AuthorizationException extends _Abstract {} class BadGateway extends _Abstract {} class BadRequest extends _Abstract {} class BlockedByWindowsParentalControls extends _Abstract {} class ClientClosedRequest extends _Abstract {} class Conflict extends _Abstract {} class ExpectationFailed extends _Abstract {} class GatewayTimeout extends _Abstract {} class HTTPToHTTPS extends _Abstract {} class HTTPVersionNotSupported extends _Abstract {} class ImATeapot extends _Abstract {} class InternalServerError extends _Abstract {} class LengthRequired extends _Abstract {} class MethodNotAllowed extends _Abstract {} class MovedPermanently extends _Abstract {} class MultipleChoices extends _Abstract {} class NotAcceptable extends _Abstract {} class NotExtended extends _Abstract {} class NotFound extends _Abstract {} class NotImplemented extends _Abstract {} class NotModified extends _Abstract {} class PaymentRequired extends _Abstract {} class PermanentRedirect extends _Abstract {} class PreconditionFailed extends _Abstract {} class ProxyAuthenticationRequired extends _Abstract {} class RequestedRangeNotSatisfiable extends _Abstract {} class RequestEntityTooLarge extends _Abstract {} class RequestHeaderTooLarge extends _Abstract {} class RequestTimeout extends _Abstract {} class RequestURITooLong extends _Abstract {} class SeeOther extends _Abstract {} class ServiceUnavailable extends _Abstract {} class TemporaryRedirect extends _Abstract {} class TooManyConnectionsFromThisIP extends _Abstract {} class TooManyRequests extends _Abstract {} class UnsupportedMediaType extends _Abstract {} class UpgradeRequired extends _Abstract {} class UseProxy extends _Abstract {} class VariantAlsoNegotiates extends _Abstract {} }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type MyBidsRefetchQueryVariables = {}; export type MyBidsRefetchQueryResponse = { readonly me: { readonly " $fragmentRefs": FragmentRefs<"MyBids_me">; } | null; }; export type MyBidsRefetchQuery = { readonly response: MyBidsRefetchQueryResponse; readonly variables: MyBidsRefetchQueryVariables; }; /* query MyBidsRefetchQuery { me { ...MyBids_me id } } fragment ActiveLotStanding_saleArtwork on SaleArtwork { ...Lot_saleArtwork isHighestBidder sale { status liveStartAt endAt id } lotState { bidCount reserveStatus soldStatus sellingPrice { display } } artwork { internalID href slug id } currentBid { display } estimate } fragment ClosedLotStanding_saleArtwork on SaleArtwork { ...Lot_saleArtwork isHighestBidder estimate artwork { internalID href slug id } lotState { soldStatus sellingPrice { display } } sale { endAt status id } } fragment LotStatusListItem_saleArtwork on SaleArtwork { ...ClosedLotStanding_saleArtwork ...ActiveLotStanding_saleArtwork ...WatchedLot_saleArtwork isWatching lotState { soldStatus } } fragment Lot_saleArtwork on SaleArtwork { lotLabel artwork { artistNames image { url(version: "medium") } id } } fragment MyBids_me on Me { ...SaleCard_me myBids { active { sale { ...SaleCard_sale internalID registrationStatus { qualifiedForBidding id } id } saleArtworks { ...LotStatusListItem_saleArtwork internalID id } } closed { sale { ...SaleCard_sale internalID registrationStatus { qualifiedForBidding id } id } saleArtworks { ...LotStatusListItem_saleArtwork internalID id } } } } fragment SaleCard_me on Me { identityVerified pendingIdentityVerification { internalID id } } fragment SaleCard_sale on Sale { internalID href slug name liveStartAt endAt coverImage { url } partner { name id } registrationStatus { qualifiedForBidding id } requireIdentityVerification } fragment WatchedLot_saleArtwork on SaleArtwork { ...Lot_saleArtwork lotState { bidCount sellingPrice { display } } artwork { internalID href slug id } currentBid { display } estimate } */ const node: ConcreteRequest = (function(){ var v0 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "liveStartAt", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "endAt", "storageKey": null }, v7 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ], v8 = [ { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ (v0/*: any*/), (v2/*: any*/), (v3/*: any*/), (v4/*: any*/), (v5/*: any*/), (v6/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "coverImage", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "url", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ (v4/*: any*/), (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Bidder", "kind": "LinkedField", "name": "registrationStatus", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "qualifiedForBidding", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "requireIdentityVerification", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtworks", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "lotLabel", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "medium" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"medium\")" } ], "storageKey": null }, (v1/*: any*/), (v0/*: any*/), (v2/*: any*/), (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isHighestBidder", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "estimate", "storageKey": null }, { "alias": null, "args": null, "concreteType": "CausalityLotState", "kind": "LinkedField", "name": "lotState", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "soldStatus", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Money", "kind": "LinkedField", "name": "sellingPrice", "plural": false, "selections": (v7/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "bidCount", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "reserveStatus", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ (v6/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, (v1/*: any*/), (v5/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": (v7/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isWatching", "storageKey": null }, (v0/*: any*/), (v1/*: any*/) ], "storageKey": null } ]; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "MyBidsRefetchQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "MyBids_me" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "MyBidsRefetchQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "identityVerified", "storageKey": null }, { "alias": null, "args": null, "concreteType": "IdentityVerification", "kind": "LinkedField", "name": "pendingIdentityVerification", "plural": false, "selections": [ (v0/*: any*/), (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "MyBids", "kind": "LinkedField", "name": "myBids", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "MyBid", "kind": "LinkedField", "name": "active", "plural": true, "selections": (v8/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "MyBid", "kind": "LinkedField", "name": "closed", "plural": true, "selections": (v8/*: any*/), "storageKey": null } ], "storageKey": null }, (v1/*: any*/) ], "storageKey": null } ] }, "params": { "id": "d9dfd137d0a2c8c2a494fb5943571d15", "metadata": {}, "name": "MyBidsRefetchQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '8462103a964907270808a756e26494dc'; export default node;
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type OrderDetailsTestsQueryVariables = {}; export type OrderDetailsTestsQueryResponse = { readonly commerceOrder: { readonly " $fragmentRefs": FragmentRefs<"OrderDetails_order">; } | null; }; export type OrderDetailsTestsQuery = { readonly response: OrderDetailsTestsQueryResponse; readonly variables: OrderDetailsTestsQueryVariables; }; /* query OrderDetailsTestsQuery { commerceOrder(id: "order-id") { __typename ...OrderDetails_order id } } fragment ArtworkInfoSection_artwork on CommerceOrder { __isCommerceOrder: __typename lineItems(first: 1) { edges { node { artwork { medium editionOf dimensions { in cm } date image { url(version: "square60") } title artistNames id } id } } } } fragment OrderDetailsHeader_info on CommerceOrder { __isCommerceOrder: __typename createdAt code state requestedFulfillment { __typename ... on CommerceShip { __typename } ... on CommercePickup { __typename } ... on CommerceShipArta { __typename } } lineItems(first: 1) { edges { node { shipment { status id } id } } } } fragment OrderDetailsPayment_order on CommerceOrder { __isCommerceOrder: __typename creditCard { brand lastDigits id } } fragment OrderDetails_order on CommerceOrder { __isCommerceOrder: __typename requestedFulfillment { __typename ... on CommerceShip { __typename name } ... on CommerceShipArta { __typename name } ... on CommercePickup { __typename } } lineItems(first: 1) { edges { node { artwork { partner { name id } id } id } } } ...OrderDetailsHeader_info ...ArtworkInfoSection_artwork ...SummarySection_section ...OrderDetailsPayment_order ...TrackOrderSection_section ...ShipsToSection_address ...SoldBySection_soldBy } fragment ShipsToSection_address on CommerceOrder { __isCommerceOrder: __typename requestedFulfillment { __typename ... on CommercePickup { __typename } ... on CommerceShip { __typename addressLine1 addressLine2 city country phoneNumber postalCode region } ... on CommerceShipArta { __typename addressLine1 addressLine2 city country phoneNumber postalCode region } } } fragment SoldBySection_soldBy on CommerceOrder { __isCommerceOrder: __typename requestedFulfillment { __typename ... on CommercePickup { __typename } } lineItems(first: 1) { edges { node { artwork { shippingOrigin id } fulfillments(first: 1) { edges { node { estimatedDelivery id } } } id } } } } fragment SummarySection_section on CommerceOrder { __isCommerceOrder: __typename mode buyerTotal(precision: 2) taxTotal(precision: 2) shippingTotal(precision: 2) totalListPrice(precision: 2) lineItems(first: 1) { edges { node { selectedShippingQuote { displayName id } id } } } ... on CommerceOfferOrder { lastOffer { amount(precision: 2) fromParticipant id } } } fragment TrackOrderSection_section on CommerceOrder { __isCommerceOrder: __typename state lineItems(first: 1) { edges { node { shipment { status trackingUrl trackingNumber deliveryStart deliveryEnd estimatedDeliveryWindow id } fulfillments(first: 1) { edges { node { createdAt trackingId estimatedDelivery id } } } id } } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "order-id" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v3 = [ (v2/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "addressLine1", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "addressLine2", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "city", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "country", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "phoneNumber", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "postalCode", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "region", "storageKey": null } ], v4 = [ { "kind": "Literal", "name": "first", "value": 1 } ], v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "createdAt", "storageKey": null }, v7 = [ { "kind": "Literal", "name": "precision", "value": 2 } ], v8 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v9 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v10 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "OrderDetailsTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "OrderDetails_order" } ], "storageKey": "commerceOrder(id:\"order-id\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "OrderDetailsTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ (v1/*: any*/), { "kind": "TypeDiscriminator", "abstractKey": "__isCommerceOrder" }, { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "requestedFulfillment", "plural": false, "selections": [ (v1/*: any*/), { "kind": "InlineFragment", "selections": (v3/*: any*/), "type": "CommerceShip", "abstractKey": null }, { "kind": "InlineFragment", "selections": (v3/*: any*/), "type": "CommerceShipArta", "abstractKey": null } ], "storageKey": null }, { "alias": null, "args": (v4/*: any*/), "concreteType": "CommerceLineItemConnection", "kind": "LinkedField", "name": "lineItems", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItem", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ (v2/*: any*/), (v5/*: any*/) ], "storageKey": null }, (v5/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "medium", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "editionOf", "storageKey": null }, { "alias": null, "args": null, "concreteType": "dimensions", "kind": "LinkedField", "name": "dimensions", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "in", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "cm", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "square60" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"square60\")" } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "shippingOrigin", "storageKey": null } ], "storageKey": null }, (v5/*: any*/), { "alias": null, "args": null, "concreteType": "CommerceShipment", "kind": "LinkedField", "name": "shipment", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, (v5/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingUrl", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingNumber", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "deliveryStart", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "deliveryEnd", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "estimatedDeliveryWindow", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "CommerceShippingQuote", "kind": "LinkedField", "name": "selectedShippingQuote", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "displayName", "storageKey": null }, (v5/*: any*/) ], "storageKey": null }, { "alias": null, "args": (v4/*: any*/), "concreteType": "CommerceFulfillmentConnection", "kind": "LinkedField", "name": "fulfillments", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceFulfillmentEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceFulfillment", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v6/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingId", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "estimatedDelivery", "storageKey": null }, (v5/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "fulfillments(first:1)" } ], "storageKey": null } ], "storageKey": null } ], "storageKey": "lineItems(first:1)" }, (v6/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "code", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "state", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "mode", "storageKey": null }, { "alias": null, "args": (v7/*: any*/), "kind": "ScalarField", "name": "buyerTotal", "storageKey": "buyerTotal(precision:2)" }, { "alias": null, "args": (v7/*: any*/), "kind": "ScalarField", "name": "taxTotal", "storageKey": "taxTotal(precision:2)" }, { "alias": null, "args": (v7/*: any*/), "kind": "ScalarField", "name": "shippingTotal", "storageKey": "shippingTotal(precision:2)" }, { "alias": null, "args": (v7/*: any*/), "kind": "ScalarField", "name": "totalListPrice", "storageKey": "totalListPrice(precision:2)" }, { "alias": null, "args": null, "concreteType": "CreditCard", "kind": "LinkedField", "name": "creditCard", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "brand", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lastDigits", "storageKey": null }, (v5/*: any*/) ], "storageKey": null }, (v5/*: any*/), { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "concreteType": "CommerceOffer", "kind": "LinkedField", "name": "lastOffer", "plural": false, "selections": [ { "alias": null, "args": (v7/*: any*/), "kind": "ScalarField", "name": "amount", "storageKey": "amount(precision:2)" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "fromParticipant", "storageKey": null }, (v5/*: any*/) ], "storageKey": null } ], "type": "CommerceOfferOrder", "abstractKey": null } ], "storageKey": "commerceOrder(id:\"order-id\")" } ] }, "params": { "id": "2deb519c2c3f0babb6886e2c84b60260", "metadata": { "relayTestingSelectionTypeInfo": { "commerceOrder": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOrder" }, "commerceOrder.__isCommerceOrder": (v8/*: any*/), "commerceOrder.__typename": (v8/*: any*/), "commerceOrder.buyerTotal": (v9/*: any*/), "commerceOrder.code": (v8/*: any*/), "commerceOrder.createdAt": (v8/*: any*/), "commerceOrder.creditCard": { "enumValues": null, "nullable": true, "plural": false, "type": "CreditCard" }, "commerceOrder.creditCard.brand": (v8/*: any*/), "commerceOrder.creditCard.id": (v10/*: any*/), "commerceOrder.creditCard.lastDigits": (v8/*: any*/), "commerceOrder.id": (v10/*: any*/), "commerceOrder.lastOffer": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOffer" }, "commerceOrder.lastOffer.amount": (v9/*: any*/), "commerceOrder.lastOffer.fromParticipant": { "enumValues": [ "BUYER", "SELLER" ], "nullable": true, "plural": false, "type": "CommerceOrderParticipantEnum" }, "commerceOrder.lastOffer.id": (v10/*: any*/), "commerceOrder.lineItems": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItemConnection" }, "commerceOrder.lineItems.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceLineItemEdge" }, "commerceOrder.lineItems.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItem" }, "commerceOrder.lineItems.edges.node.artwork": { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, "commerceOrder.lineItems.edges.node.artwork.artistNames": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.date": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.dimensions": { "enumValues": null, "nullable": true, "plural": false, "type": "dimensions" }, "commerceOrder.lineItems.edges.node.artwork.dimensions.cm": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.dimensions.in": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.editionOf": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.id": (v10/*: any*/), "commerceOrder.lineItems.edges.node.artwork.image": { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, "commerceOrder.lineItems.edges.node.artwork.image.url": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.medium": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.partner": { "enumValues": null, "nullable": true, "plural": false, "type": "Partner" }, "commerceOrder.lineItems.edges.node.artwork.partner.id": (v10/*: any*/), "commerceOrder.lineItems.edges.node.artwork.partner.name": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.shippingOrigin": (v9/*: any*/), "commerceOrder.lineItems.edges.node.artwork.title": (v9/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceFulfillmentConnection" }, "commerceOrder.lineItems.edges.node.fulfillments.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceFulfillmentEdge" }, "commerceOrder.lineItems.edges.node.fulfillments.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceFulfillment" }, "commerceOrder.lineItems.edges.node.fulfillments.edges.node.createdAt": (v8/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments.edges.node.estimatedDelivery": (v9/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments.edges.node.id": (v10/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments.edges.node.trackingId": (v9/*: any*/), "commerceOrder.lineItems.edges.node.id": (v10/*: any*/), "commerceOrder.lineItems.edges.node.selectedShippingQuote": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceShippingQuote" }, "commerceOrder.lineItems.edges.node.selectedShippingQuote.displayName": (v8/*: any*/), "commerceOrder.lineItems.edges.node.selectedShippingQuote.id": (v10/*: any*/), "commerceOrder.lineItems.edges.node.shipment": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceShipment" }, "commerceOrder.lineItems.edges.node.shipment.deliveryEnd": (v9/*: any*/), "commerceOrder.lineItems.edges.node.shipment.deliveryStart": (v9/*: any*/), "commerceOrder.lineItems.edges.node.shipment.estimatedDeliveryWindow": (v9/*: any*/), "commerceOrder.lineItems.edges.node.shipment.id": (v10/*: any*/), "commerceOrder.lineItems.edges.node.shipment.status": (v9/*: any*/), "commerceOrder.lineItems.edges.node.shipment.trackingNumber": (v9/*: any*/), "commerceOrder.lineItems.edges.node.shipment.trackingUrl": (v9/*: any*/), "commerceOrder.mode": { "enumValues": [ "BUY", "OFFER" ], "nullable": true, "plural": false, "type": "CommerceOrderModeEnum" }, "commerceOrder.requestedFulfillment": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceRequestedFulfillmentUnion" }, "commerceOrder.requestedFulfillment.__typename": (v8/*: any*/), "commerceOrder.requestedFulfillment.addressLine1": (v9/*: any*/), "commerceOrder.requestedFulfillment.addressLine2": (v9/*: any*/), "commerceOrder.requestedFulfillment.city": (v9/*: any*/), "commerceOrder.requestedFulfillment.country": (v9/*: any*/), "commerceOrder.requestedFulfillment.name": (v9/*: any*/), "commerceOrder.requestedFulfillment.phoneNumber": (v9/*: any*/), "commerceOrder.requestedFulfillment.postalCode": (v9/*: any*/), "commerceOrder.requestedFulfillment.region": (v9/*: any*/), "commerceOrder.shippingTotal": (v9/*: any*/), "commerceOrder.state": { "enumValues": [ "ABANDONED", "APPROVED", "CANCELED", "FULFILLED", "PENDING", "REFUNDED", "SUBMITTED" ], "nullable": false, "plural": false, "type": "CommerceOrderStateEnum" }, "commerceOrder.taxTotal": (v9/*: any*/), "commerceOrder.totalListPrice": (v9/*: any*/) } }, "name": "OrderDetailsTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '76f7f61c266d40b4bf94126da71e5bb3'; export default node;
the_stack
import { StackFrame } from "error-stack-parser"; import { forkJoin, Observable, of, Subscriber, Subscription } from "rxjs"; import { mapTo } from "rxjs/operators"; import { identify } from "../identify"; import { read } from "../match"; import { hide } from "../operators"; import { Spy } from "../spy-interface"; import { SubscriberRef, SubscriptionRef } from "../subscription-ref"; import { inferPath, inferType } from "../util"; import { getGraphRef, GraphRef } from "./graph-plugin"; import { BasePlugin } from "./plugin"; import { getMappedStackTrace, getStackTrace } from "./stack-trace-plugin"; const snapshotRefSymbol = Symbol("snapshotRef"); export interface SnapshotRef { complete: boolean; error: any; tick: number; timestamp: number; unsubscribed: boolean; values: { tick: number; timestamp: number; value: any; }[]; valuesFlushed: number; } export function getSnapshotRef(ref: SubscriberRef): SnapshotRef { return ref[snapshotRefSymbol]; } function mapStackTraces(observableSnapshots: ObservableSnapshot[]): Observable<void>; function mapStackTraces(subscriberSnapshots: SubscriberSnapshot[]): Observable<void>; function mapStackTraces(subscriptionSnapshots: SubscriptionSnapshot[]): Observable<void>; function mapStackTraces(snapshots: any[]): Observable<void> { const observables: Observable<any>[] = [of(null)]; snapshots.forEach(snapshot => { if (snapshot.subscriptions) { snapshot.subscriptions.forEach(mapSubscriptionStackTraces); } else { mapSubscriptionStackTraces(snapshot); } }); return forkJoin(observables).pipe( mapTo(undefined), hide() ); function mapSubscriptionStackTraces(subscriptionSnapshot: SubscriptionSnapshot): void { observables.push(subscriptionSnapshot.mappedStackTrace); if (subscriptionSnapshot.rootSink) { observables.push(subscriptionSnapshot.rootSink.mappedStackTrace); } } } function setSnapshotRef(ref: SubscriberRef, value: SnapshotRef): SnapshotRef { ref[snapshotRefSymbol] = value; return value; } export interface Snapshot { observables: Map<Observable<any>, ObservableSnapshot>; subscribers: Map<Subscriber<any>, SubscriberSnapshot>; subscriptions: Map<Subscription, SubscriptionSnapshot>; tick: number; mapStackTraces(observableSnapshots: ObservableSnapshot[]): Observable<void>; mapStackTraces(subscriberSnapshots: SubscriberSnapshot[]): Observable<void>; mapStackTraces(subscriptionSnapshots: SubscriptionSnapshot[]): Observable<void>; } export interface ObservableSnapshot { id: string; observable: Observable<any>; path: string; subscriptions: Map<Subscription, SubscriptionSnapshot>; tag: string | undefined; tick: number; type: string; } export interface SubscriberSnapshot { id: string; subscriber: Subscriber<any>; subscriptions: Map<Subscription, SubscriptionSnapshot>; tick: number; values: { tick: number; timestamp: number; value: any; }[]; valuesFlushed: number; } export interface SubscriptionSnapshot { complete: boolean; error: any; flattenings: Map<Subscription, SubscriptionSnapshot>; flatteningsFlushed: number; id: string; mappedStackTrace: Observable<StackFrame[]>; observable: Observable<any>; rootSink: SubscriptionSnapshot | undefined; sink: SubscriptionSnapshot | undefined; sources: Map<Subscription, SubscriptionSnapshot>; sourcesFlushed: number; stackTrace: StackFrame[]; subscriber: Subscriber<any>; subscription: Subscription; tick: number; timestamp: number; unsubscribed: boolean; } export class SnapshotPlugin extends BasePlugin { private keptValues_: number; private sentinel_: GraphRef | undefined; private spy_: Spy; constructor(spy: Spy, { keptValues = 4 }: { keptValues?: number } = {}) { super("snapshot"); this.keptValues_ = keptValues; this.sentinel_ = undefined; this.spy_ = spy; } afterUnsubscribe(ref: SubscriptionRef): void { const snapshotRef = getSnapshotRef(ref); snapshotRef.tick = this.spy_.tick; snapshotRef.unsubscribed = true; } beforeComplete(ref: SubscriptionRef): void { const snapshotRef = getSnapshotRef(ref); snapshotRef.tick = this.spy_.tick; snapshotRef.complete = true; } beforeError(ref: SubscriptionRef, error: any): void { const snapshotRef = getSnapshotRef(ref); snapshotRef.tick = this.spy_.tick; snapshotRef.error = error; } beforeNext(ref: SubscriptionRef, value: any): void { const tick = this.spy_.tick; const snapshotRef = getSnapshotRef(ref); snapshotRef.tick = tick; snapshotRef.values.push({ tick, timestamp: Date.now(), value }); const { keptValues_ } = this; const count = snapshotRef.values.length - keptValues_; if (count > 0) { snapshotRef.values.splice(0, count); snapshotRef.valuesFlushed += count; } } beforeSubscribe(ref: SubscriberRef): void { setSnapshotRef(ref, { complete: false, error: undefined, tick: this.spy_.tick, timestamp: Date.now(), unsubscribed: false, values: [], valuesFlushed: 0 }); const graphRef = getGraphRef(ref); if (graphRef) { this.sentinel_ = graphRef.sentinel; } else { this.spy_.warnOnce(console, "Graphing is not enabled; add the GraphPlugin before the SnapshotPlugin."); } } snapshotAll({ since }: { since?: Snapshot } = {}): Snapshot { const observables = new Map<Observable<any>, ObservableSnapshot>(); const subscribers = new Map<Subscriber<any>, SubscriberSnapshot>(); const subscriptions = new Map<Subscription, SubscriptionSnapshot>(); const subscriptionRefs = this.getSubscriptionRefs_(); subscriptionRefs.forEach((unused, ref) => { const { observable, subscriber, subscription } = ref; const graphRef = getGraphRef(ref); const { flatteningsFlushed, sourcesFlushed } = graphRef; const snapshotRef = getSnapshotRef(ref); const { complete, error, tick, timestamp, unsubscribed, values, valuesFlushed } = snapshotRef; const subscriptionSnapshot: SubscriptionSnapshot = { complete, error, flattenings: new Map<Subscription, SubscriptionSnapshot>(), flatteningsFlushed, id: identify(ref), mappedStackTrace: getMappedStackTrace(ref), observable, rootSink: undefined, sink: undefined, sources: new Map<Subscription, SubscriptionSnapshot>(), sourcesFlushed, stackTrace: getStackTrace(ref), subscriber, subscription, tick, timestamp, unsubscribed }; subscriptions.set(subscription, subscriptionSnapshot); let subscriberSnapshot = subscribers.get(subscriber); if (!subscriberSnapshot) { subscriberSnapshot = { id: identify(subscriber), subscriber, subscriptions: new Map<Subscription, SubscriptionSnapshot>(), tick, values: [], valuesFlushed: 0 }; subscribers.set(subscriber, subscriberSnapshot); } subscriberSnapshot.subscriptions.set(subscription, subscriptionSnapshot); subscriberSnapshot.tick = Math.max(subscriberSnapshot.tick, tick); subscriberSnapshot.values.push(...values); subscriberSnapshot.valuesFlushed += valuesFlushed; let observableSnapshot = observables.get(observable); if (!observableSnapshot) { observableSnapshot = { id: identify(observable), observable, path: inferPath(observable), subscriptions: new Map<Subscription, SubscriptionSnapshot>(), tag: read(observable), tick, type: inferType(observable) }; observables.set(observable, observableSnapshot); } observableSnapshot.subscriptions.set(subscription, subscriptionSnapshot); observableSnapshot.tick = Math.max(observableSnapshot.tick, tick); }); subscriptionRefs.forEach((unused, ref) => { const graphRef = getGraphRef(ref); const subscriptionSnapshot = subscriptions.get(ref.subscription)!; if (graphRef.sink) { subscriptionSnapshot.sink = subscriptions.get(graphRef.sink.subscription)!; } if (graphRef.rootSink) { subscriptionSnapshot.rootSink = subscriptions.get(graphRef.rootSink.subscription)!; } graphRef.flattenings.forEach((m) => subscriptionSnapshot.flattenings.set(m.subscription, subscriptions.get(m.subscription)!)); graphRef.sources.forEach((s) => subscriptionSnapshot.sources.set(s.subscription, subscriptions.get(s.subscription)!)); }); subscribers.forEach((subscriberSnapshot) => { subscriberSnapshot.values.sort((a, b) => a.tick - b.tick); }); if (since !== undefined) { observables.forEach((value, key) => { if (value.tick <= since.tick) { observables.delete(key); } }); subscribers.forEach((value, key) => { if (value.tick <= since.tick) { subscribers.delete(key); } }); subscriptions.forEach((value, key) => { if (value.tick <= since.tick) { subscriptions.delete(key); } }); } return { mapStackTraces, observables, subscribers, subscriptions, tick: this.spy_.tick }; } snapshotObservable(ref: SubscriptionRef): ObservableSnapshot | undefined { const snapshot = this.snapshotAll(); return snapshot.observables.get(ref.observable); } snapshotSubscriber(ref: SubscriptionRef): SubscriberSnapshot | undefined { const snapshot = this.snapshotAll(); return snapshot.subscribers.get(ref.subscriber); } private addSubscriptionRefs_(ref: SubscriptionRef, map: Map<SubscriptionRef, boolean>): void { map.set(ref, true); const graphRef = getGraphRef(ref); graphRef.flattenings.forEach((m) => this.addSubscriptionRefs_(m, map)); graphRef.sources.forEach((s) => this.addSubscriptionRefs_(s, map)); } private getSubscriptionRefs_(): Map<SubscriptionRef, boolean> { const { sentinel_ } = this; const map = new Map<SubscriptionRef, boolean>(); if (sentinel_) { sentinel_.sources.forEach(ref => this.addSubscriptionRefs_(ref, map)); } return map; } }
the_stack
export interface RequestPermissionReq { permissionList: Array<string>; } export interface CheckPermissionReq { permissionList: Array<string>; } export interface statisticsnReq { isAllowed:boolean; } export interface MLBounds { marginTop?: number, marginBottom?: number, marginLeft?:number, marginRight?:number } export interface MLconfig{ lensEngineReq: lensEngineReq; } export interface lensEngineReq{ analyzerName: MLAnalyzerName; lensEngineSetting ?: MLLensEngineSetting; grapgicSetting?: FaceGraphicSetting | sceneSettings| HandkeyGraphicSetting | SkeletonGraphicSetting | ObjectGraphicSetting | null; analyzerSetting?: mlFaceAnalyzerSetting |mlHandKeypointSetting|mlImageSegmentationSetting|mlObjectAnalyserSetting |null; } export interface MLconfigComposite{ lensEngineReq:compositeAnalyser } export interface compositeAnalyser{ analyzerNames?: Array<MLAnalyzerName>; lensEngineSetting ?: MLLensEngineSetting; grapgicSetting?: FaceGraphicSetting | sceneSettings| HandkeyGraphicSetting | SkeletonGraphicSetting | ObjectGraphicSetting | null; analyzerSetting?: mlFaceAnalyzerSetting |mlHandKeypointSetting|mlImageSegmentationSetting|mlObjectAnalyserSetting |null; } export interface MLLensEngineSetting{ fps?:number | null; displayDimensionI?:number | null; displayDimensionI1?:number | null; lensType?: MLLensType |null; enableFocus?:boolean|null; flashMode?:MLFlashMode|null; } export enum MLFlashMode{ AUTO="auto", ON="on", OFF="off" } export enum MLLensType{ BACK_LENS=0, FRONT_LENS = 1 } export enum MLStillCompositerName{ FACE="FACE", HAND="HAND", SKELETON="SKELETON", OBJECT="OBJECT", TEXT="TEXT", CLASSIFICATION="classification" } export enum MLAnalyzerName{ LIVEFACE="FACE", LIVEFACE3D="FACE3D", LIVEFACEMAX="FACEMAX", LIVEHAND="HAND", LIVESKELETON="SKELETON", LIVEOBJECT="OBJECT", LIVECLASSIFICATION="CLASSIFICATION", LIVESCENE="SCENE", LIVETEXT="TEXT" } export interface doZoomReq{ scale?:number|null; } export interface mlFrameReq{ actionName:MLFrame; filePath:any; } export enum MLFrame{ getPreviewBitmap="getPreviewBitmap", readBitmap="readBitmap", rotate="rotate" } ///////****///////// // API KEY ///////****///////// export interface configReq{ apiKey: string; } export interface appSettingReq{ apiKey?:string|null; applicationId?:string|null; certFingerprint?:string|null; } ///////****///////// // COMPOSITE ///////****///////// export interface compositeAnalyserReq{ compositeAnalyserConfig: compositeAnalyserConfig } export interface compositeAnalyserConfig{ filePath : any; analyzerNames?: Array<MLStillCompositerName>; analyzerSetting?: mlFaceAnalyzerSetting |mlHandKeypointSetting|mlImageSegmentationSetting|mlObjectAnalyserSetting |null; } ///////****///////// // AFT ANALYSER ///////****///////// export interface aftReq { audioPath: any; aftSetting?: (AftSetting); } export interface AftSetting{ languageCode ?: string | null; punctuationEnabled ?: boolean | null; timeOffset ?: boolean | null; wordTimeOffsetEnabled ?: boolean | null; sentenceTimeOffsetEnabled ?: boolean | null ; } ///////****///////// // ASR ANALYSER ///////****///////// export interface asrReq { language ?: LANGUAGE | null; feature ?: FEATURE | null; } export enum FEATURE { FEATURE_ALLINONE = 12, FEATURE_WORDFLUX = 11, } export enum LANGUAGE { LAN_EN_US = "en-US", LAN_FR_FR = "fr-FR", LAN_ZH = "zh", LAN_ZH_CN = "zh-CN", LAN_ES_ES="es-ES", LAN_DE_DE="de-DE" } ///////****///////// // SDK BANK CARD ANALYSER ///////****///////// export interface bankCardSDKDetectorReq { filePath: any; detectType: 0; mLBcrAnalyzerSetting?: MLBcrAnalyzerSetting | null; } export interface MLBcrAnalyzerSetting { langType?: string | null; resultType?: MLBcrResultConfig | null; } ///////****///////// // PLUGIN BANK CARD ANALYSER ///////****///////// export interface bankCardPluginDetectorReq { detectType: 1; mLBcrCaptureConfig?: mLBcrCaptureConfig | null; } export interface mLBcrCaptureConfig { orientation?: MLBcrCaptureConfig | null; resultType?: MLBcrResultConfig | null; } export enum MLBcrCaptureConfig { ORIENTATION_AUTO = 0, ORIENTATION_LANDSCAPE = 1, ORIENTATION_PORTRAIT = 2 } export enum MLBcrResultConfig { RESULT_NUM_ONLY = 0, RESULT_SIMPLE = 1, RESULT_ALL = 2 } ///////****///////// //Classify ///////****///////// export interface localImageClassificationReq { ocrType: MLImageClassificationConfig | null; analyseMode?: number | null; localClassificationAnalyzerSetting?: (LocalClassificationAnalyzerSetting) | null; filePath: any; } export interface LocalClassificationAnalyzerSetting { possibility?: number | null; } export interface remoteImageClassificationReq { ocrType: MLImageClassificationConfig; analyseMode?: number; remoteClassificationAnalyzerSetting?: (RemoteClassificationAnalyzerSetting) | null; filePath: any; } export interface RemoteClassificationAnalyzerSetting { maxResults?: number | null; possibility?: number | null; isEnableFingerprintVerification?: boolean |null; } export enum MLImageClassificationConfig { TYPE_LOCAL = 0, TYPE_REMOTE = 1 } ///////****///////// //Custom Model Download ///////****///////// export interface downloadModelReq{ detectType: 1; filePath: any; downloadStrategySetting ?:DownloadStrategySetting | null; } export interface DownloadStrategySetting { isChargingNeed:boolean | null; isWifiNeed:boolean | null ; isDeviceIdleNeed:boolean | null; setRegion?: DownloadStrategyCustom | null; } export enum DownloadStrategyCustom{ REGION_DR_CHINA = 1002, REGION_DR_AFILA = 1003, REGION_DR_EUROPE = 1004, REGION_DR_RUSSIA = 1005 } export interface ownCustomModelReq{ detectType:number; filePath:any; modelFullName:string |null ; modelName:string |null; labelFileName:string |null; bitmapHeight:number |null; bitmapWidth:number |null; outPutSize:number |null; } ///////****///////// //Document Analyser ///////****///////// export interface documentImageAnalyserReq { documentSetting?: DocumentSetting | null; filePath: any; } export interface DocumentSetting { borderType?: MLRemoteTextSetting | null; LanguageList?: Array<string> | null; enableFingerprintVerification :boolean | null; } export enum MLRemoteTextSetting { OCR_LOOSE_SCENE = 1, OCR_COMPACT_SCENE = 2, NGON = "NGON", ARC = "ARC" } ///////****///////// //Form Recognizer Analyser ///////****///////// export interface formRecognizerAnalyserReq { filePath: any; syncType: MLFormRecogitionConfig; } export enum MLFormRecogitionConfig{ SYNC_TYPE=1, ASYNC_TYPE=0 } ///////****///////// //Document Skew Correction ///////****///////// export interface documentSkewCorrectionReq{ filePath: any; syncMode?: MLFormRecogitionConfig|null; } ///////****///////// // STILL && LIVE FACE ANALYSER ///////****///////// export interface faceReq { mlFaceAnalyserSetting?: mlFaceAnalyzerSetting | null; analyseMode?: MLFaceConfigs |null; filePath: any; } export enum MLFaceConfigs{ TYPE_2D_SYNC=0, TYPE_2D_ASYNC=1, TYPE_3D_SYNC=2, TYPE_3D_ASYNC=3 } export interface FaceGraphicSetting{ facePositionPaintSetting ?: FacePositionPaintSetting | null; textPaintSetting ?:TextPaintSettingFace | null; faceFeaturePaintTextSetting ?:FaceFeaturePaintTextSetting | null; keypointPaintSetting ?: KeypointPaintSetting | null; boxPaintSetting ?: BoxPaintSettingFace | null; facePaintSetting ?: FacePaintSetting | null; eyePaintSetting ?:EyePaintSetting | null; eyebrowPaintSetting ?:EyebrowPaintSetting | null; nosePaintSetting ?:NosePaintSetting | null; noseBasePaintSetting ?:NoseBasePaintSetting | null; lipPaintSetting ?:LipPaintSetting | null; } export interface LipPaintSetting{ color?:String | Colors|null; style?:RectStyle | null; strokeWidth:Number | null; } export interface NosePaintSetting{ color?:String | Colors |null; style?:RectStyle | null; strokeWidth ?:Number; } export interface NoseBasePaintSetting{ color ?:String |Colors | null; style ?:RectStyle | null; strokeWidth ?:Number; } export interface EyebrowPaintSetting{ color?:String |Colors | null; style?:RectStyle; strokeWidth?:Number; } export interface EyePaintSetting{ color?:String |Colors; style?:RectStyle |Colors; strokeWidth:Number | null; } export interface FacePaintSetting{ color ?:String | Colors | null ; style ?: RectStyle | null; strokeWidth:Number | null; } export interface BoxPaintSettingFace{ color ?:String |Colors | null; style ?:RectStyle | null; strokeWidth ?:Number | null; } export interface KeypointPaintSetting{ color?: Colors | Colors | null; style?:RectStyle | null; textSize:Number | null ; } export interface FaceFeaturePaintTextSetting{ color?:Colors | null; textSize:Number | null; } export interface FacePositionPaintSetting{ color ?: Colors | null; } export interface TextPaintSettingFace{ color ?: Colors | null; textSize ?: Number | null; } export interface mlFaceAnalyzerSetting { featureType?: MLFaceSetting | null; keyPointType?: MLFaceSetting | null; maxSizeFaceOnly?: boolean | null; minFaceProportion?: number | null; performanceType?: MLFaceSetting | null; poseDisabled?:boolean | null; shapeType?: MLFaceSetting | null; tracingAllowed?: boolean | null; } export enum MLFaceSetting { TYPE_FEATURES = 1, TYPE_UNSUPPORT_FEATURES = 2, TYPE_KEYPOINTS = 0, TYPE_UNSUPPORT_KEYPOINTS = 2, TYPE_PRECISION = 1, TYPE_SPEED = 2, TYPE_SHAPES = 2, TYPE_UNSUPPORT_SHAPES = 3, TYPE_FEATURE_EMOTION = 4, TYPE_FEATURE_EYEGLASS = 8, TYPE_FEATURE_HAT = 16, TYPE_FEATURE_BEARD = 32, TYPE_FEATURE_OPENCLOSEEYE = 64, TYPE_FEATURE_GENDAR = 128, TYPE_FEATURE_AGE = 256, MODE_TRACING_FAST = 1, MODE_TRACING_ROBUST = 2 } ///////****///////// // GENERAL CARD ANALYSER ///////****///////// export interface generalCardDetectorReq { gcrCaptureConfig?: gcrCaptureConfig; gcrCaptureUIConfig?: gcrCaptureUIConfig; captureType?: gcrCaptureType|null; } export interface gcrCaptureConfig { language: string; } export enum gcrCaptureType{ CAPTURE_ACTIVITY=0, CAPTURE_PHOTO=1, CAPTURE_IMAGE=2 } export interface gcrCaptureUIConfig { orientation?: MLGcrCaptureUIConfig | null; tipText?: string | null; tipTextColor?: number | null; photoButtonResId?: number | null; scanBoxCornerColor?: number | null; backButtonRedId?: number | null; torchRedId?: number | null; } export enum MLGcrCaptureUIConfig { ORIENTATION_AUTO = 0, ORIENTATION_LANDSCAPE = 1, ORIENTATION_PORTRAIT = 2, } ///////****///////// // ID CARD ANALYSER ///////****///////// export interface idCardAnalyserReqWithSDK { detectType: number; isRemote?: boolean | null; isFront?: boolean | null ; countryCode?: string; filePath: any; } export interface idCardAnalyserReqWithPlugin { detectType: number; isRemote?: boolean | null; isFront?: boolean | null; countryCode?: string; } ///////****///////// //Live && Stil HandkeyPoint ///////****///////// export interface stillHandKeypointReq{ syncType?: syncType |null; filePath: any; handkeySetting ?: mlHandKeypointSetting | null; } export enum syncType{ SYNC_MODE=0, ASYNC_MODE=1 } export interface HandkeyGraphicSetting{ idPaintnewSetting ?: IdPaintnewSetting | null; rectPaintSetting ?: RectPaintSetting | null; } export interface IdPaintnewSetting{ color ?: Colors | null; textSize ?: Number | null; } export interface RectPaintSetting{ color ?: Colors | null; style ?: RectStyle | null; boxStrokeWidth ?: Number | null; } export interface mlHandKeypointSetting{ sceneType ?: HandkeyPointConfig | null; maxHandResults ?: number | null; } export enum HandkeyPointConfig{ TYPE_ALL = 0, TYPE_KEYPOINT_ONLY = 1, TYPE_RECT_ONLY = 2 } ///////****///////// //Image Super Resolution ///////****///////// export interface imageSuperResolutionReq{ filePath:any; imgSuperResolutionSetting ?: (ImgSuperResolutionSetting) | null; syncType?: MLFormRecogitionConfig | null; } export interface ImgSuperResolutionSetting{ scaleType ?: ImgSuperResolutionConfig; } export enum ImgSuperResolutionConfig{ ISR_SCALE_1X = 1.0, ISR_SCALE_3X = 3.0 } ///////****///////// //Product Vision Analyser ///////****///////// export interface productReq{ filePath?:any |null; detectType?:number; mlProductSetting ?: (mlProductSetting) | null; } export interface mlProductSetting{ largestNumOfReturns ?: number|null; productSetId?:string|null; region?:MLProductConfig|null; } export enum MLProductConfig{ REGION_DR_CHINA = 1002, REGION_DR_AFILA = 1003, REGION_DR_EUROPE = 1004, REGION_DR_RUSSIA = 1005, REGION_DR_GERMAN = 1006, REGION_DR_SIANGAPORE = 1007 } ///////****///////// //Text Image Super Resolution ///////****///////// export interface textImageSuperResolutionReq{ filePath:any; analyseMode?: MLFormRecogitionConfig |null; } ///////****///////// //IMAGE STILL && LIVESEGMENTATION ///////****///////// export interface imgSegmentationReq { imageSegmentationSetting?: (mlImageSegmentationSetting); filePath: any; analyseMode?: MLFormRecogitionConfig | null; } export interface mlImageSegmentationSetting { isExact:boolean | null; analyserType?: MLImageSegmentationSetting | null ; scene?: MLImageSegmentationScene; } export enum MLImageSegmentationSetting { BODY_SEG = 0, IMAGE_SEG = 1, } export enum MLImageSegmentationScene { ALL = 0, MASK_ONLY = 1, FOREGROUND_ONLY = 2, GRAYSCALE_ONLY = 3, } ///////****///////// //LAND MARK ///////****///////// export interface imgLandMarkReq { landmarkAnalyzerSetting?: landmarkAnalyzerSetting; filePath: any; } export interface landmarkAnalyzerSetting { maxResults?: number | null; modelType?: MLRemoteLandmarkSetting | null; } export enum MLRemoteLandmarkSetting { STEADY_PATTERN = 1, NEWEST_PATTERN = 2, } ///////****///////// //Lang Detect ///////****///////// export interface remoteLangDetectionReq { sourceText: string; taskMode?: number; trustedThreshold?: number; } export interface localLangDetectionReq{ sourceText:string; trustedThreshold?:number; } ///////****///////// //Liveness Detection ///////****///////// export interface livenessDetectionReq{ analyserMode?: MLLivenessCaptureResult | null; } export enum MLLivenessConfig{ DEFAULT=0, CUSTOM=1 } ///////****///////// // STILL && LIVEOBJECT ANALYSER ///////****///////// export interface objectReq { filePath: any; mlObjectAnalyserSetting?: mlObjectAnalyserSetting; syncType?: MLFormRecogitionConfig |null; } export interface ObjectGraphicSetting{ boxPaintSetting?: BoxPaintSetting| null; textPaintSetting?: TextPaintSetting| null; } export interface BoxPaintSetting{ color?:Colors | null; style?: RectStyle | null; boxStrokeWidth?: Number | null; } export interface TextPaintSetting{ color ?:Colors | null; textSize ?: Number | null; } export interface mlObjectAnalyserSetting { isClassificationAllowed?: boolean | null; isMultipleResultsAllowed?: boolean | null; analyzerType: MlObjectAnalyserConfig; } export enum MlObjectAnalyserConfig{ TYPE_VIDEO = 1, TYPE_PICTURE = 0 } ///////****///////// //RTT ///////****///////// export interface rttReq{ mLSpeechRealTimeTranscriptionConfig : MLSpeechRealTimeTranscriptionConfig; } export interface MLSpeechRealTimeTranscriptionConfig { language: MLRttLanguages | null ; punctuationEnable: boolean | null ; wordTimeOffsetEnable: boolean | null; sentenceTimeOffsetEnable: boolean | null ; scenes?: MLRttScenes |null; } export enum MLRttLanguages{ LAN_ZH_CN = "zh-CN", LAN_EN_US = "en-US", LAN_FR_FR = "fr-FR", LAN_ES_ES = "es-ES", LAN_EN_IN = "en-IN", LAN_DE_DE = "de-DE" } export enum MLRttScenes{ SCENES_SHOPPING="shopping" } ///////****///////// //STILL && LIVE SCENE ANALYSER ///////****///////// export interface stillSceneReq{ filePath: any; analyseMode?: syncType | null; } export interface sceneSettings{ color ?: Colors | null; textSize ?: Number | null; } ///////****///////// //STILL && LIVE SKELETON ANALYSER ///////****///////// export interface stillSkeletonReq{ filePath: any; syncType: MLSkeletonConfig; analyzerType: MLSkeletonConfig; } export interface stillSkeletonSimilarityReq{ filePath: any; filepath2: any; syncType: MLSkeletonConfig; analyzerType: MLSkeletonConfig; } export enum MLSkeletonConfig{ SYNC_MODE=0, ASYNC_MODE=1, SIMILARITTY_MODE=2, TYPE_YOGA=1, TYPE_NORMAL=0, } export interface SkeletonGraphicSetting{ circlePaintSetting ?: circlePaintSetting | null; linePaintSetting ?: linePaintSetting | null; } export interface circlePaintSetting{ color?: Colors| null; style?: RectStyle | null; antiAlias?:boolean| null; } export interface linePaintSetting{ color?:Colors| null; style?: RectStyle | null; strokeWidth?:Number| null; antiAlias?:boolean| null; } ///////****///////// //Text Analyser ///////****///////// export interface localImageTextReq { ocrType: MLTextConfig; analyseMode?: number; localTextSetting?: (localTextSetting) | null; filePath: any; } export interface localTextSetting { ocrMode?: MLLocalTextSetting; language?: string; } export enum MLLocalTextSetting { OCR_DETECT_MODE = 1, OCR_TRACKING_MODE = 2 } export enum MLTextConfig { OCR_LOCAL_TYPE = 0, OCR_REMOTE_TYPE = 1 } export interface remoteImageTextReq { ocrType: MLTextConfig; analyseMode?: number; remoteTextSetting?: (remoteTextSetting); filePath: any; } export interface remoteTextSetting { textDensityScene?: MLRemoteTextSetting; languageList?: Array<string>; borderType?: MLRemoteTextSetting; } ///////****///////// //TRANSLATE ///////****///////// export interface remotetranslateReq { USE_SYNC: boolean, targetLangCode: string; sourceLangCode?: string; sourceText: string; } export interface localtranslateReq { USE_SYNC: boolean, targetLangCode: string; sourceLangCode: string; sourceText: string; } export interface deleteTranslateReq{ USE_SYNC: boolean, langcode:string; } export interface downloadTranslateReq{ USE_SYNC: boolean, langcode:string; } export interface localAllLangReq{ USE_SYNC: boolean, } export interface remoteAllLangReq{ USE_SYNC: boolean, } ///////****///////// // Sound Dect ///////****///////// export interface soundDectReq { startType: boolean | null; } ///////****///////// // Text Embedding ///////****///////// export interface textEmbeddingDicInfoReq { textEmbeddingSetting: textEmbeddingSetting; } export interface textEmbeddingWordtoVectorReq { textEmbeddingSetting?: textEmbeddingSetting; wordText:string; } export interface textEmbeddingSentencetoVectorReq { textEmbeddingSetting?: textEmbeddingSetting; sentenceText:string; } export interface textEmbeddingWordSimilarityReq { textEmbeddingSetting?: textEmbeddingSetting; wordText1 : string; wordText2 : string; } export interface textEmbeddingSentenceSimilarityReq { textEmbeddingSetting?: textEmbeddingSetting; sentenceText1 : string; sentenceText2 : string; } export interface textEmbeddingSimilarWordsReq { textEmbeddingSetting?: textEmbeddingSetting; multipleText:string; similarityNumber:number; } export interface textEmbeddingWordBatchReq{ textEmbeddingSetting?: textEmbeddingSetting; batchText:string; } export interface textEmbeddingSetting{ language:string } ///////****///////// // TTS ANALYSER ///////****///////// export interface ttsEngineReq { language?: string |null; } export interface ttsReq { text: string; mlConfigs: MLConfigs; queuingMode: MLTtsConstants; } export interface MLConfigs { language: MLTtsConstants; person: MLTtsConstants; speed: number; volume: number; synthesizeMode: MLTtsConstants; } export enum MLTtsConstants { TTS_EN_US = "en-US", TTS_LAN_ES_ES = "es-ES", TTS_LAN_FR_FR = "fr-FR", TTS_LAN_DE_DE ="de-DE", TTS_LAN_IT_IT = "it-IT", TTS_ZH_HANS = "zh-Hans", TTS_SPEAKER_FEMALE_EN = "Female-en", TTS_SPEAKER_FEMALE_ZH = "Female-zh", TTS_SPEAKER_MALE_EN = "Male-en", TTS_SPEAKER_MALE_ZH = "Male-zh", TTS_SPEAKER_FEMALE_DE = "de-DE-st-1", TTS_SPEAKER_FEMALE_ES = "it-IT-st-1", TTS_SPEAKER_FEMALE_IT = "es-ES-st-1", TTS_SPEAKER_FEMALE_FR = "fr-FR-st-1", TTS_SPEAKER_OFFLINE_EN_US_MALE_BOLT = "en-US-st-bolt-2", TTS_SPEAKER_OFFLINE_ZH_HANS_FEMALE_EAGLE = "zh-Hans-st-eagle-1", TTS_SPEAKER_OFFLINE_ZH_HANS_MALE_EAGLE = "zh-Hans-st-eagle-2", TTS_SPEAKER_OFFLINE_EN_US_FEMALE_EAGLE = "en-US-st-eagle-1", TTS_SPEAKER_OFFLINE_EN_US_MALE_EAGLE = "en-US-st-eagle-2", TTS_SPEAKER_OFFLINE_EN_US_FEMALE_BEE = "en-US-st-bee-1", TTS_SPEAKER_OFFLINE_FR_FR_FEMALE_BEE = "fr-FR-st-bee-1", TTS_SPEAKER_OFFLINE_ES_ES_FEMALE_BEE = "es-ES-st-bee-1", TTS_SPEAKER_OFFLINE_DE_DE_FEMALE_BEE = "de-DE-st-bee-1", TTS_SPEAKER_OFFLINE_IT_IT_FEMALE_BEE = "it-IT-st-bee-1", TTS_SPEAKER_OFFLINE_ZH_HANS_FEMALE_BOLT = "zh-Hans-st-bolt-1", TTS_SPEAKER_OFFLINE_ZH_HANS_MALE_BOLT = "zh-Hans-st-bolt-2", TTS_SPEAKER_OFFLINE_EN_US_FEMALE_BOLT = "en-US-st-bolt-1", TTS_ONLINE_MODE = "online", TTS_OFFLINE_MODE = "offline", QUEUE_APPEND = 0, QUEUE_FLUSH = 1, EXTERNAL_PLAYBACK =2, OPEN_STREAM = 4 } export enum Colors { RED = -65536, DKGRAY = -12303292, GRAY = -7829368, WHITE = -1, BLUE = -16776961, BLACK = -16777216, LTGRAY = -3355444, MAGENTA = -65281, YELLOW = -256, CYAN = -16711681, GREEN = -16711936, TRANSPARENT = 0 } export enum RectStyle { STROKE = 1, FILL = 2, FILL_AND_STROKE = 3, } /* ----------------- return */ export interface MLAftResult { eventName: string; text: string; taskId: string; complete: boolean; } export interface MLAftErrorResult{ eventName: string; taskId:string; errorCode:MLAftErrorCodes; message:string; } export enum MLAftErrorCodes{ EROTSUPPORTED = 11101, LANGUAGE_CODE_NOTSUPPORTED = 11102, ERR_AUDIO_FILE_SIZE_OVERFLOW = 11103, ERR_AUDIO_LENGTH_OVERFLOW = 11104, ERR_FILE_NOT_FOUND = 11105, ERR_ILLEGAL_PARAMETER = 11106, ERR_ENGINE_BUSY = 11107, ERR_NETCONNECT_FAILED = 11108, ERR_RESULT_WHEN_UPLOADING = 11109, ERR_TASK_NOT_EXISTED = 11110, ERR_AUDIO_TRANSCRIPT_FAILED = 11111, ERR_AUDIO_INIT_FAILED = 11112, ERR_AUDIO_UPLOAD_FAILED = 11113, ERR_TASK_ALREADY_INPROGRESS = 11114, ERR_NO_ENOUGH_STORAGE = 11115, ERR_AUTHORIZE_FAILED = 11119, ERR_SERVICE_CREDIT = 11122, ERR_INTERNAL = 11198, ERR_UNKNOWN = 11199 } export interface MLAftEventResult{ eventName: string; taskId:string; ext:string; eventId:string; } export enum MLAFTEventCodes{ PAUSE_EVENT=2, STOP_EVENT=3, UPLOADED_EVENT=1 } export interface MLBankCard { number: string; expire: string; issuer: string; type: string; organization:string; originalBitmap:any; numberBitmap:any; } export interface MLCustomBankCard { number: string; expire: string; issuer: string; type: string; organization:string; originalBitmap:any; numberBitmap:any; } export interface MLFace { Result?: (ResultEntity)[] | null; } export interface ResultEntity { opennessOfLeftEye: number; tracingIdentity: number; possibilityOfSmiling: number; opennessOfRightEye: number; rotationAngleX: number; rotationAngleY: number; rotationAngleZ: number; height: number; width: number; border: Border; features: Features; emotions: Emotions; allPoints?: (AllPointsEntity)[] | null; keyPoints?: (null)[] | null; faceShapeList?: (FaceShapeListEntity)[] | null; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface Features { sunGlassProbability: number; sexProbability: number; rightEyeOpenProbability: number; moustacheProbability: number; leftEyeOpenProbability: number; age: number; hatProbability: number; } export interface Emotions { surpriseProbability: number; smilingProbability: number; sadProbability: number; neutralProbability: number; fearProbability: number; disgustProbability: number; angryProbability: number; } export interface AllPointsEntity { X: number; Y: number; } export interface FaceShapeListEntity { points?: (PointsEntity)[] | null; faceShapeType: number; } export interface PointsEntity { X: number; Y: number; Z: number; } export interface MLImageClassification { result?: (ResultEntity)[] | null; } export interface ResultEntity { identity: string; name: string; possibility: number; hashCode: number; } export interface MLDocument { stringValue: string; blocks?: (Blocks)[]; } export interface Blocks { stringValue: string; possibility: number; border: Border; interval: Interval; sections?: (Sections)[]; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface Interval { intervalType: number; isTextFollowed: boolean; } export interface Sections { stringValue: string; border: Border; interval: Interval; possibility: number; languageList?: (LanguageList)[]; lineList?: (LineList)[]; } export interface LanguageList { language: string; } export interface LineList { stringValue: string; border: Border; possibility: number; languageList?: (LanguageList)[]; wordList?: (WordList)[]; } export interface WordList { stringValue: string; border: Border; characterList?: (CharacterList)[]; languageList?: (LanguageList)[]; possibility?: number; interval?: Interval; } export interface CharacterList { stringValue: string; possibility: number; border?: Border; languageList?: (LanguageList)[]; interval?: Interval; } export interface MLDocumentSkewDetectResult { resultCode: number; bitmap: any; } export interface MLGcrCaptureResult { text: string; cardBitmap: any; } export interface MLHandKeypoints { handkeyPoints: handkeyPoints; rect: Rect; score: number; } export interface handkeyPoints{ x:number; y:number; score:number; type:number; } export interface Rect { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface MLImageSegmentation { bitmapForeground: any; bitmapGrayscale: any; masks: number; bitmapOriginal: any; } export interface MLRemoteLandmark { landmark: string; landmarkIdentity: string; possibility: number; border: Border; positionInfo?: (PositionInfoEntity)[] | null; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface PositionInfoEntity { lng: number; lat: number; } export interface MLRemoteLangDetection { langCode: string; probability: number; hashCode: number; } export interface MLlangDetectionWithFirstDetect { langCode: string; } export interface MLLivenessCaptureResult { bitmap: Bitmap; isLive: boolean; pitch: number; roll: number; score: number; yaw: number; } export interface Bitmap { mGalleryCached: boolean; mHeight: number; mNativePtr: number; mWidth: number; } export interface MLObject { typeIdentity: number; typePossibility: number; border: Border; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface MLSkeleton { joints: joints; } export interface joints{ x:number; y:number; score:number; type:number; hashCode:number; } export interface MLText { stringValue: string; blocks?: (Blocks)[]; } export interface Blocks { contents?: (Contents)[]; } export interface Contents { stringValue: string; rotatingDegree: number; isVertical: boolean; language: string; border: Border; contents?: (Contents)[]; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface Contents { stringValue: string; border: Border; language: string; languageList?: (LanguageList)[]; vertexes?: (Vertexes)[]; } export interface LanguageList { language: string; } export interface Vertexes { x: number; y: number; describeContents: number; } export interface MLTtsResult { eventName: string; taskID: string; start: number; end: number; } export interface MLSceneDetectionResult { resultString: string; confidence: number; } export interface LiveScenAnalyser { analyseList: [AnalyseList]; frameProperty: FrameProperty; } export interface AnalyseList { 0: a; } export interface a{ result: string; confidence: number; } export interface FrameProperty { ext: string; formatType: number; height: number; itemIdentity: number; quadrant: number; timestamp: number; width: number; } export interface MLSoundDectResult { soundType: MLSoundDectSoundTypeResult; eventName: string; } export enum MLSoundDectSoundTypeResult{ SOUND_DECT_ERROR_NO_MEM = 12201, SOUND_DECT_ERROR_FATAL_ERROR = 12202, SOUND_DECT_ERROR_AUDIO = 12203, SOUND_DECT_ERROR_INTERNAL = 12298, SOUND_EVENT_TYPE_LAUGHTER = 0, SOUND_EVENT_TYPE_BABY_CRY = 1, SOUND_EVENT_TYPE_SNORING = 2, SOUND_EVENT_TYPE_SNEEZE = 3, SOUND_EVENT_TYPE_SCREAMING = 4, SOUND_EVENT_TYPE_MEOW = 5, SOUND_EVENT_TYPE_BARK = 6, SOUND_EVENT_TYPE_WATER = 7, SOUND_EVENT_TYPE_CAR_ALARM = 8, SOUND_EVENT_TYPE_DOOR_BELL = 9, SOUND_EVENT_TYPE_KNOCK = 10, SOUND_EVENT_TYPE_ALARM = 11, SOUND_EVENT_TYPE_STEAM_WHISTLE = 12 } export interface MLVocabularyVersion { dictionaryDimension: string; dictionarySize: string; versionNo: string; } export interface MLWordtoVectorResult { result: Result; } export interface Result { wordText: string; vector: string; } export interface MlSentencetoVectorResult { sentence: string; vector: string; } export interface MLWordSimilarityResult { wordSimilarity: number; } export interface MLSentenceSimilarityResult { sentenceSimilarity: number; } export interface MLSimilarWordsResult { result?: (string)[] | null; } export interface MLFormRecogitionResult { retCode: number; tableContent: TableContent; } export interface TableContent { tableCount: number; tables?: (TablesEntity)[] | null; } export interface TablesEntity { tableID: number; headerInfo: string; footerInfo: string; tableBody?: (TableBodyEntity)[] | null; } export interface TableBodyEntity { startRow: number; endRow: number; startCol: number; endCol: number; cellCoordinate: CellCoordinate; textInfo: string; } export interface CellCoordinate { topLeft_x: number; topLeft_y: number; topRight_x: number; topRight_y: number; bottomLeft_x: number; bottomLeft_y: number; bottomRight_x: number; bottomRight_y: number; } export interface MLProductVisionResult { type: string; border: Border; list?: (ListEntity)[] | null; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface ListEntity { customcontent: string; imagelist?: (ImagelistEntity)[] | null; possibility: number; productURL: string; } export interface ImagelistEntity { imageId: string; possibility: number; productId: string; }
the_stack
* This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from "@stencil/core/internal"; import { DiscordTimestamp } from "./util"; export namespace Components { interface DiscordActionRow { } interface DiscordAttachment { /** * The alt text to show in case the image was unable to load * @default 'discord attachment' */ "alt": string; /** * The height of the image in pixels */ "height": number; /** * The URL for the image attachment * @important Should be a valid image URL, i.e. matching the regex `/\.(bmp|jpe?g|png|gif|webp|tiff)$/i` */ "url": string; /** * The width of the image in pixels */ "width": number; } interface DiscordAttachments { } interface DiscordButton { /** * Whether to show the button as disabled. */ "disabled": boolean; /** * The emoji URL to use in the button. */ "emoji": string; /** * The name of the emoji used in the button. */ "emojiName": string; /** * The type of button this is, this will change the color of the button. Valid values: `primary`, `secondary`, `success`, `destructive`. */ "type": 'primary' | 'secondary' | 'success' | 'destructive'; /** * The URL for the button. Setting this will force the button type to be `secondary`. */ "url": string; } interface DiscordCommand { /** * The message author's username. * @default 'User' */ "author": string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar": string; /** * The name of the command invoked. */ "command": string; /** * The id of the profile data to use. */ "profile": string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor": string; } interface DiscordEmbed { /** * The author's avatar URL. */ "authorImage": string; /** * The author's name. */ "authorName": string; /** * The URL to open when you click on the author's name. */ "authorUrl": string; /** * The color to use for the embed's left border. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "color": string; /** * The embed title. */ "embedTitle": string; /** * The image to use next to the footer text. */ "footerImage": string; /** * The embed image to use (displayed at the bottom). */ "image": string; /** * The provider to show above the embed, for example for YouTube videos it will show "YouTube" at the top of the embed (above the author) * @example YouTube */ "provider": string; /** * The thumbnail image to use. */ "thumbnail": string; /** * The timestamp to use for the message date. When supplying a string, the format must be `01/31/2000`. */ "timestamp"?: DiscordTimestamp; /** * The URL to open when you click on the embed title. */ "url": string; /** * The embed video to use (displayed at the bottom, same slot as the image). * @important YouTube videos will not be playable on your projects, this is due to YouTube using DASH to play their videos rather than providing the raw media stream (in a container such as mp4 or ogg). Links to regular MP4 files (such as on a CDN) however will autoplay! * @note Video takes priority over image. * @remark Providing both a video and an image will ensure the image is shown to users with browsers that do not support HTML5 video playback. * @example https://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_1080p_stereo.ogg */ "video": string; } interface DiscordEmbedField { /** * The field's title. */ "fieldTitle": string; /** * Whether this field should be displayed inline or not. */ "inline": boolean; /** * The index of this inline field * @remark This defines the position of this inline field. 1 is left, 2 is middle and 3 is right. * @oneof [1, 2, 3] * @default 1 */ "inlineIndex": number; } interface DiscordEmbedFields { } interface DiscordInvite { /** * The server icon to display for the invite. */ "icon": string | undefined; /** * The number of members on the server. * @default 0 */ "members": number; /** * The server's name. * @default 'Discord Server' */ "name": string; /** * The number of members online on the server. * @default 0 */ "online": number; /** * Whether the server is partnered. Only works if `verified` is `false` or `undefined`. */ "partnered": boolean; /** * The URL to open when you click on the join button. */ "url": string; /** * Whether the server is verified. Only works if `partnered` is `false` or `undefined`. */ "verified": boolean; } interface DiscordMention { /** * The color to use for this mention. Only works for role mentions and must be in hex format. */ "color": string; /** * Whether this entire message block should be highlighted (to emulate the "logged in user" being pinged). */ "highlight": boolean; /** * The type of mention this should be. This will prepend the proper prefix character. Valid values: `user`, `channel`, `role`, `voice`, and `locked`. */ "type": 'user' | 'channel' | 'role' | 'voice' | 'locked' | 'thread'; } interface DiscordMessage { /** * The message author's username. * @default 'User' */ "author": string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar": string; /** * Whether the message author is a bot or not. Only works if `server` is `false` or `undefined`. */ "bot": boolean; /** * Whether the message has been edited or not. */ "edited": boolean; /** * Whether to highlight this message. */ "highlight": boolean; /** * The id of the profile data to use. */ "profile": string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor": string; /** * Whether the message author is a server crosspost webhook or not. Only works if `bot` is `false` or `undefined`. */ "server": boolean; /** * The timestamp to use for the message date. */ "timestamp": DiscordTimestamp; /** * Whether to use 24-hour format for the timestamp. */ "twentyFour": boolean; /** * Whether the bot is verified or not. Only works if `bot` is `true` */ "verified": boolean; } interface DiscordMessages { /** * Whether to use compact mode or not. */ "compactMode": boolean; /** * Whether to use light theme or not. */ "lightTheme": boolean; /** * Whether to exclude the background or not. */ "noBackground": boolean; } interface DiscordReaction { /** * The number of people who reacted. * @default 1 */ "count": number; /** * The reaction emoji image URL. */ "emoji": string; /** * Whether the reaction should be reactive. * @remark When the reaction is interactive left clicking it will add 1 to the counter. Whereas when holding the Shift key and left clicking it will decrease the counter. The counter cannot go below 1. * @default false */ "interactive": boolean; /** * The name of the emoji to use as alternative image text. * @default ':emoji' */ "name": string; /** * Whether the reaction should show as reacted by the user. * @default false */ "reacted": boolean; } interface DiscordReactions { } interface DiscordReply { /** * Whether the referenced message contains attachments. */ "attachment": boolean; /** * The message author's username. * @default 'User' */ "author": string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar": string; /** * Whether the message author is a bot or not. Only works if `server` is `false` or `undefined`. */ "bot": boolean; /** * Whether the referenced message is from a response of a slash command. */ "command": boolean; /** * Whether the message has been edited or not. */ "edited": boolean; /** * Whether this reply pings the original message sender, prepending an "@" on the author's username. */ "mentions": boolean; /** * The id of the profile data to use. */ "profile": string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor": string; /** * Whether the message author is a server crosspost webhook or not. Only works if `bot` is `false` or `undefined`. */ "server": boolean; /** * Whether the bot is verified or not. Only works if `bot` is `true` */ "verified": boolean; } interface DiscordSystemMessage { /** * Whether this message is to show channel name changes, used to match Discord's style. */ "channelName": boolean; /** * The timestamp to use for the message date. */ "timestamp": DiscordTimestamp; /** * The type of system message this is, this will change the icon shown. Valid values: `join`, `leave`, `call`, `missed-call`, `boost`, `edit`, `thread`, `alert`, and `error`. */ "type": 'join' | 'leave' | 'call' | 'missed-call' | 'boost' | 'edit' | 'thread' | 'alert' | 'error'; } interface DiscordTenorVideo { /** * The height of the video in pixels */ "height": number; /** * The URL for the video */ "url": string; /** * The width of the video in pixels */ "width": number; } interface DiscordThread { /** * The the text within the call to action text. (i.e. 'See Thread' or 'x Messages') */ "cta": string; /** * The name of the thread. */ "name": string; } interface DiscordThreadMessage { /** * The message author's username. * @default 'User' */ "author": string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar": string; /** * Whether the message author is a bot or not. Only works if `server` is `false` or `undefined`. */ "bot": boolean; /** * Whether the message has been edited or not. */ "edited": boolean; /** * The id of the profile data to use. */ "profile": string; /** * The relative timestamp of the message. */ "relativeTimestamp": string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor": string; /** * Whether the message author is a server crosspost webhook or not. Only works if `bot` is `false` or `undefined`. */ "server": boolean; /** * Whether the bot is verified or not. Only works if `bot` is `true` */ "verified": boolean; } } declare global { interface HTMLDiscordActionRowElement extends Components.DiscordActionRow, HTMLStencilElement { } var HTMLDiscordActionRowElement: { prototype: HTMLDiscordActionRowElement; new (): HTMLDiscordActionRowElement; }; interface HTMLDiscordAttachmentElement extends Components.DiscordAttachment, HTMLStencilElement { } var HTMLDiscordAttachmentElement: { prototype: HTMLDiscordAttachmentElement; new (): HTMLDiscordAttachmentElement; }; interface HTMLDiscordAttachmentsElement extends Components.DiscordAttachments, HTMLStencilElement { } var HTMLDiscordAttachmentsElement: { prototype: HTMLDiscordAttachmentsElement; new (): HTMLDiscordAttachmentsElement; }; interface HTMLDiscordButtonElement extends Components.DiscordButton, HTMLStencilElement { } var HTMLDiscordButtonElement: { prototype: HTMLDiscordButtonElement; new (): HTMLDiscordButtonElement; }; interface HTMLDiscordCommandElement extends Components.DiscordCommand, HTMLStencilElement { } var HTMLDiscordCommandElement: { prototype: HTMLDiscordCommandElement; new (): HTMLDiscordCommandElement; }; interface HTMLDiscordEmbedElement extends Components.DiscordEmbed, HTMLStencilElement { } var HTMLDiscordEmbedElement: { prototype: HTMLDiscordEmbedElement; new (): HTMLDiscordEmbedElement; }; interface HTMLDiscordEmbedFieldElement extends Components.DiscordEmbedField, HTMLStencilElement { } var HTMLDiscordEmbedFieldElement: { prototype: HTMLDiscordEmbedFieldElement; new (): HTMLDiscordEmbedFieldElement; }; interface HTMLDiscordEmbedFieldsElement extends Components.DiscordEmbedFields, HTMLStencilElement { } var HTMLDiscordEmbedFieldsElement: { prototype: HTMLDiscordEmbedFieldsElement; new (): HTMLDiscordEmbedFieldsElement; }; interface HTMLDiscordInviteElement extends Components.DiscordInvite, HTMLStencilElement { } var HTMLDiscordInviteElement: { prototype: HTMLDiscordInviteElement; new (): HTMLDiscordInviteElement; }; interface HTMLDiscordMentionElement extends Components.DiscordMention, HTMLStencilElement { } var HTMLDiscordMentionElement: { prototype: HTMLDiscordMentionElement; new (): HTMLDiscordMentionElement; }; interface HTMLDiscordMessageElement extends Components.DiscordMessage, HTMLStencilElement { } var HTMLDiscordMessageElement: { prototype: HTMLDiscordMessageElement; new (): HTMLDiscordMessageElement; }; interface HTMLDiscordMessagesElement extends Components.DiscordMessages, HTMLStencilElement { } var HTMLDiscordMessagesElement: { prototype: HTMLDiscordMessagesElement; new (): HTMLDiscordMessagesElement; }; interface HTMLDiscordReactionElement extends Components.DiscordReaction, HTMLStencilElement { } var HTMLDiscordReactionElement: { prototype: HTMLDiscordReactionElement; new (): HTMLDiscordReactionElement; }; interface HTMLDiscordReactionsElement extends Components.DiscordReactions, HTMLStencilElement { } var HTMLDiscordReactionsElement: { prototype: HTMLDiscordReactionsElement; new (): HTMLDiscordReactionsElement; }; interface HTMLDiscordReplyElement extends Components.DiscordReply, HTMLStencilElement { } var HTMLDiscordReplyElement: { prototype: HTMLDiscordReplyElement; new (): HTMLDiscordReplyElement; }; interface HTMLDiscordSystemMessageElement extends Components.DiscordSystemMessage, HTMLStencilElement { } var HTMLDiscordSystemMessageElement: { prototype: HTMLDiscordSystemMessageElement; new (): HTMLDiscordSystemMessageElement; }; interface HTMLDiscordTenorVideoElement extends Components.DiscordTenorVideo, HTMLStencilElement { } var HTMLDiscordTenorVideoElement: { prototype: HTMLDiscordTenorVideoElement; new (): HTMLDiscordTenorVideoElement; }; interface HTMLDiscordThreadElement extends Components.DiscordThread, HTMLStencilElement { } var HTMLDiscordThreadElement: { prototype: HTMLDiscordThreadElement; new (): HTMLDiscordThreadElement; }; interface HTMLDiscordThreadMessageElement extends Components.DiscordThreadMessage, HTMLStencilElement { } var HTMLDiscordThreadMessageElement: { prototype: HTMLDiscordThreadMessageElement; new (): HTMLDiscordThreadMessageElement; }; interface HTMLElementTagNameMap { "discord-action-row": HTMLDiscordActionRowElement; "discord-attachment": HTMLDiscordAttachmentElement; "discord-attachments": HTMLDiscordAttachmentsElement; "discord-button": HTMLDiscordButtonElement; "discord-command": HTMLDiscordCommandElement; "discord-embed": HTMLDiscordEmbedElement; "discord-embed-field": HTMLDiscordEmbedFieldElement; "discord-embed-fields": HTMLDiscordEmbedFieldsElement; "discord-invite": HTMLDiscordInviteElement; "discord-mention": HTMLDiscordMentionElement; "discord-message": HTMLDiscordMessageElement; "discord-messages": HTMLDiscordMessagesElement; "discord-reaction": HTMLDiscordReactionElement; "discord-reactions": HTMLDiscordReactionsElement; "discord-reply": HTMLDiscordReplyElement; "discord-system-message": HTMLDiscordSystemMessageElement; "discord-tenor-video": HTMLDiscordTenorVideoElement; "discord-thread": HTMLDiscordThreadElement; "discord-thread-message": HTMLDiscordThreadMessageElement; } } declare namespace LocalJSX { interface DiscordActionRow { } interface DiscordAttachment { /** * The alt text to show in case the image was unable to load * @default 'discord attachment' */ "alt"?: string; /** * The height of the image in pixels */ "height"?: number; /** * The URL for the image attachment * @important Should be a valid image URL, i.e. matching the regex `/\.(bmp|jpe?g|png|gif|webp|tiff)$/i` */ "url"?: string; /** * The width of the image in pixels */ "width"?: number; } interface DiscordAttachments { } interface DiscordButton { /** * Whether to show the button as disabled. */ "disabled"?: boolean; /** * The emoji URL to use in the button. */ "emoji"?: string; /** * The name of the emoji used in the button. */ "emojiName"?: string; /** * The type of button this is, this will change the color of the button. Valid values: `primary`, `secondary`, `success`, `destructive`. */ "type"?: 'primary' | 'secondary' | 'success' | 'destructive'; /** * The URL for the button. Setting this will force the button type to be `secondary`. */ "url"?: string; } interface DiscordCommand { /** * The message author's username. * @default 'User' */ "author"?: string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar"?: string; /** * The name of the command invoked. */ "command"?: string; /** * The id of the profile data to use. */ "profile"?: string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor"?: string; } interface DiscordEmbed { /** * The author's avatar URL. */ "authorImage"?: string; /** * The author's name. */ "authorName"?: string; /** * The URL to open when you click on the author's name. */ "authorUrl"?: string; /** * The color to use for the embed's left border. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "color"?: string; /** * The embed title. */ "embedTitle"?: string; /** * The image to use next to the footer text. */ "footerImage"?: string; /** * The embed image to use (displayed at the bottom). */ "image"?: string; /** * The provider to show above the embed, for example for YouTube videos it will show "YouTube" at the top of the embed (above the author) * @example YouTube */ "provider"?: string; /** * The thumbnail image to use. */ "thumbnail"?: string; /** * The timestamp to use for the message date. When supplying a string, the format must be `01/31/2000`. */ "timestamp"?: DiscordTimestamp; /** * The URL to open when you click on the embed title. */ "url"?: string; /** * The embed video to use (displayed at the bottom, same slot as the image). * @important YouTube videos will not be playable on your projects, this is due to YouTube using DASH to play their videos rather than providing the raw media stream (in a container such as mp4 or ogg). Links to regular MP4 files (such as on a CDN) however will autoplay! * @note Video takes priority over image. * @remark Providing both a video and an image will ensure the image is shown to users with browsers that do not support HTML5 video playback. * @example https://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_1080p_stereo.ogg */ "video"?: string; } interface DiscordEmbedField { /** * The field's title. */ "fieldTitle": string; /** * Whether this field should be displayed inline or not. */ "inline"?: boolean; /** * The index of this inline field * @remark This defines the position of this inline field. 1 is left, 2 is middle and 3 is right. * @oneof [1, 2, 3] * @default 1 */ "inlineIndex"?: number; } interface DiscordEmbedFields { } interface DiscordInvite { /** * The server icon to display for the invite. */ "icon"?: string | undefined; /** * The number of members on the server. * @default 0 */ "members"?: number; /** * The server's name. * @default 'Discord Server' */ "name"?: string; /** * The number of members online on the server. * @default 0 */ "online"?: number; /** * Whether the server is partnered. Only works if `verified` is `false` or `undefined`. */ "partnered"?: boolean; /** * The URL to open when you click on the join button. */ "url"?: string; /** * Whether the server is verified. Only works if `partnered` is `false` or `undefined`. */ "verified"?: boolean; } interface DiscordMention { /** * The color to use for this mention. Only works for role mentions and must be in hex format. */ "color"?: string; /** * Whether this entire message block should be highlighted (to emulate the "logged in user" being pinged). */ "highlight"?: boolean; /** * The type of mention this should be. This will prepend the proper prefix character. Valid values: `user`, `channel`, `role`, `voice`, and `locked`. */ "type"?: 'user' | 'channel' | 'role' | 'voice' | 'locked' | 'thread'; } interface DiscordMessage { /** * The message author's username. * @default 'User' */ "author"?: string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar"?: string; /** * Whether the message author is a bot or not. Only works if `server` is `false` or `undefined`. */ "bot"?: boolean; /** * Whether the message has been edited or not. */ "edited"?: boolean; /** * Whether to highlight this message. */ "highlight"?: boolean; /** * The id of the profile data to use. */ "profile"?: string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor"?: string; /** * Whether the message author is a server crosspost webhook or not. Only works if `bot` is `false` or `undefined`. */ "server"?: boolean; /** * The timestamp to use for the message date. */ "timestamp"?: DiscordTimestamp; /** * Whether to use 24-hour format for the timestamp. */ "twentyFour"?: boolean; /** * Whether the bot is verified or not. Only works if `bot` is `true` */ "verified"?: boolean; } interface DiscordMessages { /** * Whether to use compact mode or not. */ "compactMode"?: boolean; /** * Whether to use light theme or not. */ "lightTheme"?: boolean; /** * Whether to exclude the background or not. */ "noBackground"?: boolean; } interface DiscordReaction { /** * The number of people who reacted. * @default 1 */ "count"?: number; /** * The reaction emoji image URL. */ "emoji"?: string; /** * Whether the reaction should be reactive. * @remark When the reaction is interactive left clicking it will add 1 to the counter. Whereas when holding the Shift key and left clicking it will decrease the counter. The counter cannot go below 1. * @default false */ "interactive"?: boolean; /** * The name of the emoji to use as alternative image text. * @default ':emoji' */ "name"?: string; /** * Whether the reaction should show as reacted by the user. * @default false */ "reacted"?: boolean; } interface DiscordReactions { } interface DiscordReply { /** * Whether the referenced message contains attachments. */ "attachment"?: boolean; /** * The message author's username. * @default 'User' */ "author"?: string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar"?: string; /** * Whether the message author is a bot or not. Only works if `server` is `false` or `undefined`. */ "bot"?: boolean; /** * Whether the referenced message is from a response of a slash command. */ "command"?: boolean; /** * Whether the message has been edited or not. */ "edited"?: boolean; /** * Whether this reply pings the original message sender, prepending an "@" on the author's username. */ "mentions"?: boolean; /** * The id of the profile data to use. */ "profile"?: string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor"?: string; /** * Whether the message author is a server crosspost webhook or not. Only works if `bot` is `false` or `undefined`. */ "server"?: boolean; /** * Whether the bot is verified or not. Only works if `bot` is `true` */ "verified"?: boolean; } interface DiscordSystemMessage { /** * Whether this message is to show channel name changes, used to match Discord's style. */ "channelName"?: boolean; /** * The timestamp to use for the message date. */ "timestamp"?: DiscordTimestamp; /** * The type of system message this is, this will change the icon shown. Valid values: `join`, `leave`, `call`, `missed-call`, `boost`, `edit`, `thread`, `alert`, and `error`. */ "type"?: 'join' | 'leave' | 'call' | 'missed-call' | 'boost' | 'edit' | 'thread' | 'alert' | 'error'; } interface DiscordTenorVideo { /** * The height of the video in pixels */ "height"?: number; /** * The URL for the video */ "url"?: string; /** * The width of the video in pixels */ "width"?: number; } interface DiscordThread { /** * The the text within the call to action text. (i.e. 'See Thread' or 'x Messages') */ "cta"?: string; /** * The name of the thread. */ "name"?: string; } interface DiscordThreadMessage { /** * The message author's username. * @default 'User' */ "author"?: string; /** * The message author's avatar. Can be an avatar shortcut, relative path, or external link. */ "avatar"?: string; /** * Whether the message author is a bot or not. Only works if `server` is `false` or `undefined`. */ "bot"?: boolean; /** * Whether the message has been edited or not. */ "edited"?: boolean; /** * The id of the profile data to use. */ "profile"?: string; /** * The relative timestamp of the message. */ "relativeTimestamp"?: string; /** * The message author's primary role color. Can be any [CSS color value](https://www.w3schools.com/cssref/css_colors_legal.asp). */ "roleColor"?: string; /** * Whether the message author is a server crosspost webhook or not. Only works if `bot` is `false` or `undefined`. */ "server"?: boolean; /** * Whether the bot is verified or not. Only works if `bot` is `true` */ "verified"?: boolean; } interface IntrinsicElements { "discord-action-row": DiscordActionRow; "discord-attachment": DiscordAttachment; "discord-attachments": DiscordAttachments; "discord-button": DiscordButton; "discord-command": DiscordCommand; "discord-embed": DiscordEmbed; "discord-embed-field": DiscordEmbedField; "discord-embed-fields": DiscordEmbedFields; "discord-invite": DiscordInvite; "discord-mention": DiscordMention; "discord-message": DiscordMessage; "discord-messages": DiscordMessages; "discord-reaction": DiscordReaction; "discord-reactions": DiscordReactions; "discord-reply": DiscordReply; "discord-system-message": DiscordSystemMessage; "discord-tenor-video": DiscordTenorVideo; "discord-thread": DiscordThread; "discord-thread-message": DiscordThreadMessage; } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { "discord-action-row": LocalJSX.DiscordActionRow & JSXBase.HTMLAttributes<HTMLDiscordActionRowElement>; "discord-attachment": LocalJSX.DiscordAttachment & JSXBase.HTMLAttributes<HTMLDiscordAttachmentElement>; "discord-attachments": LocalJSX.DiscordAttachments & JSXBase.HTMLAttributes<HTMLDiscordAttachmentsElement>; "discord-button": LocalJSX.DiscordButton & JSXBase.HTMLAttributes<HTMLDiscordButtonElement>; "discord-command": LocalJSX.DiscordCommand & JSXBase.HTMLAttributes<HTMLDiscordCommandElement>; "discord-embed": LocalJSX.DiscordEmbed & JSXBase.HTMLAttributes<HTMLDiscordEmbedElement>; "discord-embed-field": LocalJSX.DiscordEmbedField & JSXBase.HTMLAttributes<HTMLDiscordEmbedFieldElement>; "discord-embed-fields": LocalJSX.DiscordEmbedFields & JSXBase.HTMLAttributes<HTMLDiscordEmbedFieldsElement>; "discord-invite": LocalJSX.DiscordInvite & JSXBase.HTMLAttributes<HTMLDiscordInviteElement>; "discord-mention": LocalJSX.DiscordMention & JSXBase.HTMLAttributes<HTMLDiscordMentionElement>; "discord-message": LocalJSX.DiscordMessage & JSXBase.HTMLAttributes<HTMLDiscordMessageElement>; "discord-messages": LocalJSX.DiscordMessages & JSXBase.HTMLAttributes<HTMLDiscordMessagesElement>; "discord-reaction": LocalJSX.DiscordReaction & JSXBase.HTMLAttributes<HTMLDiscordReactionElement>; "discord-reactions": LocalJSX.DiscordReactions & JSXBase.HTMLAttributes<HTMLDiscordReactionsElement>; "discord-reply": LocalJSX.DiscordReply & JSXBase.HTMLAttributes<HTMLDiscordReplyElement>; "discord-system-message": LocalJSX.DiscordSystemMessage & JSXBase.HTMLAttributes<HTMLDiscordSystemMessageElement>; "discord-tenor-video": LocalJSX.DiscordTenorVideo & JSXBase.HTMLAttributes<HTMLDiscordTenorVideoElement>; "discord-thread": LocalJSX.DiscordThread & JSXBase.HTMLAttributes<HTMLDiscordThreadElement>; "discord-thread-message": LocalJSX.DiscordThreadMessage & JSXBase.HTMLAttributes<HTMLDiscordThreadMessageElement>; } } }
the_stack
module android.widget { import Canvas = android.graphics.Canvas; import Rect = android.graphics.Rect; import Log = android.util.Log; import FocusFinder = android.view.FocusFinder; import KeyEvent = android.view.KeyEvent; import MotionEvent = android.view.MotionEvent; import VelocityTracker = android.view.VelocityTracker; import View = android.view.View; import ViewConfiguration = android.view.ViewConfiguration; import ViewGroup = android.view.ViewGroup; import ViewParent = android.view.ViewParent; import AnimationUtils = android.view.animation.AnimationUtils; import List = java.util.List; import Integer = java.lang.Integer; import System = java.lang.System; import FrameLayout = android.widget.FrameLayout; import LinearLayout = android.widget.LinearLayout; import ListView = android.widget.ListView; import OverScroller = android.widget.OverScroller; import ScrollView = android.widget.ScrollView; import TextView = android.widget.TextView; /** * Layout container for a view hierarchy that can be scrolled by the user, * allowing it to be larger than the physical display. A HorizontalScrollView * is a {@link FrameLayout}, meaning you should place one child in it * containing the entire contents to scroll; this child may itself be a layout * manager with a complex hierarchy of objects. A child that is often used * is a {@link LinearLayout} in a horizontal orientation, presenting a horizontal * array of top-level items that the user can scroll through. * * <p>The {@link TextView} class also * takes care of its own scrolling, so does not require a HorizontalScrollView, but * using the two together is possible to achieve the effect of a text view * within a larger container. * * <p>HorizontalScrollView only supports horizontal scrolling. For vertical scrolling, * use either {@link ScrollView} or {@link ListView}. * * @attr ref android.R.styleable#HorizontalScrollView_fillViewport */ export class HorizontalScrollView extends FrameLayout { private static ANIMATED_SCROLL_GAP:number = ScrollView.ANIMATED_SCROLL_GAP; private static MAX_SCROLL_FACTOR:number = ScrollView.MAX_SCROLL_FACTOR; private static TAG:string = "HorizontalScrollView"; private mLastScroll:number = 0; private mTempRect:Rect = new Rect(); private mScroller:OverScroller; //private mEdgeGlowLeft:EdgeEffect; // //private mEdgeGlowRight:EdgeEffect; /** * Position of the last motion event. */ private mLastMotionX:number = 0; /** * True when the layout has changed but the traversal has not come through yet. * Ideally the view hierarchy would keep track of this for us. */ private mIsLayoutDirty:boolean = true; /** * The child to give focus to in the event that a child has requested focus while the * layout is dirty. This prevents the scroll from being wrong if the child has not been * laid out before requesting focus. */ private mChildToScrollTo:View = null; /** * True if the user is currently dragging this ScrollView around. This is * not the same as 'is being flinged', which can be checked by * mScroller.isFinished() (flinging begins when the user lifts his finger). */ private mIsBeingDragged:boolean = false; /** * Determines speed during touch scrolling */ private mVelocityTracker:VelocityTracker; /** * When set to true, the scroll view measure its child to make it fill the currently * visible area. */ private mFillViewport:boolean; /** * Whether arrow scrolling is animated. */ private mSmoothScrollingEnabled:boolean = true; //private mTouchSlop:number = 0; private mMinimumVelocity:number = 0; private mMaximumVelocity:number = 0; private mOverscrollDistance:number = 0; private _mOverflingDistance:number = 0; private get mOverflingDistance():number { if (this.mScrollX < -this._mOverflingDistance) return -this.mScrollX; let overDistance = this.mScrollX - this.getScrollRange(); if (overDistance > this._mOverflingDistance) return overDistance; return this._mOverflingDistance; } private set mOverflingDistance(value:number) { this._mOverflingDistance = value; } /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private mActivePointerId:number = HorizontalScrollView.INVALID_POINTER; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static INVALID_POINTER:number = -1; //private mSavedState:HorizontalScrollView.SavedState; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); this.initScrollView(); let a = context.obtainStyledAttributes(bindElement, defStyle); this.setFillViewport(a.getBoolean('fillViewport', false)); a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('', { setter(v:HorizontalScrollView, value:any, attrBinder:androidui.attr.AttrBinder) { v.setFillViewport(attrBinder.parseBoolean(value)); }, getter(v:HorizontalScrollView) { return v.isFillViewport(); } }); } protected getLeftFadingEdgeStrength():number { if (this.getChildCount() == 0) { return 0.0; } const length:number = this.getHorizontalFadingEdgeLength(); if (this.mScrollX < length) { return this.mScrollX / <number> length; } return 1.0; } protected getRightFadingEdgeStrength():number { if (this.getChildCount() == 0) { return 0.0; } const length:number = this.getHorizontalFadingEdgeLength(); const rightEdge:number = this.getWidth() - this.mPaddingRight; const span:number = this.getChildAt(0).getRight() - this.mScrollX - rightEdge; if (span < length) { return span / <number> length; } return 1.0; } /** * @return The maximum amount this scroll view will scroll in response to * an arrow event. */ getMaxScrollAmount():number { return Math.floor((HorizontalScrollView.MAX_SCROLL_FACTOR * (this.mRight - this.mLeft))); } private initScrollView():void { this.mScroller = new OverScroller(); this.setFocusable(true); this.setDescendantFocusability(HorizontalScrollView.FOCUS_AFTER_DESCENDANTS); this.setWillNotDraw(false); const configuration:ViewConfiguration = ViewConfiguration.get(); this.mTouchSlop = configuration.getScaledTouchSlop(); this.mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); this.mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); this.mOverscrollDistance = configuration.getScaledOverscrollDistance(); this._mOverflingDistance = configuration.getScaledOverflingDistance(); this.initScrollCache(); this.setHorizontalScrollBarEnabled(true); } addView(...args) { if (this.getChildCount() > 0) { throw new Error("ScrollView can host only one direct child"); } return super.addView(...args); } /** * @return Returns true this HorizontalScrollView can be scrolled */ private canScroll():boolean { let child:View = this.getChildAt(0); if (child != null) { let childWidth:number = child.getWidth(); return this.getWidth() < childWidth + this.mPaddingLeft + this.mPaddingRight; } return false; } /** * Indicates whether this HorizontalScrollView's content is stretched to * fill the viewport. * * @return True if the content fills the viewport, false otherwise. * * @attr ref android.R.styleable#HorizontalScrollView_fillViewport */ isFillViewport():boolean { return this.mFillViewport; } /** * Indicates this HorizontalScrollView whether it should stretch its content width * to fill the viewport or not. * * @param fillViewport True to stretch the content's width to the viewport's * boundaries, false otherwise. * * @attr ref android.R.styleable#HorizontalScrollView_fillViewport */ setFillViewport(fillViewport:boolean):void { if (fillViewport != this.mFillViewport) { this.mFillViewport = fillViewport; this.requestLayout(); } } /** * @return Whether arrow scrolling will animate its transition. */ isSmoothScrollingEnabled():boolean { return this.mSmoothScrollingEnabled; } /** * Set whether arrow scrolling will animate its transition. * @param smoothScrollingEnabled whether arrow scrolling will animate its transition */ setSmoothScrollingEnabled(smoothScrollingEnabled:boolean):void { this.mSmoothScrollingEnabled = smoothScrollingEnabled; } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (!this.mFillViewport) { return; } const widthMode:number = View.MeasureSpec.getMode(widthMeasureSpec); if (widthMode == View.MeasureSpec.UNSPECIFIED) { return; } if (this.getChildCount() > 0) { const child:View = this.getChildAt(0); let width:number = this.getMeasuredWidth(); if (child.getMeasuredWidth() < width) { const lp:FrameLayout.LayoutParams = <FrameLayout.LayoutParams> child.getLayoutParams(); let childHeightMeasureSpec:number = HorizontalScrollView.getChildMeasureSpec(heightMeasureSpec, this.mPaddingTop + this.mPaddingBottom, lp.height); width -= this.mPaddingLeft; width -= this.mPaddingRight; let childWidthMeasureSpec:number = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } } dispatchKeyEvent(event:KeyEvent):boolean { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || this.executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ executeKeyEvent(event:KeyEvent):boolean { this.mTempRect.setEmpty(); if (!this.canScroll()) { if (this.isFocused()) { let currentFocused:View = this.findFocus(); if (currentFocused == this) currentFocused = null; let nextFocused:View = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_RIGHT); return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_RIGHT); } return false; } let handled:boolean = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch(event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: if (!event.isAltPressed()) { handled = this.arrowScroll(View.FOCUS_LEFT); } else { handled = this.fullScroll(View.FOCUS_LEFT); } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (!event.isAltPressed()) { handled = this.arrowScroll(View.FOCUS_RIGHT); } else { handled = this.fullScroll(View.FOCUS_RIGHT); } break; case KeyEvent.KEYCODE_SPACE: this.pageScroll(event.isShiftPressed() ? View.FOCUS_LEFT : View.FOCUS_RIGHT); break; } } return handled; } private inChild(x:number, y:number):boolean { if (this.getChildCount() > 0) { const scrollX:number = this.mScrollX; const child:View = this.getChildAt(0); return !(y < child.getTop() || y >= child.getBottom() || x < child.getLeft() - scrollX || x >= child.getRight() - scrollX); } return false; } private initOrResetVelocityTracker():void { if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } else { this.mVelocityTracker.clear(); } } private initVelocityTrackerIfNotExists():void { if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } } private recycleVelocityTracker():void { if (this.mVelocityTracker != null) { this.mVelocityTracker.recycle(); this.mVelocityTracker = null; } } requestDisallowInterceptTouchEvent(disallowIntercept:boolean):void { if (disallowIntercept) { this.recycleVelocityTracker(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } onInterceptTouchEvent(ev:MotionEvent):boolean { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ const action:number = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (this.mIsBeingDragged)) { return true; } switch(action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionX is set to the x value * of the down event. */ const activePointerId:number = this.mActivePointerId; if (activePointerId == HorizontalScrollView.INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } const pointerIndex:number = ev.findPointerIndex(activePointerId); if (pointerIndex == -1) { Log.e(HorizontalScrollView.TAG, "Invalid pointerId=" + activePointerId + " in onInterceptTouchEvent"); break; } const x:number = Math.floor(ev.getX(pointerIndex)); const xDiff:number = Math.floor(Math.abs(x - this.mLastMotionX)); if (xDiff > this.mTouchSlop) { this.mIsBeingDragged = true; this.mLastMotionX = x; this.initVelocityTrackerIfNotExists(); this.mVelocityTracker.addMovement(ev); if (this.mParent != null) this.mParent.requestDisallowInterceptTouchEvent(true); } break; } case MotionEvent.ACTION_DOWN: { const x:number = Math.floor(ev.getX()); if (!this.inChild(Math.floor(x), Math.floor(ev.getY()))) { this.mIsBeingDragged = false; this.recycleVelocityTracker(); break; } /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ this.mLastMotionX = x; this.mActivePointerId = ev.getPointerId(0); this.initOrResetVelocityTracker(); this.mVelocityTracker.addMovement(ev); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ this.mIsBeingDragged = !this.mScroller.isFinished(); break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: /* Release the drag */ this.mIsBeingDragged = false; this.mActivePointerId = HorizontalScrollView.INVALID_POINTER; if (this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, this.getScrollRange(), 0, 0)) { this.postInvalidateOnAnimation(); } break; case MotionEvent.ACTION_POINTER_DOWN: { const index:number = ev.getActionIndex(); this.mLastMotionX = Math.floor(ev.getX(index)); this.mActivePointerId = ev.getPointerId(index); break; } case MotionEvent.ACTION_POINTER_UP: this.onSecondaryPointerUp(ev); this.mLastMotionX = Math.floor(ev.getX(ev.findPointerIndex(this.mActivePointerId))); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return this.mIsBeingDragged; } onTouchEvent(ev:MotionEvent):boolean { this.initVelocityTrackerIfNotExists(); this.mVelocityTracker.addMovement(ev); const action:number = ev.getAction(); switch(action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { if (this.getChildCount() == 0) { return false; } if ((this.mIsBeingDragged = !this.mScroller.isFinished())) { const parent:ViewParent = this.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!this.mScroller.isFinished()) { this.mScroller.abortAnimation(); } // Remember where the motion event started this.mLastMotionX = Math.floor(ev.getX()); this.mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: const activePointerIndex:number = ev.findPointerIndex(this.mActivePointerId); if (activePointerIndex == -1) { Log.e(HorizontalScrollView.TAG, "Invalid pointerId=" + this.mActivePointerId + " in onTouchEvent"); break; } const x:number = Math.floor(ev.getX(activePointerIndex)); let deltaX:number = this.mLastMotionX - x; if (!this.mIsBeingDragged && Math.abs(deltaX) > this.mTouchSlop) { const parent:ViewParent = this.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } this.mIsBeingDragged = true; if (deltaX > 0) { deltaX -= this.mTouchSlop; } else { deltaX += this.mTouchSlop; } } if (this.mIsBeingDragged) { // Scroll to follow the motion event this.mLastMotionX = x; const oldX:number = this.mScrollX; const oldY:number = this.mScrollY; const range:number = this.getScrollRange(); const overscrollMode:number = this.getOverScrollMode(); const canOverscroll:boolean = overscrollMode == HorizontalScrollView.OVER_SCROLL_ALWAYS || (overscrollMode == HorizontalScrollView.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); // calls onScrollChanged if applicable. if (this.overScrollBy(deltaX, 0, this.mScrollX, 0, range, 0, this.mOverscrollDistance, 0, true)) { // Break our velocity if we hit a scroll barrier. this.mVelocityTracker.clear(); } if (canOverscroll) { //const pulledToX:number = oldX + deltaX; //if (pulledToX < 0) { // this.mEdgeGlowLeft.onPull(<number> deltaX / this.getWidth()); // if (!this.mEdgeGlowRight.isFinished()) { // this.mEdgeGlowRight.onRelease(); // } //} else if (pulledToX > range) { // this.mEdgeGlowRight.onPull(<number> deltaX / this.getWidth()); // if (!this.mEdgeGlowLeft.isFinished()) { // this.mEdgeGlowLeft.onRelease(); // } //} //if (this.mEdgeGlowLeft != null && (!this.mEdgeGlowLeft.isFinished() || !this.mEdgeGlowRight.isFinished())) { // this.postInvalidateOnAnimation(); //} } } break; case MotionEvent.ACTION_UP: if (this.mIsBeingDragged) { const velocityTracker:VelocityTracker = this.mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, this.mMaximumVelocity); let initialVelocity:number = Math.floor(velocityTracker.getXVelocity(this.mActivePointerId)); if (this.getChildCount() > 0) { let isOverDrag = this.mScrollX < 0 || this.mScrollX > this.getScrollRange(); if (!isOverDrag && (Math.abs(initialVelocity) > this.mMinimumVelocity)) { this.fling(-initialVelocity); } else { if (this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, this.getScrollRange(), 0, 0)) { this.postInvalidateOnAnimation(); } } } this.mActivePointerId = HorizontalScrollView.INVALID_POINTER; this.mIsBeingDragged = false; this.recycleVelocityTracker(); //if (this.mEdgeGlowLeft != null) { // this.mEdgeGlowLeft.onRelease(); // this.mEdgeGlowRight.onRelease(); //} } break; case MotionEvent.ACTION_CANCEL: if (this.mIsBeingDragged && this.getChildCount() > 0) { if (this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, this.getScrollRange(), 0, 0)) { this.postInvalidateOnAnimation(); } this.mActivePointerId = HorizontalScrollView.INVALID_POINTER; this.mIsBeingDragged = false; this.recycleVelocityTracker(); //if (this.mEdgeGlowLeft != null) { // this.mEdgeGlowLeft.onRelease(); // this.mEdgeGlowRight.onRelease(); //} } break; case MotionEvent.ACTION_POINTER_UP: this.onSecondaryPointerUp(ev); break; } return true; } private onSecondaryPointerUp(ev:MotionEvent):void { const pointerIndex:number = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; const pointerId:number = ev.getPointerId(pointerIndex); if (pointerId == this.mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. const newPointerIndex:number = pointerIndex == 0 ? 1 : 0; this.mLastMotionX = Math.floor(ev.getX(newPointerIndex)); this.mActivePointerId = ev.getPointerId(newPointerIndex); if (this.mVelocityTracker != null) { this.mVelocityTracker.clear(); } } } onGenericMotionEvent(event:MotionEvent):boolean { if (event.isPointerEvent()) { switch(event.getAction()) { case MotionEvent.ACTION_SCROLL: { if (!this.mIsBeingDragged) { let hscroll:number; //if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { hscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); //} else { // hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); //} if (hscroll != 0) { const delta:number = Math.floor((hscroll * this.getHorizontalScrollFactor())); const range:number = this.getScrollRange(); let oldScrollX:number = this.mScrollX; let newScrollX:number = oldScrollX + delta; if (newScrollX < 0) { newScrollX = 0; } else if (newScrollX > range) { newScrollX = range; } if (newScrollX != oldScrollX) { super.scrollTo(newScrollX, this.mScrollY); return true; } } } } } } return super.onGenericMotionEvent(event); } shouldDelayChildPressedState():boolean { return true; } protected onOverScrolled(scrollX:number, scrollY:number, clampedX:boolean, clampedY:boolean):void { // Treat animating scrolls differently; see #computeScroll() for why. if (!this.mScroller.isFinished()) { const oldX:number = this.mScrollX; const oldY:number = this.mScrollY; this.mScrollX = scrollX; this.mScrollY = scrollY; this.invalidateParentIfNeeded(); this.onScrollChanged(this.mScrollX, this.mScrollY, oldX, oldY); if (clampedX) { this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, this.getScrollRange(), 0, 0); } } else { super.scrollTo(scrollX, scrollY); } this.awakenScrollBars(); } //performAccessibilityAction(action:number, arguments:Bundle):boolean { // if (super.performAccessibilityAction(action, arguments)) { // return true; // } // switch(action) { // case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: // { // if (!this.isEnabled()) { // return false; // } // const viewportWidth:number = this.getWidth() - this.mPaddingLeft - this.mPaddingRight; // const targetScrollX:number = Math.min(this.mScrollX + viewportWidth, this.getScrollRange()); // if (targetScrollX != this.mScrollX) { // this.smoothScrollTo(targetScrollX, 0); // return true; // } // } // return false; // case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: // { // if (!this.isEnabled()) { // return false; // } // const viewportWidth:number = this.getWidth() - this.mPaddingLeft - this.mPaddingRight; // const targetScrollX:number = Math.max(0, this.mScrollX - viewportWidth); // if (targetScrollX != this.mScrollX) { // this.smoothScrollTo(targetScrollX, 0); // return true; // } // } // return false; // } // return false; //} // //onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void { // super.onInitializeAccessibilityNodeInfo(info); // info.setClassName(HorizontalScrollView.class.getName()); // const scrollRange:number = this.getScrollRange(); // if (scrollRange > 0) { // info.setScrollable(true); // if (this.isEnabled() && this.mScrollX > 0) { // info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); // } // if (this.isEnabled() && this.mScrollX < scrollRange) { // info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); // } // } //} // //onInitializeAccessibilityEvent(event:AccessibilityEvent):void { // super.onInitializeAccessibilityEvent(event); // event.setClassName(HorizontalScrollView.class.getName()); // event.setScrollable(this.getScrollRange() > 0); // event.setScrollX(this.mScrollX); // event.setScrollY(this.mScrollY); // event.setMaxScrollX(this.getScrollRange()); // event.setMaxScrollY(this.mScrollY); //} private getScrollRange():number { let scrollRange:number = 0; if (this.getChildCount() > 0) { let child:View = this.getChildAt(0); scrollRange = Math.max(0, child.getWidth() - (this.getWidth() - this.mPaddingLeft - this.mPaddingRight)); } return scrollRange; } /** * <p> * Finds the next focusable component that fits in this View's bounds * (excluding fading edges) pretending that this View's left is located at * the parameter left. * </p> * * @param leftFocus look for a candidate is the one at the left of the bounds * if leftFocus is true, or at the right of the bounds if leftFocus * is false * @param left the left offset of the bounds in which a focusable must be * found (the fading edge is assumed to start at this position) * @param preferredFocusable the View that has highest priority and will be * returned if it is within my bounds (null is valid) * @return the next focusable component in the bounds or null if none can be found */ private findFocusableViewInMyBounds(leftFocus:boolean, left:number, preferredFocusable:View):View { /* * The fading edge's transparent side should be considered for focus * since it's mostly visible, so we divide the actual fading edge length * by 2. */ const fadingEdgeLength:number = this.getHorizontalFadingEdgeLength() / 2; const leftWithoutFadingEdge:number = left + fadingEdgeLength; const rightWithoutFadingEdge:number = left + this.getWidth() - fadingEdgeLength; if ((preferredFocusable != null) && (preferredFocusable.getLeft() < rightWithoutFadingEdge) && (preferredFocusable.getRight() > leftWithoutFadingEdge)) { return preferredFocusable; } return this.findFocusableViewInBounds(leftFocus, leftWithoutFadingEdge, rightWithoutFadingEdge); } /** * <p> * Finds the next focusable component that fits in the specified bounds. * </p> * * @param leftFocus look for a candidate is the one at the left of the bounds * if leftFocus is true, or at the right of the bounds if * leftFocus is false * @param left the left offset of the bounds in which a focusable must be * found * @param right the right offset of the bounds in which a focusable must * be found * @return the next focusable component in the bounds or null if none can * be found */ private findFocusableViewInBounds(leftFocus:boolean, left:number, right:number):View { let focusables:List<View> = this.getFocusables(View.FOCUS_FORWARD); let focusCandidate:View = null; /* * A fully contained focusable is one where its left is below the bound's * left, and its right is above the bound's right. A partially * contained focusable is one where some part of it is within the * bounds, but it also has some part that is not within bounds. A fully contained * focusable is preferred to a partially contained focusable. */ let foundFullyContainedFocusable:boolean = false; let count:number = focusables.size(); for (let i:number = 0; i < count; i++) { let view:View = focusables.get(i); let viewLeft:number = view.getLeft(); let viewRight:number = view.getRight(); if (left < viewRight && viewLeft < right) { /* * the focusable is in the target area, it is a candidate for * focusing */ const viewIsFullyContained:boolean = (left < viewLeft) && (viewRight < right); if (focusCandidate == null) { /* No candidate, take this one */ focusCandidate = view; foundFullyContainedFocusable = viewIsFullyContained; } else { const viewIsCloserToBoundary:boolean = (leftFocus && viewLeft < focusCandidate.getLeft()) || (!leftFocus && viewRight > focusCandidate.getRight()); if (foundFullyContainedFocusable) { if (viewIsFullyContained && viewIsCloserToBoundary) { /* * We're dealing with only fully contained views, so * it has to be closer to the boundary to beat our * candidate */ focusCandidate = view; } } else { if (viewIsFullyContained) { /* Any fully contained view beats a partially contained view */ focusCandidate = view; foundFullyContainedFocusable = true; } else if (viewIsCloserToBoundary) { /* * Partially contained view beats another partially * contained view if it's closer */ focusCandidate = view; } } } } } return focusCandidate; } /** * <p>Handles scrolling in response to a "page up/down" shortcut press. This * method will scroll the view by one page left or right and give the focus * to the leftmost/rightmost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} * to go one page left or {@link android.view.View#FOCUS_RIGHT} * to go one page right * @return true if the key event is consumed by this method, false otherwise */ pageScroll(direction:number):boolean { let right:boolean = direction == View.FOCUS_RIGHT; let width:number = this.getWidth(); if (right) { this.mTempRect.left = this.getScrollX() + width; let count:number = this.getChildCount(); if (count > 0) { let view:View = this.getChildAt(0); if (this.mTempRect.left + width > view.getRight()) { this.mTempRect.left = view.getRight() - width; } } } else { this.mTempRect.left = this.getScrollX() - width; if (this.mTempRect.left < 0) { this.mTempRect.left = 0; } } this.mTempRect.right = this.mTempRect.left + width; return this.scrollAndFocus(direction, this.mTempRect.left, this.mTempRect.right); } /** * <p>Handles scrolling in response to a "home/end" shortcut press. This * method will scroll the view to the left or right and give the focus * to the leftmost/rightmost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} * to go the left of the view or {@link android.view.View#FOCUS_RIGHT} * to go the right * @return true if the key event is consumed by this method, false otherwise */ fullScroll(direction:number):boolean { let right:boolean = direction == View.FOCUS_RIGHT; let width:number = this.getWidth(); this.mTempRect.left = 0; this.mTempRect.right = width; if (right) { let count:number = this.getChildCount(); if (count > 0) { let view:View = this.getChildAt(0); this.mTempRect.right = view.getRight(); this.mTempRect.left = this.mTempRect.right - width; } } return this.scrollAndFocus(direction, this.mTempRect.left, this.mTempRect.right); } /** * <p>Scrolls the view to make the area defined by <code>left</code> and * <code>right</code> visible. This method attempts to give the focus * to a component visible in this area. If no component can be focused in * the new visible area, the focus is reclaimed by this scrollview.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} * to go left {@link android.view.View#FOCUS_RIGHT} to right * @param left the left offset of the new area to be made visible * @param right the right offset of the new area to be made visible * @return true if the key event is consumed by this method, false otherwise */ private scrollAndFocus(direction:number, left:number, right:number):boolean { let handled:boolean = true; let width:number = this.getWidth(); let containerLeft:number = this.getScrollX(); let containerRight:number = containerLeft + width; let goLeft:boolean = direction == View.FOCUS_LEFT; let newFocused:View = this.findFocusableViewInBounds(goLeft, left, right); if (newFocused == null) { newFocused = this; } if (left >= containerLeft && right <= containerRight) { handled = false; } else { let delta:number = goLeft ? (left - containerLeft) : (right - containerRight); this.doScrollX(delta); } if (newFocused != this.findFocus()) newFocused.requestFocus(direction); return handled; } /** * Handle scrolling in response to a left or right arrow click. * * @param direction The direction corresponding to the arrow key that was * pressed * @return True if we consumed the event, false otherwise */ arrowScroll(direction:number):boolean { let currentFocused:View = this.findFocus(); if (currentFocused == this) currentFocused = null; let nextFocused:View = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); const maxJump:number = this.getMaxScrollAmount(); if (nextFocused != null && this.isWithinDeltaOfScreen(nextFocused, maxJump)) { nextFocused.getDrawingRect(this.mTempRect); this.offsetDescendantRectToMyCoords(nextFocused, this.mTempRect); let scrollDelta:number = this.computeScrollDeltaToGetChildRectOnScreen(this.mTempRect); this.doScrollX(scrollDelta); nextFocused.requestFocus(direction); } else { // no new focus let scrollDelta:number = maxJump; if (direction == View.FOCUS_LEFT && this.getScrollX() < scrollDelta) { scrollDelta = this.getScrollX(); } else if (direction == View.FOCUS_RIGHT && this.getChildCount() > 0) { let daRight:number = this.getChildAt(0).getRight(); let screenRight:number = this.getScrollX() + this.getWidth(); if (daRight - screenRight < maxJump) { scrollDelta = daRight - screenRight; } } if (scrollDelta == 0) { return false; } this.doScrollX(direction == View.FOCUS_RIGHT ? scrollDelta : -scrollDelta); } if (currentFocused != null && currentFocused.isFocused() && this.isOffScreen(currentFocused)) { // previously focused item still has focus and is off screen, give // it up (take it back to ourselves) // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are // sure to // get it) // save const descendantFocusability:number = this.getDescendantFocusability(); this.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); this.requestFocus(); // restore this.setDescendantFocusability(descendantFocusability); } return true; } /** * @return whether the descendant of this scroll view is scrolled off * screen. */ private isOffScreen(descendant:View):boolean { return !this.isWithinDeltaOfScreen(descendant, 0); } /** * @return whether the descendant of this scroll view is within delta * pixels of being on the screen. */ private isWithinDeltaOfScreen(descendant:View, delta:number):boolean { descendant.getDrawingRect(this.mTempRect); this.offsetDescendantRectToMyCoords(descendant, this.mTempRect); return (this.mTempRect.right + delta) >= this.getScrollX() && (this.mTempRect.left - delta) <= (this.getScrollX() + this.getWidth()); } /** * Smooth scroll by a X delta * * @param delta the number of pixels to scroll by on the X axis */ private doScrollX(delta:number):void { if (delta != 0) { if (this.mSmoothScrollingEnabled) { this.smoothScrollBy(delta, 0); } else { this.scrollBy(delta, 0); } } } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis */ smoothScrollBy(dx:number, dy:number):void { if (this.getChildCount() == 0) { // Nothing to do. return; } let duration:number = AnimationUtils.currentAnimationTimeMillis() - this.mLastScroll; if (duration > HorizontalScrollView.ANIMATED_SCROLL_GAP) { const width:number = this.getWidth() - this.mPaddingRight - this.mPaddingLeft; const right:number = this.getChildAt(0).getWidth(); const maxX:number = Math.max(0, right - width); const scrollX:number = this.mScrollX; dx = Math.max(0, Math.min(scrollX + dx, maxX)) - scrollX; this.mScroller.startScroll(scrollX, this.mScrollY, dx, 0); this.postInvalidateOnAnimation(); } else { if (!this.mScroller.isFinished()) { this.mScroller.abortAnimation(); } this.scrollBy(dx, dy); } this.mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } /** * Like {@link #scrollTo}, but scroll smoothly instead of immediately. * * @param x the position where to scroll on the X axis * @param y the position where to scroll on the Y axis */ smoothScrollTo(x:number, y:number):void { this.smoothScrollBy(x - this.mScrollX, y - this.mScrollY); } /** * <p>The scroll range of a scroll view is the overall width of all of its * children.</p> */ protected computeHorizontalScrollRange():number { const count:number = this.getChildCount(); const contentWidth:number = this.getWidth() - this.mPaddingLeft - this.mPaddingRight; if (count == 0) { return contentWidth; } let scrollRange:number = this.getChildAt(0).getRight(); const scrollX:number = this.mScrollX; const overscrollRight:number = Math.max(0, scrollRange - contentWidth); if (scrollX < 0) { scrollRange -= scrollX; } else if (scrollX > overscrollRight) { scrollRange += scrollX - overscrollRight; } return scrollRange; } protected computeHorizontalScrollOffset():number { return Math.max(0, super.computeHorizontalScrollOffset()); } protected measureChild(child:View, parentWidthMeasureSpec:number, parentHeightMeasureSpec:number):void { let lp:ViewGroup.LayoutParams = child.getLayoutParams(); let childWidthMeasureSpec:number; let childHeightMeasureSpec:number; childHeightMeasureSpec = HorizontalScrollView.getChildMeasureSpec(parentHeightMeasureSpec, this.mPaddingTop + this.mPaddingBottom, lp.height); childWidthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } protected measureChildWithMargins(child:View, parentWidthMeasureSpec:number, widthUsed:number, parentHeightMeasureSpec:number, heightUsed:number):void { const lp:ViewGroup.MarginLayoutParams = <ViewGroup.MarginLayoutParams> child.getLayoutParams(); const childHeightMeasureSpec:number = HorizontalScrollView.getChildMeasureSpec(parentHeightMeasureSpec, this.mPaddingTop + this.mPaddingBottom + lp.topMargin + lp.bottomMargin + heightUsed, lp.height); const childWidthMeasureSpec:number = View.MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, View.MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } computeScroll():void { if (this.mScroller.computeScrollOffset()) { // This is called at drawing time by ViewGroup. We don't want to // re-show the scrollbars at this point, which scrollTo will do, // so we replicate most of scrollTo here. // // It's a little odd to call onScrollChanged from inside the drawing. // // It is, except when you remember that computeScroll() is used to // animate scrolling. So unless we want to defer the onScrollChanged() // until the end of the animated scrolling, we don't really have a // choice here. // // I agree. The alternative, which I think would be worse, is to post // something and tell the subclasses later. This is bad because there // will be a window where mScrollX/Y is different from what the app // thinks it is. // let oldX:number = this.mScrollX; let oldY:number = this.mScrollY; let x:number = this.mScroller.getCurrX(); let y:number = this.mScroller.getCurrY(); if (oldX != x || oldY != y) { const range:number = this.getScrollRange(); const overscrollMode:number = this.getOverScrollMode(); const canOverscroll:boolean = overscrollMode == HorizontalScrollView.OVER_SCROLL_ALWAYS || (overscrollMode == HorizontalScrollView.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); this.overScrollBy(x - oldX, y - oldY, oldX, oldY, range, 0, this.mOverflingDistance, 0, false); this.onScrollChanged(this.mScrollX, this.mScrollY, oldX, oldY); if (canOverscroll) { //if (x < 0 && oldX >= 0) { // this.mEdgeGlowLeft.onAbsorb(Math.floor(this.mScroller.getCurrVelocity())); //} else if (x > range && oldX <= range) { // this.mEdgeGlowRight.onAbsorb(Math.floor(this.mScroller.getCurrVelocity())); //} } } if (!this.awakenScrollBars()) { this.postInvalidateOnAnimation(); } } } /** * Scrolls the view to the given child. * * @param child the View to scroll to */ private scrollToChild(child:View):void { child.getDrawingRect(this.mTempRect); /* Offset from child's local coordinates to ScrollView coordinates */ this.offsetDescendantRectToMyCoords(child, this.mTempRect); let scrollDelta:number = this.computeScrollDeltaToGetChildRectOnScreen(this.mTempRect); if (scrollDelta != 0) { this.scrollBy(scrollDelta, 0); } } /** * If rect is off screen, scroll just enough to get it (or at least the * first screen size chunk of it) on screen. * * @param rect The rectangle. * @param immediate True to scroll immediately without animation * @return true if scrolling was performed */ private scrollToChildRect(rect:Rect, immediate:boolean):boolean { const delta:number = this.computeScrollDeltaToGetChildRectOnScreen(rect); const scroll:boolean = delta != 0; if (scroll) { if (immediate) { this.scrollBy(delta, 0); } else { this.smoothScrollBy(delta, 0); } } return scroll; } /** * Compute the amount to scroll in the X direction in order to get * a rectangle completely on the screen (or, if taller than the screen, * at least the first screen size chunk of it). * * @param rect The rect. * @return The scroll delta. */ protected computeScrollDeltaToGetChildRectOnScreen(rect:Rect):number { if (this.getChildCount() == 0) return 0; let width:number = this.getWidth(); let screenLeft:number = this.getScrollX(); let screenRight:number = screenLeft + width; let fadingEdge:number = this.getHorizontalFadingEdgeLength(); // leave room for left fading edge as long as rect isn't at very left if (rect.left > 0) { screenLeft += fadingEdge; } // leave room for right fading edge as long as rect isn't at very right if (rect.right < this.getChildAt(0).getWidth()) { screenRight -= fadingEdge; } let scrollXDelta:number = 0; if (rect.right > screenRight && rect.left > screenLeft) { if (rect.width() > width) { // just enough to get screen size chunk on scrollXDelta += (rect.left - screenLeft); } else { // get entire rect at right of screen scrollXDelta += (rect.right - screenRight); } // make sure we aren't scrolling beyond the end of our content let right:number = this.getChildAt(0).getRight(); let distanceToRight:number = right - screenRight; scrollXDelta = Math.min(scrollXDelta, distanceToRight); } else if (rect.left < screenLeft && rect.right < screenRight) { if (rect.width() > width) { // screen size chunk scrollXDelta -= (screenRight - rect.right); } else { // entire rect at left scrollXDelta -= (screenLeft - rect.left); } // make sure we aren't scrolling any further than the left our content scrollXDelta = Math.max(scrollXDelta, -this.getScrollX()); } return scrollXDelta; } requestChildFocus(child:View, focused:View):void { if (!this.mIsLayoutDirty) { this.scrollToChild(focused); } else { // The child may not be laid out yet, we can't compute the scroll yet this.mChildToScrollTo = focused; } super.requestChildFocus(child, focused); } /** * When looking for focus in children of a scroll view, need to be a little * more careful not to give focus to something that is scrolled off screen. * * This is more expensive than the default {@link android.view.ViewGroup} * implementation, otherwise this behavior might have been made the default. */ protected onRequestFocusInDescendants(direction:number, previouslyFocusedRect:Rect):boolean { // (ugh). if (direction == View.FOCUS_FORWARD) { direction = View.FOCUS_RIGHT; } else if (direction == View.FOCUS_BACKWARD) { direction = View.FOCUS_LEFT; } const nextFocus:View = previouslyFocusedRect == null ? FocusFinder.getInstance().findNextFocus(this, null, direction) : FocusFinder.getInstance().findNextFocusFromRect(this, previouslyFocusedRect, direction); if (nextFocus == null) { return false; } if (this.isOffScreen(nextFocus)) { return false; } return nextFocus.requestFocus(direction, previouslyFocusedRect); } requestChildRectangleOnScreen(child:View, rectangle:Rect, immediate:boolean):boolean { // offset into coordinate space of this scroll view rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY()); return this.scrollToChildRect(rectangle, immediate); } requestLayout():void { this.mIsLayoutDirty = true; super.requestLayout(); } protected onLayout(changed:boolean, l:number, t:number, r:number, b:number):void { let childWidth:number = 0; let childMargins:number = 0; if (this.getChildCount() > 0) { childWidth = this.getChildAt(0).getMeasuredWidth(); let childParams:FrameLayout.LayoutParams = <FrameLayout.LayoutParams> this.getChildAt(0).getLayoutParams(); childMargins = childParams.leftMargin + childParams.rightMargin; } const available:number = r - l - this.getPaddingLeftWithForeground() - this.getPaddingRightWithForeground() - childMargins; const forceLeftGravity:boolean = (childWidth > available); this.layoutChildren(l, t, r, b, forceLeftGravity); this.mIsLayoutDirty = false; // Give a child focus if it needs it if (this.mChildToScrollTo != null && HorizontalScrollView.isViewDescendantOf(this.mChildToScrollTo, this)) { this.scrollToChild(this.mChildToScrollTo); } this.mChildToScrollTo = null; if (!this.isLaidOut()) { const scrollRange:number = Math.max(0, childWidth - (r - l - this.mPaddingLeft - this.mPaddingRight)); //if (this.mSavedState != null) { // if (this.isLayoutRtl() == this.mSavedState.isLayoutRtl) { // this.mScrollX = this.mSavedState.scrollPosition; // } else { // this.mScrollX = scrollRange - this.mSavedState.scrollPosition; // } // this.mSavedState = null; //} else { if (this.isLayoutRtl()) { this.mScrollX = scrollRange - this.mScrollX; } // mScrollX default value is "0" for LTR } // Don't forget to clamp if (this.mScrollX > scrollRange) { this.mScrollX = scrollRange; } else if (this.mScrollX < 0) { this.mScrollX = 0; } } // Calling this with the present values causes it to re-claim them this.scrollTo(this.mScrollX, this.mScrollY); } protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void { super.onSizeChanged(w, h, oldw, oldh); let currentFocused:View = this.findFocus(); if (null == currentFocused || this == currentFocused) return; const maxJump:number = this.mRight - this.mLeft; if (this.isWithinDeltaOfScreen(currentFocused, maxJump)) { currentFocused.getDrawingRect(this.mTempRect); this.offsetDescendantRectToMyCoords(currentFocused, this.mTempRect); let scrollDelta:number = this.computeScrollDeltaToGetChildRectOnScreen(this.mTempRect); this.doScrollX(scrollDelta); } } /** * Return true if child is a descendant of parent, (or equal to the parent). */ private static isViewDescendantOf(child:View, parent:View):boolean { if (child == parent) { return true; } const theParent:ViewParent = child.getParent(); return (theParent instanceof ViewGroup) && HorizontalScrollView.isViewDescendantOf(<View> theParent, parent); } /** * Fling the scroll view * * @param velocityX The initial velocity in the X direction. Positive * numbers mean that the finger/cursor is moving down the screen, * which means we want to scroll towards the left. */ fling(velocityX:number):void { if (this.getChildCount() > 0) { let width:number = this.getWidth() - this.mPaddingRight - this.mPaddingLeft; let right:number = this.getChildAt(0).getWidth(); this.mScroller.fling(this.mScrollX, this.mScrollY, velocityX, 0, 0, Math.max(0, right - width), 0, 0, width / 2, 0); const movingRight:boolean = velocityX > 0; let currentFocused:View = this.findFocus(); let newFocused:View = this.findFocusableViewInMyBounds(movingRight, this.mScroller.getFinalX(), currentFocused); if (newFocused == null) { newFocused = this; } if (newFocused != currentFocused) { newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT); } this.postInvalidateOnAnimation(); } } /** * {@inheritDoc} * * <p>This version also clamps the scrolling to the bounds of our child. */ scrollTo(x:number, y:number):void { // we rely on the fact the View.scrollBy calls scrollTo. if (this.getChildCount() > 0) { let child:View = this.getChildAt(0); x = HorizontalScrollView.clamp(x, this.getWidth() - this.mPaddingRight - this.mPaddingLeft, child.getWidth()); y = HorizontalScrollView.clamp(y, this.getHeight() - this.mPaddingBottom - this.mPaddingTop, child.getHeight()); if (x != this.mScrollX || y != this.mScrollY) { super.scrollTo(x, y); } } } setOverScrollMode(mode:number):void { //if (mode != HorizontalScrollView.OVER_SCROLL_NEVER) { // if (this.mEdgeGlowLeft == null) { // let context:Context = this.getContext(); // this.mEdgeGlowLeft = new EdgeEffect(context); // this.mEdgeGlowRight = new EdgeEffect(context); // } //} else { // this.mEdgeGlowLeft = null; // this.mEdgeGlowRight = null; //} super.setOverScrollMode(mode); } draw(canvas:Canvas):void { super.draw(canvas); //if (this.mEdgeGlowLeft != null) { // const scrollX:number = this.mScrollX; // if (!this.mEdgeGlowLeft.isFinished()) { // const restoreCount:number = canvas.save(); // const height:number = this.getHeight() - this.mPaddingTop - this.mPaddingBottom; // canvas.rotate(270); // canvas.translate(-height + this.mPaddingTop, Math.min(0, scrollX)); // this.mEdgeGlowLeft.setSize(height, this.getWidth()); // if (this.mEdgeGlowLeft.draw(canvas)) { // this.postInvalidateOnAnimation(); // } // canvas.restoreToCount(restoreCount); // } // if (!this.mEdgeGlowRight.isFinished()) { // const restoreCount:number = canvas.save(); // const width:number = this.getWidth(); // const height:number = this.getHeight() - this.mPaddingTop - this.mPaddingBottom; // canvas.rotate(90); // canvas.translate(-this.mPaddingTop, -(Math.max(this.getScrollRange(), scrollX) + width)); // this.mEdgeGlowRight.setSize(height, width); // if (this.mEdgeGlowRight.draw(canvas)) { // this.postInvalidateOnAnimation(); // } // canvas.restoreToCount(restoreCount); // } //} } private static clamp(n:number, my:number, child:number):number { if (my >= child || n < 0) { return 0; } if ((my + n) > child) { return child - my; } return n; } //protected onRestoreInstanceState(state:Parcelable):void { // if (this.mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // // Some old apps reused IDs in ways they shouldn't have. // // Don't break them, but they don't get scroll state restoration. // super.onRestoreInstanceState(state); // return; // } // let ss:HorizontalScrollView.SavedState = <HorizontalScrollView.SavedState> state; // super.onRestoreInstanceState(ss.getSuperState()); // this.mSavedState = ss; // this.requestLayout(); //} // //protected onSaveInstanceState():Parcelable { // if (this.mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // // Don't break them, but they don't get scroll state restoration. // return super.onSaveInstanceState(); // } // let superState:Parcelable = super.onSaveInstanceState(); // let ss:HorizontalScrollView.SavedState = new HorizontalScrollView.SavedState(superState); // ss.scrollPosition = this.mScrollX; // ss.isLayoutRtl = this.isLayoutRtl(); // return ss; //} } //export module HorizontalScrollView{ //export class SavedState extends View.BaseSavedState { // // scrollPosition:number = 0; // // isLayoutRtl:boolean; // // constructor( superState:Parcelable) { // super(superState); // } // // constructor( source:Parcel) { // super(source); // this.scrollPosition = source.readInt(); // this.isLayoutRtl = (source.readInt() == 0) ? true : false; // } // // writeToParcel(dest:Parcel, flags:number):void { // super.writeToParcel(dest, flags); // dest.writeInt(this.scrollPosition); // dest.writeInt(this.isLayoutRtl ? 1 : 0); // } // // toString():string { // return "HorizontalScrollView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " scrollPosition=" + this.scrollPosition + " isLayoutRtl=" + this.isLayoutRtl + "}"; // } // // static CREATOR:Parcelable.Creator<SavedState> = (()=>{ // const inner_this=this; // class _Inner extends Parcelable.Creator<SavedState> { // // createFromParcel(_in:Parcel):SavedState { // return new SavedState(_in); // } // // newArray(size:number):SavedState[] { // return new Array<SavedState>(size); // } // } // return new _Inner(); // })(); //} //} }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormAsyncOperation_Information { interface tab_generaltab_Sections { custom: DevKit.Controls.Section; general: DevKit.Controls.Section; systemlinksection: DevKit.Controls.Section; } interface tab_generaltab extends DevKit.Controls.ITab { Section: tab_generaltab_Sections; } interface Tabs { generaltab: tab_generaltab; } interface Body { Tab: Tabs; /** Date and time when the system job was completed. */ CompletedOn: DevKit.Controls.DateTime; /** Date and time when the system job was created. */ CreatedOn: DevKit.Controls.DateTime; /** Message provided by the system job. */ FriendlyMessage: DevKit.Controls.String; /** Message related to the system job. */ Message: DevKit.Controls.String; /** Name of the system job. */ Name: DevKit.Controls.String; /** Type of the system job. */ OperationType: DevKit.Controls.OptionSet; /** Unique identifier of the user or team who owns the system job. */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the object with which the system job is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Number of times to retry the system job. */ RetryCount: DevKit.Controls.Integer; WebResource_systemjob: DevKit.Controls.WebResource; } } class FormAsyncOperation_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form AsyncOperation_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 AsyncOperation_Information */ Body: DevKit.FormAsyncOperation_Information.Body; } class AsyncOperationApi { /** * DynamicsCrm.DevKit AsyncOperationApi * @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 system job. */ AsyncOperationId: DevKit.WebApi.GuidValue; /** The breadcrumb record ID. */ BreadcrumbId: DevKit.WebApi.GuidValue; /** The origin of the caller. */ CallerOrigin: DevKit.WebApi.StringValue; /** Date and time when the system job was completed. */ CompletedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier used to correlate between multiple SDK requests and system jobs. */ CorrelationId: DevKit.WebApi.GuidValue; /** Last time the correlation depth was updated. */ CorrelationUpdatedTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the user who created the system job. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the system job was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the asyncoperation. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unstructured data associated with the system job. */ Data: DevKit.WebApi.StringValue; DataBlobId_Name: DevKit.WebApi.StringValueReadonly; /** Execution of all operations with the same dependency token is serialized. */ DependencyToken: DevKit.WebApi.StringValue; /** Number of SDK calls made since the first call. */ Depth: DevKit.WebApi.IntegerValue; /** Error code returned from a canceled system job. */ ErrorCode: DevKit.WebApi.IntegerValueReadonly; /** Time that the system job has taken to execute. */ ExecutionTimeSpan: DevKit.WebApi.DoubleValueReadonly; /** The datetime when the Expander pipeline started. */ ExpanderStartTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Message provided by the system job. */ FriendlyMessage: DevKit.WebApi.StringValue; /** Unique identifier of the host that owns this system job. */ HostId: DevKit.WebApi.StringValue; /** Indicates that the system job is waiting for an event. */ IsWaitingForEvent: DevKit.WebApi.BooleanValueReadonly; /** Message related to the system job. */ Message: DevKit.WebApi.StringValueReadonly; /** Name of the message that started this system job. */ MessageName: DevKit.WebApi.StringValue; /** Unique identifier of the user who last modified the system job. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the system job was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the asyncoperation. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the system job. */ Name: DevKit.WebApi.StringValue; /** Type of the system job. */ OperationType: DevKit.WebApi.OptionSetValue; /** 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 system job. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the owning extension with which the system job is associated. */ OwningExtensionId: DevKit.WebApi.LookupValue; /** Unique identifier of the team who owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; ParentPluginExecutionId: DevKit.WebApi.GuidValue; /** Indicates whether the system job should run only after the specified date and time. */ PostponeUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Pattern of the system job's recurrence. */ RecurrencePattern: DevKit.WebApi.StringValue; /** Starting time in UTC for the recurrence pattern. */ RecurrenceStartTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_account: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_activityfileattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_activitymimeattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_activitypointer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_annotation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_annualfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appelement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_applicationuser: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appmodulecomponentedge: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appmodulecomponentnode: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appnotification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appusersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_attributeimageconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_attributemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bot: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_botcomponent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_businessunit: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_businessunitnewsarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_calendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_catalog: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_catalogassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ channelaccessprofile_asyncoperations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ channelaccessprofileruleid: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connection: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connectionreference: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connectionrole: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connector: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_conversationtranscript: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_convertrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customapi: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customapirequestparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customapiresponseproperty: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customeraddress: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customerrelationship: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakefolder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakefolderpermission: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakeworkspace: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_devkit_bpfaccount: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_displaystring: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_email: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_emailserverprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entityanalyticsconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entityimageconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitymap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_environmentvariabledefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_environmentvariablevalue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_exportsolutionupload: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ externalparty_asyncoperations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ externalpartyitem_asyncoperations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_featurecontrolsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_fixedmonthlyfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_flowmachine: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_flowmachinegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_flowsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_goal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_goalrollupquery: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_holidaywrapper: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_import: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importlog: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importmap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_new_interactionforemail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_internalcatalogassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_isvconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_kbarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_kbarticlecomment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_kbarticletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_keyvaultreference: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_letter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_mailbox: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_mailmergetemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_managedidentity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_metric: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_monthlyfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdynce_botcontent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdataset: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aimodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aitemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataflow: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_helppage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_pmrecording: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_richtextfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_slakpi: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_tour: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organization: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organizationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_package: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_pdfsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_phonecall: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_pluginpackage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_position: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_post: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_postfollow: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_privilege: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_processstageparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_provisionlanguageforuser: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_quarterlyfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_queue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_queueitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_relationshipattribute: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_relationshiprole: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_relationshiprolemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_report: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_role: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_rollupfield: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_routingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_routingruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_savedquery: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_semiannualfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_serviceplan: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_serviceplanmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_settingdefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_sharepointdocumentlocation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_sharepointsite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_similarityrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_sla: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_socialactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_socialprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_solutioncomponentbatchconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_stagesolutionupload: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_subject: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_systemform: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_systemuser: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_team: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_template: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_territory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_theme: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_transactioncurrency: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_userform: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_usermapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_userquery: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_virtualentitymetadata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_workflowbinary: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Unique identifier of the request that generated the system job. */ RequestId: DevKit.WebApi.GuidValue; /** Retain job history. */ RetainJobHistory: DevKit.WebApi.BooleanValue; /** Number of times to retry the system job. */ RetryCount: DevKit.WebApi.IntegerValueReadonly; /** Root execution context of the job that trigerred async job. */ RootExecutionContext: DevKit.WebApi.StringValue; /** Order in which operations were submitted. */ Sequence: DevKit.WebApi.BigIntValueReadonly; /** Date and time when the system job was started. */ StartedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Status of the system job. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the system job. */ StatusCode: DevKit.WebApi.OptionSetValue; /** The Subtype of the Async Job */ Subtype: DevKit.WebApi.IntegerValueReadonly; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Unique identifier of the workflow activation related to the system job. */ WorkflowActivationId: DevKit.WebApi.LookupValue; /** Indicates whether the workflow instance was blocked when it was persisted. */ WorkflowIsBlocked: DevKit.WebApi.BooleanValueReadonly; /** Name of a workflow stage. */ WorkflowStageName: DevKit.WebApi.StringValueReadonly; /** State of the workflow job. */ WorkflowState: DevKit.WebApi.StringValueReadonly; /** The workload name. */ Workload: DevKit.WebApi.StringValue; } } declare namespace OptionSet { namespace AsyncOperation { enum OperationType { /** 6 */ Activity_Propagation, /** 190690092 */ AI_Builder_Prediction_Events, /** 190690091 */ AI_Builder_Training_Events, /** 73 */ ALM_Anomaly_Detection_Operation, /** 72 */ App_Module_Metadata_Operation, /** 41 */ Audit_Partition_Creation, /** 13 */ Bulk_Delete, /** 94 */ Bulk_Delete_File_Attachment, /** 23 */ Bulk_Delete_Subprocess, /** 8 */ Bulk_Duplicate_Detection, /** 2 */ Bulk_Email, /** 22 */ Calculate_Organization_Maximum_Storage_Size, /** 18 */ Calculate_Organization_Storage_Size, /** 57 */ Calculate_Rollup_Field, /** 79 */ CallbackRegistration_Expander_Operation, /** 100 */ Cascade_FlowSession_Permissions_Async_Operation, /** 12801 */ Cascade_Grant_or_Revoke_Access_Version_Tracking_Async_Operation, /** 90 */ CascadeAssign, /** 91 */ CascadeDelete, /** 42 */ Check_For_Language_Pack_Updates, /** 32 */ Cleanup_inactive_workflow_assemblies, /** 71 */ Cleanup_Solution_Components, /** 19 */ Collect_Organization_Database_Statistics, /** 16 */ Collect_Organization_Statistics, /** 20 */ Collection_Organization_Size_Statistics, /** 62 */ Convert_Date_And_Time_Behavior, /** 98 */ Create_Or_Refresh_Virtual_Entity, /** 26 */ Database_log_backup, /** 21 */ Database_Tuning, /** 28 */ DBCC_SHRINKDATABASE_maintenance_job, /** 29 */ DBCC_SHRINKFILE_maintenance_job, /** 14 */ Deletion_Service, /** 7 */ Duplicate_Detection_Rule_Publish, /** 53 */ Encryption_Health_Check, /** 63 */ EntityKey_Index_Creation, /** 92 */ Event_Expander_Operation, /** 54 */ Execute_Async_Request, /** 202 */ Export_Solution_Async_Operation, /** 75 */ Flow_Notification, /** 40 */ Goal_Roll_Up, /** 5 */ Import, /** 3 */ Import_File_Parse, /** 38 */ Import_Sample_Data, /** 203 */ Import_Solution_Async_Operation, /** 93 */ Import_Solution_Metadata, /** 17 */ Import_Subprocess, /** 59 */ Import_Translation, /** 51 */ Incoming_Email_Processing, /** 15 */ Index_Management, /** 52 */ Mailbox_Test_Access, /** 58 */ Mass_Calculate_Rollup_Field, /** 12 */ Matchcode_Update, /** 25 */ Organization_Full_Text_Catalog_Index, /** 50 */ Outgoing_Activity, /** 49 */ Post_to_Yammer, /** 201 */ Provision_language_for_user, /** 43 */ Provision_Language_Pack, /** 11 */ Quick_Campaign, /** 35 */ Recurring_Series_Expansion, /** 95 */ Refresh_Business_Unit_for_Records_Owned_By_Principal, /** 250 */ Refresh_Runtime_Integration_Components_Async_Operation, /** 46 */ Regenerate_Entity_Row_Count_Snapshot_Data, /** 47 */ Regenerate_Read_Share_Snapshot_Data, /** 30 */ Reindex_all_indices_maintenance_job, /** 69 */ Relationship_Assistant_Cards, /** 68 */ Resource_Booking_Sync, /** 96 */ Revoke_Inherited_Access, /** 76 */ Ribbon_Client_Metadata_Operation, /** 9 */ SQM_Data_Collection, /** 31 */ Storage_Limit_Notification, /** 1 */ System_Event, /** 4 */ Transform_Parse_Data, /** 27 */ Update_Contract_States, /** 56 */ Update_Entitlement_States, /** 65 */ Update_Knowledge_Article_States, /** 101 */ Update_Modern_Flow_Async_Operation, /** 44 */ Update_Organization_Database, /** 45 */ Update_Solution, /** 24 */ Update_Statistic_Intervals, /** 10 */ Workflow } enum StateCode { /** 3 */ Completed, /** 2 */ Locked, /** 0 */ Ready, /** 1 */ Suspended } enum StatusCode { /** 32 */ Canceled, /** 22 */ Canceling, /** 31 */ Failed, /** 20 */ In_Progress, /** 21 */ Pausing, /** 30 */ Succeeded, /** 10 */ Waiting, /** 0 */ Waiting_For_Resources } 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 { render, act } from '@testing-library/react'; import React, { ReactElement, useEffect } from 'react'; import { renderToString } from 'react-dom/server'; import LooselyLazy, { lazyForPaint, lazyAfterPaint, LazySuspense, useLazyPhase, MODE, } from '../src'; import { PHASE } from '../src/constants'; import { isNodeEnvironment } from '../src/utils'; import { createMockImport, nextTick } from './test-utils'; jest.mock('../src/utils', () => ({ ...jest.requireActual<any>('../src/utils'), isNodeEnvironment: jest.fn(), })); const createApp = ({ hydrate, lazyMethod = lazyForPaint, server, ssr, }: { hydrate: boolean; lazyMethod?: typeof lazyForPaint; server: boolean; ssr: boolean; }) => { (isNodeEnvironment as any).mockImplementation(() => server); const Child = jest.fn(() => <p className="p">Content</p>); const Fallback = jest.fn<any, void[]>(() => <i>Fallback</i>); const { mockImport, resolveImport } = createMockImport(Child, ssr && server); // @ts-ignore - We are mocking the import const AsyncComponent = lazyMethod(() => mockImport, { moduleId: './mock', ssr, }); LooselyLazy.init({ mode: hydrate ? MODE.HYDRATE : MODE.RENDER, manifest: { publicPath: '/', assets: { './mock': [''], }, }, }); const PhaseManager = ({ children, phase, }: { children: ReactElement; phase?: number; }) => { const { startNextPhase } = useLazyPhase(); useEffect(() => { if (phase === PHASE.AFTER_PAINT) startNextPhase(); }, [phase, startNextPhase]); return children; }; const App = ({ phase }: { phase?: number }) => ( <PhaseManager phase={phase}> <LazySuspense fallback={<Fallback />}> <AsyncComponent /> </LazySuspense> </PhaseManager> ); return { App, resolveImport, Fallback, Child }; }; describe('hydrates', () => { const hydrate = true; describe('a lazyForPaint component', () => { describe('when ssr is true', () => { const ssr = true; it('by rendering and persisting the server content, before replacing', async () => { const { App: ServerApp } = createApp({ hydrate, server: true, ssr, }); document.body.innerHTML = ` <div id="root">${renderToString(<ServerApp />)}</div> `; // expect ssr to render content expect(document.body).toContainHTML('<p class="p">Content</p>'); expect(document.body.querySelector('input')).toBeInTheDocument(); const { App: ClientApp, Child, resolveImport, } = createApp({ hydrate, server: false, ssr, }); const { container } = render(<ClientApp />, { container: document.getElementById('root') as HTMLElement, hydrate, }); // expect client to use placeholder and persist ssr content expect(Child).not.toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).toBeInTheDocument(); await act(resolveImport); // expect component to be live after being resolved expect(Child).toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).not.toBeInTheDocument(); }); }); describe('when ssr is false', () => { const ssr = false; it('by rendering the server fallback, before rendering the fallback and replacing', async () => { const { App: ServerApp } = createApp({ hydrate, server: true, ssr, }); document.body.innerHTML = ` <div id="root">${renderToString(<ServerApp />)}</div> `; // expect ssr to render fallback expect(document.body).toContainHTML('<i>Fallback</i>'); expect(document.body.querySelector('input')).toBeInTheDocument(); const { App: ClientApp, Child, Fallback, resolveImport, } = createApp({ hydrate, server: false, ssr, }); const { container } = render(<ClientApp />, { container: document.getElementById('root') as HTMLElement, hydrate, }); // expect client to use live fallback ASAP expect(Child).not.toHaveBeenCalled(); expect(Fallback).toHaveBeenCalled(); expect(container).toContainHTML('<i>Fallback</i>'); expect(container.querySelector('input')).not.toBeInTheDocument(); await act(resolveImport); // expect component to be live after being resolved expect(Child).toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).not.toBeInTheDocument(); }); }); }); describe('a lazyAfterPaint component', () => { const lazyMethod = lazyAfterPaint; describe('when ssr is true', () => { const ssr = true; it('by rendering and persisting the server content, before replacing', async () => { const { App: ServerApp } = createApp({ hydrate, lazyMethod, server: true, ssr, }); document.body.innerHTML = ` <div id="root">${renderToString(<ServerApp />)}</div> `; // expect ssr to render content expect(document.body).toContainHTML('<p class="p">Content</p>'); expect(document.body.querySelector('input')).toBeInTheDocument(); const { App: ClientApp, Child, resolveImport, } = createApp({ hydrate, lazyMethod, server: false, ssr, }); const { container, rerender } = render(<ClientApp />, { container: document.getElementById('root') as HTMLElement, hydrate, }); // simulate component being ready on next tick await act(resolveImport); // expect client to use placeholder and persist ssr content regardless expect(Child).not.toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).toBeInTheDocument(); rerender(<ClientApp phase={PHASE.AFTER_PAINT} />); await nextTick(); // expect component to be live after phase changed expect(Child).toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).not.toBeInTheDocument(); }); }); describe('when ssr is false', () => { const ssr = false; it('by rendering the server fallback, before rendering the fallback and replacing', async () => { const { App: ServerApp } = createApp({ hydrate, lazyMethod, server: true, ssr, }); document.body.innerHTML = ` <div id="root">${renderToString(<ServerApp />)}</div> `; // expect ssr to render fallback expect(document.body).toContainHTML('<i>Fallback</i>'); expect(document.body.querySelector('input')).toBeInTheDocument(); const { App: ClientApp, Child, Fallback, resolveImport, } = createApp({ hydrate, lazyMethod, server: false, ssr, }); const { container, rerender } = render(<ClientApp />, { container: document.getElementById('root') as HTMLElement, hydrate, }); // simulate component being ready on next tick await act(resolveImport); // expect client to use live fallback ASAP expect(Child).not.toHaveBeenCalled(); expect(Fallback).toHaveBeenCalled(); expect(container).toContainHTML('<i>Fallback</i>'); expect(container.querySelector('input')).not.toBeInTheDocument(); rerender(<ClientApp phase={PHASE.AFTER_PAINT} />); await nextTick(); // expect component to be live after phase changed expect(Child).toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).not.toBeInTheDocument(); }); }); }); }); describe('renders', () => { const hydrate = false; describe('a lazyForPaint component', () => { describe('when ssr is true', () => { const ssr = true; it('by rendering and persisting the server content, before replacing', async () => { const { App: ServerApp } = createApp({ hydrate, server: true, ssr, }); document.body.innerHTML = ` <div id="root">${renderToString(<ServerApp />)}</div> `; // expect ssr to render content expect(document.body).toContainHTML('<p class="p">Content</p>'); expect(document.body.querySelector('input')).toBeInTheDocument(); const { App: ClientApp, Child, resolveImport, } = createApp({ hydrate, server: false, ssr, }); const { container } = render(<ClientApp />, { container: document.getElementById('root') as HTMLElement, hydrate, }); // expect client to use placeholder and persist ssr content expect(Child).not.toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).toBeInTheDocument(); await act(resolveImport); // expect component to be live after being resolved expect(Child).toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).not.toBeInTheDocument(); }); }); describe('when ssr is false', () => { const ssr = false; it('by rendering the server fallback, before rendering the fallback and replacing', async () => { const { App: ServerApp } = createApp({ hydrate, server: true, ssr, }); document.body.innerHTML = ` <div id="root">${renderToString(<ServerApp />)}</div> `; // expect ssr to render fallback expect(document.body).toContainHTML('<i>Fallback</i>'); expect(document.body.querySelector('input')).toBeInTheDocument(); const { App: ClientApp, Child, Fallback, resolveImport, } = createApp({ hydrate, server: false, ssr, }); const { container } = render(<ClientApp />, { container: document.getElementById('root') as HTMLElement, hydrate, }); // expect client to use live fallback ASAP expect(Child).not.toHaveBeenCalled(); expect(Fallback).toHaveBeenCalled(); expect(container).toContainHTML('<i>Fallback</i>'); expect(container.querySelector('input')).not.toBeInTheDocument(); await act(resolveImport); // expect component to be live after being resolved expect(Child).toHaveBeenCalled(); expect(container).toContainHTML('<p class="p">Content</p>'); expect(container.querySelector('input')).not.toBeInTheDocument(); }); }); }); });
the_stack
import Vue from 'vue'; import Vuex from 'vuex'; import chai, { expect } from 'chai'; import spies from 'chai-spies'; import createMultiTabState from '../src/index'; chai.use(spies); Vue.use(Vuex); // Do not show tips Vue.config.productionTip = false; describe('vuex-multi-tab-state basic tests', () => { const warnSpy = chai.spy.on(console, 'warn'); afterEach(() => { if (window.localStorage !== null) { window.localStorage.clear(); } }); it('should fetch state from local storage', () => { const testState = { id: 'randomIdHere', state: { random: 6 } }; window.localStorage.setItem('vuex-multi-tab', JSON.stringify(testState)); const store = new Vuex.Store({ state: { random: 0 } }); const plugin = createMultiTabState(); const spy = chai.spy.on(store, 'replaceState'); plugin(store); expect(spy).to.have.been.called.with(testState.state); }); it('should fetch filtered nested modules state from local storage without no-state-mutation errors', () => { const testState = { id: 'randomIdHere', state: { random: 1, modA: { rainbow: [1, 2, 3], some: { value1: 3, value2: 4, }, }, }, }; window.localStorage.setItem('vuex-multi-tab', JSON.stringify(testState)); const store = new Vuex.Store({ strict: true, state: { random: 0 }, modules: { modA: { //namespaced: true, state: { rainbow: [], some: { value1: 0, value2: 0, }, }, }, }, }); const plugin = createMultiTabState({ statesPaths: ['random', 'modA.rainbow', 'modA.some.value1'], }); plugin(store); expect(store.state).to.be.eql({ random: 1, modA: { rainbow: [1, 2, 3], some: { value1: 3, value2: 0, // not set during read-from-storage }, }, }); }); it('should save only the specified states in local storage', () => { const store = new Vuex.Store({ state: { bar: { random: 0, rainbow: 0 }, foo: 0 }, mutations: { incrementBarRandom(state) { state.bar.random += 1; }, incrementFoo(state) { state.foo += 1; }, }, plugins: [createMultiTabState({ statesPaths: ['bar.random', 'foo'] })], }); store.commit('incrementBarRandom'); store.commit('incrementFoo'); const stateInLs: string | null = window.localStorage.getItem( 'vuex-multi-tab' ); if (typeof stateInLs === 'string') { const parsedStateInLs = JSON.parse(stateInLs); expect(parsedStateInLs.state.bar.random).to.be.eq(1); expect(parsedStateInLs.state.foo).to.be.eq(1); expect(parsedStateInLs.state.bar.rainbow).to.be.undefined; } }); it('should properly merge specified states from same parent when saving to local storage', () => { const store = new Vuex.Store({ state: { bar: { random: 0, rainbow: 0 } }, mutations: { incrementBarRandom(state) { state.bar.random += 1; }, }, plugins: [ createMultiTabState({ statesPaths: ['bar.random', 'bar.rainbow'] }), ], }); store.commit('incrementBarRandom'); const stateInLs: string | null = window.localStorage.getItem( 'vuex-multi-tab' ); if (typeof stateInLs === 'string') { const parsedStateInLs = JSON.parse(stateInLs); expect(parsedStateInLs.state.bar.random).to.be.eq(1); expect(parsedStateInLs.state.bar.rainbow).to.be.eq(0); } }); it('should merge arrays correctly', () => { const store = new Vuex.Store({ state: { random: ['bar', 'foo'] }, }); const plugin = createMultiTabState(); window.localStorage.setItem( 'vuex-multi-tab', JSON.stringify({ id: 'randomIdHere', state: { random: ['bar'], }, }) ); plugin(store); expect(store.state.random).to.be.eql(['bar']); }); it('should merge objects correctly', () => { const store = new Vuex.Store({ state: { random: { bar1: 'foo1', bar2: 'foo1' } }, }); const plugin = createMultiTabState(); window.localStorage.setItem( 'vuex-multi-tab', JSON.stringify({ id: 'randomIdHere', state: { random: { bar2: 'foo2' }, }, }) ); plugin(store); expect(store.state.random).to.be.eql({ bar2: 'foo2' }); }); it('should merge objects only from specified paths', () => { const store = new Vuex.Store({ state: { random: { bar1: 'foo1', bar2: 'foo1', bar3: 'foo1' } }, }); const plugin = createMultiTabState({ statesPaths: ['random.bar2', 'random.bar3'], }); window.localStorage.setItem( 'vuex-multi-tab', JSON.stringify({ id: 'randomIdHere', state: { random: { bar2: 'foo2' }, }, }) ); plugin(store); expect(store.state.random).to.be.eql({ bar1: 'foo1', bar2: 'foo2' }); }); it('should properly merge falsy values', () => { const store = new Vuex.Store({ state: { random: { bar1: 0, bar2: true }, }, }); const plugin = createMultiTabState({ statesPaths: ['random.bar1', 'random.bar2'], }); window.localStorage.setItem( 'vuex-multi-tab', JSON.stringify({ id: 'randomIdHere', state: { random: { bar1: 0, bar2: false }, }, }) ); plugin(store); expect(store.state.random).to.be.eql({ bar1: 0, bar2: false }); }); it('should warn the user if the state in local storage is invalid', () => { window.localStorage.setItem('vuex-multi-tab', '<unparseable to json>'); // eslint-disable-next-line no-unused-vars const store = new Vuex.Store({ state: { random: 0 }, plugins: [createMultiTabState()], }); expect(warnSpy).to.have.been.called; }); it('should work with onBeforeSave option set', () => { const store = new Vuex.Store({ strict: true, state: { counter: 1, }, mutations: { count(state) { state.counter += 1; }, }, plugins: [ createMultiTabState({ onBeforeSave(state) { if (state.counter > 2) return; return { ...state, __time: Date.now(), }; }, }), ], }); store.commit('count'); store.commit('count'); store.commit('count'); const stateInLs: string | null = window.localStorage.getItem('vuex-multi-tab'); expect(typeof stateInLs).to.be.eq('string'); if (typeof stateInLs === 'string') { const parsedStateInLs = JSON.parse(stateInLs); expect(parsedStateInLs.state.__time).to.be.lte(Date.now()); expect(parsedStateInLs.state.counter).to.be.eq(2); } }); it('should work with onBeforeReplace option set', () => { const testState = { id: 'randomIdHere', state: { random: 6 } }; window.localStorage.setItem('vuex-multi-tab', JSON.stringify(testState)); const store = new Vuex.Store({ strict: true, state: { random: 0 }, }); const plugin = createMultiTabState({ onBeforeReplace(state) { return { random: 12 }; }, }); const spy = chai.spy.on(store, 'replaceState'); plugin(store); expect(spy).to.have.been.called.with({ random: 12 }); expect(store.state.random).to.be.eq(12); }); it('should work with onBeforeReplace option returning falsy value', () => { const testState = { id: 'randomIdHere', state: { random: 6 } }; window.localStorage.setItem('vuex-multi-tab', JSON.stringify(testState)); const store = new Vuex.Store({ strict: true, state: { random: 0 }, }); const plugin = createMultiTabState({ onBeforeReplace(state) { return; }, }); const spy = chai.spy.on(store, 'replaceState'); plugin(store); expect(spy).to.not.have.been.called; expect(store.state.random).to.be.eq(0); }); it('should not fetch state from local storage if event newValue property is undefined', () => { const testState = { id: 'randomIdHere', state: { random: 6 } }; window.localStorage.setItem('vuex-multi-tab', JSON.stringify(testState)); const store = new Vuex.Store({ state: { random: 0 }, plugins: [createMultiTabState()], }); const spy = chai.spy.on(store, 'replaceState'); const event = new CustomEvent('storage'); window.dispatchEvent(event); expect(spy).to.not.have.been.called.twice; }); it('should save state in local storage when new state is set', () => { const store = new Vuex.Store({ state: { random: 0 }, mutations: { increment(state) { state.random += 1; }, }, plugins: [createMultiTabState()], }); store.commit('increment'); const stateInLs: string | null = window.localStorage.getItem( 'vuex-multi-tab' ); if (typeof stateInLs === 'string') { const parsedStateInLs = JSON.parse(stateInLs); expect(parsedStateInLs.state.random).to.be.eq(1); } }); it('should fetch state when it has been changed', () => { Object.defineProperty(window, 'addEventListener', { value: (type: string, fn: Function) => { fn({ key: 'vuex-multi-tab', newValue: JSON.stringify({ id: 'randomIdHere', state: { random: 8, }, }), }); }, }); const testState = { id: 'randomIdHere', state: { random: 6 } }; window.localStorage.setItem('vuex-multi-tab', JSON.stringify(testState)); const store = new Vuex.Store({ state: { random: 0 }, plugins: [createMultiTabState()], }); expect(store.state.random).to.be.eq(8); }); it('should warn the user if the new state in local storage is invalid', () => { Object.defineProperty(window, 'addEventListener', { value: (type: string, fn: Function) => { fn({ key: 'vuex-multi-tab', newValue: '<unparseable to json>', }); }, }); // eslint-disable-next-line no-unused-vars const store = new Vuex.Store({ state: { random: 0 }, plugins: [createMultiTabState()], }); expect(warnSpy).to.have.been.called; }); it('should accept custom local storage key', () => { const store = new Vuex.Store({ state: { bar: 'foo1' }, }); const plugin = createMultiTabState({ key: 'custom-key' }); window.localStorage.setItem( 'custom-key', JSON.stringify({ id: 'randomIdHere', state: { bar: 'foo2' }, }) ); plugin(store); expect(store.state.bar).to.be.eql('foo2'); }); it('should throw if local storage is not available', () => { Object.defineProperty(window, 'localStorage', { value: null, }); expect(() => createMultiTabState()).to.throw(); }); });
the_stack
export interface TableServiceError { /** * The error message. */ message?: string; } /** * The retention policy. */ export interface RetentionPolicy { /** * Indicates whether a retention policy is enabled for the service. */ enabled: boolean; /** * Indicates the number of days that metrics or logging or soft-deleted data should be retained. * All data older than this value will be deleted. */ days?: number; } /** * Azure Analytics Logging settings. */ export interface Logging { /** * The version of Analytics to configure. */ version: string; /** * Indicates whether all delete requests should be logged. */ deleteProperty: boolean; /** * Indicates whether all read requests should be logged. */ read: boolean; /** * Indicates whether all write requests should be logged. */ write: boolean; retentionPolicy: RetentionPolicy; } /** * An interface representing Metrics. */ export interface Metrics { /** * The version of Analytics to configure. */ version?: string; /** * Indicates whether metrics are enabled for the Table service. */ enabled: boolean; /** * Indicates whether metrics should generate summary statistics for called API operations. */ includeAPIs?: boolean; retentionPolicy?: RetentionPolicy; } /** * CORS is an HTTP feature that enables a web application running under one domain to access * resources in another domain. Web browsers implement a security restriction known as same-origin * policy that prevents a web page from calling APIs in a different domain; CORS provides a secure * way to allow one domain (the origin domain) to call APIs in another domain. */ export interface CorsRule { /** * The origin domains that are permitted to make a request against the service via CORS. The * origin domain is the domain from which the request originates. Note that the origin must be an * exact case-sensitive match with the origin that the user age sends to the service. You can * also use the wildcard character '*' to allow all origin domains to make requests via CORS. */ allowedOrigins: string; /** * The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma * separated) */ allowedMethods: string; /** * The request headers that the origin domain may specify on the CORS request. */ allowedHeaders: string; /** * The response headers that may be sent in the response to the CORS request and exposed by the * browser to the request issuer. */ exposedHeaders: string; /** * The maximum amount time that a browser should cache the preflight OPTIONS request. */ maxAgeInSeconds: number; } /** * Table Service Properties. */ export interface TableServiceProperties { /** * Azure Analytics Logging settings. */ logging?: Logging; /** * A summary of request statistics grouped by API in hourly aggregates for tables. */ hourMetrics?: Metrics; /** * A summary of request statistics grouped by API in minute aggregates for tables. */ minuteMetrics?: Metrics; /** * The set of CORS rules. */ cors?: CorsRule[]; } /** * An interface representing GeoReplication. */ export interface GeoReplication { /** * The status of the secondary location. Possible values include: 'live', 'bootstrap', * 'unavailable' */ status: GeoReplicationStatusType; /** * A GMT date/time value, to the second. All primary writes preceding this value are guaranteed * to be available for read operations at the secondary. Primary writes after this point in time * may or may not be available for reads. */ lastSyncTime: Date; } /** * Stats for the service. */ export interface TableServiceStats { /** * Geo-Replication information for the Secondary Storage Service. */ geoReplication?: GeoReplication; } /** * The properties for creating a table. */ export interface TableProperties { /** * The name of the table to create. */ tableName?: string; } /** * The response for a single table. */ export interface TableResponse { /** * The metadata response of the table. */ odatametadata?: string; /** * The name of the table. */ tableName?: string; /** * The odata type of the table. */ odatatype?: string; /** * The id of the table. */ odataid?: string; /** * The edit link of the table. */ odataeditLink?: string; } /** * The properties for the table response. */ export interface TableResponseProperties { /** * The name of the table. */ tableName?: string; /** * The odata type of the table. */ odatatype?: string; /** * The id of the table. */ odataid?: string; /** * The edit link of the table. */ odataeditLink?: string; } /** * The properties for the table query response. */ export interface TableQueryResponse { /** * The metadata response of the table. */ odatametadata?: string; /** * List of tables. */ value?: TableResponseProperties[]; } /** * An Access policy. */ export interface AccessPolicy { /** * The start datetime from which the policy is active. * **NOTE: This entity will be treated as a string instead of a Date because the API can * potentially deal with a higher precision value than what is supported by JavaScript.** */ start: string; /** * The datetime that the policy expires. * **NOTE: This entity will be treated as a string instead of a Date because the API can * potentially deal with a higher precision value than what is supported by JavaScript.** */ expiry: string; /** * The permissions for the acl policy. */ permission: string; } /** * A signed identifier. */ export interface SignedIdentifier { /** * A unique id. */ id: string; /** * The access policy. */ accessPolicy: AccessPolicy; } /** * The properties for the table entity query response. */ export interface TableEntityQueryResponse { /** * The metadata response of the table. */ odatametadata?: string; /** * List of table entities. */ value?: { [propertyName: string]: any }[]; } /** * Additional parameters for a set of operations. */ export interface QueryOptions { /** * Specifies the media type for the response. Possible values include: * 'application/json;odata=nometadata', 'application/json;odata=minimalmetadata', * 'application/json;odata=fullmetadata' */ format?: OdataMetadataFormat; /** * Maximum number of records to return. */ top?: number; /** * Select expression using OData notation. Limits the columns on each record to just those * requested, e.g. "$select=PolicyAssignmentId, ResourceId". */ select?: string; /** * OData filter expression. */ filter?: string; } /** * An interface representing AzuriteServerTableOptions. */ export interface AzuriteServerTableOptions { /** * Specifies the version of the operation to use for this request. Possible values include: * '2019-02-02' */ version?: Version; } /** * Optional Parameters. */ export interface TableQueryOptionalParams { /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion; /** * A table query continuation token from a previous call. */ nextTableName?: string; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableCreateOptionalParams { /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion1; /** * Specifies whether the response should include the inserted entity in the payload. Possible * values are return-no-content and return-content. Possible values include: 'return-no-content', * 'return-content' */ responsePreference?: ResponseFormat; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableBatchOptionalParams { /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion2; } /** * Optional Parameters. */ export interface TableDeleteMethodOptionalParams { /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; } /** * Optional Parameters. */ export interface TableQueryEntitiesOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion3; /** * An entity query continuation token from a previous call. */ nextPartitionKey?: string; /** * An entity query continuation token from a previous call. */ nextRowKey?: string; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableQueryEntitiesWithPartitionAndRowKeyOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion4; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableUpdateEntityOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion5; /** * The properties for the table entity. */ tableEntityProperties?: { [propertyName: string]: any }; /** * Match condition for an entity to be updated. If specified and a matching entity is not found, * an error will be raised. To force an unconditional update, set to the wildcard character (*). * If not specified, an insert will be performed when no existing entity is found to update and a * replace will be performed if an existing entity is found. */ ifMatch?: string; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableMergeEntityOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion6; /** * The properties for the table entity. */ tableEntityProperties?: { [propertyName: string]: any }; /** * Match condition for an entity to be updated. If specified and a matching entity is not found, * an error will be raised. To force an unconditional update, set to the wildcard character (*). * If not specified, an insert will be performed when no existing entity is found to update and a * merge will be performed if an existing entity is found. */ ifMatch?: string; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableDeleteEntityOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion7; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableMergeEntityWithMergeOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion8; /** * The properties for the table entity. */ tableEntityProperties?: { [propertyName: string]: any }; /** * Match condition for an entity to be updated. If specified and a matching entity is not found, * an error will be raised. To force an unconditional update, set to the wildcard character (*). * If not specified, an insert will be performed when no existing entity is found to update and a * merge will be performed if an existing entity is found. */ ifMatch?: string; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableInsertEntityOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; /** * Specifies the data service version. Possible values include: '3.0' */ dataServiceVersion?: DataServiceVersion9; /** * The properties for the table entity. */ tableEntityProperties?: { [propertyName: string]: any }; /** * Specifies whether the response should include the inserted entity in the payload. Possible * values are return-no-content and return-content. Possible values include: 'return-no-content', * 'return-content' */ responsePreference?: ResponseFormat; /** * Additional parameters for the operation */ queryOptions?: QueryOptions; } /** * Optional Parameters. */ export interface TableGetAccessPolicyOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; } /** * Optional Parameters. */ export interface TableSetAccessPolicyOptionalParams { /** * The acls for the table. */ tableAcl?: SignedIdentifier[]; /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; } /** * Optional Parameters. */ export interface ServiceSetPropertiesOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; } /** * Optional Parameters. */ export interface ServiceGetPropertiesOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; } /** * Optional Parameters. */ export interface ServiceGetStatisticsOptionalParams { /** * The timeout parameter is expressed in seconds. */ timeout?: number; /** * Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the * analytics logs when analytics logging is enabled. */ requestId?: string; } /** * Defines headers for Query operation. */ export interface TableQueryHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * This header contains the continuation token value. */ xMsContinuationNextTableName?: string; } /** * Defines headers for Create operation. */ export interface TableCreateHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * Indicates whether the Prefer request header was honored. If the response does not include this * header, then the Prefer header was not honored. If this header is returned, its value will * either be return-content or return-no-content. */ preferenceApplied?: string; errorCode?: string; } /** * Defines headers for Batch operation. */ export interface TableBatchHeaders { /** * The media type of the body of the response. For batch requests, this is multipart/mixed; * boundary=batchresponse_GUID */ contentType?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Blob service used to execute the request. This header is returned * for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; errorCode?: string; } /** * Defines headers for Delete operation. */ export interface TableDeleteHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; errorCode?: string; } /** * Defines headers for QueryEntities operation. */ export interface TableQueryEntitiesHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * This header contains the continuation token value for partition key. */ xMsContinuationNextPartitionKey?: string; /** * This header contains the continuation token value for row key. */ xMsContinuationNextRowKey?: string; errorCode?: string; } /** * Defines headers for QueryEntitiesWithPartitionAndRowKey operation. */ export interface TableQueryEntitiesWithPartitionAndRowKeyHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated */ eTag?: string; /** * This header contains the continuation token value for partition key. */ xMsContinuationNextPartitionKey?: string; /** * This header contains the continuation token value for row key. */ xMsContinuationNextRowKey?: string; errorCode?: string; } /** * Defines headers for UpdateEntity operation. */ export interface TableUpdateEntityHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * UTC date/time value generated by the service that indicates the time at which the entity was * last updated. */ eTag?: string; errorCode?: string; } /** * Defines headers for MergeEntity operation. */ export interface TableMergeEntityHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * UTC date/time value generated by the service that indicates the time at which the entity was * last updated. */ eTag?: string; errorCode?: string; } /** * Defines headers for DeleteEntity operation. */ export interface TableDeleteEntityHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; errorCode?: string; } /** * Defines headers for MergeEntityWithMerge operation. */ export interface TableMergeEntityWithMergeHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * UTC date/time value generated by the service that indicates the time at which the entity was * last updated. */ eTag?: string; errorCode?: string; } /** * Defines headers for InsertEntity operation. */ export interface TableInsertEntityHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; /** * UTC date/time value generated by the service that indicates the time at which the entity was * last updated. */ eTag?: string; /** * Indicates whether the Prefer request header was honored. If the response does not include this * header, then the Prefer header was not honored. If this header is returned, its value will * either be return-content or return-no-content. */ preferenceApplied?: string; /** * Indicates the content type of the payload. The value depends on the value specified for the * Accept request header. */ contentType?: string; errorCode?: string; } /** * Defines headers for GetAccessPolicy operation. */ export interface TableGetAccessPolicyHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; errorCode?: string; } /** * Defines headers for SetAccessPolicy operation. */ export interface TableSetAccessPolicyHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; errorCode?: string; } /** * Defines headers for SetProperties operation. */ export interface ServiceSetPropertiesHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; errorCode?: string; } /** * Defines headers for GetProperties operation. */ export interface ServiceGetPropertiesHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; errorCode?: string; } /** * Defines headers for GetStatistics operation. */ export interface ServiceGetStatisticsHeaders { /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. */ clientRequestId?: string; /** * This header uniquely identifies the request that was made and can be used for troubleshooting * the request. */ requestId?: string; /** * Indicates the version of the Table service used to execute the request. This header is * returned for requests made against version 2009-09-19 and above. */ version?: string; /** * UTC date/time value generated by the service that indicates the time at which the response was * initiated. */ date?: Date; errorCode?: string; } /** * Defines values for GeoReplicationStatusType. * Possible values include: 'live', 'bootstrap', 'unavailable' * @readonly * @enum {string} */ export enum GeoReplicationStatusType { Live = "live", Bootstrap = "bootstrap", Unavailable = "unavailable" } /** * Defines values for OdataMetadataFormat. * Possible values include: 'application/json;odata=nometadata', * 'application/json;odata=minimalmetadata', 'application/json;odata=fullmetadata' * @readonly * @enum {string} */ export enum OdataMetadataFormat { Applicationjsonodatanometadata = "application/json;odata=nometadata", Applicationjsonodataminimalmetadata = "application/json;odata=minimalmetadata", Applicationjsonodatafullmetadata = "application/json;odata=fullmetadata" } /** * Defines values for ResponseFormat. * Possible values include: 'return-no-content', 'return-content' * @readonly * @enum {string} */ export enum ResponseFormat { ReturnNoContent = "return-no-content", ReturnContent = "return-content" } /** * Defines values for Version. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for DataServiceVersion. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion1. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion1 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion2. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion2 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion3. * Possible values include: '3.0' * Changing all table batch related logic to point to this version * becuase the other versions seem redundant and are complicating the code * unnecessarily * @readonly * @enum {string} */ export enum DataServiceVersion3 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion4. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion4 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion5. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion5 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion6. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion6 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion7. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion7 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion8. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion8 { ThreeFullStopZero = "3.0" } /** * Defines values for DataServiceVersion9. * Possible values include: '3.0' * @readonly * @enum {string} */ export enum DataServiceVersion9 { ThreeFullStopZero = "3.0" } /** * Defines values for Version1. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version1 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version2. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version2 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version3. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version3 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version4. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version4 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version5. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version5 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version6. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version6 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version7. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version7 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version8. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version8 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version9. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version9 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version10. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version10 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version11. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version11 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version12. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version12 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version13. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version13 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version14. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version14 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version15. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version15 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Defines values for Version16. * Possible values include: '2019-02-02' * @readonly * @enum {string} */ export enum Version16 { TwoZeroOneNineHyphenMinusZeroTwoHyphenMinusZeroTwo = "2019-02-02" } /** * Contains response data for the query operation. */ export type TableQueryResponse2 = TableQueryResponse & TableQueryHeaders & { /** * The response status code. */ statusCode: 200; }; /** * Contains response data for the create operation. */ export type TableCreateResponse = TableResponse & TableCreateHeaders & { /** * The response status code. */ statusCode: 201 | 204; }; /** * Contains response data for the batch operation. */ export type TableBatchResponse = TableBatchHeaders & { /** * The response body as a node.js Readable stream. */ body?: NodeJS.ReadableStream; } & { /** * The response status code. */ statusCode: 202; }; /** * Contains response data for the deleteMethod operation. */ export type TableDeleteResponse = TableDeleteHeaders & { /** * The response status code. */ statusCode: 204; }; /** * Contains response data for the queryEntities operation. */ export type TableQueryEntitiesResponse = TableQueryEntitiesHeaders & { /** * The response body as a node.js Readable stream. */ body?: NodeJS.ReadableStream; } & { /** * The response status code. */ statusCode: 200; }; /** * Contains response data for the queryEntitiesWithPartitionAndRowKey operation. */ export type TableQueryEntitiesWithPartitionAndRowKeyResponse = TableQueryEntitiesWithPartitionAndRowKeyHeaders & { /** * The response body as a node.js Readable stream. */ body?: NodeJS.ReadableStream; } & { /** * The response status code. */ statusCode: 200; }; /** * Contains response data for the updateEntity operation. */ export type TableUpdateEntityResponse = TableUpdateEntityHeaders & { /** * The response status code. */ statusCode: 204; }; /** * Contains response data for the mergeEntity operation. */ export type TableMergeEntityResponse = TableMergeEntityHeaders & { /** * The response status code. */ statusCode: 204; }; /** * Contains response data for the deleteEntity operation. */ export type TableDeleteEntityResponse = TableDeleteEntityHeaders & { /** * The response status code. */ statusCode: 204; }; /** * Contains response data for the mergeEntityWithMerge operation. */ export type TableMergeEntityWithMergeResponse = TableMergeEntityWithMergeHeaders & { /** * The response status code. */ statusCode: 204; }; /** * Contains response data for the insertEntity operation. */ export type TableInsertEntityResponse = TableInsertEntityHeaders & { /** * The response body as a node.js Readable stream. */ body?: NodeJS.ReadableStream; } & { /** * The response status code. */ statusCode: 201 | 204; }; /** * Contains response data for the getAccessPolicy operation. */ export type TableGetAccessPolicyResponse = Array<SignedIdentifier> & TableGetAccessPolicyHeaders & { /** * The response status code. */ statusCode: 200; }; /** * Contains response data for the setAccessPolicy operation. */ export type TableSetAccessPolicyResponse = TableSetAccessPolicyHeaders & { /** * The response status code. */ statusCode: 204; }; /** * Contains response data for the setProperties operation. */ export type ServiceSetPropertiesResponse = ServiceSetPropertiesHeaders & { /** * The response status code. */ statusCode: 202; }; /** * Contains response data for the getProperties operation. */ export type ServiceGetPropertiesResponse = TableServiceProperties & ServiceGetPropertiesHeaders & { /** * The response status code. */ statusCode: 200; }; /** * Contains response data for the getStatistics operation. */ export type ServiceGetStatisticsResponse = TableServiceStats & ServiceGetStatisticsHeaders & { /** * The response status code. */ statusCode: 200; };
the_stack
import { Observable } from 'rxjs'; import { Writer, Reader } from 'protobufjs/minimal'; export interface TenantSubscription { /** * @inject_tag: bson:"_id,omitempty" */ id: string; /** * @inject_tag: bson:"tenantId,omitempty" */ tenantId: string; /** * @inject_tag: bson:"status,omitempty" */ status: string; /** * @inject_tag: bson:"createdAt,omitempty" */ createdAt: string; /** * @inject_tag: bson:"updatedAt,omitempty" */ updatedAt: string; /** * @inject_tag: bson:"collectionMethod,omitempty" */ collectionMethod: string; currentPeriodStart: string; currentPeriodEnd: string; endedAt: string; canceledAt: string; latestInvoiceId: string; startDate: string; trialStart: string; trialEnd: string; customerEmail: string; customerName: string; } export interface Customer { /** * @inject_tag: bson:"_id,omitempty" */ id: string; /** * @inject_tag: bson:"email,omitempty" */ email: string; /** * @inject_tag: bson:"name,omitempty" */ name: string; } export interface Address { id: string; country: string; state: string; city: string; postalCode: string; line: string; line2: string; } export interface Card { id: string; name: string; cvc: string; number: string; brand: string; currency: string; address: Address | undefined; expMonth: number; expYear: number; lastFourDigit: string; isDefault: boolean; } export interface Price { /** * @inject_tag: bson:"name,omitempty" */ name: string; /** * @inject_tag: bson:"currency,omitempty" */ currency: string; /** * @inject_tag: bson:"id,omitempty" */ id: string; /** * @inject_tag: bson:"trialDays,omitempty" */ trialDays: number; /** * @inject_tag: bson:"amount,omitempty" */ amount: number; } export interface StripePlan { /** * @inject_tag: bson:"name,omitempty" */ name: string; /** * @inject_tag: bson:"currency,omitempty" */ currency: string; /** * @inject_tag: bson:"id,omitempty" */ id: string; /** * @inject_tag: bson:"trialDays,omitempty" */ trialDays: number; /** * @inject_tag: bson:"amount,omitempty" */ amount: number; } export interface Feature { /** * @inject_tag: bson:"name,omitempty" */ name: string; /** * @inject_tag: bson:"normalizedName,omitempty" */ normalizedName: string; /** * @inject_tag: bson:"description,omitempty" */ description: string; /** * @inject_tag: bson:"min,omitempty" */ min: number; /** * @inject_tag: bson:"max,omitempty" */ max: number; /** * @inject_tag: bson:"active,omitempty" */ active: boolean; /** * @inject_tag: bson:"full,omitempty" */ full: boolean; /** * @inject_tag: bson:"full,omitempty" */ unit: string; } export interface Plan { /** * @inject_tag: bson:"_id,omitempty" */ id: string; /** * @inject_tag: bson:"normalizedName,omitempty" */ normalizedName: string; /** * @inject_tag: bson:"prices,omitempty" */ price: Price | undefined; /** * @inject_tag: bson:"features,omitempty" */ features: Feature[]; /** * @inject_tag: bson:"active,omitempty" */ active: boolean; /** * @inject_tag: bson:"free,omitempty" */ free: boolean; /** * @inject_tag: bson:"createdAt,omitempty" */ createdAt: string; /** * @inject_tag: bson:"updatedAt,omitempty" */ updatedAt: string; /** * @inject_tag: bson:"name,omitempty" */ name: string; /** * @inject_tag: bson:"stripeId,omitempty" */ stripeId: string; } export interface Invoice { /** * @inject_tag: bson:"id,omitempty" */ id: string; accountCountry: string; accountName: string; amountDue: number; amountPaid: number; amountRemaining: number; billingReason: string; currency: string; customerEmail: string; customerName: string; description: string; dueDate: string; endingBalance: number; hostedInvoiceUrl: string; invoicePdf: string; number: string; paid: boolean; receiptNumber: string; startingBalance: number; statementDescriptor: string; status: string; subtotal: number; tax: number; taxPercent: number; total: number; /** * @inject_tag: bson:"createdAt,omitempty" */ createdAt: string; /** * @inject_tag: bson:"updatedAt,omitempty" */ updatedAt: string; } export interface CreatePriceRequest { price: number; currency: string; id: string; nickname: string; trialDays: number; intervalCount: number; interval: string; } export interface CreatePlanRequest { name: string; description: string; prices: CreatePriceRequest[]; features: Feature[]; active: boolean; free: boolean; } export interface CreatePlanResponse { plan: Plan | undefined; } export interface ReadPlanRequest { id: string; } export interface ReadPlanResponse { plan: Plan | undefined; } export interface FindPlansRequest {} export interface FindPlansResponse { plans: Plan[]; } export interface ReadStripePlanRequest { id: string; } export interface ReadStripePlanResponse { plan: StripePlan | undefined; } export interface FindStripePlansRequest { productId: string; } export interface FindStripePlansResponse { plans: StripePlan[]; } export interface ReadInvoiceRequest { id: string; } export interface ReadInvoiceResponse { invoice: Invoice | undefined; } export interface FindInvoicesRequest {} export interface FindInvoicesResponse { invoices: Invoice[]; } /** * Subscription */ export interface CreateSubscriptionRequest { customerId: string; tenantId: string; planId: string; couponId: string; cardId: string; } export interface CreateSubscriptionResponse { subscription: TenantSubscription | undefined; } export interface ChangeSubscriptionRequest { customerId: string; tenantId: string; planId: string; couponId: string; } export interface ChangeSubscriptionResponse { subscription: TenantSubscription | undefined; } export interface CancelSubscriptionRequest { customerId: string; tenantId: string; } export interface CancelSubscriptionResponse { subscription: TenantSubscription | undefined; } export interface ReadSubscriptionRequest { id: string; tenantId: string; } export interface ReadSubscriptionResponse { subscription: TenantSubscription | undefined; } export interface FindSubscriptionsRequest { tenantId: string; } export interface FindSubscriptionsResponse { subscriptions: TenantSubscription[]; } /** * Cards */ export interface CreateCardRequest { name: string; cvc: string; number: string; currency: string; expMonth: string; expYear: string; address: Address | undefined; } export interface CreateCardResponse { card: Card | undefined; } export interface SetDefaultCardRequest { id: string; } export interface SetDefaultCardResponse { card: Card | undefined; } export interface DeleteCardRequest { id: string; } export interface DeleteCardResponse { card: Card | undefined; } export interface ReadCardRequest { id: string; } export interface ReadCardResponse { card: Card | undefined; } export interface FindCardsRequest {} export interface FindCardsResponse { cards: Card[]; } export interface CreateCustomerRequest { name: string; email: string; number: string; currency: string; } export interface CreateCustomerResponse { customer: Customer | undefined; } export interface DeleteCustomerRequest { id: string; } export interface DeleteCustomerResponse { customer: Customer | undefined; } export interface ReadCustomerRequest { id: string; } export interface ReadCustomerResponse { customer: Customer | undefined; } export interface Message { say: string; } export interface Event { /** * unique id */ id: string; /** * unix timestamp */ timestamp: number; /** * message */ message: string; /** * message */ topic: string; } const baseTenantSubscription: object = { id: '', tenantId: '', status: '', createdAt: '', updatedAt: '', collectionMethod: '', currentPeriodStart: '', currentPeriodEnd: '', endedAt: '', canceledAt: '', latestInvoiceId: '', startDate: '', trialStart: '', trialEnd: '', customerEmail: '', customerName: '', }; const baseCustomer: object = { id: '', email: '', name: '', }; const baseAddress: object = { id: '', country: '', state: '', city: '', postalCode: '', line: '', line2: '', }; const baseCard: object = { id: '', name: '', cvc: '', number: '', brand: '', currency: '', address: undefined, expMonth: 0, expYear: 0, lastFourDigit: '', isDefault: false, }; const basePrice: object = { name: '', currency: '', id: '', trialDays: 0, amount: 0, }; const baseStripePlan: object = { name: '', currency: '', id: '', trialDays: 0, amount: 0, }; const baseFeature: object = { name: '', normalizedName: '', description: '', min: 0, max: 0, active: false, full: false, unit: '', }; const basePlan: object = { id: '', normalizedName: '', price: undefined, features: undefined, active: false, free: false, createdAt: '', updatedAt: '', name: '', stripeId: '', }; const baseInvoice: object = { id: '', accountCountry: '', accountName: '', amountDue: 0, amountPaid: 0, amountRemaining: 0, billingReason: '', currency: '', customerEmail: '', customerName: '', description: '', dueDate: '', endingBalance: 0, hostedInvoiceUrl: '', invoicePdf: '', number: '', paid: false, receiptNumber: '', startingBalance: 0, statementDescriptor: '', status: '', subtotal: 0, tax: 0, taxPercent: 0, total: 0, createdAt: '', updatedAt: '', }; const baseCreatePriceRequest: object = { price: 0, currency: '', id: '', nickname: '', trialDays: 0, intervalCount: 0, interval: '', }; const baseCreatePlanRequest: object = { name: '', description: '', prices: undefined, features: undefined, active: false, free: false, }; const baseCreatePlanResponse: object = { plan: undefined, }; const baseReadPlanRequest: object = { id: '', }; const baseReadPlanResponse: object = { plan: undefined, }; const baseFindPlansRequest: object = {}; const baseFindPlansResponse: object = { plans: undefined, }; const baseReadStripePlanRequest: object = { id: '', }; const baseReadStripePlanResponse: object = { plan: undefined, }; const baseFindStripePlansRequest: object = { productId: '', }; const baseFindStripePlansResponse: object = { plans: undefined, }; const baseReadInvoiceRequest: object = { id: '', }; const baseReadInvoiceResponse: object = { invoice: undefined, }; const baseFindInvoicesRequest: object = {}; const baseFindInvoicesResponse: object = { invoices: undefined, }; const baseCreateSubscriptionRequest: object = { customerId: '', tenantId: '', planId: '', couponId: '', cardId: '', }; const baseCreateSubscriptionResponse: object = { subscription: undefined, }; const baseChangeSubscriptionRequest: object = { customerId: '', tenantId: '', planId: '', couponId: '', }; const baseChangeSubscriptionResponse: object = { subscription: undefined, }; const baseCancelSubscriptionRequest: object = { customerId: '', tenantId: '', }; const baseCancelSubscriptionResponse: object = { subscription: undefined, }; const baseReadSubscriptionRequest: object = { id: '', tenantId: '', }; const baseReadSubscriptionResponse: object = { subscription: undefined, }; const baseFindSubscriptionsRequest: object = { tenantId: '', }; const baseFindSubscriptionsResponse: object = { subscriptions: undefined, }; const baseCreateCardRequest: object = { name: '', cvc: '', number: '', currency: '', expMonth: '', expYear: '', address: undefined, }; const baseCreateCardResponse: object = { card: undefined, }; const baseSetDefaultCardRequest: object = { id: '', }; const baseSetDefaultCardResponse: object = { card: undefined, }; const baseDeleteCardRequest: object = { id: '', }; const baseDeleteCardResponse: object = { card: undefined, }; const baseReadCardRequest: object = { id: '', }; const baseReadCardResponse: object = { card: undefined, }; const baseFindCardsRequest: object = {}; const baseFindCardsResponse: object = { cards: undefined, }; const baseCreateCustomerRequest: object = { name: '', email: '', number: '', currency: '', }; const baseCreateCustomerResponse: object = { customer: undefined, }; const baseDeleteCustomerRequest: object = { id: '', }; const baseDeleteCustomerResponse: object = { customer: undefined, }; const baseReadCustomerRequest: object = { id: '', }; const baseReadCustomerResponse: object = { customer: undefined, }; const baseMessage: object = { say: '', }; const baseEvent: object = { id: '', timestamp: 0, message: '', topic: '', }; export interface BillingService<Context extends DataLoaders> { createCustomer( request: CreateCustomerRequest, ctx: Context, ): Promise<CreateCustomerResponse>; deleteCustomer( request: DeleteCustomerRequest, ctx: Context, ): Promise<DeleteCustomerResponse>; readCustomer( request: ReadCustomerRequest, ctx: Context, ): Promise<ReadCustomerResponse>; createPlan( request: CreatePlanRequest, ctx: Context, ): Promise<CreatePlanResponse>; readPlan(request: ReadPlanRequest, ctx: Context): Promise<ReadPlanResponse>; findPlans( request: FindPlansRequest, ctx: Context, ): Promise<FindPlansResponse>; readStripePlan( request: ReadStripePlanRequest, ctx: Context, ): Promise<ReadStripePlanResponse>; findStripePlans( request: FindStripePlansRequest, ctx: Context, ): Promise<FindStripePlansResponse>; createCard( request: CreateCardRequest, ctx: Context, ): Promise<CreateCardResponse>; deleteCard( request: DeleteCardRequest, ctx: Context, ): Promise<DeleteCardResponse>; setDefaultCard( request: SetDefaultCardRequest, ctx: Context, ): Promise<SetDefaultCardResponse>; readCard(request: ReadCardRequest, ctx: Context): Promise<ReadCardResponse>; findCards( request: FindCardsRequest, ctx: Context, ): Promise<FindCardsResponse>; createSubscription( request: CreateSubscriptionRequest, ctx: Context, ): Promise<CreateSubscriptionResponse>; cancelSubscription( request: CancelSubscriptionRequest, ctx: Context, ): Promise<CancelSubscriptionResponse>; changeSubscription( request: ChangeSubscriptionRequest, ctx: Context, ): Promise<ChangeSubscriptionResponse>; readSubscription( request: ReadSubscriptionRequest, ctx: Context, ): Promise<ReadSubscriptionResponse>; findSubscriptions( request: FindSubscriptionsRequest, ctx: Context, ): Promise<FindSubscriptionsResponse>; readInvoice( request: ReadInvoiceRequest, ctx: Context, ): Promise<ReadInvoiceResponse>; findInvoices( request: FindInvoicesRequest, ctx: Context, ): Promise<FindInvoicesResponse>; } export interface BillingServiceClient<Context extends DataLoaders> { createCustomer( request: CreateCustomerRequest, ctx?: Context, ): Observable<CreateCustomerResponse>; deleteCustomer( request: DeleteCustomerRequest, ctx?: Context, ): Observable<DeleteCustomerResponse>; readCustomer( request: ReadCustomerRequest, ctx?: Context, ): Observable<ReadCustomerResponse>; createPlan( request: CreatePlanRequest, ctx?: Context, ): Observable<CreatePlanResponse>; readPlan( request: ReadPlanRequest, ctx?: Context, ): Observable<ReadPlanResponse>; findPlans( request: FindPlansRequest, ctx?: Context, ): Observable<FindPlansResponse>; readStripePlan( request: ReadStripePlanRequest, ctx?: Context, ): Observable<ReadStripePlanResponse>; findStripePlans( request: FindStripePlansRequest, ctx?: Context, ): Observable<FindStripePlansResponse>; createCard( request: CreateCardRequest, ctx?: Context, ): Observable<CreateCardResponse>; deleteCard( request: DeleteCardRequest, ctx?: Context, ): Observable<DeleteCardResponse>; setDefaultCard( request: SetDefaultCardRequest, ctx?: Context, ): Observable<SetDefaultCardResponse>; readCard( request: ReadCardRequest, ctx?: Context, ): Observable<ReadCardResponse>; findCards( request: FindCardsRequest, ctx?: Context, ): Observable<FindCardsResponse>; createSubscription( request: CreateSubscriptionRequest, ctx?: Context, ): Observable<CreateSubscriptionResponse>; cancelSubscription( request: CancelSubscriptionRequest, ctx?: Context, ): Observable<CancelSubscriptionResponse>; changeSubscription( request: ChangeSubscriptionRequest, ctx?: Context, ): Observable<ChangeSubscriptionResponse>; readSubscription( request: ReadSubscriptionRequest, ctx?: Context, ): Observable<ReadSubscriptionResponse>; findSubscriptions( request: FindSubscriptionsRequest, ctx?: Context, ): Observable<FindSubscriptionsResponse>; readInvoice( request: ReadInvoiceRequest, ctx?: Context, ): Observable<ReadInvoiceResponse>; findInvoices( request: FindInvoicesRequest, ctx?: Context, ): Observable<FindInvoicesResponse>; } interface DataLoaders { getDataLoader<T>(identifier: string, constructorFn: () => T): T; } export const PlanPriceInterval = { MONTH: 0 as PlanPriceInterval, YEAR: 1 as PlanPriceInterval, WEEK: 2 as PlanPriceInterval, DAY: 3 as PlanPriceInterval, fromJSON(object: any): PlanPriceInterval { switch (object) { case 0: case 'MONTH': return PlanPriceInterval.MONTH; case 1: case 'YEAR': return PlanPriceInterval.YEAR; case 2: case 'WEEK': return PlanPriceInterval.WEEK; case 3: case 'DAY': return PlanPriceInterval.DAY; default: throw new global.Error(`Invalid value ${object}`); } }, toJSON(object: PlanPriceInterval): string { switch (object) { case PlanPriceInterval.MONTH: return 'MONTH'; case PlanPriceInterval.YEAR: return 'YEAR'; case PlanPriceInterval.WEEK: return 'WEEK'; case PlanPriceInterval.DAY: return 'DAY'; default: return 'UNKNOWN'; } }, }; export type PlanPriceInterval = 0 | 1 | 2 | 3; export const InvoiceStatus = { DRAFT: 0 as InvoiceStatus, OPEN: 1 as InvoiceStatus, PAID: 2 as InvoiceStatus, UNCOLLECTIBLE: 3 as InvoiceStatus, VOID: 4 as InvoiceStatus, fromJSON(object: any): InvoiceStatus { switch (object) { case 0: case 'DRAFT': return InvoiceStatus.DRAFT; case 1: case 'OPEN': return InvoiceStatus.OPEN; case 2: case 'PAID': return InvoiceStatus.PAID; case 3: case 'UNCOLLECTIBLE': return InvoiceStatus.UNCOLLECTIBLE; case 4: case 'VOID': return InvoiceStatus.VOID; default: throw new global.Error(`Invalid value ${object}`); } }, toJSON(object: InvoiceStatus): string { switch (object) { case InvoiceStatus.DRAFT: return 'DRAFT'; case InvoiceStatus.OPEN: return 'OPEN'; case InvoiceStatus.PAID: return 'PAID'; case InvoiceStatus.UNCOLLECTIBLE: return 'UNCOLLECTIBLE'; case InvoiceStatus.VOID: return 'VOID'; default: return 'UNKNOWN'; } }, }; export type InvoiceStatus = 0 | 1 | 2 | 3 | 4; export const SubscriptionStatus = { ACTIVE: 0 as SubscriptionStatus, ALL: 1 as SubscriptionStatus, CANCELED: 2 as SubscriptionStatus, INCOMPLETE: 3 as SubscriptionStatus, INCOMPLETE_EXPIRED: 4 as SubscriptionStatus, PAST_DUE: 5 as SubscriptionStatus, TRIALING: 6 as SubscriptionStatus, UNPAID: 7 as SubscriptionStatus, fromJSON(object: any): SubscriptionStatus { switch (object) { case 0: case 'ACTIVE': return SubscriptionStatus.ACTIVE; case 1: case 'ALL': return SubscriptionStatus.ALL; case 2: case 'CANCELED': return SubscriptionStatus.CANCELED; case 3: case 'INCOMPLETE': return SubscriptionStatus.INCOMPLETE; case 4: case 'INCOMPLETE_EXPIRED': return SubscriptionStatus.INCOMPLETE_EXPIRED; case 5: case 'PAST_DUE': return SubscriptionStatus.PAST_DUE; case 6: case 'TRIALING': return SubscriptionStatus.TRIALING; case 7: case 'UNPAID': return SubscriptionStatus.UNPAID; default: throw new global.Error(`Invalid value ${object}`); } }, toJSON(object: SubscriptionStatus): string { switch (object) { case SubscriptionStatus.ACTIVE: return 'ACTIVE'; case SubscriptionStatus.ALL: return 'ALL'; case SubscriptionStatus.CANCELED: return 'CANCELED'; case SubscriptionStatus.INCOMPLETE: return 'INCOMPLETE'; case SubscriptionStatus.INCOMPLETE_EXPIRED: return 'INCOMPLETE_EXPIRED'; case SubscriptionStatus.PAST_DUE: return 'PAST_DUE'; case SubscriptionStatus.TRIALING: return 'TRIALING'; case SubscriptionStatus.UNPAID: return 'UNPAID'; default: return 'UNKNOWN'; } }, }; export type SubscriptionStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7; export const TenantSubscription = { encode( message: TenantSubscription, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.id); writer.uint32(18).string(message.tenantId); writer.uint32(26).string(message.status); writer.uint32(50).string(message.createdAt); writer.uint32(58).string(message.updatedAt); writer.uint32(66).string(message.collectionMethod); writer.uint32(74).string(message.currentPeriodStart); writer.uint32(82).string(message.currentPeriodEnd); writer.uint32(90).string(message.endedAt); writer.uint32(98).string(message.canceledAt); writer.uint32(106).string(message.latestInvoiceId); writer.uint32(114).string(message.startDate); writer.uint32(122).string(message.trialStart); writer.uint32(130).string(message.trialEnd); writer.uint32(138).string(message.customerEmail); writer.uint32(146).string(message.customerName); return writer; }, decode(reader: Reader, length?: number): TenantSubscription { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseTenantSubscription) as TenantSubscription; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.tenantId = reader.string(); break; case 3: message.status = reader.string(); break; case 6: message.createdAt = reader.string(); break; case 7: message.updatedAt = reader.string(); break; case 8: message.collectionMethod = reader.string(); break; case 9: message.currentPeriodStart = reader.string(); break; case 10: message.currentPeriodEnd = reader.string(); break; case 11: message.endedAt = reader.string(); break; case 12: message.canceledAt = reader.string(); break; case 13: message.latestInvoiceId = reader.string(); break; case 14: message.startDate = reader.string(); break; case 15: message.trialStart = reader.string(); break; case 16: message.trialEnd = reader.string(); break; case 17: message.customerEmail = reader.string(); break; case 18: message.customerName = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): TenantSubscription { const message = Object.create(baseTenantSubscription) as TenantSubscription; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = String(object.tenantId); } else { message.tenantId = ''; } if (object.status !== undefined && object.status !== null) { message.status = String(object.status); } else { message.status = ''; } if (object.createdAt !== undefined && object.createdAt !== null) { message.createdAt = String(object.createdAt); } else { message.createdAt = ''; } if (object.updatedAt !== undefined && object.updatedAt !== null) { message.updatedAt = String(object.updatedAt); } else { message.updatedAt = ''; } if ( object.collectionMethod !== undefined && object.collectionMethod !== null ) { message.collectionMethod = String(object.collectionMethod); } else { message.collectionMethod = ''; } if ( object.currentPeriodStart !== undefined && object.currentPeriodStart !== null ) { message.currentPeriodStart = String(object.currentPeriodStart); } else { message.currentPeriodStart = ''; } if ( object.currentPeriodEnd !== undefined && object.currentPeriodEnd !== null ) { message.currentPeriodEnd = String(object.currentPeriodEnd); } else { message.currentPeriodEnd = ''; } if (object.endedAt !== undefined && object.endedAt !== null) { message.endedAt = String(object.endedAt); } else { message.endedAt = ''; } if (object.canceledAt !== undefined && object.canceledAt !== null) { message.canceledAt = String(object.canceledAt); } else { message.canceledAt = ''; } if ( object.latestInvoiceId !== undefined && object.latestInvoiceId !== null ) { message.latestInvoiceId = String(object.latestInvoiceId); } else { message.latestInvoiceId = ''; } if (object.startDate !== undefined && object.startDate !== null) { message.startDate = String(object.startDate); } else { message.startDate = ''; } if (object.trialStart !== undefined && object.trialStart !== null) { message.trialStart = String(object.trialStart); } else { message.trialStart = ''; } if (object.trialEnd !== undefined && object.trialEnd !== null) { message.trialEnd = String(object.trialEnd); } else { message.trialEnd = ''; } if (object.customerEmail !== undefined && object.customerEmail !== null) { message.customerEmail = String(object.customerEmail); } else { message.customerEmail = ''; } if (object.customerName !== undefined && object.customerName !== null) { message.customerName = String(object.customerName); } else { message.customerName = ''; } return message; }, fromPartial(object: DeepPartial<TenantSubscription>): TenantSubscription { const message = Object.create(baseTenantSubscription) as TenantSubscription; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = object.tenantId; } else { message.tenantId = ''; } if (object.status !== undefined && object.status !== null) { message.status = object.status; } else { message.status = ''; } if (object.createdAt !== undefined && object.createdAt !== null) { message.createdAt = object.createdAt; } else { message.createdAt = ''; } if (object.updatedAt !== undefined && object.updatedAt !== null) { message.updatedAt = object.updatedAt; } else { message.updatedAt = ''; } if ( object.collectionMethod !== undefined && object.collectionMethod !== null ) { message.collectionMethod = object.collectionMethod; } else { message.collectionMethod = ''; } if ( object.currentPeriodStart !== undefined && object.currentPeriodStart !== null ) { message.currentPeriodStart = object.currentPeriodStart; } else { message.currentPeriodStart = ''; } if ( object.currentPeriodEnd !== undefined && object.currentPeriodEnd !== null ) { message.currentPeriodEnd = object.currentPeriodEnd; } else { message.currentPeriodEnd = ''; } if (object.endedAt !== undefined && object.endedAt !== null) { message.endedAt = object.endedAt; } else { message.endedAt = ''; } if (object.canceledAt !== undefined && object.canceledAt !== null) { message.canceledAt = object.canceledAt; } else { message.canceledAt = ''; } if ( object.latestInvoiceId !== undefined && object.latestInvoiceId !== null ) { message.latestInvoiceId = object.latestInvoiceId; } else { message.latestInvoiceId = ''; } if (object.startDate !== undefined && object.startDate !== null) { message.startDate = object.startDate; } else { message.startDate = ''; } if (object.trialStart !== undefined && object.trialStart !== null) { message.trialStart = object.trialStart; } else { message.trialStart = ''; } if (object.trialEnd !== undefined && object.trialEnd !== null) { message.trialEnd = object.trialEnd; } else { message.trialEnd = ''; } if (object.customerEmail !== undefined && object.customerEmail !== null) { message.customerEmail = object.customerEmail; } else { message.customerEmail = ''; } if (object.customerName !== undefined && object.customerName !== null) { message.customerName = object.customerName; } else { message.customerName = ''; } return message; }, toJSON(message: TenantSubscription): unknown { const obj: any = {}; obj.id = message.id || ''; obj.tenantId = message.tenantId || ''; obj.status = message.status || ''; obj.createdAt = message.createdAt || ''; obj.updatedAt = message.updatedAt || ''; obj.collectionMethod = message.collectionMethod || ''; obj.currentPeriodStart = message.currentPeriodStart || ''; obj.currentPeriodEnd = message.currentPeriodEnd || ''; obj.endedAt = message.endedAt || ''; obj.canceledAt = message.canceledAt || ''; obj.latestInvoiceId = message.latestInvoiceId || ''; obj.startDate = message.startDate || ''; obj.trialStart = message.trialStart || ''; obj.trialEnd = message.trialEnd || ''; obj.customerEmail = message.customerEmail || ''; obj.customerName = message.customerName || ''; return obj; }, }; export const Customer = { encode(message: Customer, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); writer.uint32(34).string(message.email); writer.uint32(42).string(message.name); return writer; }, decode(reader: Reader, length?: number): Customer { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseCustomer) as Customer; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 4: message.email = reader.string(); break; case 5: message.name = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Customer { const message = Object.create(baseCustomer) as Customer; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.email !== undefined && object.email !== null) { message.email = String(object.email); } else { message.email = ''; } if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } return message; }, fromPartial(object: DeepPartial<Customer>): Customer { const message = Object.create(baseCustomer) as Customer; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.email !== undefined && object.email !== null) { message.email = object.email; } else { message.email = ''; } if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } return message; }, toJSON(message: Customer): unknown { const obj: any = {}; obj.id = message.id || ''; obj.email = message.email || ''; obj.name = message.name || ''; return obj; }, }; export const Address = { encode(message: Address, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); writer.uint32(18).string(message.country); writer.uint32(26).string(message.state); writer.uint32(34).string(message.city); writer.uint32(42).string(message.postalCode); writer.uint32(50).string(message.line); writer.uint32(58).string(message.line2); return writer; }, decode(reader: Reader, length?: number): Address { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseAddress) as Address; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.country = reader.string(); break; case 3: message.state = reader.string(); break; case 4: message.city = reader.string(); break; case 5: message.postalCode = reader.string(); break; case 6: message.line = reader.string(); break; case 7: message.line2 = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Address { const message = Object.create(baseAddress) as Address; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.country !== undefined && object.country !== null) { message.country = String(object.country); } else { message.country = ''; } if (object.state !== undefined && object.state !== null) { message.state = String(object.state); } else { message.state = ''; } if (object.city !== undefined && object.city !== null) { message.city = String(object.city); } else { message.city = ''; } if (object.postalCode !== undefined && object.postalCode !== null) { message.postalCode = String(object.postalCode); } else { message.postalCode = ''; } if (object.line !== undefined && object.line !== null) { message.line = String(object.line); } else { message.line = ''; } if (object.line2 !== undefined && object.line2 !== null) { message.line2 = String(object.line2); } else { message.line2 = ''; } return message; }, fromPartial(object: DeepPartial<Address>): Address { const message = Object.create(baseAddress) as Address; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.country !== undefined && object.country !== null) { message.country = object.country; } else { message.country = ''; } if (object.state !== undefined && object.state !== null) { message.state = object.state; } else { message.state = ''; } if (object.city !== undefined && object.city !== null) { message.city = object.city; } else { message.city = ''; } if (object.postalCode !== undefined && object.postalCode !== null) { message.postalCode = object.postalCode; } else { message.postalCode = ''; } if (object.line !== undefined && object.line !== null) { message.line = object.line; } else { message.line = ''; } if (object.line2 !== undefined && object.line2 !== null) { message.line2 = object.line2; } else { message.line2 = ''; } return message; }, toJSON(message: Address): unknown { const obj: any = {}; obj.id = message.id || ''; obj.country = message.country || ''; obj.state = message.state || ''; obj.city = message.city || ''; obj.postalCode = message.postalCode || ''; obj.line = message.line || ''; obj.line2 = message.line2 || ''; return obj; }, }; export const Card = { encode(message: Card, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); writer.uint32(18).string(message.name); writer.uint32(26).string(message.cvc); writer.uint32(34).string(message.number); writer.uint32(42).string(message.brand); writer.uint32(50).string(message.currency); if (message.address !== undefined && message.address !== undefined) { Address.encode(message.address, writer.uint32(58).fork()).ldelim(); } writer.uint32(64).uint32(message.expMonth); writer.uint32(72).uint32(message.expYear); writer.uint32(82).string(message.lastFourDigit); writer.uint32(88).bool(message.isDefault); return writer; }, decode(reader: Reader, length?: number): Card { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseCard) as Card; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.name = reader.string(); break; case 3: message.cvc = reader.string(); break; case 4: message.number = reader.string(); break; case 5: message.brand = reader.string(); break; case 6: message.currency = reader.string(); break; case 7: message.address = Address.decode(reader, reader.uint32()); break; case 8: message.expMonth = reader.uint32(); break; case 9: message.expYear = reader.uint32(); break; case 10: message.lastFourDigit = reader.string(); break; case 11: message.isDefault = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Card { const message = Object.create(baseCard) as Card; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.cvc !== undefined && object.cvc !== null) { message.cvc = String(object.cvc); } else { message.cvc = ''; } if (object.number !== undefined && object.number !== null) { message.number = String(object.number); } else { message.number = ''; } if (object.brand !== undefined && object.brand !== null) { message.brand = String(object.brand); } else { message.brand = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = String(object.currency); } else { message.currency = ''; } if (object.address !== undefined && object.address !== null) { message.address = Address.fromJSON(object.address); } else { message.address = undefined; } if (object.expMonth !== undefined && object.expMonth !== null) { message.expMonth = Number(object.expMonth); } else { message.expMonth = 0; } if (object.expYear !== undefined && object.expYear !== null) { message.expYear = Number(object.expYear); } else { message.expYear = 0; } if (object.lastFourDigit !== undefined && object.lastFourDigit !== null) { message.lastFourDigit = String(object.lastFourDigit); } else { message.lastFourDigit = ''; } if (object.isDefault !== undefined && object.isDefault !== null) { message.isDefault = Boolean(object.isDefault); } else { message.isDefault = false; } return message; }, fromPartial(object: DeepPartial<Card>): Card { const message = Object.create(baseCard) as Card; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.cvc !== undefined && object.cvc !== null) { message.cvc = object.cvc; } else { message.cvc = ''; } if (object.number !== undefined && object.number !== null) { message.number = object.number; } else { message.number = ''; } if (object.brand !== undefined && object.brand !== null) { message.brand = object.brand; } else { message.brand = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = object.currency; } else { message.currency = ''; } if (object.address !== undefined && object.address !== null) { message.address = Address.fromPartial(object.address); } else { message.address = undefined; } if (object.expMonth !== undefined && object.expMonth !== null) { message.expMonth = object.expMonth; } else { message.expMonth = 0; } if (object.expYear !== undefined && object.expYear !== null) { message.expYear = object.expYear; } else { message.expYear = 0; } if (object.lastFourDigit !== undefined && object.lastFourDigit !== null) { message.lastFourDigit = object.lastFourDigit; } else { message.lastFourDigit = ''; } if (object.isDefault !== undefined && object.isDefault !== null) { message.isDefault = object.isDefault; } else { message.isDefault = false; } return message; }, toJSON(message: Card): unknown { const obj: any = {}; obj.id = message.id || ''; obj.name = message.name || ''; obj.cvc = message.cvc || ''; obj.number = message.number || ''; obj.brand = message.brand || ''; obj.currency = message.currency || ''; obj.address = message.address ? Address.toJSON(message.address) : undefined; obj.expMonth = message.expMonth || 0; obj.expYear = message.expYear || 0; obj.lastFourDigit = message.lastFourDigit || ''; obj.isDefault = message.isDefault || false; return obj; }, }; export const Price = { encode(message: Price, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.name); writer.uint32(18).string(message.currency); writer.uint32(26).string(message.id); writer.uint32(32).int32(message.trialDays); writer.uint32(45).float(message.amount); return writer; }, decode(reader: Reader, length?: number): Price { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(basePrice) as Price; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.currency = reader.string(); break; case 3: message.id = reader.string(); break; case 4: message.trialDays = reader.int32(); break; case 5: message.amount = reader.float(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Price { const message = Object.create(basePrice) as Price; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = String(object.currency); } else { message.currency = ''; } if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.trialDays !== undefined && object.trialDays !== null) { message.trialDays = Number(object.trialDays); } else { message.trialDays = 0; } if (object.amount !== undefined && object.amount !== null) { message.amount = Number(object.amount); } else { message.amount = 0; } return message; }, fromPartial(object: DeepPartial<Price>): Price { const message = Object.create(basePrice) as Price; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = object.currency; } else { message.currency = ''; } if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.trialDays !== undefined && object.trialDays !== null) { message.trialDays = object.trialDays; } else { message.trialDays = 0; } if (object.amount !== undefined && object.amount !== null) { message.amount = object.amount; } else { message.amount = 0; } return message; }, toJSON(message: Price): unknown { const obj: any = {}; obj.name = message.name || ''; obj.currency = message.currency || ''; obj.id = message.id || ''; obj.trialDays = message.trialDays || 0; obj.amount = message.amount || 0; return obj; }, }; export const StripePlan = { encode(message: StripePlan, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.name); writer.uint32(18).string(message.currency); writer.uint32(26).string(message.id); writer.uint32(32).int32(message.trialDays); writer.uint32(45).float(message.amount); return writer; }, decode(reader: Reader, length?: number): StripePlan { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseStripePlan) as StripePlan; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.currency = reader.string(); break; case 3: message.id = reader.string(); break; case 4: message.trialDays = reader.int32(); break; case 5: message.amount = reader.float(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StripePlan { const message = Object.create(baseStripePlan) as StripePlan; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = String(object.currency); } else { message.currency = ''; } if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.trialDays !== undefined && object.trialDays !== null) { message.trialDays = Number(object.trialDays); } else { message.trialDays = 0; } if (object.amount !== undefined && object.amount !== null) { message.amount = Number(object.amount); } else { message.amount = 0; } return message; }, fromPartial(object: DeepPartial<StripePlan>): StripePlan { const message = Object.create(baseStripePlan) as StripePlan; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = object.currency; } else { message.currency = ''; } if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.trialDays !== undefined && object.trialDays !== null) { message.trialDays = object.trialDays; } else { message.trialDays = 0; } if (object.amount !== undefined && object.amount !== null) { message.amount = object.amount; } else { message.amount = 0; } return message; }, toJSON(message: StripePlan): unknown { const obj: any = {}; obj.name = message.name || ''; obj.currency = message.currency || ''; obj.id = message.id || ''; obj.trialDays = message.trialDays || 0; obj.amount = message.amount || 0; return obj; }, }; export const Feature = { encode(message: Feature, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.name); writer.uint32(18).string(message.normalizedName); writer.uint32(26).string(message.description); writer.uint32(32).int32(message.min); writer.uint32(40).int32(message.max); writer.uint32(48).bool(message.active); writer.uint32(56).bool(message.full); writer.uint32(66).string(message.unit); return writer; }, decode(reader: Reader, length?: number): Feature { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseFeature) as Feature; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.normalizedName = reader.string(); break; case 3: message.description = reader.string(); break; case 4: message.min = reader.int32(); break; case 5: message.max = reader.int32(); break; case 6: message.active = reader.bool(); break; case 7: message.full = reader.bool(); break; case 8: message.unit = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Feature { const message = Object.create(baseFeature) as Feature; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.normalizedName !== undefined && object.normalizedName !== null) { message.normalizedName = String(object.normalizedName); } else { message.normalizedName = ''; } if (object.description !== undefined && object.description !== null) { message.description = String(object.description); } else { message.description = ''; } if (object.min !== undefined && object.min !== null) { message.min = Number(object.min); } else { message.min = 0; } if (object.max !== undefined && object.max !== null) { message.max = Number(object.max); } else { message.max = 0; } if (object.active !== undefined && object.active !== null) { message.active = Boolean(object.active); } else { message.active = false; } if (object.full !== undefined && object.full !== null) { message.full = Boolean(object.full); } else { message.full = false; } if (object.unit !== undefined && object.unit !== null) { message.unit = String(object.unit); } else { message.unit = ''; } return message; }, fromPartial(object: DeepPartial<Feature>): Feature { const message = Object.create(baseFeature) as Feature; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.normalizedName !== undefined && object.normalizedName !== null) { message.normalizedName = object.normalizedName; } else { message.normalizedName = ''; } if (object.description !== undefined && object.description !== null) { message.description = object.description; } else { message.description = ''; } if (object.min !== undefined && object.min !== null) { message.min = object.min; } else { message.min = 0; } if (object.max !== undefined && object.max !== null) { message.max = object.max; } else { message.max = 0; } if (object.active !== undefined && object.active !== null) { message.active = object.active; } else { message.active = false; } if (object.full !== undefined && object.full !== null) { message.full = object.full; } else { message.full = false; } if (object.unit !== undefined && object.unit !== null) { message.unit = object.unit; } else { message.unit = ''; } return message; }, toJSON(message: Feature): unknown { const obj: any = {}; obj.name = message.name || ''; obj.normalizedName = message.normalizedName || ''; obj.description = message.description || ''; obj.min = message.min || 0; obj.max = message.max || 0; obj.active = message.active || false; obj.full = message.full || false; obj.unit = message.unit || ''; return obj; }, }; export const Plan = { encode(message: Plan, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); writer.uint32(18).string(message.normalizedName); if (message.price !== undefined && message.price !== undefined) { Price.encode(message.price, writer.uint32(26).fork()).ldelim(); } for (const v of message.features) { Feature.encode(v!, writer.uint32(34).fork()).ldelim(); } writer.uint32(40).bool(message.active); writer.uint32(48).bool(message.free); writer.uint32(58).string(message.createdAt); writer.uint32(66).string(message.updatedAt); writer.uint32(74).string(message.name); writer.uint32(82).string(message.stripeId); return writer; }, decode(reader: Reader, length?: number): Plan { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(basePlan) as Plan; message.features = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.normalizedName = reader.string(); break; case 3: message.price = Price.decode(reader, reader.uint32()); break; case 4: message.features.push(Feature.decode(reader, reader.uint32())); break; case 5: message.active = reader.bool(); break; case 6: message.free = reader.bool(); break; case 7: message.createdAt = reader.string(); break; case 8: message.updatedAt = reader.string(); break; case 9: message.name = reader.string(); break; case 10: message.stripeId = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Plan { const message = Object.create(basePlan) as Plan; message.features = []; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.normalizedName !== undefined && object.normalizedName !== null) { message.normalizedName = String(object.normalizedName); } else { message.normalizedName = ''; } if (object.price !== undefined && object.price !== null) { message.price = Price.fromJSON(object.price); } else { message.price = undefined; } if (object.features !== undefined && object.features !== null) { for (const e of object.features) { message.features.push(Feature.fromJSON(e)); } } if (object.active !== undefined && object.active !== null) { message.active = Boolean(object.active); } else { message.active = false; } if (object.free !== undefined && object.free !== null) { message.free = Boolean(object.free); } else { message.free = false; } if (object.createdAt !== undefined && object.createdAt !== null) { message.createdAt = String(object.createdAt); } else { message.createdAt = ''; } if (object.updatedAt !== undefined && object.updatedAt !== null) { message.updatedAt = String(object.updatedAt); } else { message.updatedAt = ''; } if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.stripeId !== undefined && object.stripeId !== null) { message.stripeId = String(object.stripeId); } else { message.stripeId = ''; } return message; }, fromPartial(object: DeepPartial<Plan>): Plan { const message = Object.create(basePlan) as Plan; message.features = []; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.normalizedName !== undefined && object.normalizedName !== null) { message.normalizedName = object.normalizedName; } else { message.normalizedName = ''; } if (object.price !== undefined && object.price !== null) { message.price = Price.fromPartial(object.price); } else { message.price = undefined; } if (object.features !== undefined && object.features !== null) { for (const e of object.features) { message.features.push(Feature.fromPartial(e)); } } if (object.active !== undefined && object.active !== null) { message.active = object.active; } else { message.active = false; } if (object.free !== undefined && object.free !== null) { message.free = object.free; } else { message.free = false; } if (object.createdAt !== undefined && object.createdAt !== null) { message.createdAt = object.createdAt; } else { message.createdAt = ''; } if (object.updatedAt !== undefined && object.updatedAt !== null) { message.updatedAt = object.updatedAt; } else { message.updatedAt = ''; } if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.stripeId !== undefined && object.stripeId !== null) { message.stripeId = object.stripeId; } else { message.stripeId = ''; } return message; }, toJSON(message: Plan): unknown { const obj: any = {}; obj.id = message.id || ''; obj.normalizedName = message.normalizedName || ''; obj.price = message.price ? Price.toJSON(message.price) : undefined; if (message.features) { obj.features = message.features.map((e) => e ? Feature.toJSON(e) : undefined, ); } else { obj.features = []; } obj.active = message.active || false; obj.free = message.free || false; obj.createdAt = message.createdAt || ''; obj.updatedAt = message.updatedAt || ''; obj.name = message.name || ''; obj.stripeId = message.stripeId || ''; return obj; }, }; export const Invoice = { encode(message: Invoice, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); writer.uint32(18).string(message.accountCountry); writer.uint32(26).string(message.accountName); writer.uint32(37).float(message.amountDue); writer.uint32(45).float(message.amountPaid); writer.uint32(53).float(message.amountRemaining); writer.uint32(58).string(message.billingReason); writer.uint32(66).string(message.currency); writer.uint32(74).string(message.customerEmail); writer.uint32(82).string(message.customerName); writer.uint32(90).string(message.description); writer.uint32(98).string(message.dueDate); writer.uint32(109).float(message.endingBalance); writer.uint32(114).string(message.hostedInvoiceUrl); writer.uint32(122).string(message.invoicePdf); writer.uint32(130).string(message.number); writer.uint32(136).bool(message.paid); writer.uint32(146).string(message.receiptNumber); writer.uint32(157).float(message.startingBalance); writer.uint32(162).string(message.statementDescriptor); writer.uint32(170).string(message.status); writer.uint32(176).int32(message.subtotal); writer.uint32(189).float(message.tax); writer.uint32(197).float(message.taxPercent); writer.uint32(205).float(message.total); writer.uint32(210).string(message.createdAt); writer.uint32(218).string(message.updatedAt); return writer; }, decode(reader: Reader, length?: number): Invoice { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseInvoice) as Invoice; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.accountCountry = reader.string(); break; case 3: message.accountName = reader.string(); break; case 4: message.amountDue = reader.float(); break; case 5: message.amountPaid = reader.float(); break; case 6: message.amountRemaining = reader.float(); break; case 7: message.billingReason = reader.string(); break; case 8: message.currency = reader.string(); break; case 9: message.customerEmail = reader.string(); break; case 10: message.customerName = reader.string(); break; case 11: message.description = reader.string(); break; case 12: message.dueDate = reader.string(); break; case 13: message.endingBalance = reader.float(); break; case 14: message.hostedInvoiceUrl = reader.string(); break; case 15: message.invoicePdf = reader.string(); break; case 16: message.number = reader.string(); break; case 17: message.paid = reader.bool(); break; case 18: message.receiptNumber = reader.string(); break; case 19: message.startingBalance = reader.float(); break; case 20: message.statementDescriptor = reader.string(); break; case 21: message.status = reader.string(); break; case 22: message.subtotal = reader.int32(); break; case 23: message.tax = reader.float(); break; case 24: message.taxPercent = reader.float(); break; case 25: message.total = reader.float(); break; case 26: message.createdAt = reader.string(); break; case 27: message.updatedAt = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Invoice { const message = Object.create(baseInvoice) as Invoice; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.accountCountry !== undefined && object.accountCountry !== null) { message.accountCountry = String(object.accountCountry); } else { message.accountCountry = ''; } if (object.accountName !== undefined && object.accountName !== null) { message.accountName = String(object.accountName); } else { message.accountName = ''; } if (object.amountDue !== undefined && object.amountDue !== null) { message.amountDue = Number(object.amountDue); } else { message.amountDue = 0; } if (object.amountPaid !== undefined && object.amountPaid !== null) { message.amountPaid = Number(object.amountPaid); } else { message.amountPaid = 0; } if ( object.amountRemaining !== undefined && object.amountRemaining !== null ) { message.amountRemaining = Number(object.amountRemaining); } else { message.amountRemaining = 0; } if (object.billingReason !== undefined && object.billingReason !== null) { message.billingReason = String(object.billingReason); } else { message.billingReason = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = String(object.currency); } else { message.currency = ''; } if (object.customerEmail !== undefined && object.customerEmail !== null) { message.customerEmail = String(object.customerEmail); } else { message.customerEmail = ''; } if (object.customerName !== undefined && object.customerName !== null) { message.customerName = String(object.customerName); } else { message.customerName = ''; } if (object.description !== undefined && object.description !== null) { message.description = String(object.description); } else { message.description = ''; } if (object.dueDate !== undefined && object.dueDate !== null) { message.dueDate = String(object.dueDate); } else { message.dueDate = ''; } if (object.endingBalance !== undefined && object.endingBalance !== null) { message.endingBalance = Number(object.endingBalance); } else { message.endingBalance = 0; } if ( object.hostedInvoiceUrl !== undefined && object.hostedInvoiceUrl !== null ) { message.hostedInvoiceUrl = String(object.hostedInvoiceUrl); } else { message.hostedInvoiceUrl = ''; } if (object.invoicePdf !== undefined && object.invoicePdf !== null) { message.invoicePdf = String(object.invoicePdf); } else { message.invoicePdf = ''; } if (object.number !== undefined && object.number !== null) { message.number = String(object.number); } else { message.number = ''; } if (object.paid !== undefined && object.paid !== null) { message.paid = Boolean(object.paid); } else { message.paid = false; } if (object.receiptNumber !== undefined && object.receiptNumber !== null) { message.receiptNumber = String(object.receiptNumber); } else { message.receiptNumber = ''; } if ( object.startingBalance !== undefined && object.startingBalance !== null ) { message.startingBalance = Number(object.startingBalance); } else { message.startingBalance = 0; } if ( object.statementDescriptor !== undefined && object.statementDescriptor !== null ) { message.statementDescriptor = String(object.statementDescriptor); } else { message.statementDescriptor = ''; } if (object.status !== undefined && object.status !== null) { message.status = String(object.status); } else { message.status = ''; } if (object.subtotal !== undefined && object.subtotal !== null) { message.subtotal = Number(object.subtotal); } else { message.subtotal = 0; } if (object.tax !== undefined && object.tax !== null) { message.tax = Number(object.tax); } else { message.tax = 0; } if (object.taxPercent !== undefined && object.taxPercent !== null) { message.taxPercent = Number(object.taxPercent); } else { message.taxPercent = 0; } if (object.total !== undefined && object.total !== null) { message.total = Number(object.total); } else { message.total = 0; } if (object.createdAt !== undefined && object.createdAt !== null) { message.createdAt = String(object.createdAt); } else { message.createdAt = ''; } if (object.updatedAt !== undefined && object.updatedAt !== null) { message.updatedAt = String(object.updatedAt); } else { message.updatedAt = ''; } return message; }, fromPartial(object: DeepPartial<Invoice>): Invoice { const message = Object.create(baseInvoice) as Invoice; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.accountCountry !== undefined && object.accountCountry !== null) { message.accountCountry = object.accountCountry; } else { message.accountCountry = ''; } if (object.accountName !== undefined && object.accountName !== null) { message.accountName = object.accountName; } else { message.accountName = ''; } if (object.amountDue !== undefined && object.amountDue !== null) { message.amountDue = object.amountDue; } else { message.amountDue = 0; } if (object.amountPaid !== undefined && object.amountPaid !== null) { message.amountPaid = object.amountPaid; } else { message.amountPaid = 0; } if ( object.amountRemaining !== undefined && object.amountRemaining !== null ) { message.amountRemaining = object.amountRemaining; } else { message.amountRemaining = 0; } if (object.billingReason !== undefined && object.billingReason !== null) { message.billingReason = object.billingReason; } else { message.billingReason = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = object.currency; } else { message.currency = ''; } if (object.customerEmail !== undefined && object.customerEmail !== null) { message.customerEmail = object.customerEmail; } else { message.customerEmail = ''; } if (object.customerName !== undefined && object.customerName !== null) { message.customerName = object.customerName; } else { message.customerName = ''; } if (object.description !== undefined && object.description !== null) { message.description = object.description; } else { message.description = ''; } if (object.dueDate !== undefined && object.dueDate !== null) { message.dueDate = object.dueDate; } else { message.dueDate = ''; } if (object.endingBalance !== undefined && object.endingBalance !== null) { message.endingBalance = object.endingBalance; } else { message.endingBalance = 0; } if ( object.hostedInvoiceUrl !== undefined && object.hostedInvoiceUrl !== null ) { message.hostedInvoiceUrl = object.hostedInvoiceUrl; } else { message.hostedInvoiceUrl = ''; } if (object.invoicePdf !== undefined && object.invoicePdf !== null) { message.invoicePdf = object.invoicePdf; } else { message.invoicePdf = ''; } if (object.number !== undefined && object.number !== null) { message.number = object.number; } else { message.number = ''; } if (object.paid !== undefined && object.paid !== null) { message.paid = object.paid; } else { message.paid = false; } if (object.receiptNumber !== undefined && object.receiptNumber !== null) { message.receiptNumber = object.receiptNumber; } else { message.receiptNumber = ''; } if ( object.startingBalance !== undefined && object.startingBalance !== null ) { message.startingBalance = object.startingBalance; } else { message.startingBalance = 0; } if ( object.statementDescriptor !== undefined && object.statementDescriptor !== null ) { message.statementDescriptor = object.statementDescriptor; } else { message.statementDescriptor = ''; } if (object.status !== undefined && object.status !== null) { message.status = object.status; } else { message.status = ''; } if (object.subtotal !== undefined && object.subtotal !== null) { message.subtotal = object.subtotal; } else { message.subtotal = 0; } if (object.tax !== undefined && object.tax !== null) { message.tax = object.tax; } else { message.tax = 0; } if (object.taxPercent !== undefined && object.taxPercent !== null) { message.taxPercent = object.taxPercent; } else { message.taxPercent = 0; } if (object.total !== undefined && object.total !== null) { message.total = object.total; } else { message.total = 0; } if (object.createdAt !== undefined && object.createdAt !== null) { message.createdAt = object.createdAt; } else { message.createdAt = ''; } if (object.updatedAt !== undefined && object.updatedAt !== null) { message.updatedAt = object.updatedAt; } else { message.updatedAt = ''; } return message; }, toJSON(message: Invoice): unknown { const obj: any = {}; obj.id = message.id || ''; obj.accountCountry = message.accountCountry || ''; obj.accountName = message.accountName || ''; obj.amountDue = message.amountDue || 0; obj.amountPaid = message.amountPaid || 0; obj.amountRemaining = message.amountRemaining || 0; obj.billingReason = message.billingReason || ''; obj.currency = message.currency || ''; obj.customerEmail = message.customerEmail || ''; obj.customerName = message.customerName || ''; obj.description = message.description || ''; obj.dueDate = message.dueDate || ''; obj.endingBalance = message.endingBalance || 0; obj.hostedInvoiceUrl = message.hostedInvoiceUrl || ''; obj.invoicePdf = message.invoicePdf || ''; obj.number = message.number || ''; obj.paid = message.paid || false; obj.receiptNumber = message.receiptNumber || ''; obj.startingBalance = message.startingBalance || 0; obj.statementDescriptor = message.statementDescriptor || ''; obj.status = message.status || ''; obj.subtotal = message.subtotal || 0; obj.tax = message.tax || 0; obj.taxPercent = message.taxPercent || 0; obj.total = message.total || 0; obj.createdAt = message.createdAt || ''; obj.updatedAt = message.updatedAt || ''; return obj; }, }; export const CreatePriceRequest = { encode( message: CreatePriceRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(13).float(message.price); writer.uint32(18).string(message.currency); writer.uint32(26).string(message.id); writer.uint32(34).string(message.nickname); writer.uint32(40).int32(message.trialDays); writer.uint32(48).int32(message.intervalCount); writer.uint32(58).string(message.interval); return writer; }, decode(reader: Reader, length?: number): CreatePriceRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseCreatePriceRequest) as CreatePriceRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.price = reader.float(); break; case 2: message.currency = reader.string(); break; case 3: message.id = reader.string(); break; case 4: message.nickname = reader.string(); break; case 5: message.trialDays = reader.int32(); break; case 6: message.intervalCount = reader.int32(); break; case 7: message.interval = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreatePriceRequest { const message = Object.create(baseCreatePriceRequest) as CreatePriceRequest; if (object.price !== undefined && object.price !== null) { message.price = Number(object.price); } else { message.price = 0; } if (object.currency !== undefined && object.currency !== null) { message.currency = String(object.currency); } else { message.currency = ''; } if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.nickname !== undefined && object.nickname !== null) { message.nickname = String(object.nickname); } else { message.nickname = ''; } if (object.trialDays !== undefined && object.trialDays !== null) { message.trialDays = Number(object.trialDays); } else { message.trialDays = 0; } if (object.intervalCount !== undefined && object.intervalCount !== null) { message.intervalCount = Number(object.intervalCount); } else { message.intervalCount = 0; } if (object.interval !== undefined && object.interval !== null) { message.interval = String(object.interval); } else { message.interval = ''; } return message; }, fromPartial(object: DeepPartial<CreatePriceRequest>): CreatePriceRequest { const message = Object.create(baseCreatePriceRequest) as CreatePriceRequest; if (object.price !== undefined && object.price !== null) { message.price = object.price; } else { message.price = 0; } if (object.currency !== undefined && object.currency !== null) { message.currency = object.currency; } else { message.currency = ''; } if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.nickname !== undefined && object.nickname !== null) { message.nickname = object.nickname; } else { message.nickname = ''; } if (object.trialDays !== undefined && object.trialDays !== null) { message.trialDays = object.trialDays; } else { message.trialDays = 0; } if (object.intervalCount !== undefined && object.intervalCount !== null) { message.intervalCount = object.intervalCount; } else { message.intervalCount = 0; } if (object.interval !== undefined && object.interval !== null) { message.interval = object.interval; } else { message.interval = ''; } return message; }, toJSON(message: CreatePriceRequest): unknown { const obj: any = {}; obj.price = message.price || 0; obj.currency = message.currency || ''; obj.id = message.id || ''; obj.nickname = message.nickname || ''; obj.trialDays = message.trialDays || 0; obj.intervalCount = message.intervalCount || 0; obj.interval = message.interval || ''; return obj; }, }; export const CreatePlanRequest = { encode(message: CreatePlanRequest, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.name); writer.uint32(18).string(message.description); for (const v of message.prices) { CreatePriceRequest.encode(v!, writer.uint32(26).fork()).ldelim(); } for (const v of message.features) { Feature.encode(v!, writer.uint32(34).fork()).ldelim(); } writer.uint32(64).bool(message.active); writer.uint32(72).bool(message.free); return writer; }, decode(reader: Reader, length?: number): CreatePlanRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseCreatePlanRequest) as CreatePlanRequest; message.prices = []; message.features = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.description = reader.string(); break; case 3: message.prices.push( CreatePriceRequest.decode(reader, reader.uint32()), ); break; case 4: message.features.push(Feature.decode(reader, reader.uint32())); break; case 8: message.active = reader.bool(); break; case 9: message.free = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreatePlanRequest { const message = Object.create(baseCreatePlanRequest) as CreatePlanRequest; message.prices = []; message.features = []; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.description !== undefined && object.description !== null) { message.description = String(object.description); } else { message.description = ''; } if (object.prices !== undefined && object.prices !== null) { for (const e of object.prices) { message.prices.push(CreatePriceRequest.fromJSON(e)); } } if (object.features !== undefined && object.features !== null) { for (const e of object.features) { message.features.push(Feature.fromJSON(e)); } } if (object.active !== undefined && object.active !== null) { message.active = Boolean(object.active); } else { message.active = false; } if (object.free !== undefined && object.free !== null) { message.free = Boolean(object.free); } else { message.free = false; } return message; }, fromPartial(object: DeepPartial<CreatePlanRequest>): CreatePlanRequest { const message = Object.create(baseCreatePlanRequest) as CreatePlanRequest; message.prices = []; message.features = []; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.description !== undefined && object.description !== null) { message.description = object.description; } else { message.description = ''; } if (object.prices !== undefined && object.prices !== null) { for (const e of object.prices) { message.prices.push(CreatePriceRequest.fromPartial(e)); } } if (object.features !== undefined && object.features !== null) { for (const e of object.features) { message.features.push(Feature.fromPartial(e)); } } if (object.active !== undefined && object.active !== null) { message.active = object.active; } else { message.active = false; } if (object.free !== undefined && object.free !== null) { message.free = object.free; } else { message.free = false; } return message; }, toJSON(message: CreatePlanRequest): unknown { const obj: any = {}; obj.name = message.name || ''; obj.description = message.description || ''; if (message.prices) { obj.prices = message.prices.map((e) => e ? CreatePriceRequest.toJSON(e) : undefined, ); } else { obj.prices = []; } if (message.features) { obj.features = message.features.map((e) => e ? Feature.toJSON(e) : undefined, ); } else { obj.features = []; } obj.active = message.active || false; obj.free = message.free || false; return obj; }, }; export const CreatePlanResponse = { encode( message: CreatePlanResponse, writer: Writer = Writer.create(), ): Writer { if (message.plan !== undefined && message.plan !== undefined) { Plan.encode(message.plan, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): CreatePlanResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseCreatePlanResponse) as CreatePlanResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.plan = Plan.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreatePlanResponse { const message = Object.create(baseCreatePlanResponse) as CreatePlanResponse; if (object.plan !== undefined && object.plan !== null) { message.plan = Plan.fromJSON(object.plan); } else { message.plan = undefined; } return message; }, fromPartial(object: DeepPartial<CreatePlanResponse>): CreatePlanResponse { const message = Object.create(baseCreatePlanResponse) as CreatePlanResponse; if (object.plan !== undefined && object.plan !== null) { message.plan = Plan.fromPartial(object.plan); } else { message.plan = undefined; } return message; }, toJSON(message: CreatePlanResponse): unknown { const obj: any = {}; obj.plan = message.plan ? Plan.toJSON(message.plan) : undefined; return obj; }, }; export const ReadPlanRequest = { encode(message: ReadPlanRequest, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): ReadPlanRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseReadPlanRequest) as ReadPlanRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadPlanRequest { const message = Object.create(baseReadPlanRequest) as ReadPlanRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial(object: DeepPartial<ReadPlanRequest>): ReadPlanRequest { const message = Object.create(baseReadPlanRequest) as ReadPlanRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: ReadPlanRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const ReadPlanResponse = { encode(message: ReadPlanResponse, writer: Writer = Writer.create()): Writer { if (message.plan !== undefined && message.plan !== undefined) { Plan.encode(message.plan, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): ReadPlanResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseReadPlanResponse) as ReadPlanResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.plan = Plan.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadPlanResponse { const message = Object.create(baseReadPlanResponse) as ReadPlanResponse; if (object.plan !== undefined && object.plan !== null) { message.plan = Plan.fromJSON(object.plan); } else { message.plan = undefined; } return message; }, fromPartial(object: DeepPartial<ReadPlanResponse>): ReadPlanResponse { const message = Object.create(baseReadPlanResponse) as ReadPlanResponse; if (object.plan !== undefined && object.plan !== null) { message.plan = Plan.fromPartial(object.plan); } else { message.plan = undefined; } return message; }, toJSON(message: ReadPlanResponse): unknown { const obj: any = {}; obj.plan = message.plan ? Plan.toJSON(message.plan) : undefined; return obj; }, }; export const FindPlansRequest = { encode(message: FindPlansRequest, writer: Writer = Writer.create()): Writer { return writer; }, decode(reader: Reader, length?: number): FindPlansRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseFindPlansRequest) as FindPlansRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindPlansRequest { const message = Object.create(baseFindPlansRequest) as FindPlansRequest; return message; }, fromPartial(object: DeepPartial<FindPlansRequest>): FindPlansRequest { const message = Object.create(baseFindPlansRequest) as FindPlansRequest; return message; }, toJSON(message: FindPlansRequest): unknown { const obj: any = {}; return obj; }, }; export const FindPlansResponse = { encode(message: FindPlansResponse, writer: Writer = Writer.create()): Writer { for (const v of message.plans) { Plan.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): FindPlansResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseFindPlansResponse) as FindPlansResponse; message.plans = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.plans.push(Plan.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindPlansResponse { const message = Object.create(baseFindPlansResponse) as FindPlansResponse; message.plans = []; if (object.plans !== undefined && object.plans !== null) { for (const e of object.plans) { message.plans.push(Plan.fromJSON(e)); } } return message; }, fromPartial(object: DeepPartial<FindPlansResponse>): FindPlansResponse { const message = Object.create(baseFindPlansResponse) as FindPlansResponse; message.plans = []; if (object.plans !== undefined && object.plans !== null) { for (const e of object.plans) { message.plans.push(Plan.fromPartial(e)); } } return message; }, toJSON(message: FindPlansResponse): unknown { const obj: any = {}; if (message.plans) { obj.plans = message.plans.map((e) => (e ? Plan.toJSON(e) : undefined)); } else { obj.plans = []; } return obj; }, }; export const ReadStripePlanRequest = { encode( message: ReadStripePlanRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): ReadStripePlanRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseReadStripePlanRequest, ) as ReadStripePlanRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadStripePlanRequest { const message = Object.create( baseReadStripePlanRequest, ) as ReadStripePlanRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial( object: DeepPartial<ReadStripePlanRequest>, ): ReadStripePlanRequest { const message = Object.create( baseReadStripePlanRequest, ) as ReadStripePlanRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: ReadStripePlanRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const ReadStripePlanResponse = { encode( message: ReadStripePlanResponse, writer: Writer = Writer.create(), ): Writer { if (message.plan !== undefined && message.plan !== undefined) { StripePlan.encode(message.plan, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): ReadStripePlanResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseReadStripePlanResponse, ) as ReadStripePlanResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.plan = StripePlan.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadStripePlanResponse { const message = Object.create( baseReadStripePlanResponse, ) as ReadStripePlanResponse; if (object.plan !== undefined && object.plan !== null) { message.plan = StripePlan.fromJSON(object.plan); } else { message.plan = undefined; } return message; }, fromPartial( object: DeepPartial<ReadStripePlanResponse>, ): ReadStripePlanResponse { const message = Object.create( baseReadStripePlanResponse, ) as ReadStripePlanResponse; if (object.plan !== undefined && object.plan !== null) { message.plan = StripePlan.fromPartial(object.plan); } else { message.plan = undefined; } return message; }, toJSON(message: ReadStripePlanResponse): unknown { const obj: any = {}; obj.plan = message.plan ? StripePlan.toJSON(message.plan) : undefined; return obj; }, }; export const FindStripePlansRequest = { encode( message: FindStripePlansRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.productId); return writer; }, decode(reader: Reader, length?: number): FindStripePlansRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseFindStripePlansRequest, ) as FindStripePlansRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.productId = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindStripePlansRequest { const message = Object.create( baseFindStripePlansRequest, ) as FindStripePlansRequest; if (object.productId !== undefined && object.productId !== null) { message.productId = String(object.productId); } else { message.productId = ''; } return message; }, fromPartial( object: DeepPartial<FindStripePlansRequest>, ): FindStripePlansRequest { const message = Object.create( baseFindStripePlansRequest, ) as FindStripePlansRequest; if (object.productId !== undefined && object.productId !== null) { message.productId = object.productId; } else { message.productId = ''; } return message; }, toJSON(message: FindStripePlansRequest): unknown { const obj: any = {}; obj.productId = message.productId || ''; return obj; }, }; export const FindStripePlansResponse = { encode( message: FindStripePlansResponse, writer: Writer = Writer.create(), ): Writer { for (const v of message.plans) { StripePlan.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): FindStripePlansResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseFindStripePlansResponse, ) as FindStripePlansResponse; message.plans = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.plans.push(StripePlan.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindStripePlansResponse { const message = Object.create( baseFindStripePlansResponse, ) as FindStripePlansResponse; message.plans = []; if (object.plans !== undefined && object.plans !== null) { for (const e of object.plans) { message.plans.push(StripePlan.fromJSON(e)); } } return message; }, fromPartial( object: DeepPartial<FindStripePlansResponse>, ): FindStripePlansResponse { const message = Object.create( baseFindStripePlansResponse, ) as FindStripePlansResponse; message.plans = []; if (object.plans !== undefined && object.plans !== null) { for (const e of object.plans) { message.plans.push(StripePlan.fromPartial(e)); } } return message; }, toJSON(message: FindStripePlansResponse): unknown { const obj: any = {}; if (message.plans) { obj.plans = message.plans.map((e) => e ? StripePlan.toJSON(e) : undefined, ); } else { obj.plans = []; } return obj; }, }; export const ReadInvoiceRequest = { encode( message: ReadInvoiceRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): ReadInvoiceRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseReadInvoiceRequest) as ReadInvoiceRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadInvoiceRequest { const message = Object.create(baseReadInvoiceRequest) as ReadInvoiceRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial(object: DeepPartial<ReadInvoiceRequest>): ReadInvoiceRequest { const message = Object.create(baseReadInvoiceRequest) as ReadInvoiceRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: ReadInvoiceRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const ReadInvoiceResponse = { encode( message: ReadInvoiceResponse, writer: Writer = Writer.create(), ): Writer { if (message.invoice !== undefined && message.invoice !== undefined) { Invoice.encode(message.invoice, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): ReadInvoiceResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseReadInvoiceResponse, ) as ReadInvoiceResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.invoice = Invoice.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadInvoiceResponse { const message = Object.create( baseReadInvoiceResponse, ) as ReadInvoiceResponse; if (object.invoice !== undefined && object.invoice !== null) { message.invoice = Invoice.fromJSON(object.invoice); } else { message.invoice = undefined; } return message; }, fromPartial(object: DeepPartial<ReadInvoiceResponse>): ReadInvoiceResponse { const message = Object.create( baseReadInvoiceResponse, ) as ReadInvoiceResponse; if (object.invoice !== undefined && object.invoice !== null) { message.invoice = Invoice.fromPartial(object.invoice); } else { message.invoice = undefined; } return message; }, toJSON(message: ReadInvoiceResponse): unknown { const obj: any = {}; obj.invoice = message.invoice ? Invoice.toJSON(message.invoice) : undefined; return obj; }, }; export const FindInvoicesRequest = { encode( message: FindInvoicesRequest, writer: Writer = Writer.create(), ): Writer { return writer; }, decode(reader: Reader, length?: number): FindInvoicesRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseFindInvoicesRequest, ) as FindInvoicesRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindInvoicesRequest { const message = Object.create( baseFindInvoicesRequest, ) as FindInvoicesRequest; return message; }, fromPartial(object: DeepPartial<FindInvoicesRequest>): FindInvoicesRequest { const message = Object.create( baseFindInvoicesRequest, ) as FindInvoicesRequest; return message; }, toJSON(message: FindInvoicesRequest): unknown { const obj: any = {}; return obj; }, }; export const FindInvoicesResponse = { encode( message: FindInvoicesResponse, writer: Writer = Writer.create(), ): Writer { for (const v of message.invoices) { Invoice.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): FindInvoicesResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseFindInvoicesResponse, ) as FindInvoicesResponse; message.invoices = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.invoices.push(Invoice.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindInvoicesResponse { const message = Object.create( baseFindInvoicesResponse, ) as FindInvoicesResponse; message.invoices = []; if (object.invoices !== undefined && object.invoices !== null) { for (const e of object.invoices) { message.invoices.push(Invoice.fromJSON(e)); } } return message; }, fromPartial(object: DeepPartial<FindInvoicesResponse>): FindInvoicesResponse { const message = Object.create( baseFindInvoicesResponse, ) as FindInvoicesResponse; message.invoices = []; if (object.invoices !== undefined && object.invoices !== null) { for (const e of object.invoices) { message.invoices.push(Invoice.fromPartial(e)); } } return message; }, toJSON(message: FindInvoicesResponse): unknown { const obj: any = {}; if (message.invoices) { obj.invoices = message.invoices.map((e) => e ? Invoice.toJSON(e) : undefined, ); } else { obj.invoices = []; } return obj; }, }; export const CreateSubscriptionRequest = { encode( message: CreateSubscriptionRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.customerId); writer.uint32(18).string(message.tenantId); writer.uint32(26).string(message.planId); writer.uint32(34).string(message.couponId); writer.uint32(42).string(message.cardId); return writer; }, decode(reader: Reader, length?: number): CreateSubscriptionRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseCreateSubscriptionRequest, ) as CreateSubscriptionRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.customerId = reader.string(); break; case 2: message.tenantId = reader.string(); break; case 3: message.planId = reader.string(); break; case 4: message.couponId = reader.string(); break; case 5: message.cardId = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreateSubscriptionRequest { const message = Object.create( baseCreateSubscriptionRequest, ) as CreateSubscriptionRequest; if (object.customerId !== undefined && object.customerId !== null) { message.customerId = String(object.customerId); } else { message.customerId = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = String(object.tenantId); } else { message.tenantId = ''; } if (object.planId !== undefined && object.planId !== null) { message.planId = String(object.planId); } else { message.planId = ''; } if (object.couponId !== undefined && object.couponId !== null) { message.couponId = String(object.couponId); } else { message.couponId = ''; } if (object.cardId !== undefined && object.cardId !== null) { message.cardId = String(object.cardId); } else { message.cardId = ''; } return message; }, fromPartial( object: DeepPartial<CreateSubscriptionRequest>, ): CreateSubscriptionRequest { const message = Object.create( baseCreateSubscriptionRequest, ) as CreateSubscriptionRequest; if (object.customerId !== undefined && object.customerId !== null) { message.customerId = object.customerId; } else { message.customerId = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = object.tenantId; } else { message.tenantId = ''; } if (object.planId !== undefined && object.planId !== null) { message.planId = object.planId; } else { message.planId = ''; } if (object.couponId !== undefined && object.couponId !== null) { message.couponId = object.couponId; } else { message.couponId = ''; } if (object.cardId !== undefined && object.cardId !== null) { message.cardId = object.cardId; } else { message.cardId = ''; } return message; }, toJSON(message: CreateSubscriptionRequest): unknown { const obj: any = {}; obj.customerId = message.customerId || ''; obj.tenantId = message.tenantId || ''; obj.planId = message.planId || ''; obj.couponId = message.couponId || ''; obj.cardId = message.cardId || ''; return obj; }, }; export const CreateSubscriptionResponse = { encode( message: CreateSubscriptionResponse, writer: Writer = Writer.create(), ): Writer { if ( message.subscription !== undefined && message.subscription !== undefined ) { TenantSubscription.encode( message.subscription, writer.uint32(10).fork(), ).ldelim(); } return writer; }, decode(reader: Reader, length?: number): CreateSubscriptionResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseCreateSubscriptionResponse, ) as CreateSubscriptionResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.subscription = TenantSubscription.decode( reader, reader.uint32(), ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreateSubscriptionResponse { const message = Object.create( baseCreateSubscriptionResponse, ) as CreateSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromJSON(object.subscription); } else { message.subscription = undefined; } return message; }, fromPartial( object: DeepPartial<CreateSubscriptionResponse>, ): CreateSubscriptionResponse { const message = Object.create( baseCreateSubscriptionResponse, ) as CreateSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromPartial( object.subscription, ); } else { message.subscription = undefined; } return message; }, toJSON(message: CreateSubscriptionResponse): unknown { const obj: any = {}; obj.subscription = message.subscription ? TenantSubscription.toJSON(message.subscription) : undefined; return obj; }, }; export const ChangeSubscriptionRequest = { encode( message: ChangeSubscriptionRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.customerId); writer.uint32(18).string(message.tenantId); writer.uint32(26).string(message.planId); writer.uint32(34).string(message.couponId); return writer; }, decode(reader: Reader, length?: number): ChangeSubscriptionRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseChangeSubscriptionRequest, ) as ChangeSubscriptionRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.customerId = reader.string(); break; case 2: message.tenantId = reader.string(); break; case 3: message.planId = reader.string(); break; case 4: message.couponId = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChangeSubscriptionRequest { const message = Object.create( baseChangeSubscriptionRequest, ) as ChangeSubscriptionRequest; if (object.customerId !== undefined && object.customerId !== null) { message.customerId = String(object.customerId); } else { message.customerId = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = String(object.tenantId); } else { message.tenantId = ''; } if (object.planId !== undefined && object.planId !== null) { message.planId = String(object.planId); } else { message.planId = ''; } if (object.couponId !== undefined && object.couponId !== null) { message.couponId = String(object.couponId); } else { message.couponId = ''; } return message; }, fromPartial( object: DeepPartial<ChangeSubscriptionRequest>, ): ChangeSubscriptionRequest { const message = Object.create( baseChangeSubscriptionRequest, ) as ChangeSubscriptionRequest; if (object.customerId !== undefined && object.customerId !== null) { message.customerId = object.customerId; } else { message.customerId = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = object.tenantId; } else { message.tenantId = ''; } if (object.planId !== undefined && object.planId !== null) { message.planId = object.planId; } else { message.planId = ''; } if (object.couponId !== undefined && object.couponId !== null) { message.couponId = object.couponId; } else { message.couponId = ''; } return message; }, toJSON(message: ChangeSubscriptionRequest): unknown { const obj: any = {}; obj.customerId = message.customerId || ''; obj.tenantId = message.tenantId || ''; obj.planId = message.planId || ''; obj.couponId = message.couponId || ''; return obj; }, }; export const ChangeSubscriptionResponse = { encode( message: ChangeSubscriptionResponse, writer: Writer = Writer.create(), ): Writer { if ( message.subscription !== undefined && message.subscription !== undefined ) { TenantSubscription.encode( message.subscription, writer.uint32(10).fork(), ).ldelim(); } return writer; }, decode(reader: Reader, length?: number): ChangeSubscriptionResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseChangeSubscriptionResponse, ) as ChangeSubscriptionResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.subscription = TenantSubscription.decode( reader, reader.uint32(), ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChangeSubscriptionResponse { const message = Object.create( baseChangeSubscriptionResponse, ) as ChangeSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromJSON(object.subscription); } else { message.subscription = undefined; } return message; }, fromPartial( object: DeepPartial<ChangeSubscriptionResponse>, ): ChangeSubscriptionResponse { const message = Object.create( baseChangeSubscriptionResponse, ) as ChangeSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromPartial( object.subscription, ); } else { message.subscription = undefined; } return message; }, toJSON(message: ChangeSubscriptionResponse): unknown { const obj: any = {}; obj.subscription = message.subscription ? TenantSubscription.toJSON(message.subscription) : undefined; return obj; }, }; export const CancelSubscriptionRequest = { encode( message: CancelSubscriptionRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.customerId); writer.uint32(18).string(message.tenantId); return writer; }, decode(reader: Reader, length?: number): CancelSubscriptionRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseCancelSubscriptionRequest, ) as CancelSubscriptionRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.customerId = reader.string(); break; case 2: message.tenantId = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CancelSubscriptionRequest { const message = Object.create( baseCancelSubscriptionRequest, ) as CancelSubscriptionRequest; if (object.customerId !== undefined && object.customerId !== null) { message.customerId = String(object.customerId); } else { message.customerId = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = String(object.tenantId); } else { message.tenantId = ''; } return message; }, fromPartial( object: DeepPartial<CancelSubscriptionRequest>, ): CancelSubscriptionRequest { const message = Object.create( baseCancelSubscriptionRequest, ) as CancelSubscriptionRequest; if (object.customerId !== undefined && object.customerId !== null) { message.customerId = object.customerId; } else { message.customerId = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = object.tenantId; } else { message.tenantId = ''; } return message; }, toJSON(message: CancelSubscriptionRequest): unknown { const obj: any = {}; obj.customerId = message.customerId || ''; obj.tenantId = message.tenantId || ''; return obj; }, }; export const CancelSubscriptionResponse = { encode( message: CancelSubscriptionResponse, writer: Writer = Writer.create(), ): Writer { if ( message.subscription !== undefined && message.subscription !== undefined ) { TenantSubscription.encode( message.subscription, writer.uint32(10).fork(), ).ldelim(); } return writer; }, decode(reader: Reader, length?: number): CancelSubscriptionResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseCancelSubscriptionResponse, ) as CancelSubscriptionResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.subscription = TenantSubscription.decode( reader, reader.uint32(), ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CancelSubscriptionResponse { const message = Object.create( baseCancelSubscriptionResponse, ) as CancelSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromJSON(object.subscription); } else { message.subscription = undefined; } return message; }, fromPartial( object: DeepPartial<CancelSubscriptionResponse>, ): CancelSubscriptionResponse { const message = Object.create( baseCancelSubscriptionResponse, ) as CancelSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromPartial( object.subscription, ); } else { message.subscription = undefined; } return message; }, toJSON(message: CancelSubscriptionResponse): unknown { const obj: any = {}; obj.subscription = message.subscription ? TenantSubscription.toJSON(message.subscription) : undefined; return obj; }, }; export const ReadSubscriptionRequest = { encode( message: ReadSubscriptionRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.id); writer.uint32(18).string(message.tenantId); return writer; }, decode(reader: Reader, length?: number): ReadSubscriptionRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseReadSubscriptionRequest, ) as ReadSubscriptionRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.tenantId = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadSubscriptionRequest { const message = Object.create( baseReadSubscriptionRequest, ) as ReadSubscriptionRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = String(object.tenantId); } else { message.tenantId = ''; } return message; }, fromPartial( object: DeepPartial<ReadSubscriptionRequest>, ): ReadSubscriptionRequest { const message = Object.create( baseReadSubscriptionRequest, ) as ReadSubscriptionRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = object.tenantId; } else { message.tenantId = ''; } return message; }, toJSON(message: ReadSubscriptionRequest): unknown { const obj: any = {}; obj.id = message.id || ''; obj.tenantId = message.tenantId || ''; return obj; }, }; export const ReadSubscriptionResponse = { encode( message: ReadSubscriptionResponse, writer: Writer = Writer.create(), ): Writer { if ( message.subscription !== undefined && message.subscription !== undefined ) { TenantSubscription.encode( message.subscription, writer.uint32(10).fork(), ).ldelim(); } return writer; }, decode(reader: Reader, length?: number): ReadSubscriptionResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseReadSubscriptionResponse, ) as ReadSubscriptionResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.subscription = TenantSubscription.decode( reader, reader.uint32(), ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadSubscriptionResponse { const message = Object.create( baseReadSubscriptionResponse, ) as ReadSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromJSON(object.subscription); } else { message.subscription = undefined; } return message; }, fromPartial( object: DeepPartial<ReadSubscriptionResponse>, ): ReadSubscriptionResponse { const message = Object.create( baseReadSubscriptionResponse, ) as ReadSubscriptionResponse; if (object.subscription !== undefined && object.subscription !== null) { message.subscription = TenantSubscription.fromPartial( object.subscription, ); } else { message.subscription = undefined; } return message; }, toJSON(message: ReadSubscriptionResponse): unknown { const obj: any = {}; obj.subscription = message.subscription ? TenantSubscription.toJSON(message.subscription) : undefined; return obj; }, }; export const FindSubscriptionsRequest = { encode( message: FindSubscriptionsRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.tenantId); return writer; }, decode(reader: Reader, length?: number): FindSubscriptionsRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseFindSubscriptionsRequest, ) as FindSubscriptionsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tenantId = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindSubscriptionsRequest { const message = Object.create( baseFindSubscriptionsRequest, ) as FindSubscriptionsRequest; if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = String(object.tenantId); } else { message.tenantId = ''; } return message; }, fromPartial( object: DeepPartial<FindSubscriptionsRequest>, ): FindSubscriptionsRequest { const message = Object.create( baseFindSubscriptionsRequest, ) as FindSubscriptionsRequest; if (object.tenantId !== undefined && object.tenantId !== null) { message.tenantId = object.tenantId; } else { message.tenantId = ''; } return message; }, toJSON(message: FindSubscriptionsRequest): unknown { const obj: any = {}; obj.tenantId = message.tenantId || ''; return obj; }, }; export const FindSubscriptionsResponse = { encode( message: FindSubscriptionsResponse, writer: Writer = Writer.create(), ): Writer { for (const v of message.subscriptions) { TenantSubscription.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): FindSubscriptionsResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseFindSubscriptionsResponse, ) as FindSubscriptionsResponse; message.subscriptions = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.subscriptions.push( TenantSubscription.decode(reader, reader.uint32()), ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindSubscriptionsResponse { const message = Object.create( baseFindSubscriptionsResponse, ) as FindSubscriptionsResponse; message.subscriptions = []; if (object.subscriptions !== undefined && object.subscriptions !== null) { for (const e of object.subscriptions) { message.subscriptions.push(TenantSubscription.fromJSON(e)); } } return message; }, fromPartial( object: DeepPartial<FindSubscriptionsResponse>, ): FindSubscriptionsResponse { const message = Object.create( baseFindSubscriptionsResponse, ) as FindSubscriptionsResponse; message.subscriptions = []; if (object.subscriptions !== undefined && object.subscriptions !== null) { for (const e of object.subscriptions) { message.subscriptions.push(TenantSubscription.fromPartial(e)); } } return message; }, toJSON(message: FindSubscriptionsResponse): unknown { const obj: any = {}; if (message.subscriptions) { obj.subscriptions = message.subscriptions.map((e) => e ? TenantSubscription.toJSON(e) : undefined, ); } else { obj.subscriptions = []; } return obj; }, }; export const CreateCardRequest = { encode(message: CreateCardRequest, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.name); writer.uint32(18).string(message.cvc); writer.uint32(26).string(message.number); writer.uint32(34).string(message.currency); writer.uint32(66).string(message.expMonth); writer.uint32(74).string(message.expYear); if (message.address !== undefined && message.address !== undefined) { Address.encode(message.address, writer.uint32(82).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): CreateCardRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseCreateCardRequest) as CreateCardRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.cvc = reader.string(); break; case 3: message.number = reader.string(); break; case 4: message.currency = reader.string(); break; case 8: message.expMonth = reader.string(); break; case 9: message.expYear = reader.string(); break; case 10: message.address = Address.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreateCardRequest { const message = Object.create(baseCreateCardRequest) as CreateCardRequest; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.cvc !== undefined && object.cvc !== null) { message.cvc = String(object.cvc); } else { message.cvc = ''; } if (object.number !== undefined && object.number !== null) { message.number = String(object.number); } else { message.number = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = String(object.currency); } else { message.currency = ''; } if (object.expMonth !== undefined && object.expMonth !== null) { message.expMonth = String(object.expMonth); } else { message.expMonth = ''; } if (object.expYear !== undefined && object.expYear !== null) { message.expYear = String(object.expYear); } else { message.expYear = ''; } if (object.address !== undefined && object.address !== null) { message.address = Address.fromJSON(object.address); } else { message.address = undefined; } return message; }, fromPartial(object: DeepPartial<CreateCardRequest>): CreateCardRequest { const message = Object.create(baseCreateCardRequest) as CreateCardRequest; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.cvc !== undefined && object.cvc !== null) { message.cvc = object.cvc; } else { message.cvc = ''; } if (object.number !== undefined && object.number !== null) { message.number = object.number; } else { message.number = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = object.currency; } else { message.currency = ''; } if (object.expMonth !== undefined && object.expMonth !== null) { message.expMonth = object.expMonth; } else { message.expMonth = ''; } if (object.expYear !== undefined && object.expYear !== null) { message.expYear = object.expYear; } else { message.expYear = ''; } if (object.address !== undefined && object.address !== null) { message.address = Address.fromPartial(object.address); } else { message.address = undefined; } return message; }, toJSON(message: CreateCardRequest): unknown { const obj: any = {}; obj.name = message.name || ''; obj.cvc = message.cvc || ''; obj.number = message.number || ''; obj.currency = message.currency || ''; obj.expMonth = message.expMonth || ''; obj.expYear = message.expYear || ''; obj.address = message.address ? Address.toJSON(message.address) : undefined; return obj; }, }; export const CreateCardResponse = { encode( message: CreateCardResponse, writer: Writer = Writer.create(), ): Writer { if (message.card !== undefined && message.card !== undefined) { Card.encode(message.card, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): CreateCardResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseCreateCardResponse) as CreateCardResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.card = Card.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreateCardResponse { const message = Object.create(baseCreateCardResponse) as CreateCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromJSON(object.card); } else { message.card = undefined; } return message; }, fromPartial(object: DeepPartial<CreateCardResponse>): CreateCardResponse { const message = Object.create(baseCreateCardResponse) as CreateCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromPartial(object.card); } else { message.card = undefined; } return message; }, toJSON(message: CreateCardResponse): unknown { const obj: any = {}; obj.card = message.card ? Card.toJSON(message.card) : undefined; return obj; }, }; export const SetDefaultCardRequest = { encode( message: SetDefaultCardRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): SetDefaultCardRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseSetDefaultCardRequest, ) as SetDefaultCardRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SetDefaultCardRequest { const message = Object.create( baseSetDefaultCardRequest, ) as SetDefaultCardRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial( object: DeepPartial<SetDefaultCardRequest>, ): SetDefaultCardRequest { const message = Object.create( baseSetDefaultCardRequest, ) as SetDefaultCardRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: SetDefaultCardRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const SetDefaultCardResponse = { encode( message: SetDefaultCardResponse, writer: Writer = Writer.create(), ): Writer { if (message.card !== undefined && message.card !== undefined) { Card.encode(message.card, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): SetDefaultCardResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseSetDefaultCardResponse, ) as SetDefaultCardResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.card = Card.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SetDefaultCardResponse { const message = Object.create( baseSetDefaultCardResponse, ) as SetDefaultCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromJSON(object.card); } else { message.card = undefined; } return message; }, fromPartial( object: DeepPartial<SetDefaultCardResponse>, ): SetDefaultCardResponse { const message = Object.create( baseSetDefaultCardResponse, ) as SetDefaultCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromPartial(object.card); } else { message.card = undefined; } return message; }, toJSON(message: SetDefaultCardResponse): unknown { const obj: any = {}; obj.card = message.card ? Card.toJSON(message.card) : undefined; return obj; }, }; export const DeleteCardRequest = { encode(message: DeleteCardRequest, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): DeleteCardRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseDeleteCardRequest) as DeleteCardRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteCardRequest { const message = Object.create(baseDeleteCardRequest) as DeleteCardRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial(object: DeepPartial<DeleteCardRequest>): DeleteCardRequest { const message = Object.create(baseDeleteCardRequest) as DeleteCardRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: DeleteCardRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const DeleteCardResponse = { encode( message: DeleteCardResponse, writer: Writer = Writer.create(), ): Writer { if (message.card !== undefined && message.card !== undefined) { Card.encode(message.card, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): DeleteCardResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseDeleteCardResponse) as DeleteCardResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.card = Card.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteCardResponse { const message = Object.create(baseDeleteCardResponse) as DeleteCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromJSON(object.card); } else { message.card = undefined; } return message; }, fromPartial(object: DeepPartial<DeleteCardResponse>): DeleteCardResponse { const message = Object.create(baseDeleteCardResponse) as DeleteCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromPartial(object.card); } else { message.card = undefined; } return message; }, toJSON(message: DeleteCardResponse): unknown { const obj: any = {}; obj.card = message.card ? Card.toJSON(message.card) : undefined; return obj; }, }; export const ReadCardRequest = { encode(message: ReadCardRequest, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): ReadCardRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseReadCardRequest) as ReadCardRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadCardRequest { const message = Object.create(baseReadCardRequest) as ReadCardRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial(object: DeepPartial<ReadCardRequest>): ReadCardRequest { const message = Object.create(baseReadCardRequest) as ReadCardRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: ReadCardRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const ReadCardResponse = { encode(message: ReadCardResponse, writer: Writer = Writer.create()): Writer { if (message.card !== undefined && message.card !== undefined) { Card.encode(message.card, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): ReadCardResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseReadCardResponse) as ReadCardResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.card = Card.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadCardResponse { const message = Object.create(baseReadCardResponse) as ReadCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromJSON(object.card); } else { message.card = undefined; } return message; }, fromPartial(object: DeepPartial<ReadCardResponse>): ReadCardResponse { const message = Object.create(baseReadCardResponse) as ReadCardResponse; if (object.card !== undefined && object.card !== null) { message.card = Card.fromPartial(object.card); } else { message.card = undefined; } return message; }, toJSON(message: ReadCardResponse): unknown { const obj: any = {}; obj.card = message.card ? Card.toJSON(message.card) : undefined; return obj; }, }; export const FindCardsRequest = { encode(message: FindCardsRequest, writer: Writer = Writer.create()): Writer { return writer; }, decode(reader: Reader, length?: number): FindCardsRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseFindCardsRequest) as FindCardsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindCardsRequest { const message = Object.create(baseFindCardsRequest) as FindCardsRequest; return message; }, fromPartial(object: DeepPartial<FindCardsRequest>): FindCardsRequest { const message = Object.create(baseFindCardsRequest) as FindCardsRequest; return message; }, toJSON(message: FindCardsRequest): unknown { const obj: any = {}; return obj; }, }; export const FindCardsResponse = { encode(message: FindCardsResponse, writer: Writer = Writer.create()): Writer { for (const v of message.cards) { Card.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): FindCardsResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseFindCardsResponse) as FindCardsResponse; message.cards = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.cards.push(Card.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FindCardsResponse { const message = Object.create(baseFindCardsResponse) as FindCardsResponse; message.cards = []; if (object.cards !== undefined && object.cards !== null) { for (const e of object.cards) { message.cards.push(Card.fromJSON(e)); } } return message; }, fromPartial(object: DeepPartial<FindCardsResponse>): FindCardsResponse { const message = Object.create(baseFindCardsResponse) as FindCardsResponse; message.cards = []; if (object.cards !== undefined && object.cards !== null) { for (const e of object.cards) { message.cards.push(Card.fromPartial(e)); } } return message; }, toJSON(message: FindCardsResponse): unknown { const obj: any = {}; if (message.cards) { obj.cards = message.cards.map((e) => (e ? Card.toJSON(e) : undefined)); } else { obj.cards = []; } return obj; }, }; export const CreateCustomerRequest = { encode( message: CreateCustomerRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.name); writer.uint32(18).string(message.email); writer.uint32(26).string(message.number); writer.uint32(34).string(message.currency); return writer; }, decode(reader: Reader, length?: number): CreateCustomerRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseCreateCustomerRequest, ) as CreateCustomerRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.email = reader.string(); break; case 3: message.number = reader.string(); break; case 4: message.currency = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreateCustomerRequest { const message = Object.create( baseCreateCustomerRequest, ) as CreateCustomerRequest; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } else { message.name = ''; } if (object.email !== undefined && object.email !== null) { message.email = String(object.email); } else { message.email = ''; } if (object.number !== undefined && object.number !== null) { message.number = String(object.number); } else { message.number = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = String(object.currency); } else { message.currency = ''; } return message; }, fromPartial( object: DeepPartial<CreateCustomerRequest>, ): CreateCustomerRequest { const message = Object.create( baseCreateCustomerRequest, ) as CreateCustomerRequest; if (object.name !== undefined && object.name !== null) { message.name = object.name; } else { message.name = ''; } if (object.email !== undefined && object.email !== null) { message.email = object.email; } else { message.email = ''; } if (object.number !== undefined && object.number !== null) { message.number = object.number; } else { message.number = ''; } if (object.currency !== undefined && object.currency !== null) { message.currency = object.currency; } else { message.currency = ''; } return message; }, toJSON(message: CreateCustomerRequest): unknown { const obj: any = {}; obj.name = message.name || ''; obj.email = message.email || ''; obj.number = message.number || ''; obj.currency = message.currency || ''; return obj; }, }; export const CreateCustomerResponse = { encode( message: CreateCustomerResponse, writer: Writer = Writer.create(), ): Writer { if (message.customer !== undefined && message.customer !== undefined) { Customer.encode(message.customer, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): CreateCustomerResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseCreateCustomerResponse, ) as CreateCustomerResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.customer = Customer.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreateCustomerResponse { const message = Object.create( baseCreateCustomerResponse, ) as CreateCustomerResponse; if (object.customer !== undefined && object.customer !== null) { message.customer = Customer.fromJSON(object.customer); } else { message.customer = undefined; } return message; }, fromPartial( object: DeepPartial<CreateCustomerResponse>, ): CreateCustomerResponse { const message = Object.create( baseCreateCustomerResponse, ) as CreateCustomerResponse; if (object.customer !== undefined && object.customer !== null) { message.customer = Customer.fromPartial(object.customer); } else { message.customer = undefined; } return message; }, toJSON(message: CreateCustomerResponse): unknown { const obj: any = {}; obj.customer = message.customer ? Customer.toJSON(message.customer) : undefined; return obj; }, }; export const DeleteCustomerRequest = { encode( message: DeleteCustomerRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): DeleteCustomerRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseDeleteCustomerRequest, ) as DeleteCustomerRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteCustomerRequest { const message = Object.create( baseDeleteCustomerRequest, ) as DeleteCustomerRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial( object: DeepPartial<DeleteCustomerRequest>, ): DeleteCustomerRequest { const message = Object.create( baseDeleteCustomerRequest, ) as DeleteCustomerRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: DeleteCustomerRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const DeleteCustomerResponse = { encode( message: DeleteCustomerResponse, writer: Writer = Writer.create(), ): Writer { if (message.customer !== undefined && message.customer !== undefined) { Customer.encode(message.customer, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): DeleteCustomerResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseDeleteCustomerResponse, ) as DeleteCustomerResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.customer = Customer.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteCustomerResponse { const message = Object.create( baseDeleteCustomerResponse, ) as DeleteCustomerResponse; if (object.customer !== undefined && object.customer !== null) { message.customer = Customer.fromJSON(object.customer); } else { message.customer = undefined; } return message; }, fromPartial( object: DeepPartial<DeleteCustomerResponse>, ): DeleteCustomerResponse { const message = Object.create( baseDeleteCustomerResponse, ) as DeleteCustomerResponse; if (object.customer !== undefined && object.customer !== null) { message.customer = Customer.fromPartial(object.customer); } else { message.customer = undefined; } return message; }, toJSON(message: DeleteCustomerResponse): unknown { const obj: any = {}; obj.customer = message.customer ? Customer.toJSON(message.customer) : undefined; return obj; }, }; export const ReadCustomerRequest = { encode( message: ReadCustomerRequest, writer: Writer = Writer.create(), ): Writer { writer.uint32(10).string(message.id); return writer; }, decode(reader: Reader, length?: number): ReadCustomerRequest { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseReadCustomerRequest, ) as ReadCustomerRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadCustomerRequest { const message = Object.create( baseReadCustomerRequest, ) as ReadCustomerRequest; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } return message; }, fromPartial(object: DeepPartial<ReadCustomerRequest>): ReadCustomerRequest { const message = Object.create( baseReadCustomerRequest, ) as ReadCustomerRequest; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } return message; }, toJSON(message: ReadCustomerRequest): unknown { const obj: any = {}; obj.id = message.id || ''; return obj; }, }; export const ReadCustomerResponse = { encode( message: ReadCustomerResponse, writer: Writer = Writer.create(), ): Writer { if (message.customer !== undefined && message.customer !== undefined) { Customer.encode(message.customer, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(reader: Reader, length?: number): ReadCustomerResponse { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create( baseReadCustomerResponse, ) as ReadCustomerResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.customer = Customer.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadCustomerResponse { const message = Object.create( baseReadCustomerResponse, ) as ReadCustomerResponse; if (object.customer !== undefined && object.customer !== null) { message.customer = Customer.fromJSON(object.customer); } else { message.customer = undefined; } return message; }, fromPartial(object: DeepPartial<ReadCustomerResponse>): ReadCustomerResponse { const message = Object.create( baseReadCustomerResponse, ) as ReadCustomerResponse; if (object.customer !== undefined && object.customer !== null) { message.customer = Customer.fromPartial(object.customer); } else { message.customer = undefined; } return message; }, toJSON(message: ReadCustomerResponse): unknown { const obj: any = {}; obj.customer = message.customer ? Customer.toJSON(message.customer) : undefined; return obj; }, }; export const Message = { encode(message: Message, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.say); return writer; }, decode(reader: Reader, length?: number): Message { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseMessage) as Message; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.say = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Message { const message = Object.create(baseMessage) as Message; if (object.say !== undefined && object.say !== null) { message.say = String(object.say); } else { message.say = ''; } return message; }, fromPartial(object: DeepPartial<Message>): Message { const message = Object.create(baseMessage) as Message; if (object.say !== undefined && object.say !== null) { message.say = object.say; } else { message.say = ''; } return message; }, toJSON(message: Message): unknown { const obj: any = {}; obj.say = message.say || ''; return obj; }, }; export const Event = { encode(message: Event, writer: Writer = Writer.create()): Writer { writer.uint32(10).string(message.id); writer.uint32(16).int32(message.timestamp); writer.uint32(26).string(message.message); writer.uint32(34).string(message.topic); return writer; }, decode(reader: Reader, length?: number): Event { let end = length === undefined ? reader.len : reader.pos + length; const message = Object.create(baseEvent) as Event; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.timestamp = reader.int32(); break; case 3: message.message = reader.string(); break; case 4: message.topic = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Event { const message = Object.create(baseEvent) as Event; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } else { message.id = ''; } if (object.timestamp !== undefined && object.timestamp !== null) { message.timestamp = Number(object.timestamp); } else { message.timestamp = 0; } if (object.message !== undefined && object.message !== null) { message.message = String(object.message); } else { message.message = ''; } if (object.topic !== undefined && object.topic !== null) { message.topic = String(object.topic); } else { message.topic = ''; } return message; }, fromPartial(object: DeepPartial<Event>): Event { const message = Object.create(baseEvent) as Event; if (object.id !== undefined && object.id !== null) { message.id = object.id; } else { message.id = ''; } if (object.timestamp !== undefined && object.timestamp !== null) { message.timestamp = object.timestamp; } else { message.timestamp = 0; } if (object.message !== undefined && object.message !== null) { message.message = object.message; } else { message.message = ''; } if (object.topic !== undefined && object.topic !== null) { message.topic = object.topic; } else { message.topic = ''; } return message; }, toJSON(message: Event): unknown { const obj: any = {}; obj.id = message.id || ''; obj.timestamp = message.timestamp || 0; obj.message = message.message || ''; obj.topic = message.topic || ''; return obj; }, }; type DeepPartial<T> = { [P in keyof T]?: T[P] extends Array<infer U> ? Array<DeepPartial<U>> : T[P] extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T[P] extends Date | Function | Uint8Array | undefined ? T[P] : T[P] extends infer U | undefined ? DeepPartial<U> : T[P] extends object ? DeepPartial<T[P]> : T[P]; };
the_stack
import React from 'react'; /** * 'JSON path' from root of a state object to a nested property. * Return type of [StateMethod.path](#readonly-path). * * For example, an object `{ a: [{ b: 1 }, { 1000: 'value' }, '3rd'] }`, * has got the following paths pointing to existing properties: * * - `[]` * - `['a']` * - `['a', 0]` * - `['a', 0, 'b']` * - `['a', 1]` * - `['a', 1, 1000]` * - `['a', 2]` */ export declare type Path = ReadonlyArray<string | number>; /** * Type of an argument of [StateMethods.set](#set). * * @typeparam S Type of a value of a state */ export declare type SetStateAction<S> = (S | Promise<S>) | ((prevState: S) => (S | Promise<S>)); /** * Type of an argument of [StateMethods.merge](#merge). * * @typeparam S Type of a value of a state */ export declare type SetPartialStateAction<S> = S extends ReadonlyArray<(infer U)> ? ReadonlyArray<U> | Record<number, U> | ((prevValue: S) => (ReadonlyArray<U> | Record<number, U>)) : S extends object | string ? Partial<S> | ((prevValue: S) => Partial<S>) : React.SetStateAction<S>; /** * Type of an argument of [createState](#createstate) and [useState](#usestate). * * @typeparam S Type of a value of a state */ export declare type SetInitialStateAction<S> = S | Promise<S> | (() => S | Promise<S>); /** * Special symbol which might be returned by onPromised callback of [StateMethods.map](#map) function. * * [Learn more...](https://hookstate.js.org/docs/asynchronous-state#executing-an-action-when-state-is-loaded) */ export declare const postpone: unique symbol; /** * Special symbol which might be used to delete properties * from an object calling [StateMethods.set](#set) or [StateMethods.merge](#merge). * * [Learn more...](https://hookstate.js.org/docs/nested-state#deleting-existing-element) */ export declare const none: any; /** * Return type of [StateMethods.keys](#readonly-keys). * * @typeparam S Type of a value of a state */ export declare type InferredStateKeysType<S> = S extends ReadonlyArray<infer _> ? ReadonlyArray<number> : S extends null ? undefined : S extends object ? ReadonlyArray<keyof S> : undefined; /** * Return type of [StateMethods.map()](#map). * * @typeparam S Type of a value of a state */ export declare type InferredStateOrnullType<S> = S extends undefined ? undefined : S extends null ? null : State<S>; /** * For plugin developers only. * An instance to manipulate the state in more controlled way. * * @typeparam S Type of a value of a state * * [Learn more...](https://hookstate.js.org/docs/writing-plugin) */ export interface PluginStateControl<S> { /** * Get state value, but do not leave the traces of reading it. */ getUntracked(): S; /** * Set new state value, but do not trigger rerender. * * @param newValue new value to set to a state. */ setUntracked(newValue: SetStateAction<S>): Path[]; /** * Merge new state value, but do not trigger rerender. * * @param mergeValue new partial value to merge with the current state value and set. */ mergeUntracked(mergeValue: SetPartialStateAction<S>): Path[]; /** * Trigger rerender for hooked states, where values at the specified paths are used. * * @param paths paths of the state variables to search for being used by components and rerender */ rerender(paths: Path[]): void; } /** * An interface to manage a state in Hookstate. * * @typeparam S Type of a value of a state */ export interface StateMethods<S> { /** * 'Javascript' object 'path' to an element relative to the root object * in the state. For example: * * ```tsx * const state = useState([{ name: 'First Task' }]) * state.path IS [] * state[0].path IS [0] * state.[0].name.path IS [0, 'name'] * ``` */ readonly path: Path; /** * Return the keys of nested states. * For a given state of [State](#state) type, * `state.keys` will be structurally equal to Object.keys(state), * with two minor difference: * 1. if `state.value` is an array, the returned result will be * an array of numbers, not strings like with `Object.keys`. * 2. if `state.value` is not an object, the returned result will be undefined. */ readonly keys: InferredStateKeysType<S>; /** * Unwraps and returns the underlying state value referred by * [path](#readonly-path) of this state instance. * * It returns the same result as [StateMethods.get](#get) method. * * This property is more useful than [get](#get) method for the cases, * when a value may hold null or undefined values. * Typescript compiler does not handle elimination of undefined with get(), * like in the following examples, but value does: * * ```tsx * const state = useState<number | undefined>(0) * const myvalue: number = state.value * ? state.value + 1 * : 0; // <-- compiles * const myvalue: number = state.get() * ? state.get() + 1 * : 0; // <-- does not compile * ``` */ readonly value: S; /** * True if state value is not yet available (eg. equal to a promise) */ readonly promised: boolean; /** * If a state was set to a promise and the promise was rejected, * this property will return the error captured from the promise rejection */ readonly error: StateErrorAtRoot | undefined; /** * Unwraps and returns the underlying state value referred by * [path](#readonly-path) of this state instance. * * It returns the same result as [StateMethods.value](#readonly-value) method. */ get(): S; /** * Sets new value for a state. * If `this.path === []`, * it is similar to the `setState` variable returned by `React.useState` hook. * If `this.path !== []`, it sets only the segment of the state value, pointed out by the path. * Unlike [merge](#merge) method, this method will not accept partial updates. * Partial updates can be also done by walking the nested states and setting those. * * @param newValue new value to set to a state. * It can be a value, a promise resolving to a value * (only if [this.path](#readonly-path) is `[]`), * or a function returning one of these. * The function receives the current state value as an argument. */ set(newValue: SetStateAction<S>): void; /** * Similarly to [set](#set) method updates state value. * * - If current state value is an object, it does partial update for the object. * - If state value is an array and the argument is an array too, * it concatenates the current value with the value of the argument and sets it to the state. * - If state value is an array and the `merge` argument is an object, * it does partial update for the current array value. * - If current state value is a string, it concatenates the current state * value with the argument converted to string and sets the result to the state. */ merge(newValue: SetPartialStateAction<S>): void; /** * Returns nested state by key. * `state.nested('myprop')` returns the same as `state.myprop` or `state['myprop']`, * but also works for properties, which names collide with names of state methods. * * [Learn more about nested states...](https://hookstate.js.org/docs/nested-state) * * @param key child property name or index */ nested<K extends keyof S>(key: K): State<S[K]>; /** * Runs the provided action callback with optimised re-rendering. * Updating state within a batch action does not trigger immediate rerendering. * Instead, all required rerendering is done once the batch is finished. * * [Learn more about batching...](https://hookstate.js.org/docs/performance-batched-updates * * @param action callback function to execute in a batch * * @param context custom user's value, which is passed to plugins */ batch<R, C>(action: (s: State<S>) => R, context?: Exclude<C, Function>): R; /** * If state value is null or undefined, returns state value. * Otherwise, it returns this state instance but * with null and undefined removed from the type parameter. * * [Learn more...](https://hookstate.js.org/docs/nullable-state) */ ornull: InferredStateOrnullType<S>; /** * Adds plugin to the state. * * [Learn more...](https://hookstate.js.org/docs/extensions-overview) */ attach(plugin: () => Plugin): State<S>; /** * For plugin developers only. * It is a method to get the instance of the previously attached plugin. * If a plugin has not been attached to a state, * it returns an Error as the first element. * A plugin may trhow an error to indicate that plugin has not been attached. * * [Learn more...](https://hookstate.js.org/docs/writing-plugin) */ attach(pluginId: symbol): [PluginCallbacks | Error, PluginStateControl<S>]; } /** * Mixin for the [StateMethods](#interfacesstatemethodsmd) for a [State](#state), * which can be destroyed by a client. */ export interface StateMethodsDestroy { /** * Destroys an instance of a state, so * it can clear the allocated native resources (if any) * and can not be used anymore after it has been destroyed. */ destroy(): void; } /** * Type of a result of [createState](#createstate) and [useState](#usestate) functions * * @typeparam S Type of a value of a state * * [Learn more about global states...](https://hookstate.js.org/docs/global-state) * [Learn more about local states...](https://hookstate.js.org/docs/local-state) * [Learn more about nested states...](https://hookstate.js.org/docs/nested-state) */ export declare type State<S> = StateMethods<S> & (S extends ReadonlyArray<(infer U)> ? ReadonlyArray<State<U>> : S extends object ? Omit<{ readonly [K in keyof Required<S>]: State<S[K]>; }, keyof StateMethods<S> | keyof StateMethodsDestroy> : {}); /** * For plugin developers only. * Type alias to highlight the places where we are dealing with root state value. * * @hidden * @ignore */ export declare type StateValueAtRoot = any; /** * For plugin developers only. * Type alias to highlight the places where we are dealing with nested state value. * * @hidden * @ignore */ export declare type StateValueAtPath = any; /** * For plugin developers only. * Type alias to highlight the places where we are dealing with state error. * * @hidden * @ignore */ export declare type StateErrorAtRoot = any; /** * For plugin developers only. * Type alias to highlight the places where we are dealing with context value. * * @hidden * @ignore */ export declare type AnyContext = any; /** * For plugin developers only. * PluginCallbacks.onSet argument type. */ export interface PluginCallbacksOnSetArgument { readonly path: Path; readonly state?: StateValueAtRoot; /** * **A note about previous values and merging:** * State values are muteable in Hookstate for performance reasons. This causes a side effect in the merge operation. * While merging, the previous state object is mutated as the desired changes are applied. This means the value of * `previous` will reflect the merged changes as well, matching the new `state` value rather than the previous * state value. As a result, the `previous` property is unreliable when merge is used. The * [merged](#optional-readonly-merged) property can be used to detect which values were merged in but it will not * inform you whether those values are different from the previous state. * * As a workaround, you can [batch state updates](https://hookstate.js.org/docs/performance-batched-updates) or * replace merge calls with the immutable-style set operation like so: * * ``` * state.set(p => { * let copy = p.clone(); /// here it is up to you to define how to clone the current state * copy.field = 'new value for field'; * delete copy.fieldToDelete; * return copy; * }) * ``` */ readonly previous?: StateValueAtPath; readonly value?: StateValueAtPath; readonly merged?: StateValueAtPath; } /** * For plugin developers only. * PluginCallbacks.onDestroy argument type. */ export interface PluginCallbacksOnDestroyArgument { readonly state?: StateValueAtRoot; } /** * For plugin developers only. * PluginCallbacks.onBatchStart/Finish argument type. */ export interface PluginCallbacksOnBatchArgument { readonly path: Path; readonly state?: StateValueAtRoot; readonly context?: AnyContext; } /** * For plugin developers only. * Set of callbacks, a plugin may subscribe to. * * [Learn more...](https://hookstate.js.org/docs/writing-plugin) */ export interface PluginCallbacks { readonly onSet?: (arg: PluginCallbacksOnSetArgument) => void; readonly onDestroy?: (arg: PluginCallbacksOnDestroyArgument) => void; readonly onBatchStart?: (arg: PluginCallbacksOnBatchArgument) => void; readonly onBatchFinish?: (arg: PluginCallbacksOnBatchArgument) => void; } /** * For plugin developers only. * Hookstate plugin specification and factory method. * * [Learn more...](https://hookstate.js.org/docs/writing-plugin) */ export interface Plugin { /** * Unique identifier of a plugin. */ readonly id: symbol; /** * Initializer for a plugin when it is attached for the first time. */ readonly init?: (state: State<StateValueAtRoot>) => PluginCallbacks; } /** * Creates new state and returns it. * * You can create as many global states as you need. * * When you the state is not needed anymore, * it should be destroyed by calling * `destroy()` method of the returned instance. * This is necessary for some plugins, * which allocate native resources, * like subscription to databases, broadcast channels, etc. * In most cases, a global state is used during * whole life time of an application and would not require * destruction. However, if you have got, for example, * a catalog of dynamically created and destroyed global states, * the states should be destroyed as advised above. * * @param initial Initial value of the state. * It can be a value OR a promise, * which asynchronously resolves to a value, * OR a function returning a value or a promise. * * @typeparam S Type of a value of the state * * @returns [State](#state) instance, * which can be used directly to get and set state value * outside of React components. * When you need to use the state in a functional `React` component, * pass the created state to [useState](#usestate) function and * use the returned result in the component's logic. */ export declare function createState<S>(initial: SetInitialStateAction<S>): State<S> & StateMethodsDestroy; /** * Enables a functional React component to use a state, * either created by [createState](#createstate) (*global* state) or * derived from another call to [useState](#usestate) (*scoped* state). * * The `useState` forces a component to rerender every time, when: * - a segment/part of the state data is updated *AND only if* * - this segment was **used** by the component during or after the latest rendering. * * For example, if the state value is `{ a: 1, b: 2 }` and * a component uses only `a` property of the state, it will rerender * only when the whole state object is updated or when `a` property is updated. * Setting the state value/property to the same value is also considered as an update. * * A component can use one or many states, * i.e. you may call `useState` multiple times for multiple states. * * The same state can be used by multiple different components. * * @param source a reference to the state to hook into * * The `useState` is a hook and should follow React's rules of hooks. * * @returns an instance of [State](#state), * which **must be** used within the component (during rendering * or in effects) or it's children. */ export declare function useState<S>(source: State<S>): State<S>; /** * This function enables a functional React component to use a state, * created per component by [useState](#usestate) (*local* state). * In this case `useState` behaves similarly to `React.useState`, * but the returned instance of [State](#state) * has got more features. * * When a state is used by only one component, and maybe it's children, * it is recommended to use *local* state instead of *global*, * which is created by [createState](#createstate). * * *Local* (per component) state is created when a component is mounted * and automatically destroyed when a component is unmounted. * * The same as with the usage of a *global* state, * `useState` forces a component to rerender when: * - a segment/part of the state data is updated *AND only if* * - this segment was **used** by the component during or after the latest rendering. * * You can use as many local states within the same component as you need. * * @param source An initial value state. * * @returns an instance of [State](#state), * which **must be** used within the component (during rendering * or in effects) or it's children. */ export declare function useState<S>(source: SetInitialStateAction<S>): State<S>; /** * Alias to [useState](#usestate) which provides a workaround * for [React 20613 bug](https://github.com/facebook/react/issues/20613) */ export declare function useHookstate<S>(source: State<S>): State<S>; /** * Alias to [useState](#usestate) which provides a workaround * for [React 20613 bug](https://github.com/facebook/react/issues/20613) */ export declare function useHookstate<S>(source: SetInitialStateAction<S>): State<S>; /** * Allows to use a state without defining a functional react component. * It can be also used in class-based React components. It is also * particularly useful for creating *scoped* states. * * [Learn more...](https://hookstate.js.org/docs/using-without-statehook) * * @typeparam S Type of a value of a state */ export declare function StateFragment<S>(props: { state: State<S>; children: (state: State<S>) => React.ReactElement; }): React.ReactElement; /** * Allows to use a state without defining a functional react component. * See more at [StateFragment](#statefragment) * * [Learn more...](https://hookstate.js.org/docs/using-without-statehook) * * @typeparam S Type of a value of a state */ export declare function StateFragment<S>(props: { state: SetInitialStateAction<S>; children: (state: State<S>) => React.ReactElement; }): React.ReactElement; /** * A plugin which allows to opt-out from usage of Javascript proxies for * state usage tracking. It is useful for performance tuning. * * [Learn more...](https://hookstate.js.org/docs/performance-managed-rendering#downgraded-plugin) */ export declare function Downgraded(): Plugin; /** * For plugin developers only. * Reserved plugin ID for developers tools extension. * * @hidden * @ignore */ export declare const DevToolsID: unique symbol; /** * Return type of [DevTools](#devtools). */ export interface DevToolsExtensions { /** * Assigns custom label to identify the state in the development tools * @param name label for development tools */ label(name: string): void; /** * Logs to the development tools */ log(str: string, data?: any): void; } /** * Returns access to the development tools for a given state. * Development tools are delivered as optional plugins. * You can activate development tools from `@hookstate/devtools`package, * for example. If no development tools are activated, * it returns an instance of dummy tools, which do nothing, when called. * * [Learn more...](https://hookstate.js.org/docs/devtools) * * @param state A state to relate to the extension. * * @returns Interface to interact with the development tools for a given state. * * @typeparam S Type of a value of a state */ export declare function DevTools<S>(state: State<S>): DevToolsExtensions;
the_stack
import {AjaxPoller} from "helpers/ajax_poller"; import {ApiResult} from "helpers/api_request_builder"; import {pipeline} from "helpers/utils"; import _ from "lodash"; import m from "mithril"; import Stream from "mithril/stream"; import {AbstractObjCache, ObjectCache} from "models/base/cache"; import {ConfigReposCRUD} from "models/config_repos/config_repos_crud"; import {DefinedStructures} from "models/config_repos/defined_structures"; import {ConfigRepo} from "models/config_repos/types"; import { baseUrlProvider, currentUrlOriginAndPath } from "models/server-configuration/base_url_provider"; import {SiteUrls} from "models/server-configuration/server_configuration"; import {Permissions, SupportedEntity} from "models/shared/permissions"; import {ExtensionTypeString} from "models/shared/plugin_infos_new/extension_type"; import {PluginInfos} from "models/shared/plugin_infos_new/plugin_info"; import {PluginInfoCRUD} from "models/shared/plugin_infos_new/plugin_info_crud"; import {AnchorVM, ScrollManager} from "views/components/anchor/anchor"; import * as Buttons from "views/components/buttons"; import {FlashMessage, MessageType} from "views/components/flash_message"; import {SearchField} from "views/components/forms/input_fields"; import {HeaderPanel} from "views/components/header_panel"; import {ConfigReposWidget} from "views/pages/config_repos/config_repos_widget"; import {ConfigRepoVM, WebhookUrlGenerator} from "views/pages/config_repos/config_repo_view_model"; import {NewConfigRepoModal} from "views/pages/config_repos/modals"; import {Page, PageState} from "views/pages/page"; import {AddOperation, FlashContainer, RequiresPluginInfos, SaveOperation} from "views/pages/page_operations"; import styles from "./config_repos/index.scss"; interface SearchOperation { unfilteredModels: Stream<ConfigRepoVM[]>; filteredModels: Stream<ConfigRepoVM[]>; searchText: Stream<string>; resourceAutocompleteHelper: Stream<Map<string, string[]>>; } type State = AddOperation<ConfigRepo> & SaveOperation & SearchOperation & RequiresPluginInfos & FlashContainer & WebhookUrlGenerator; // This instance will be shared with all config repo widgets and never changes const sm: ScrollManager = new AnchorVM(); class ConfigReposCache extends AbstractObjCache<ConfigRepo[]> { etag: Stream<string> = Stream(); autocompleteSuggestions = Stream(new Map<string, string[]>()); doFetch(resolve: (data: ConfigRepo[]) => void, reject: (error: string) => void) { ConfigReposCRUD.all(this.etag()).then((apiResult) => { if (304 === apiResult.getStatusCode()) { return resolve(this.contents()); } apiResult.do((successResponse) => { if (apiResult.getEtag()) { this.etag(apiResult.getEtag()!); } this.autocompleteSuggestions( _.reduce(successResponse.body.autoCompletion, (map, s) => { map.set(s.key, ["*"].concat(s.value)); return map; }, new Map<string, string[]>() ) ); resolve(successResponse.body.configRepos); }, errorResponse => { reject(errorResponse.body!); }); }); } markStale() { // don't dump the old contents, just allow overwrite } flushEtag() { this.etag = Stream(); } promise(): Promise<ConfigRepo[]> { this.invalidate(); return new Promise((res, rej) => { if (this.ready()) { // shouldn't get here because we just invalidated, but just in case return res(this.contents()); } this.prime(() => res(this.contents()), () => rej(this.failureReason())); }); } } export class ConfigReposPage extends Page<null, State> { cache = new ConfigReposCache(); resultCaches = new Map<string, ObjectCache<DefinedStructures>>(); siteUrls = Stream(new SiteUrls()); oninit(vnode: m.Vnode<null, State>) { vnode.state.pluginInfos = Stream(); vnode.state.unfilteredModels = Stream(); vnode.state.searchText = Stream(); vnode.state.flash = this.flashMessage; vnode.state.resourceAutocompleteHelper = this.cache.autocompleteSuggestions; this.updateFilterText(vnode); this.fetchData(vnode); vnode.state.onError = (msg) => { this.flashMessage.alert(msg); }; vnode.state.onSuccessfulSave = (msg) => { this.flashMessage.success(msg); this.fetchData(vnode); }; vnode.state.onAdd = (e: MouseEvent) => { e.stopPropagation(); this.flashMessage.clear(); new NewConfigRepoModal(vnode.state.onSuccessfulSave, vnode.state.onError, vnode.state.pluginInfos, vnode.state.resourceAutocompleteHelper()).render(); }; vnode.state.webhookUrlFor = (_, __) => "server url provider not initialized."; vnode.state.siteUrlsConfigured = () => this.siteUrls().isConfigured(); new AjaxPoller({repeaterFn: this.refreshConfigRepos.bind(this, vnode), initialIntervalSeconds: 10}).start(); } oncreate(vnode: m.Vnode<null, State>) { const el = document.querySelector("[data-server-site-urls]"); if (el) { const json = JSON.parse(el.getAttribute("data-server-site-urls")!); this.siteUrls(SiteUrls.fromJSON(json)); } const fallback = pipeline( // To derive the base URI from the ConfigRepos page: currentUrlOriginAndPath(), // 1. get the origin and path of the current URI (u) => u.replace(/\/admin\/config_repos(\/)?$/, "") // 2. then slice off the last 2 path segments ); // try to get the configured site URLs, then fall back to guessing if absent const serverUrl = baseUrlProvider(this.siteUrls(), () => fallback); vnode.state.webhookUrlFor = (type, id) => `${serverUrl()}/api/webhooks/${encodeURIComponent(type)}/config_repos/${encodeURIComponent(id)}`; } updateFilterText(vnode: m.Vnode<null, State>) { vnode.state.filteredModels = Stream.combine<ConfigRepoVM[]>( (collection: Stream<ConfigRepoVM[]>) => _.filter(collection(), (vm) => vm.repo.matches(vnode.state.searchText())), [vnode.state.unfilteredModels] ); } componentToDisplay(vnode: m.Vnode<null, State>): m.Children { this.parseRepoLink(sm); if (vnode.state.searchText() && _.isEmpty(vnode.state.filteredModels())) { return <div><FlashMessage type={MessageType.info}>No Results</FlashMessage> </div>; } return <div> <FlashMessage type={this.flashMessage.type} message={this.flashMessage.message}/> <ConfigReposWidget models={vnode.state.filteredModels} flushEtag={() => this.cache.flushEtag()} pluginInfos={vnode.state.pluginInfos} sm={sm} urlGenerator={vnode.state} /> </div>; } headerPanel(vnode: m.Vnode<null, State>) { const headerButtons = [ <div class={styles.wrapperForSearchBox}> <SearchField property={vnode.state.searchText} oninput={this.updateFilterText.bind(this, vnode)} dataTestId={"search-box"} placeholder="Search Config Repo"/> </div>, <Buttons.Primary onclick={vnode.state.onAdd.bind(vnode.state)}>Add</Buttons.Primary> ]; return <HeaderPanel title="Config Repositories" buttons={headerButtons} help={this.helpText()}/>; } fetchData(vnode: m.Vnode<null, State>) { const state = vnode.state; this.pageState = PageState.LOADING; return Promise.all([ PluginInfoCRUD.all({type: ExtensionTypeString.CONFIG_REPO}), this.cache.promise(), Permissions.all([SupportedEntity.config_repo]) ]).then((args) => { const pluginInfosResponse: ApiResult<PluginInfos> = args[0]; pluginInfosResponse.do( (successResponse) => { state.pluginInfos(successResponse.body); this.pageState = PageState.OK; }, (errorResponse) => { state.onError(JSON.parse(errorResponse.body!).message); this.pageState = PageState.FAILED; } ); const [,configRepos, permissionsResponse] = args; this.onConfigReposAPIResponse(configRepos, permissionsResponse, vnode); }); } refreshConfigRepos(vnode: m.Vnode<null, State>) { return Promise.all([this.cache.promise(), Permissions.all([SupportedEntity.config_repo])]) .then((args) => this.onConfigReposAPIResponse(args[0], args[1], vnode)); } parseRepoLink(sm: ScrollManager) { sm.setTarget(m.route.param().id || ""); } pageName(): string { return "Config repositories"; } helpText(): m.Children { return ConfigReposWidget.helpText(); } private onConfigReposAPIResponse(configRepos: ConfigRepo[], permissionsResponse: ApiResult<Permissions>, vnode: m.Vnode<null, State>) { const onError = (errorBody: string) => { vnode.state.onError(JSON.parse(errorBody).message); this.pageState = PageState.FAILED; }; if (this.cache.failed()) { return onError(this.cache.failureReason()!); } this.pageState = PageState.OK; permissionsResponse.do((permissions) => { const repoPermissions = permissions.body.for(SupportedEntity.config_repo); configRepos.forEach((repo) => repo.canAdminister(repoPermissions.canAdminister(repo.id()))); }, (e) => onError(e.body!)); const reusedCaches = new Map<string, ObjectCache<DefinedStructures>>(); const models = _.map(configRepos, (repo) => { const vm = new ConfigRepoVM(repo, vnode.state, this.resultCaches.get(repo.id())); vm.results.invalidate(); // always refresh definitions when getting new config repo data // persist results cache to the next poll; this eliminates the flicker when pulling new data after the first load reusedCaches.set(repo.id()!, vm.results); return vm; }); this.resultCaches = reusedCaches; // release any unused caches for garbage collection vnode.state.unfilteredModels(models); } }
the_stack
import { promises as fs } from 'fs'; import { tmpdir } from 'os'; import { dirname, join, normalize, posix, sep } from 'path'; import { changeErrorMessage } from '../utils'; import { nodeResolve } from './node-resolve'; const createdPaths: string[] = []; // Cleanup created files afterAll(async () => { await Promise.all( createdPaths.map(async (path) => { // For node 12, fs.rm() is not supported. // For node 16, fs.rmdir() with recursive is deprecated (but still works) // When we drop support for node 12, switch to below line for fs.rm() await fs.rmdir(path, { recursive: true }); // Await fs.rm(path, { recursive: true, force: true }); }), ); }); const createFs = async (input: string) => { const dir = await fs.realpath( await fs.mkdtemp(join(tmpdir(), 'pleasantest-create-fs-')), ); createdPaths.push(dir); const paths = input .trim() .split('\n') .map((line) => { const [, originalPath, contents] = /(\S*)(.*)/.exec(line.trim()) || []; const path = normalize( join(dir, originalPath.split(posix.sep).join(sep)), ); return { path, contents }; }); await Promise.all( paths.map(async ({ path, contents }) => { await fs.mkdir(dirname(path), { recursive: true }); await fs.writeFile(path, contents || ''); }), ); /** Replaces all instances of randomized tmp dir with "." */ const unrandomizePath = (text: string) => text.split(dir).join('.'); const resolve = async (id: string, { from }: { from?: string } = {}) => { const result = await nodeResolve( id, join(dir, from || 'index.js'), dir, ).catch((error) => { throw changeErrorMessage(error, (error) => unrandomizePath(error)); }); if (result) return unrandomizePath(typeof result === 'string' ? result : result.path); }; return { resolve }; }; describe('resolving in node_modules', () => { test('throws a useful error for a node_module that does not exist', async () => { const fs = await createFs(` ./node_modules/foo/package.json {} `); await expect( fs.resolve('not-existing'), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Could not find not-existing in node_modules"`, ); }); test('resolves main field with higher priority than index.js', async () => { const fs = await createFs(` ./node_modules/foo/package.json {"main": "entry.js"} ./node_modules/foo/entry.js ./node_modules/foo/index.js `); expect(await fs.resolve('foo')).toBe('./node_modules/foo/entry.js'); }); test("throws a useful error if the main field points to something that doesn't exist", async () => { const fs = await createFs(` ./node_modules/foo/package.json {"main": "not-existing.js"} ./node_modules/foo/index.js `); await expect(fs.resolve('foo')).rejects.toThrowErrorMatchingInlineSnapshot( `"Could not resolve foo: ./node_modules/foo/not-existing.js does not exist"`, ); }); test('throws a useful error if there is no main field or index.js', async () => { const fs = await createFs(` ./node_modules/foo/package.json {} `); await expect(fs.resolve('foo')).rejects.toThrowErrorMatchingInlineSnapshot( `"Could not resolve foo: ./node_modules/foo exists but no package entrypoint was found"`, ); }); test('resolves index.js', async () => { const fs = await createFs(` ./node_modules/foo/package.json {} ./node_modules/foo/index.js `); expect(await fs.resolve('foo')).toBe('./node_modules/foo/index.js'); }); test('resolves module field over main field and over index.js', async () => { const fs = await createFs(` ./node_modules/foo/package.json {"main": "index.js", "module": "index.esm.js"} ./node_modules/foo/index.esm.js ./node_modules/foo/index.js `); expect(await fs.resolve('foo')).toBe('./node_modules/foo/index.esm.js'); }); test('resolves exports field', async () => { const fs = await createFs(` ./node_modules/foo/package.json {"main": "index.js", "module": "index.esm.js", "exports": {".": "./index.exports.js"}} ./node_modules/foo/index.exports.js ./node_modules/foo/index.esm.js ./node_modules/foo/index.js `); expect(await fs.resolve('foo')).toBe('./node_modules/foo/index.exports.js'); }); test('resolves subpath directly if exports field is not present', async () => { const fs = await createFs(` ./node_modules/foo/package.json {"main": "index.js"} ./node_modules/foo/index.js ./node_modules/foo/asdf.js `); expect(await fs.resolve('foo')).toBe('./node_modules/foo/index.js'); expect(await fs.resolve('foo/asdf')).toBe('./node_modules/foo/asdf.js'); }); test("refuses to resolve subpath if exports field is present and doesn't allow", async () => { const fs = await createFs(` ./node_modules/foo/package.json {"name": "foo", "main": "index.js", "exports": {".": "./index.js"}} ./node_modules/foo/index.js ./node_modules/foo/asdf.js `); expect(await fs.resolve('foo')).toBe('./node_modules/foo/index.js'); await expect(fs.resolve('foo/asdf')).rejects.toThrow( 'Missing "./asdf" export in "foo" package', ); }); test('resolves subpath via exports field', async () => { const fs = await createFs(` ./node_modules/foo/package.json {"name": "foo", "main": "index.js", "exports": {"./asdf": "./dist/asdf.mjs"}} ./node_modules/foo/dist/asdf.mjs `); expect(await fs.resolve('foo/asdf')).toEqual( './node_modules/foo/dist/asdf.mjs', ); }); test('resolves subpath via second package.json', async () => { const fs = await createFs(` ./node_modules/preact/package.json {} ./node_modules/preact/index.js ./node_modules/preact/hooks/package.json {"main": "../dist/hooks/index.js"} ./node_modules/preact/dist/hooks/index.js `); expect(await fs.resolve('preact')).toBe('./node_modules/preact/index.js'); expect(await fs.resolve('preact/hooks')).toBe( './node_modules/preact/dist/hooks/index.js', ); }); test('resolves multiple versions of a package correctly', async () => { // A and B depend on different versions of C // So they each have a different copy of C in their node_modules const fs = await createFs(` ./node_modules/a/package.json {} ./node_modules/a/index.js ./node_modules/a/node_modules/c/package.json {} ./node_modules/a/node_modules/c/index.js ./node_modules/b/package.json {} ./node_modules/b/index.js ./node_modules/b/node_modules/c/package.json {} ./node_modules/b/node_modules/c/index.js ./node_modules/c/package.json {} ./node_modules/c/index.js {} `); expect(await fs.resolve('c', { from: './node_modules/b/index.js' })).toBe( './node_modules/b/node_modules/c/index.js', ); expect(await fs.resolve('c', { from: './node_modules/a/index.js' })).toBe( './node_modules/a/node_modules/c/index.js', ); expect(await fs.resolve('c')).toBe('./node_modules/c/index.js'); }); }); describe('resolving relative paths', () => { test('throws a useful error for a relative path that does not exist', async () => { const fs = await createFs(` ./asdf2.js `); await expect( fs.resolve('./asdf'), ).rejects.toThrowErrorMatchingInlineSnapshot(`"Could not resolve ./asdf"`); }); test('implicitly adds .js extension', async () => { const fs = await createFs(` ./other.js `); expect(await fs.resolve('./other')).toBe('./other.js'); }); test('implicitly adds .ts extension', async () => { const fs = await createFs(` ./other.ts `); expect(await fs.resolve('./other')).toBe('./other.ts'); }); test('implicitly adds .tsx extension', async () => { const fs = await createFs(` ./other.tsx `); expect(await fs.resolve('./other')).toBe('./other.tsx'); }); test('does not implicitly add .mjs or .cjs', async () => { const fs = await createFs(` ./other.mjs ./other.cjs `); await expect( fs.resolve('./other'), ).rejects.toThrowErrorMatchingInlineSnapshot(`"Could not resolve ./other"`); }); test('extensions can be loaded explicitly', async () => { const fs = await createFs(` ./other.mjs ./other.cjs ./other.js ./other.jsx ./other.ts ./other.tsx `); expect(await fs.resolve('./other.mjs')).toBe('./other.mjs'); expect(await fs.resolve('./other.cjs')).toBe('./other.cjs'); expect(await fs.resolve('./other.js')).toBe('./other.js'); expect(await fs.resolve('./other.jsx')).toBe('./other.jsx'); expect(await fs.resolve('./other.ts')).toBe('./other.ts'); expect(await fs.resolve('./other.tsx')).toBe('./other.tsx'); }); test('implicitly resolves folder/index.js', async () => { const fs = await createFs(` ./folder/index.js `); expect(await fs.resolve('./folder')).toBe('./folder/index.js'); }); test('implicitly resolves folder/index.ts', async () => { const fs = await createFs(` ./folder/index.ts `); expect(await fs.resolve('./folder')).toBe('./folder/index.ts'); }); test('does not implicitly resolve folder/index.cjs or folder/index.mjs', async () => { const fs = await createFs(` ./folder/index.mjs ./folder/index.cjs `); await expect( fs.resolve('./other'), ).rejects.toThrowErrorMatchingInlineSnapshot(`"Could not resolve ./other"`); }); test('resolves folder with package.json in it with main/module field, and ignores exports field', async () => { const fs = await createFs(` ./folder/package.json {"main": "./cjs.js", "module": "./mjs.js", "exports": "./dont-use.js"} ./folder/mjs.js `); expect(await fs.resolve('./folder')).toBe('./folder/mjs.js'); }); }); test.todo('LOAD_PACKAGE_SELF'); test.todo('LOAD_PACKAGE_IMPORTS');
the_stack
import * as coreClient from "@azure/core-client"; export type RoleManagementPolicyRuleUnion = | RoleManagementPolicyRule | RoleManagementPolicyApprovalRule | RoleManagementPolicyAuthenticationContextRule | RoleManagementPolicyEnablementRule | RoleManagementPolicyExpirationRule | RoleManagementPolicyNotificationRule; /** Role Assignment schedule */ export interface RoleAssignmentSchedule { /** * The role assignment schedule Id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role assignment schedule name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role assignment schedule type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The role assignment schedule scope. */ scope?: string; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; /** The principal type of the assigned principal ID. */ principalType?: PrincipalType; /** The id of roleAssignmentScheduleRequest used to create this roleAssignmentSchedule */ roleAssignmentScheduleRequestId?: string; /** The id of roleEligibilitySchedule used to activated this roleAssignmentSchedule */ linkedRoleEligibilityScheduleId?: string; /** Assignment type of the role assignment schedule */ assignmentType?: AssignmentType; /** Membership type of the role assignment schedule */ memberType?: MemberType; /** The status of the role assignment schedule. */ status?: Status; /** Start DateTime when role assignment schedule */ startDateTime?: Date; /** End DateTime when role assignment schedule */ endDateTime?: Date; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** DateTime when role assignment schedule was created */ createdOn?: Date; /** DateTime when role assignment schedule was modified */ updatedOn?: Date; /** Additional properties of principal, scope and role definition */ expandedProperties?: ExpandedProperties; } export interface ExpandedProperties { /** Details of the resource scope */ scope?: ExpandedPropertiesScope; /** Details of role definition */ roleDefinition?: ExpandedPropertiesRoleDefinition; /** Details of the principal */ principal?: ExpandedPropertiesPrincipal; } /** Details of the resource scope */ export interface ExpandedPropertiesScope { /** Scope id of the resource */ id?: string; /** Display name of the resource */ displayName?: string; /** Type of the resource */ type?: string; } /** Details of role definition */ export interface ExpandedPropertiesRoleDefinition { /** Id of the role definition */ id?: string; /** Display name of the role definition */ displayName?: string; /** Type of the role definition */ type?: string; } /** Details of the principal */ export interface ExpandedPropertiesPrincipal { /** Id of the principal */ id?: string; /** Display name of the principal */ displayName?: string; /** Email id of the principal */ email?: string; /** Type of the principal */ type?: string; } /** An error response from the service. */ export interface CloudError { /** An error response from the service. */ error?: CloudErrorBody; } /** An error response from the service. */ export interface CloudErrorBody { /** An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */ code?: string; /** A message describing the error, intended to be suitable for display in a user interface. */ message?: string; } /** Role assignment schedule list operation result. */ export interface RoleAssignmentScheduleListResult { /** Role assignment schedule list. */ value?: RoleAssignmentSchedule[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Role assignment schedule instance list operation result. */ export interface RoleAssignmentScheduleInstanceListResult { /** Role assignment schedule instance list. */ value?: RoleAssignmentScheduleInstance[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Information about current or upcoming role assignment schedule instance */ export interface RoleAssignmentScheduleInstance { /** * The role assignment schedule instance ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role assignment schedule instance name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role assignment schedule instance type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The role assignment schedule scope. */ scope?: string; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; /** The principal type of the assigned principal ID. */ principalType?: PrincipalType; /** Id of the master role assignment schedule */ roleAssignmentScheduleId?: string; /** Role Assignment Id in external system */ originRoleAssignmentId?: string; /** The status of the role assignment schedule instance. */ status?: Status; /** The startDateTime of the role assignment schedule instance */ startDateTime?: Date; /** The endDateTime of the role assignment schedule instance */ endDateTime?: Date; /** roleEligibilityScheduleId used to activate */ linkedRoleEligibilityScheduleId?: string; /** roleEligibilityScheduleInstanceId linked to this roleAssignmentScheduleInstance */ linkedRoleEligibilityScheduleInstanceId?: string; /** Assignment type of the role assignment schedule */ assignmentType?: AssignmentType; /** Membership type of the role assignment schedule */ memberType?: MemberType; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** DateTime when role assignment schedule was created */ createdOn?: Date; /** Additional properties of principal, scope and role definition */ expandedProperties?: ExpandedProperties; } /** Role Assignment schedule request */ export interface RoleAssignmentScheduleRequest { /** * The role assignment schedule request ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role assignment schedule request name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role assignment schedule request type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The role assignment schedule request scope. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly scope?: string; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; /** * The principal type of the assigned principal ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalType?: PrincipalType; /** The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign etc */ requestType?: RequestType; /** * The status of the role assignment schedule request. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status?: Status; /** * The approvalId of the role assignment schedule request. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly approvalId?: string; /** The resultant role assignment schedule id or the role assignment schedule id being updated */ targetRoleAssignmentScheduleId?: string; /** The role assignment schedule instance id being updated */ targetRoleAssignmentScheduleInstanceId?: string; /** Schedule info of the role assignment schedule */ scheduleInfo?: RoleAssignmentScheduleRequestPropertiesScheduleInfo; /** The linked role eligibility schedule id - to activate an eligibility. */ linkedRoleEligibilityScheduleId?: string; /** Justification for the role assignment */ justification?: string; /** Ticket Info of the role assignment */ ticketInfo?: RoleAssignmentScheduleRequestPropertiesTicketInfo; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** * DateTime when role assignment schedule request was created * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdOn?: Date; /** * Id of the user who created this request * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly requestorId?: string; /** * Additional properties of principal, scope and role definition * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly expandedProperties?: ExpandedProperties; } /** Schedule info of the role assignment schedule */ export interface RoleAssignmentScheduleRequestPropertiesScheduleInfo { /** Start DateTime of the role assignment schedule. */ startDateTime?: Date; /** Expiration of the role assignment schedule */ expiration?: RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration; } /** Expiration of the role assignment schedule */ export interface RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration { /** Type of the role assignment schedule expiration */ type?: Type; /** End DateTime of the role assignment schedule. */ endDateTime?: Date; /** Duration of the role assignment schedule in TimeSpan. */ duration?: string; } /** Ticket Info of the role assignment */ export interface RoleAssignmentScheduleRequestPropertiesTicketInfo { /** Ticket number for the role assignment */ ticketNumber?: string; /** Ticket system name for the role assignment */ ticketSystem?: string; } /** Role assignment schedule request list operation result. */ export interface RoleAssignmentScheduleRequestListResult { /** Role assignment schedule request list. */ value?: RoleAssignmentScheduleRequest[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Role eligibility schedule */ export interface RoleEligibilitySchedule { /** * The role eligibility schedule Id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role eligibility schedule name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role eligibility schedule type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The role eligibility schedule scope. */ scope?: string; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; /** The principal type of the assigned principal ID. */ principalType?: PrincipalType; /** The id of roleEligibilityScheduleRequest used to create this roleAssignmentSchedule */ roleEligibilityScheduleRequestId?: string; /** Membership type of the role eligibility schedule */ memberType?: MemberType; /** The status of the role eligibility schedule. */ status?: Status; /** Start DateTime when role eligibility schedule */ startDateTime?: Date; /** End DateTime when role eligibility schedule */ endDateTime?: Date; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** DateTime when role eligibility schedule was created */ createdOn?: Date; /** DateTime when role eligibility schedule was modified */ updatedOn?: Date; /** Additional properties of principal, scope and role definition */ expandedProperties?: ExpandedProperties; } /** role eligibility schedule list operation result. */ export interface RoleEligibilityScheduleListResult { /** role eligibility schedule list. */ value?: RoleEligibilitySchedule[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Role eligibility schedule instance list operation result. */ export interface RoleEligibilityScheduleInstanceListResult { /** Role eligibility schedule instance list. */ value?: RoleEligibilityScheduleInstance[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Information about current or upcoming role eligibility schedule instance */ export interface RoleEligibilityScheduleInstance { /** * The role eligibility schedule instance ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role eligibility schedule instance name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role eligibility schedule instance type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The role eligibility schedule scope. */ scope?: string; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; /** The principal type of the assigned principal ID. */ principalType?: PrincipalType; /** Id of the master role eligibility schedule */ roleEligibilityScheduleId?: string; /** The status of the role eligibility schedule instance */ status?: Status; /** The startDateTime of the role eligibility schedule instance */ startDateTime?: Date; /** The endDateTime of the role eligibility schedule instance */ endDateTime?: Date; /** Membership type of the role eligibility schedule */ memberType?: MemberType; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** DateTime when role eligibility schedule was created */ createdOn?: Date; /** Additional properties of principal, scope and role definition */ expandedProperties?: ExpandedProperties; } /** Role Eligibility schedule request */ export interface RoleEligibilityScheduleRequest { /** * The role eligibility schedule request ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role eligibility schedule request name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role eligibility schedule request type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The role eligibility schedule request scope. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly scope?: string; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; /** * The principal type of the assigned principal ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalType?: PrincipalType; /** The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign etc */ requestType?: RequestType; /** * The status of the role eligibility schedule request. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status?: Status; /** * The approvalId of the role eligibility schedule request. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly approvalId?: string; /** Schedule info of the role eligibility schedule */ scheduleInfo?: RoleEligibilityScheduleRequestPropertiesScheduleInfo; /** The resultant role eligibility schedule id or the role eligibility schedule id being updated */ targetRoleEligibilityScheduleId?: string; /** The role eligibility schedule instance id being updated */ targetRoleEligibilityScheduleInstanceId?: string; /** Justification for the role eligibility */ justification?: string; /** Ticket Info of the role eligibility */ ticketInfo?: RoleEligibilityScheduleRequestPropertiesTicketInfo; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** * DateTime when role eligibility schedule request was created * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdOn?: Date; /** * Id of the user who created this request * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly requestorId?: string; /** * Additional properties of principal, scope and role definition * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly expandedProperties?: ExpandedProperties; } /** Schedule info of the role eligibility schedule */ export interface RoleEligibilityScheduleRequestPropertiesScheduleInfo { /** Start DateTime of the role eligibility schedule. */ startDateTime?: Date; /** Expiration of the role eligibility schedule */ expiration?: RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration; } /** Expiration of the role eligibility schedule */ export interface RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration { /** Type of the role eligibility schedule expiration */ type?: Type; /** End DateTime of the role eligibility schedule. */ endDateTime?: Date; /** Duration of the role eligibility schedule in TimeSpan. */ duration?: string; } /** Ticket Info of the role eligibility */ export interface RoleEligibilityScheduleRequestPropertiesTicketInfo { /** Ticket number for the role eligibility */ ticketNumber?: string; /** Ticket system name for the role eligibility */ ticketSystem?: string; } /** Role eligibility schedule request list operation result. */ export interface RoleEligibilityScheduleRequestListResult { /** Role eligibility schedule request list. */ value?: RoleEligibilityScheduleRequest[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Role management policy */ export interface RoleManagementPolicy { /** * The role management policy Id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role management policy name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role management policy type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The role management policy scope. */ scope?: string; /** The role management policy display name. */ displayName?: string; /** The role management policy description. */ description?: string; /** The role management policy is default policy. */ isOrganizationDefault?: boolean; /** * The name of the entity last modified it * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedBy?: Principal; /** * The last modified date time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedDateTime?: Date; /** The rule applied to the policy. */ rules?: RoleManagementPolicyRuleUnion[]; /** * The readonly computed rule applied to the policy. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly effectiveRules?: RoleManagementPolicyRuleUnion[]; /** * Additional properties of scope * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly policyProperties?: PolicyProperties; } /** The name of the entity last modified it */ export interface Principal { /** The id of the principal made changes */ id?: string; /** The name of the principal made changes */ displayName?: string; /** Type of principal such as user , group etc */ type?: string; /** Email of principal */ email?: string; } /** The role management policy rule. */ export interface RoleManagementPolicyRule { /** Polymorphic discriminator, which specifies the different types this object can be */ ruleType: | "RoleManagementPolicyApprovalRule" | "RoleManagementPolicyAuthenticationContextRule" | "RoleManagementPolicyEnablementRule" | "RoleManagementPolicyExpirationRule" | "RoleManagementPolicyNotificationRule"; /** The id of the rule. */ id?: string; /** The target of the current rule. */ target?: RoleManagementPolicyRuleTarget; } /** The role management policy rule target. */ export interface RoleManagementPolicyRuleTarget { /** The caller of the setting. */ caller?: string; /** The type of operation. */ operations?: string[]; /** The assignment level to which it is applied. */ level?: string; /** The list of target objects. */ targetObjects?: string[]; /** The list of inheritable settings. */ inheritableSettings?: string[]; /** The list of enforced settings. */ enforcedSettings?: string[]; } export interface PolicyProperties { /** * Details of the resource scope * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly scope?: PolicyPropertiesScope; } /** Details of the resource scope */ export interface PolicyPropertiesScope { /** Scope id of the resource */ id?: string; /** Display name of the resource */ displayName?: string; /** Type of the resource */ type?: string; } /** Role management policy list operation result. */ export interface RoleManagementPolicyListResult { /** Role management policy list. */ value?: RoleManagementPolicy[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Role management policy */ export interface RoleManagementPolicyAssignment { /** * The role management policy Id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role management policy name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role management policy type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The role management policy scope. */ scope?: string; /** The role definition of management policy assignment. */ roleDefinitionId?: string; /** The policy id role management policy assignment. */ policyId?: string; /** * Additional properties of scope, role definition and policy * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly policyAssignmentProperties?: PolicyAssignmentProperties; } export interface PolicyAssignmentProperties { /** Details of the resource scope */ scope?: PolicyAssignmentPropertiesScope; /** Details of role definition */ roleDefinition?: PolicyAssignmentPropertiesRoleDefinition; /** Details of the policy */ policy?: PolicyAssignmentPropertiesPolicy; } /** Details of the resource scope */ export interface PolicyAssignmentPropertiesScope { /** Scope id of the resource */ id?: string; /** Display name of the resource */ displayName?: string; /** Type of the resource */ type?: string; } /** Details of role definition */ export interface PolicyAssignmentPropertiesRoleDefinition { /** Id of the role definition */ id?: string; /** Display name of the role definition */ displayName?: string; /** Type of the role definition */ type?: string; } /** Details of the policy */ export interface PolicyAssignmentPropertiesPolicy { /** Id of the policy */ id?: string; /** * The name of the entity last modified it * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedBy?: Principal; /** The last modified date time. */ lastModifiedDateTime?: Date; } /** Role management policy assignment list operation result. */ export interface RoleManagementPolicyAssignmentListResult { /** Role management policy assignment list. */ value?: RoleManagementPolicyAssignment[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Eligible child resources list operation result. */ export interface EligibleChildResourcesListResult { /** Eligible child resource list. */ value?: EligibleChildResource[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Eligible child resource */ export interface EligibleChildResource { /** * The resource scope Id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The resource name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** Role assignment list operation result. */ export interface RoleAssignmentListResult { /** Role assignment list. */ value?: RoleAssignment[]; /** * The URL to use for getting the next set of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Role Assignments */ export interface RoleAssignment { /** * The role assignment ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role assignment name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role assignment type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The role assignment scope. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly scope?: string; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; /** The principal type of the assigned principal ID. */ principalType?: PrincipalType; /** Description of role assignment */ description?: string; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** * Time it was created * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdOn?: Date; /** * Time it was updated * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedOn?: Date; /** * Id of the user who created the assignment * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdBy?: string; /** * Id of the user who updated the assignment * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedBy?: string; /** Id of the delegated managed identity resource */ delegatedManagedIdentityResourceId?: string; } /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */ export interface ErrorResponse { /** The error object. */ error?: ErrorDetail; } /** The error detail. */ export interface ErrorDetail { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * The error details. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: ErrorDetail[]; /** * The error additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly info?: Record<string, unknown>; } /** Role assignment create parameters. */ export interface RoleAssignmentCreateParameters { /** * The role assignment scope. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly scope?: string; /** The role definition ID. */ roleDefinitionId: string; /** The principal ID. */ principalId: string; /** The principal type of the assigned principal ID. */ principalType?: PrincipalType; /** Description of role assignment */ description?: string; /** The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container' */ condition?: string; /** Version of the condition. Currently accepted value is '2.0' */ conditionVersion?: string; /** * Time it was created * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdOn?: Date; /** * Time it was updated * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedOn?: Date; /** * Id of the user who created the assignment * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdBy?: string; /** * Id of the user who updated the assignment * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedBy?: string; /** Id of the delegated managed identity resource */ delegatedManagedIdentityResourceId?: string; } /** Validation response */ export interface ValidationResponse { /** * Whether or not validation succeeded * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly isValid?: boolean; /** Failed validation result details */ errorInfo?: ValidationResponseErrorInfo; } /** Failed validation result details */ export interface ValidationResponseErrorInfo { /** * Error code indicating why validation failed * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * Message indicating why validation failed * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; } /** Role assignment schedule filter */ export interface RoleAssignmentScheduleFilter { /** Returns role assignment schedule of the specific principal. */ principalId?: string; /** Returns role assignment schedule of the specific role definition. */ roleDefinitionId?: string; /** Returns role assignment schedule instances of the specific status. */ status?: string; } /** Role assignment schedule instance filter */ export interface RoleAssignmentScheduleInstanceFilter { /** Returns role assignment schedule instances of the specific principal. */ principalId?: string; /** Returns role assignment schedule instances of the specific role definition. */ roleDefinitionId?: string; /** Returns role assignment schedule instances of the specific status. */ status?: string; /** Returns role assignment schedule instances belonging to a specific role assignment schedule. */ roleAssignmentScheduleId?: string; } /** Role assignment schedule request filter */ export interface RoleAssignmentScheduleRequestFilter { /** Returns role assignment requests of the specific principal. */ principalId?: string; /** Returns role assignment requests of the specific role definition. */ roleDefinitionId?: string; /** Returns role assignment requests created by specific principal. */ requestorId?: string; /** Returns role assignment requests of specific status. */ status?: string; } /** Role eligibility schedule filter */ export interface RoleEligibilityScheduleFilter { /** Returns role eligibility schedule of the specific principal. */ principalId?: string; /** Returns role eligibility schedule of the specific role definition. */ roleDefinitionId?: string; /** Returns role eligibility schedule of the specific status. */ status?: string; } /** Role eligibility schedule instance filter */ export interface RoleEligibilityScheduleInstanceFilter { /** Returns role eligibility schedule instances of the specific principal. */ principalId?: string; /** Returns role eligibility schedule instances of the specific role definition. */ roleDefinitionId?: string; /** Returns role eligibility schedule instances of the specific status. */ status?: string; /** Returns role eligibility schedule instances belonging to a specific role eligibility schedule. */ roleEligibilityScheduleId?: string; } /** Role eligibility schedule request filter */ export interface RoleEligibilityScheduleRequestFilter { /** Returns role eligibility requests of the specific principal. */ principalId?: string; /** Returns role eligibility requests of the specific role definition. */ roleDefinitionId?: string; /** Returns role eligibility requests created by specific principal. */ requestorId?: string; /** Returns role eligibility requests of specific status. */ status?: string; } /** The approval settings. */ export interface ApprovalSettings { /** Determine whether approval is required or not. */ isApprovalRequired?: boolean; /** Determine whether approval is required for assignment extension. */ isApprovalRequiredForExtension?: boolean; /** Determine whether requestor justification required. */ isRequestorJustificationRequired?: boolean; /** The type of rule */ approvalMode?: ApprovalMode; /** The approval stages of the request. */ approvalStages?: ApprovalStage[]; } /** The approval stage. */ export interface ApprovalStage { /** The time in days when approval request would be timed out. */ approvalStageTimeOutInDays?: number; /** Determine whether approver need to provide justification for his decision. */ isApproverJustificationRequired?: boolean; /** The time in minutes when the approval request would be escalated if the primary approver does not approves. */ escalationTimeInMinutes?: number; /** The primary approver of the request. */ primaryApprovers?: UserSet[]; /** The value determine whether escalation feature is enabled. */ isEscalationEnabled?: boolean; /** The escalation approver of the request. */ escalationApprovers?: UserSet[]; } /** The detail of a user. */ export interface UserSet { /** The type of user. */ userType?: UserType; /** The value indicating whether the user is a backup fallback approver */ isBackup?: boolean; /** The object id of the user. */ id?: string; /** The description of the user. */ description?: string; } /** Role Assignments filter */ export interface RoleAssignmentFilter { /** Returns role assignment of the specific principal. */ principalId?: string; } /** The role management policy rule. */ export type RoleManagementPolicyApprovalRule = RoleManagementPolicyRule & { /** Polymorphic discriminator, which specifies the different types this object can be */ ruleType: "RoleManagementPolicyApprovalRule"; /** The approval setting */ setting?: ApprovalSettings; }; /** The role management policy rule. */ export type RoleManagementPolicyAuthenticationContextRule = RoleManagementPolicyRule & { /** Polymorphic discriminator, which specifies the different types this object can be */ ruleType: "RoleManagementPolicyAuthenticationContextRule"; /** The value indicating if rule is enabled. */ isEnabled?: boolean; /** The claim value. */ claimValue?: string; }; /** The role management policy rule. */ export type RoleManagementPolicyEnablementRule = RoleManagementPolicyRule & { /** Polymorphic discriminator, which specifies the different types this object can be */ ruleType: "RoleManagementPolicyEnablementRule"; /** The list of enabled rules. */ enabledRules?: EnablementRules[]; }; /** The role management policy rule. */ export type RoleManagementPolicyExpirationRule = RoleManagementPolicyRule & { /** Polymorphic discriminator, which specifies the different types this object can be */ ruleType: "RoleManagementPolicyExpirationRule"; /** The value indicating whether expiration is required. */ isExpirationRequired?: boolean; /** The maximum duration of expiration in timespan. */ maximumDuration?: string; }; /** The role management policy rule. */ export type RoleManagementPolicyNotificationRule = RoleManagementPolicyRule & { /** Polymorphic discriminator, which specifies the different types this object can be */ ruleType: "RoleManagementPolicyNotificationRule"; /** The type of notification. */ notificationType?: NotificationDeliveryMechanism; /** The notification level. */ notificationLevel?: NotificationLevel; /** The recipient type. */ recipientType?: RecipientType; /** The list notification recipients. */ notificationRecipients?: string[]; /** Its value determine if the notification need to be sent to the recipient type specified in policy rule. */ isDefaultRecipientsEnabled?: boolean; }; /** Known values of {@link PrincipalType} that the service accepts. */ export enum KnownPrincipalType { User = "User", Group = "Group", ServicePrincipal = "ServicePrincipal", Unknown = "Unknown", DirectoryRoleTemplate = "DirectoryRoleTemplate", ForeignGroup = "ForeignGroup", Application = "Application", MSI = "MSI", DirectoryObjectOrGroup = "DirectoryObjectOrGroup", Everyone = "Everyone", Device = "Device" } /** * Defines values for PrincipalType. \ * {@link KnownPrincipalType} can be used interchangeably with PrincipalType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Group** \ * **ServicePrincipal** \ * **Unknown** \ * **DirectoryRoleTemplate** \ * **ForeignGroup** \ * **Application** \ * **MSI** \ * **DirectoryObjectOrGroup** \ * **Everyone** \ * **Device** */ export type PrincipalType = string; /** Known values of {@link AssignmentType} that the service accepts. */ export enum KnownAssignmentType { Activated = "Activated", Assigned = "Assigned" } /** * Defines values for AssignmentType. \ * {@link KnownAssignmentType} can be used interchangeably with AssignmentType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Activated** \ * **Assigned** */ export type AssignmentType = string; /** Known values of {@link MemberType} that the service accepts. */ export enum KnownMemberType { Inherited = "Inherited", Direct = "Direct", Group = "Group" } /** * Defines values for MemberType. \ * {@link KnownMemberType} can be used interchangeably with MemberType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Inherited** \ * **Direct** \ * **Group** */ export type MemberType = string; /** Known values of {@link Status} that the service accepts. */ export enum KnownStatus { Accepted = "Accepted", PendingEvaluation = "PendingEvaluation", Granted = "Granted", Denied = "Denied", PendingProvisioning = "PendingProvisioning", Provisioned = "Provisioned", PendingRevocation = "PendingRevocation", Revoked = "Revoked", Canceled = "Canceled", Failed = "Failed", PendingApprovalProvisioning = "PendingApprovalProvisioning", PendingApproval = "PendingApproval", FailedAsResourceIsLocked = "FailedAsResourceIsLocked", PendingAdminDecision = "PendingAdminDecision", AdminApproved = "AdminApproved", AdminDenied = "AdminDenied", TimedOut = "TimedOut", ProvisioningStarted = "ProvisioningStarted", Invalid = "Invalid", PendingScheduleCreation = "PendingScheduleCreation", ScheduleCreated = "ScheduleCreated", PendingExternalProvisioning = "PendingExternalProvisioning" } /** * Defines values for Status. \ * {@link KnownStatus} can be used interchangeably with Status, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Accepted** \ * **PendingEvaluation** \ * **Granted** \ * **Denied** \ * **PendingProvisioning** \ * **Provisioned** \ * **PendingRevocation** \ * **Revoked** \ * **Canceled** \ * **Failed** \ * **PendingApprovalProvisioning** \ * **PendingApproval** \ * **FailedAsResourceIsLocked** \ * **PendingAdminDecision** \ * **AdminApproved** \ * **AdminDenied** \ * **TimedOut** \ * **ProvisioningStarted** \ * **Invalid** \ * **PendingScheduleCreation** \ * **ScheduleCreated** \ * **PendingExternalProvisioning** */ export type Status = string; /** Known values of {@link RequestType} that the service accepts. */ export enum KnownRequestType { AdminAssign = "AdminAssign", AdminRemove = "AdminRemove", AdminUpdate = "AdminUpdate", AdminExtend = "AdminExtend", AdminRenew = "AdminRenew", SelfActivate = "SelfActivate", SelfDeactivate = "SelfDeactivate", SelfExtend = "SelfExtend", SelfRenew = "SelfRenew" } /** * Defines values for RequestType. \ * {@link KnownRequestType} can be used interchangeably with RequestType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **AdminAssign** \ * **AdminRemove** \ * **AdminUpdate** \ * **AdminExtend** \ * **AdminRenew** \ * **SelfActivate** \ * **SelfDeactivate** \ * **SelfExtend** \ * **SelfRenew** */ export type RequestType = string; /** Known values of {@link Type} that the service accepts. */ export enum KnownType { AfterDuration = "AfterDuration", AfterDateTime = "AfterDateTime", NoExpiration = "NoExpiration" } /** * Defines values for Type. \ * {@link KnownType} can be used interchangeably with Type, * this enum contains the known values that the service supports. * ### Known values supported by the service * **AfterDuration** \ * **AfterDateTime** \ * **NoExpiration** */ export type Type = string; /** Known values of {@link RoleManagementPolicyRuleType} that the service accepts. */ export enum KnownRoleManagementPolicyRuleType { RoleManagementPolicyApprovalRule = "RoleManagementPolicyApprovalRule", RoleManagementPolicyAuthenticationContextRule = "RoleManagementPolicyAuthenticationContextRule", RoleManagementPolicyEnablementRule = "RoleManagementPolicyEnablementRule", RoleManagementPolicyExpirationRule = "RoleManagementPolicyExpirationRule", RoleManagementPolicyNotificationRule = "RoleManagementPolicyNotificationRule" } /** * Defines values for RoleManagementPolicyRuleType. \ * {@link KnownRoleManagementPolicyRuleType} can be used interchangeably with RoleManagementPolicyRuleType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **RoleManagementPolicyApprovalRule** \ * **RoleManagementPolicyAuthenticationContextRule** \ * **RoleManagementPolicyEnablementRule** \ * **RoleManagementPolicyExpirationRule** \ * **RoleManagementPolicyNotificationRule** */ export type RoleManagementPolicyRuleType = string; /** Known values of {@link ApprovalMode} that the service accepts. */ export enum KnownApprovalMode { SingleStage = "SingleStage", Serial = "Serial", Parallel = "Parallel", NoApproval = "NoApproval" } /** * Defines values for ApprovalMode. \ * {@link KnownApprovalMode} can be used interchangeably with ApprovalMode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **SingleStage** \ * **Serial** \ * **Parallel** \ * **NoApproval** */ export type ApprovalMode = string; /** Known values of {@link UserType} that the service accepts. */ export enum KnownUserType { User = "User", Group = "Group" } /** * Defines values for UserType. \ * {@link KnownUserType} can be used interchangeably with UserType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Group** */ export type UserType = string; /** Known values of {@link EnablementRules} that the service accepts. */ export enum KnownEnablementRules { MultiFactorAuthentication = "MultiFactorAuthentication", Justification = "Justification", Ticketing = "Ticketing" } /** * Defines values for EnablementRules. \ * {@link KnownEnablementRules} can be used interchangeably with EnablementRules, * this enum contains the known values that the service supports. * ### Known values supported by the service * **MultiFactorAuthentication** \ * **Justification** \ * **Ticketing** */ export type EnablementRules = string; /** Known values of {@link NotificationDeliveryMechanism} that the service accepts. */ export enum KnownNotificationDeliveryMechanism { Email = "Email" } /** * Defines values for NotificationDeliveryMechanism. \ * {@link KnownNotificationDeliveryMechanism} can be used interchangeably with NotificationDeliveryMechanism, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Email** */ export type NotificationDeliveryMechanism = string; /** Known values of {@link NotificationLevel} that the service accepts. */ export enum KnownNotificationLevel { None = "None", Critical = "Critical", All = "All" } /** * Defines values for NotificationLevel. \ * {@link KnownNotificationLevel} can be used interchangeably with NotificationLevel, * this enum contains the known values that the service supports. * ### Known values supported by the service * **None** \ * **Critical** \ * **All** */ export type NotificationLevel = string; /** Known values of {@link RecipientType} that the service accepts. */ export enum KnownRecipientType { Requestor = "Requestor", Approver = "Approver", Admin = "Admin" } /** * Defines values for RecipientType. \ * {@link KnownRecipientType} can be used interchangeably with RecipientType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Requestor** \ * **Approver** \ * **Admin** */ export type RecipientType = string; /** Optional parameters. */ export interface RoleAssignmentSchedulesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleAssignmentSchedulesGetResponse = RoleAssignmentSchedule; /** Optional parameters. */ export interface RoleAssignmentSchedulesListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedules for the current user. Use $filter=asTarget() to return all role assignment schedules created for the current user. */ filter?: string; } /** Contains response data for the listForScope operation. */ export type RoleAssignmentSchedulesListForScopeResponse = RoleAssignmentScheduleListResult; /** Optional parameters. */ export interface RoleAssignmentSchedulesListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedules for the current user. Use $filter=asTarget() to return all role assignment schedules created for the current user. */ filter?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleAssignmentSchedulesListForScopeNextResponse = RoleAssignmentScheduleListResult; /** Optional parameters. */ export interface RoleAssignmentScheduleInstancesListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedule instances for the user. Use $filter=asTarget() to return all role assignment schedule instances created for the current user. */ filter?: string; } /** Contains response data for the listForScope operation. */ export type RoleAssignmentScheduleInstancesListForScopeResponse = RoleAssignmentScheduleInstanceListResult; /** Optional parameters. */ export interface RoleAssignmentScheduleInstancesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleAssignmentScheduleInstancesGetResponse = RoleAssignmentScheduleInstance; /** Optional parameters. */ export interface RoleAssignmentScheduleInstancesListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedule instances for the user. Use $filter=asTarget() to return all role assignment schedule instances created for the current user. */ filter?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleAssignmentScheduleInstancesListForScopeNextResponse = RoleAssignmentScheduleInstanceListResult; /** Optional parameters. */ export interface RoleAssignmentScheduleRequestsCreateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the create operation. */ export type RoleAssignmentScheduleRequestsCreateResponse = RoleAssignmentScheduleRequest; /** Optional parameters. */ export interface RoleAssignmentScheduleRequestsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleAssignmentScheduleRequestsGetResponse = RoleAssignmentScheduleRequest; /** Optional parameters. */ export interface RoleAssignmentScheduleRequestsListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedule requests at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedule requests at, above or below the scope for the specified principal. Use $filter=asRequestor() to return all role assignment schedule requests requested by the current user. Use $filter=asTarget() to return all role assignment schedule requests created for the current user. Use $filter=asApprover() to return all role assignment schedule requests where the current user is an approver. */ filter?: string; } /** Contains response data for the listForScope operation. */ export type RoleAssignmentScheduleRequestsListForScopeResponse = RoleAssignmentScheduleRequestListResult; /** Optional parameters. */ export interface RoleAssignmentScheduleRequestsCancelOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface RoleAssignmentScheduleRequestsListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedule requests at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedule requests at, above or below the scope for the specified principal. Use $filter=asRequestor() to return all role assignment schedule requests requested by the current user. Use $filter=asTarget() to return all role assignment schedule requests created for the current user. Use $filter=asApprover() to return all role assignment schedule requests where the current user is an approver. */ filter?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleAssignmentScheduleRequestsListForScopeNextResponse = RoleAssignmentScheduleRequestListResult; /** Optional parameters. */ export interface RoleEligibilitySchedulesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleEligibilitySchedulesGetResponse = RoleEligibilitySchedule; /** Optional parameters. */ export interface RoleEligibilitySchedulesListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedules at or above the scope. Use $filter=principalId eq {id} to return all role eligibility schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. */ filter?: string; } /** Contains response data for the listForScope operation. */ export type RoleEligibilitySchedulesListForScopeResponse = RoleEligibilityScheduleListResult; /** Optional parameters. */ export interface RoleEligibilitySchedulesListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedules at or above the scope. Use $filter=principalId eq {id} to return all role eligibility schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. */ filter?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleEligibilitySchedulesListForScopeNextResponse = RoleEligibilityScheduleListResult; /** Optional parameters. */ export interface RoleEligibilityScheduleInstancesListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. */ filter?: string; } /** Contains response data for the listForScope operation. */ export type RoleEligibilityScheduleInstancesListForScopeResponse = RoleEligibilityScheduleInstanceListResult; /** Optional parameters. */ export interface RoleEligibilityScheduleInstancesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleEligibilityScheduleInstancesGetResponse = RoleEligibilityScheduleInstance; /** Optional parameters. */ export interface RoleEligibilityScheduleInstancesListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. */ filter?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleEligibilityScheduleInstancesListForScopeNextResponse = RoleEligibilityScheduleInstanceListResult; /** Optional parameters. */ export interface RoleEligibilityScheduleRequestsCreateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the create operation. */ export type RoleEligibilityScheduleRequestsCreateResponse = RoleEligibilityScheduleRequest; /** Optional parameters. */ export interface RoleEligibilityScheduleRequestsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleEligibilityScheduleRequestsGetResponse = RoleEligibilityScheduleRequest; /** Optional parameters. */ export interface RoleEligibilityScheduleRequestsListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedule requests at or above the scope. Use $filter=principalId eq {id} to return all role eligibility schedule requests at, above or below the scope for the specified principal. Use $filter=asRequestor() to return all role eligibility schedule requests requested by the current user. Use $filter=asTarget() to return all role eligibility schedule requests created for the current user. Use $filter=asApprover() to return all role eligibility schedule requests where the current user is an approver. */ filter?: string; } /** Contains response data for the listForScope operation. */ export type RoleEligibilityScheduleRequestsListForScopeResponse = RoleEligibilityScheduleRequestListResult; /** Optional parameters. */ export interface RoleEligibilityScheduleRequestsCancelOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface RoleEligibilityScheduleRequestsListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedule requests at or above the scope. Use $filter=principalId eq {id} to return all role eligibility schedule requests at, above or below the scope for the specified principal. Use $filter=asRequestor() to return all role eligibility schedule requests requested by the current user. Use $filter=asTarget() to return all role eligibility schedule requests created for the current user. Use $filter=asApprover() to return all role eligibility schedule requests where the current user is an approver. */ filter?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleEligibilityScheduleRequestsListForScopeNextResponse = RoleEligibilityScheduleRequestListResult; /** Optional parameters. */ export interface RoleManagementPoliciesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleManagementPoliciesGetResponse = RoleManagementPolicy; /** Optional parameters. */ export interface RoleManagementPoliciesUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the update operation. */ export type RoleManagementPoliciesUpdateResponse = RoleManagementPolicy; /** Optional parameters. */ export interface RoleManagementPoliciesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface RoleManagementPoliciesListForScopeOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listForScope operation. */ export type RoleManagementPoliciesListForScopeResponse = RoleManagementPolicyListResult; /** Optional parameters. */ export interface RoleManagementPoliciesListForScopeNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listForScopeNext operation. */ export type RoleManagementPoliciesListForScopeNextResponse = RoleManagementPolicyListResult; /** Optional parameters. */ export interface RoleManagementPolicyAssignmentsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleManagementPolicyAssignmentsGetResponse = RoleManagementPolicyAssignment; /** Optional parameters. */ export interface RoleManagementPolicyAssignmentsCreateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the create operation. */ export type RoleManagementPolicyAssignmentsCreateResponse = RoleManagementPolicyAssignment; /** Optional parameters. */ export interface RoleManagementPolicyAssignmentsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface RoleManagementPolicyAssignmentsListForScopeOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listForScope operation. */ export type RoleManagementPolicyAssignmentsListForScopeResponse = RoleManagementPolicyAssignmentListResult; /** Optional parameters. */ export interface RoleManagementPolicyAssignmentsListForScopeNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listForScopeNext operation. */ export type RoleManagementPolicyAssignmentsListForScopeNextResponse = RoleManagementPolicyAssignmentListResult; /** Optional parameters. */ export interface EligibleChildResourcesGetOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=resourceType+eq+'Subscription' to filter on only resource of type = 'Subscription'. Use $filter=resourceType+eq+'subscription'+or+resourceType+eq+'resourcegroup' to filter on resource of type = 'Subscription' or 'ResourceGroup' */ filter?: string; } /** Contains response data for the get operation. */ export type EligibleChildResourcesGetResponse = EligibleChildResourcesListResult; /** Optional parameters. */ export interface EligibleChildResourcesGetNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=resourceType+eq+'Subscription' to filter on only resource of type = 'Subscription'. Use $filter=resourceType+eq+'subscription'+or+resourceType+eq+'resourcegroup' to filter on resource of type = 'Subscription' or 'ResourceGroup' */ filter?: string; } /** Contains response data for the getNext operation. */ export type EligibleChildResourcesGetNextResponse = EligibleChildResourcesListResult; /** Optional parameters. */ export interface RoleAssignmentsListForSubscriptionOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForSubscription operation. */ export type RoleAssignmentsListForSubscriptionResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsListForResourceGroupOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForResourceGroup operation. */ export type RoleAssignmentsListForResourceGroupResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsListForResourceOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForResource operation. */ export type RoleAssignmentsListForResourceResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsGetOptionalParams extends coreClient.OperationOptions { /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the get operation. */ export type RoleAssignmentsGetResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsCreateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the create operation. */ export type RoleAssignmentsCreateResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsDeleteOptionalParams extends coreClient.OperationOptions { /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the delete operation. */ export type RoleAssignmentsDeleteResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsValidateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the validate operation. */ export type RoleAssignmentsValidateResponse = ValidationResponse; /** Optional parameters. */ export interface RoleAssignmentsListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForScope operation. */ export type RoleAssignmentsListForScopeResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsGetByIdOptionalParams extends coreClient.OperationOptions { /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the getById operation. */ export type RoleAssignmentsGetByIdResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsCreateByIdOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createById operation. */ export type RoleAssignmentsCreateByIdResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsDeleteByIdOptionalParams extends coreClient.OperationOptions { /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the deleteById operation. */ export type RoleAssignmentsDeleteByIdResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsValidateByIdOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the validateById operation. */ export type RoleAssignmentsValidateByIdResponse = ValidationResponse; /** Optional parameters. */ export interface RoleAssignmentsListForSubscriptionNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForSubscriptionNext operation. */ export type RoleAssignmentsListForSubscriptionNextResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsListForResourceGroupNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForResourceGroupNext operation. */ export type RoleAssignmentsListForResourceGroupNextResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsListForResourceNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForResourceNext operation. */ export type RoleAssignmentsListForResourceNextResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; /** Tenant ID for cross-tenant request */ tenantId?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleAssignmentsListForScopeNextResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface AuthorizationManagementClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { assert } from 'chai'; import { addStage, simulateMouseDown, simulateMouseMove, simulateMouseUp, createCanvas, isBrowser, isNode, compareLayerAndCanvas, compareLayers, loadImage, Konva, } from './test-utils'; describe('Shape', function () { // ====================================================== it('test intersects()', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 200, y: 100, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 4, }); layer.add(rect); stage.add(layer); assert.equal( rect.intersects({ x: 201, y: 101, }), true, '(201,101) should intersect the shape' ); assert.equal( rect.intersects({ x: 197, y: 97, }), false, '(197, 97) should not intersect the shape' ); assert.equal( rect.intersects({ x: 250, y: 125, }), true, '(250, 125) should intersect the shape' ); assert.equal( rect.intersects({ x: 300, y: 150, }), true, '(300, 150) should intersect the shape' ); assert.equal( rect.intersects({ x: 303, y: 153, }), false, '(303, 153) should not intersect the shape' ); }); // ====================================================== it('test hasShadow() method', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Shape({ sceneFunc: function (context) { context.beginPath(); context.moveTo(0, 0); context.lineTo(100, 0); context.lineTo(100, 100); context.closePath(); context.fillStrokeShape(this); }, x: 10, y: 10, fill: 'green', stroke: 'blue', strokeWidth: 5, shadowColor: 'black', shadowOffsetX: 10, shadowOpacity: 0, }); layer.add(shape); stage.add(layer); assert.equal( shape.hasShadow(), false, 'shape should not have a shadow because opacity is 0' ); shape.shadowOpacity(0.5); assert.equal( shape.hasShadow(), true, 'shape should have a shadow because opacity is nonzero' ); shape.shadowEnabled(false); assert.equal( shape.hasShadow(), false, 'shape should not have a shadow because it is not enabled' ); }); // ====================================================== it('custom shape with fill, stroke, and strokeWidth', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Shape({ sceneFunc: function (context) { context.beginPath(); context.moveTo(0, 0); context.lineTo(100, 0); context.lineTo(100, 100); context.closePath(); context.fillStrokeShape(this); }, x: 200, y: 100, fill: 'green', stroke: 'blue', strokeWidth: 5, }); layer.add(shape); stage.add(layer); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(1,0,0,1,200,100);beginPath();moveTo(0,0);lineTo(100,0);lineTo(100,100);closePath();fillStyle=green;fill();lineWidth=5;strokeStyle=blue;stroke();restore();' ); }); // ====================================================== it('add star with translated, scaled, rotated fill', function (done) { loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, fillPatternImage: imageObj, fillPatternX: -20, fillPatternY: -30, fillPatternScale: { x: 0.5, y: 0.5 }, fillPatternOffset: { x: 219, y: 150 }, fillPatternRotation: 90, fillPatternRepeat: 'no-repeat', stroke: 'blue', strokeWidth: 5, draggable: true, }); layer.add(star); stage.add(layer); /* var anim = new Konva.Animation(function() { star.attrs.fill.rotation += 0.02; }, layer); anim.start(); */ assert.equal(star.fillPatternX(), -20, 'star fill x should be -20'); assert.equal(star.fillPatternY(), -30, 'star fill y should be -30'); assert.equal( star.fillPatternScale().x, 0.5, 'star fill scale x should be 0.5' ); assert.equal( star.fillPatternScale().y, 0.5, 'star fill scale y should be 0.5' ); assert.equal( star.fillPatternOffset().x, 219, 'star fill offset x should be 219' ); assert.equal( star.fillPatternOffset().y, 150, 'star fill offset y should be 150' ); assert.equal( star.fillPatternRotation(), 90, 'star fill rotation should be 90' ); star.fillPatternRotation(180); assert.equal( star.fillPatternRotation(), 180, 'star fill rotation should be 180' ); star.fillPatternScale({ x: 1, y: 1 }); assert.equal( star.fillPatternScale().x, 1, 'star fill scale x should be 1' ); assert.equal( star.fillPatternScale().y, 1, 'star fill scale y should be 1' ); star.fillPatternOffset({ x: 100, y: 120 }); assert.equal( star.fillPatternOffset().x, 100, 'star fill offset x should be 100' ); assert.equal( star.fillPatternOffset().y, 120, 'star fill offset y should be 120' ); done(); }); }); // ====================================================== it('test size setters and getters', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 50, fill: 'red', }); var ellipse = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 50, fill: 'yellow', }); layer.add(ellipse); layer.add(circle); stage.add(layer); // circle tests assert.equal(circle.width(), 100, 'circle width should be 100'); assert.equal(circle.height(), 100, 'circle height should be 100'); assert.equal(circle.getSize().width, 100, 'circle width should be 100'); assert.equal(circle.getSize().height, 100, 'circle height should be 100'); assert.equal(circle.radius(), 50, 'circle radius should be 50'); circle.setWidth(200); assert.equal(circle.width(), 200, 'circle width should be 200'); assert.equal(circle.height(), 200, 'circle height should be 200'); assert.equal(circle.getSize().width, 200, 'circle width should be 200'); assert.equal(circle.getSize().height, 200, 'circle height should be 200'); assert.equal(circle.radius(), 100, 'circle radius should be 100'); }); // ====================================================== it('set image fill to color then image then linear gradient then back to image', function (done) { loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 200, y: 60, radius: 50, fill: 'blue', }); layer.add(circle); stage.add(layer); assert.equal(circle.fill(), 'blue', 'circle fill should be blue'); circle.fill(null); circle.fillPatternImage(imageObj); circle.fillPatternRepeat('no-repeat'); circle.fillPatternOffset({ x: -200, y: -70 }); assert.notEqual( circle.fillPatternImage(), undefined, 'circle fill image should be defined' ); assert.equal( circle.fillPatternRepeat(), 'no-repeat', 'circle fill repeat should be no-repeat' ); assert.equal( circle.fillPatternOffset().x, -200, 'circle fill offset x should be -200' ); assert.equal( circle.fillPatternOffset().y, -70, 'circle fill offset y should be -70' ); circle.fillPatternImage(null); circle.fillLinearGradientStartPoint({ x: -35, y: -35 }); circle.fillLinearGradientEndPoint({ x: 35, y: 35 }); circle.fillLinearGradientColorStops([0, 'red', 1, 'blue']); circle.fillLinearGradientStartPoint({ x: 0, y: 0 }); circle.fillPatternImage(imageObj); circle.fillPatternRepeat('repeat'); circle.fillPatternOffset({ x: 0, y: 0 }); layer.draw(); done(); }); }); it('stroke gradient', function () { var stage = addStage(); var layer = new Konva.Layer({ scaleY: 1.5, }); var shape = new Konva.Rect({ x: 10, y: 10, width: 100, height: 100, fillLinearGradientColorStops: [0, 'yellow', 0.5, 'red', 1, 'white'], fillLinearGradientStartPoint: { x: 0, y: 0, }, scaleX: 3, fillLinearGradientEndPoint: { x: 100, y: 100, }, strokeLinearGradientColorStops: [0, 'red', 0.5, 'blue', 1, 'green'], strokeLinearGradientStartPoint: { x: 0, y: 0, }, strokeLinearGradientEndPoint: { x: 100, y: 100, }, }); layer.add(shape); stage.add(layer); if (isNode) { assert.equal( layer.getContext().getTrace(true), 'clearRect();save();transform();beginPath();rect();closePath();fillStyle;fill();lineWidth;createLinearGradient();strokeStyle;stroke();restore();' ); } else { assert.equal( layer.getContext().getTrace(), 'clearRect(0,0,578,200);save();transform(3,0,0,1.5,10,15);beginPath();rect(0,0,100,100);closePath();fillStyle=[object CanvasGradient];fill();lineWidth=2;createLinearGradient(0,0,100,100);strokeStyle=[object CanvasGradient];stroke();restore();' ); } }); // ====================================================== it('test enablers and disablers', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, shadowColor: 'black', shadowBlur: 10, shadowOffset: { x: 10, y: 10 }, dash: [10, 10], scaleX: 3, }); layer.add(circle); stage.add(layer); assert.equal(circle.strokeScaleEnabled(), true); assert.equal(circle.fillEnabled(), true, 'fillEnabled should be true'); assert.equal(circle.strokeEnabled(), true, 'strokeEnabled should be true'); assert.equal(circle.shadowEnabled(), true, 'shadowEnabled should be true'); assert.equal(circle.dashEnabled(), true, 'dashEnabled should be true'); circle.strokeScaleEnabled(false); assert.equal(circle.strokeScaleEnabled(), false); layer.draw(); // var trace = layer.getContext().getTrace(); circle.fillEnabled(false); assert.equal(circle.fillEnabled(), false, 'fillEnabled should be false'); circle.strokeEnabled(false); assert.equal( circle.strokeEnabled(), false, 'strokeEnabled should be false' ); circle.shadowEnabled(false); assert.equal( circle.shadowEnabled(), false, 'shadowEnabled should be false' ); circle.dashEnabled(false); assert.equal(circle.dashEnabled(), false, 'dashEnabled should be false'); // re-enable circle.dashEnabled(true); assert.equal(circle.dashEnabled(), true, 'dashEnabled should be true'); circle.shadowEnabled(true); assert.equal(circle.shadowEnabled(), true, 'shadowEnabled should be true'); circle.strokeEnabled(true); assert.equal(circle.strokeEnabled(), true, 'strokeEnabled should be true'); circle.fillEnabled(true); assert.equal(circle.fillEnabled(), true, 'fillEnabled should be true'); }); // ====================================================== it('fill with shadow and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', opacity: 0.5, shadowColor: 'black', shadowBlur: 10, shadowOffset: { x: 10, y: 10 }, shadowOpacity: 0.5, }); layer.add(rect); stage.add(layer); assert.equal(rect.x(), 100); assert.equal(rect.y(), 50); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.globalAlpha = 0.5; // rect context.beginPath(); context.rect(100, 50, 100, 50); context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,0.5)'; context.shadowBlur = 10 * Konva.pixelRatio; context.shadowOffsetX = 10 * Konva.pixelRatio; context.shadowOffsetY = 10 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 30); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(1,0,0,1,100,50);globalAlpha=0.5;shadowColor=rgba(0,0,0,0.5);shadowBlur=10;shadowOffsetX=10;shadowOffsetY=10;beginPath();rect(0,0,100,50);closePath();fillStyle=green;fill();restore();' ); }); // ====================================================== it('draw fill after stroke', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'red', strokeWidth: 10, fillAfterStrokeEnabled: true, }); layer.add(rect); stage.add(layer); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(1,0,0,1,100,50);beginPath();rect(0,0,100,50);closePath();lineWidth=10;strokeStyle=red;stroke();fillStyle=green;fill();restore();' ); }); // ====================================================== it('test strokeWidth = 0', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', strokeWidth: 0, stroke: 'black', }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.beginPath(); context.rect(100, 50, 100, 50); context.closePath(); context.fillStyle = 'green'; context.fill(); var trace = layer.getContext().getTrace(); compareLayerAndCanvas(layer, canvas, 30); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(1,0,0,1,100,50);beginPath();rect(0,0,100,50);closePath();fillStyle=green;fill();restore();' ); }); // ====================================================== it('stroke with shadow and opacity', function () { Konva.pixelRatio = 1; var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, stroke: 'red', strokeWidth: 20, opacity: 0.5, shadowColor: 'black', shadowBlur: 10, shadowOffset: { x: 10, y: 10 }, shadowOpacity: 0.5, }); layer.add(rect); stage.add(layer); assert.equal(rect.x(), 100); assert.equal(rect.y(), 50); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.globalAlpha = 0.5; // rect context.beginPath(); context.rect(100, 50, 100, 50); context.closePath(); context.strokeStyle = 'red'; context.lineWidth = 20; context.shadowColor = 'rgba(0,0,0,0.5)'; context.shadowBlur = 10 * Konva.pixelRatio; context.shadowOffsetX = 10 * Konva.pixelRatio; context.shadowOffsetY = 10 * Konva.pixelRatio; context.stroke(); compareLayerAndCanvas(layer, canvas, 10); var trace = layer.getContext().getTrace(); //console.log(trace); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(1,0,0,1,100,50);globalAlpha=0.5;shadowColor=rgba(0,0,0,0.5);shadowBlur=10;shadowOffsetX=10;shadowOffsetY=10;beginPath();rect(0,0,100,50);closePath();lineWidth=20;strokeStyle=red;stroke();restore();' ); }); // ====================================================== it('fill and stroke with opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 10, opacity: 0.5, }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.globalAlpha = 0.5; // stroke context.beginPath(); context.moveTo(100, 50); context.lineTo(200, 50); context.lineTo(200, 100); context.lineTo(100, 100); context.closePath(); context.lineWidth = 10; context.strokeStyle = 'black'; context.stroke(); // rect context.fillStyle = 'green'; context.fillRect(105, 55, 90, 40); compareLayerAndCanvas(layer, canvas, 10); }); // ====================================================== it('fill and stroke with shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 10, shadowColor: 'grey', shadowBlur: 10, shadowOffset: { x: 20, y: 20, }, }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.beginPath(); context.rect(100, 50, 100, 50); context.closePath(); context.fillStyle = 'green'; context.lineWidth = 10; context.fill(); context.stroke(); var c2 = createCanvas(); var ctx2 = c2.getContext('2d'); ctx2.shadowColor = 'grey'; ctx2.shadowBlur = 10 * Konva.pixelRatio; ctx2.shadowOffsetX = 20 * Konva.pixelRatio; ctx2.shadowOffsetY = 20 * Konva.pixelRatio; ctx2.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2); // compareLayerAndCanvas(layer, c2, 50); if (isBrowser) { var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();shadowColor=rgba(128,128,128,1);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' ); } else { var trace = layer.getContext().getTrace(true); assert.equal( trace, 'clearRect();save();shadowColor;shadowBlur;shadowOffsetX;shadowOffsetY;drawImage();restore();' ); } }); // ====================================================== // hard to emulate the same drawing it('fill and stroke with shadow and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 10, shadowColor: 'grey', opacity: 0.5, shadowBlur: 5, shadowOffset: { x: 20, y: 20, }, }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.globalAlpha = 0.3; // draw shadow context.save(); context.beginPath(); context.rect(95, 45, 110, 60); context.closePath(); context.shadowColor = 'grey'; context.shadowBlur = 5 * Konva.pixelRatio; context.shadowOffsetX = 20 * Konva.pixelRatio; context.shadowOffsetY = 20 * Konva.pixelRatio; context.fillStyle = 'black'; context.fill(); context.restore(); // draw "stroke" context.save(); context.beginPath(); context.moveTo(100, 50); context.lineTo(200, 50); context.lineTo(200, 100); context.lineTo(100, 100); context.closePath(); context.lineWidth = 10; context.strokeStyle = 'black'; context.stroke(); context.restore(); context.save(); context.beginPath(); context.fillStyle = 'green'; context.rect(105, 55, 90, 40); context.closePath(); context.fill(); context.restore(); compareLayerAndCanvas(layer, canvas, 260); if (isBrowser) { var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();shadowColor=rgba(128,128,128,1);shadowBlur=5;shadowOffsetX=20;shadowOffsetY=20;globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' ); } else { var trace = layer.getContext().getTrace(true); assert.equal( trace, 'clearRect();save();shadowColor;shadowBlur;shadowOffsetX;shadowOffsetY;globalAlpha;drawImage();restore();' ); } }); // ====================================================== it('text with fill and stroke with shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); var text = new Konva.Text({ x: 50, y: 50, text: 'Test TEXT', fontSize: 50, fill: 'green', stroke: 'black', strokeWidth: 2, shadowColor: 'black', shadowBlur: 2, shadowOffset: { x: 20, y: 20, }, }); layer.add(text); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.save(); context.shadowColor = 'black'; context.shadowBlur = 2 * Konva.pixelRatio; context.shadowOffsetX = 20 * Konva.pixelRatio; context.shadowOffsetY = 20 * Konva.pixelRatio; context.font = 'normal 50px Arial'; context.textBaseline = 'middle'; context.fillStyle = 'green'; context.fillText('Test TEXT', 50, 75); context.lineWidth = 2; context.strokeStyle = 'black'; context.strokeText('Test TEXT', 50, 75); context.stroke(); context.fill(); context.restore(); // draw text again to remove shadow under stroke context.font = 'normal 50px Arial'; context.textBaseline = 'middle'; context.fillText('Test TEXT', 50, 75); context.fillStyle = 'green'; context.fillText('Test TEXT', 50, 75); context.lineWidth = 2; context.strokeStyle = 'black'; context.strokeText('Test TEXT', 50, 75); compareLayerAndCanvas(layer, canvas, 254); }); // ====================================================== it('shape intersect with shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ fill: '#ff0000', x: 50, y: 50, width: 200, height: 200, draggable: true, shadowColor: '#000', // if all shadow properties removed, works fine }); layer.add(rect); stage.add(layer); //error here assert.equal(rect.intersects({ x: 52, y: 52 }), true); assert.equal(rect.intersects({ x: 45, y: 45 }), false); }); // ====================================================== it('shape intersect while dragging', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ fill: '#ff0000', x: 50, y: 50, width: 200, height: 200, draggable: true, shadowColor: '#000', // if all shadow properties removed, works fine }); layer.add(rect); stage.add(layer); simulateMouseDown(stage, { x: 55, y: 55 }); simulateMouseMove(stage, { x: 65, y: 65 }); //error here assert.equal(rect.intersects({ x: 65, y: 65 }), true); simulateMouseUp(stage, { x: 65, y: 65 }); }); // ====================================================== it('overloaded getters and setters', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'red', strokeWidth: 20, draggable: true, }); layer.add(rect); stage.add(layer); rect.stroke('blue'); assert.equal(rect.stroke(), 'blue'); rect.lineJoin('bevel'); assert.equal(rect.lineJoin(), 'bevel'); rect.lineCap('square'); assert.equal(rect.lineCap(), 'square'); rect.strokeWidth(8); assert.equal(rect.strokeWidth(), 8); const f = () => {}; rect.sceneFunc(f); assert.equal(rect.sceneFunc(), f); rect.hitFunc(f); assert.equal(rect.hitFunc(), f); rect.dash([1]); assert.equal(rect.dash()[0], 1); // NOTE: skipping the rest because it would take hours to test all possible methods. // This should hopefully be enough to test Factor overloaded methods }); // ====================================================== it('create image hit region', function (done) { loadImage('lion.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); var lion = new Konva.Image({ x: 0, y: 0, image: imageObj, draggable: true, shadowColor: 'black', shadowBlur: 10, shadowOffsetX: 20, shadowOpacity: 0.2, }); // override color key with black // lion.colorKey = '#000000'; // Konva.shapes['#000000'] = lion; layer.add(lion); stage.add(layer); assert.equal(layer.getIntersection({ x: 10, y: 10 }), lion); lion.cache(); lion.drawHitFromCache(); layer.draw(); assert.equal(layer.getIntersection({ x: 10, y: 10 }), null); assert.equal(layer.getIntersection({ x: 50, y: 50 }), lion); done(); }); }); it('test defaults', function () { var shape = new Konva.Shape(); assert.equal(shape.strokeWidth(), 2); assert.equal(shape.shadowOffsetX(), 0); assert.equal(shape.shadowOffsetY(), 0); assert.equal(shape.fillPatternX(), 0); assert.equal(shape.fillPatternY(), 0); assert.equal(shape.fillRadialGradientStartRadius(), 0); assert.equal(shape.fillRadialGradientEndRadius(), 0); assert.equal(shape.fillPatternRepeat(), 'repeat'); assert.equal(shape.fillEnabled(), true); assert.equal(shape.strokeEnabled(), true); assert.equal(shape.shadowEnabled(), true); assert.equal(shape.dashEnabled(), true); assert.equal(shape.dashOffset(), 0); assert.equal(shape.strokeScaleEnabled(), true); assert.equal(shape.fillPriority(), 'color'); assert.equal(shape.fillPatternOffsetX(), 0); assert.equal(shape.fillPatternOffsetY(), 0); assert.equal(shape.fillPatternScaleX(), 1); assert.equal(shape.fillPatternScaleY(), 1); assert.equal(shape.fillLinearGradientStartPointX(), 0); assert.equal(shape.fillLinearGradientStartPointY(), 0); assert.equal(shape.fillLinearGradientEndPointX(), 0); assert.equal(shape.fillLinearGradientEndPointY(), 0); assert.equal(shape.fillRadialGradientStartPointX(), 0); assert.equal(shape.fillRadialGradientStartPointY(), 0); assert.equal(shape.fillRadialGradientEndPointX(), 0); assert.equal(shape.fillRadialGradientEndPointY(), 0); assert.equal(shape.fillPatternRotation(), 0); }); // ====================================================== it('hit graph when shape cached before adding to Layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 290, y: 111, width: 50, height: 50, fill: 'black', }); rect.cache(); var click = false; rect.on('click', function () { click = true; }); layer.add(rect); stage.add(layer); simulateMouseDown(stage, { x: 300, y: 120, }); simulateMouseUp(stage, { x: 300, y: 120, }); assert.equal( click, true, 'click event should have been fired when mousing down and then up on rect' ); }); it('class inherence', function () { var rect = new Konva.Rect(); assert.equal(rect instanceof Konva.Rect, true); assert.equal(rect instanceof Konva.Shape, true); assert.equal(rect instanceof Konva.Node, true); }); it('disable stroke for hit', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, stroke: 'red', strokeWidth: 20, draggable: true, }); // default value assert.equal(rect.hitStrokeWidth(), 'auto'); rect.hitStrokeWidth(0); assert.equal(rect.hitStrokeWidth(), 0); layer.add(rect); stage.add(layer); assert.equal(rect.y(), 50); var trace = layer.getHitCanvas().getContext().getTrace(true); assert.equal( trace, 'clearRect();save();transform();beginPath();rect();closePath();save();fillStyle;fill();restore();restore();' ); }); it('hitStrokeWidth', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 10, y: 10, width: 100, height: 100, stroke: 'red', strokeWidth: 2, }); // default value layer.add(rect); stage.add(layer); // default value is auto assert.equal(rect.hitStrokeWidth(), 'auto'); // try to hit test near edge assert.equal(stage.getIntersection({ x: 5, y: 5 }), null); rect.hitStrokeWidth(20); layer.draw(); // no we should hit the rect assert.equal(stage.getIntersection({ x: 5, y: 5 }), rect); rect.strokeHitEnabled(false); assert.equal(rect.hitStrokeWidth(), 0); rect.strokeHitEnabled(true); assert.equal(rect.hitStrokeWidth(), 'auto'); rect.hitStrokeWidth(0); assert.equal(rect.strokeHitEnabled(), false); // var trace = layer // .getHitCanvas() // .getContext() // .getTrace(true); // assert.equal( // trace, // 'clearRect();save();transform();beginPath();rect();closePath();save();fillStyle;fill();restore();restore();' // ); }); it('enable hitStrokeWidth even if we have no stroke on scene', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 10, y: 10, width: 100, height: 100, }); // default value layer.add(rect); stage.add(layer); // try to hit test near edge assert.equal(stage.getIntersection({ x: 5, y: 5 }), null); rect.hitStrokeWidth(20); layer.draw(); // no we should hit the rect assert.equal(stage.getIntersection({ x: 5, y: 5 }), rect); }); it('cache shadow color rgba', function () { var circle = new Konva.Circle({ fill: 'green', radius: 50, }); // no shadow on start assert.equal(circle.hasShadow(), false); assert.equal(circle.getShadowRGBA(), undefined); // set shadow circle.shadowColor('black'); assert.equal(circle.hasShadow(), true); assert.equal(circle.getShadowRGBA(), 'rgba(0,0,0,1)'); // set another shadow property circle.shadowOpacity(0.2); assert.equal(circle.getShadowRGBA(), 'rgba(0,0,0,0.2)'); circle.shadowColor('rgba(10,10,10,0.5)'); assert.equal(circle.getShadowRGBA(), 'rgba(10,10,10,0.1)'); // reset shadow circle.shadowColor(null); assert.equal(circle.getShadowRGBA(), undefined); }); it('scale should also effect shadow offset', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 100, width: 100, height: 100, scaleX: 0.5, scaleY: 0.5, fill: 'green', shadowColor: 'black', shadowBlur: 0, shadowOffset: { x: 10, y: 10 }, }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); // rect context.beginPath(); context.rect(100, 100, 50, 50); context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,1)'; context.shadowBlur = 0; context.shadowOffsetX = 5 * Konva.pixelRatio; context.shadowOffsetY = 5 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 10); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(0.5,0,0,0.5,100,100);shadowColor=rgba(0,0,0,1);shadowBlur=0;shadowOffsetX=5;shadowOffsetY=5;beginPath();rect(0,0,100,100);closePath();fillStyle=green;fill();restore();' ); }); // TODO: restore it! it.skip('scale should also effect shadow offset - negative scale', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 100, width: 100, height: 100, scaleX: -0.5, scaleY: 0.5, fill: 'green', shadowColor: 'black', shadowBlur: 10, shadowOffset: { x: 10, y: 10 }, }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); // rect context.beginPath(); context.rect(50, 100, 50, 50); context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,1)'; context.shadowBlur = 10; context.shadowOffsetX = -5 * Konva.pixelRatio; context.shadowOffsetY = 5 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 150); // var trace = layer.getContext().getTrace(); // assert.equal( // trace, // 'clearRect(0,0,578,200);save();transform(-0.5,0,0,0.5,100,100);save();shadowColor=rgba(0,0,0,1);shadowBlur=10;shadowOffsetX=-5;shadowOffsetY=5;beginPath();rect(0,0,100,100);closePath();fillStyle=green;fill();restore();restore();' // ); }); it('scale of parent container should also effect shadow offset', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group({ x: 100, y: 100, scaleX: 0.5, scaleY: 0.5, }); var rect = new Konva.Rect({ width: 200, height: 200, scaleX: 0.5, scaleY: 0.5, fill: 'green', shadowColor: 'black', shadowBlur: 0, shadowOffset: { x: 20, y: 20 }, }); group.add(rect); layer.add(group); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); // rect context.beginPath(); context.rect(100, 100, 50, 50); context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,1)'; context.shadowBlur = 0; context.shadowOffsetX = 5 * Konva.pixelRatio; context.shadowOffsetY = 5 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 10); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(0.25,0,0,0.25,100,100);shadowColor=rgba(0,0,0,1);shadowBlur=0;shadowOffsetX=5;shadowOffsetY=5;beginPath();rect(0,0,200,200);closePath();fillStyle=green;fill();restore();' ); }); it('optional disable buffer canvas', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 10, opacity: 0.5, perfectDrawEnabled: false, }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.globalAlpha = 0.5; // stroke context.beginPath(); context.rect(100, 50, 100, 50); context.closePath(); context.lineWidth = 10; context.strokeStyle = 'black'; context.fillStyle = 'green'; context.fill(); context.stroke(); compareLayerAndCanvas(layer, canvas, 10); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(1,0,0,1,100,50);globalAlpha=0.5;beginPath();rect(0,0,100,50);closePath();fillStyle=green;fill();lineWidth=10;strokeStyle=black;stroke();restore();' ); }); it('check lineJoin in buffer canvas', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 10, opacity: 0.5, lineJoin: 'round', }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); // stroke context.beginPath(); context.rect(100, 50, 100, 50); context.closePath(); context.lineWidth = 10; context.strokeStyle = 'black'; context.fillStyle = 'green'; context.lineJoin = 'round'; context.fill(); context.stroke(); var canvas2 = createCanvas(); var context2 = canvas2.getContext('2d'); context2.globalAlpha = 0.5; context2.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2); compareLayerAndCanvas(layer, canvas2, 150); if (isBrowser) { var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' ); } else { var trace = layer.getContext().getTrace(true); assert.equal( trace, 'clearRect();save();globalAlpha;drawImage();restore();' ); } }); // ====================================================== it('optional disable shadow for stroke', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 100, y: 50, width: 100, height: 50, fill: 'green', stroke: 'black', strokeWidth: 10, shadowColor: 'grey', shadowBlur: 10, shadowOffset: { x: 20, y: 20, }, shadowForStrokeEnabled: false, }); layer.add(rect); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.beginPath(); context.rect(100, 50, 100, 50); context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'grey'; context.shadowBlur = 10 * Konva.pixelRatio; context.shadowOffsetX = 20 * Konva.pixelRatio; context.shadowOffsetY = 20 * Konva.pixelRatio; context.lineWidth = 10; context.fill(); context.shadowColor = 'rgba(0,0,0,0)'; context.stroke(); compareLayerAndCanvas(layer, canvas, 10); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();transform(1,0,0,1,100,50);shadowColor=rgba(128,128,128,1);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;beginPath();rect(0,0,100,50);closePath();fillStyle=green;fill();lineWidth=10;shadowColor=rgba(0,0,0,0);strokeStyle=black;stroke();restore();' ); }); it('clone custom shape', function () { var className = 'myCustomName'; class CustomShape extends Konva.Shape { foo() {} } CustomShape.prototype.className = className; // var CustomShape = function () { // CustomShape.super.apply(this, arguments); // this.className = className; // }; // CustomShape.prototype.foo = function () {}; // Konva.Util.extend(CustomShape, Konva.Shape); var myShape = new CustomShape({ fill: 'grey', }); var clone = myShape.clone(); assert.equal(clone instanceof CustomShape, true); assert.equal(clone instanceof Konva.Shape, true); assert.equal(clone.className, className); assert.equal(clone.fill(), 'grey'); assert.equal(clone.foo, CustomShape.prototype.foo); }); it('getClientRect should skip disabled attributes', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Rect({ x: 200, y: 100, width: 100, height: 100, fill: 'green', stroke: 'black', strokeWidth: 4, strokeEnabled: false, shadowOffsetX: 10, shadowEnabled: false, }); layer.add(shape); stage.add(layer); var rect = shape.getClientRect(); assert.equal(rect.width, 100, 'should not effect width'); assert.equal(rect.height, 100, 'should not effect width'); }); it('getClientRect for shape in transformed parent', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var group = new Konva.Group({ x: 110, y: 0, rotation: 90, }); layer.add(group); var shape = new Konva.Rect({ x: 0, y: 0, width: 100, height: 100, fill: 'green', }); group.add(shape); var relativeRect = shape.getClientRect({ relativeTo: group }); assert.equal(relativeRect.x, 0); assert.equal(relativeRect.y, 0); assert.equal(relativeRect.width, 100); assert.equal(relativeRect.height, 100); var absRect = shape.getClientRect(); assert.equal(absRect.x, 10); assert.equal(absRect.y, 0); assert.equal(absRect.width, 100); assert.equal(absRect.height, 100); }); it('getClientRect with skew', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Rect({ x: 0, y: 0, width: 200, height: 100, skewX: 0.5, scaleX: 2, fill: 'green', }); layer.add(shape); var back = new Konva.Rect({ stroke: 'red', }); back.setAttrs(shape.getClientRect()); layer.add(back); layer.draw(); var absRect = shape.getClientRect(); assert.equal(absRect.x, 0); assert.equal(absRect.y, 0); assert.equal(absRect.width, 450); assert.equal(absRect.height, 100); }); it('decompose transform', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Rect({ x: 0, y: 0, width: 200, height: 100, skewX: 0.5, scaleX: 2, scaleY: 2, fill: 'green', }); layer.add(shape); layer.draw(); assert.equal(shape.getTransform().decompose().scaleX, 2); assert.equal(shape.getTransform().decompose().scaleY, 2); assert.equal(shape.getTransform().decompose().skewX, 0.5); shape.skewX(2); shape.scaleX(0.5); assert.equal(shape.getTransform().decompose().skewX, 2); assert.equal(shape.getTransform().decompose().scaleX, 0.5); assert.equal(shape.getTransform().decompose().scaleY, 2); }); it('shadow should respect pixel ratio', function () { var stage = addStage(); var layer = new Konva.Layer(); layer.getCanvas().setPixelRatio(2); var shape = new Konva.Rect({ width: 100, height: 100, fill: 'black', shadowColor: 'green', shadowOffsetX: 20, shadowOffsetY: 20, shadowBlur: 0, }); layer.add(shape); stage.add(layer); var data = layer.getContext().getImageData(15 * 2, (100 + 5) * 2, 1, 1); assert.equal(data.data[3], 0, 'pixel should be empty, no shadow here'); }); it('text shadow blur should take scale into account', function () { var stage = addStage(); var layer1 = new Konva.Layer(); stage.add(layer1); var rect1 = new Konva.Rect({ x: 10, y: 10, scaleX: 0.5, scaleY: 0.5, width: 80, height: 80, fill: 'black', shadowColor: 'black', shadowOffsetX: 0, shadowOffsetY: 50, shadowBlur: 10, }); layer1.add(rect1); stage.add(layer1); var layer2 = new Konva.Layer(); stage.add(layer2); var rect2 = new Konva.Rect({ x: 10, y: 10, fill: 'black', width: 40, height: 40, shadowColor: 'black', shadowOffsetX: 0, shadowOffsetY: 25, shadowBlur: 5, }); layer2.add(rect2); stage.add(layer2); compareLayers(layer1, layer2, 30); }); // ====================================================== it('sceneFunc and hitFunc should have shape as second argument', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Shape({ sceneFunc: function (context, shape) { assert.equal(this, shape); context.beginPath(); context.moveTo(0, 0); context.lineTo(100, 0); context.lineTo(100, 100); context.closePath(); context.fillStrokeShape(shape); }, x: 200, y: 100, fill: 'green', stroke: 'blue', strokeWidth: 5, }); layer.add(shape); var rect = new Konva.Rect({ hitFunc: function (ctx, shape) { assert.equal(this, shape); }, }); layer.add(rect); stage.add(layer); }); // ====================================================== it('cache fill pattern', function (done) { loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, fillPatternImage: imageObj, fillPatternX: -20, fillPatternY: -30, fillPatternScale: { x: 0.5, y: 0.5 }, fillPatternOffset: { x: 219, y: 150 }, fillPatternRotation: 90, fillPatternRepeat: 'no-repeat', stroke: 'blue', strokeWidth: 5, draggable: true, }); layer.add(star); stage.add(layer); var ctx = layer.getContext(); var oldCreate = ctx.createPattern; var callCount = 0; ctx.createPattern = function () { callCount += 1; return oldCreate.apply(this, arguments); }; layer.draw(); layer.draw(); assert.equal(callCount, 0); done(); }); }); it('recache fill pattern on changes', function (done) { loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, fillPatternImage: imageObj, fillPatternX: -20, fillPatternY: -30, fillPatternScale: { x: 0.5, y: 0.5 }, fillPatternOffset: { x: 219, y: 150 }, fillPatternRotation: 90, fillPatternRepeat: 'no-repeat', stroke: 'blue', strokeWidth: 5, draggable: true, }); layer.add(star); stage.add(layer); var pattern1 = star._getFillPattern(); star.fillPatternImage(Konva.Util.createCanvasElement()); var pattern2 = star._getFillPattern(); assert.notEqual(pattern1, pattern2); star.fillPatternRepeat('repeat'); var pattern3 = star._getFillPattern(); assert.notEqual(pattern2, pattern3); star.fillPatternX(10); var pattern4 = star._getFillPattern(); assert.notEqual(pattern4, pattern3); star.fillPatternOffsetX(10); var pattern5 = star._getFillPattern(); assert.notEqual(pattern4, pattern5); done(); }); }); // ====================================================== it('cache linear gradient', function () { var stage = addStage(); var layer = new Konva.Layer(); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, fillLinearGradientStartPoint: { x: -50, y: -50 }, fillLinearGradientEndPoint: { x: 50, y: 50 }, fillLinearGradientColorStops: [0, 'red', 1, 'yellow'], stroke: 'blue', strokeWidth: 5, draggable: true, }); layer.add(star); stage.add(layer); var ctx = layer.getContext(); var oldCreate = ctx.createLinearGradient; var callCount = 0; ctx.createLinearGradient = function () { callCount += 1; return oldCreate.apply(this, arguments); }; layer.draw(); layer.draw(); assert.equal(callCount, 0); }); it('recache linear gradient on changes', function () { var stage = addStage(); var layer = new Konva.Layer(); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, fillLinearGradientStartPoint: { x: -50, y: -50 }, fillLinearGradientEndPoint: { x: 50, y: 50 }, fillLinearGradientColorStops: [0, 'red', 1, 'yellow'], stroke: 'blue', strokeWidth: 5, draggable: true, }); layer.add(star); stage.add(layer); var gradient1 = star._getLinearGradient(); star.fillLinearGradientStartPointX(-10); var gradient2 = star._getLinearGradient(); assert.notEqual(gradient1, gradient2); star.fillLinearGradientStartPointY(-10); var gradient3 = star._getLinearGradient(); assert.notEqual(gradient2, gradient3); star.fillLinearGradientEndPointX(100); var gradient4 = star._getLinearGradient(); assert.notEqual(gradient3, gradient4); star.fillLinearGradientEndPointY(100); var gradient5 = star._getLinearGradient(); assert.notEqual(gradient4, gradient5); star.fillLinearGradientColorStops([0, 'red', 1, 'green']); var gradient6 = star._getLinearGradient(); assert.notEqual(gradient5, gradient6); layer.draw(); }); // ====================================================== it('cache radial gradient', function () { var stage = addStage(); var layer = new Konva.Layer(); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, fillRadialGradientStartPoint: { x: 0, y: 0 }, fillRadialGradientStartRadius: 0, fillRadialGradientEndPoint: { x: 0, y: 0 }, fillRadialGradientEndRadius: 70, fillRadialGradientColorStops: [0, 'red', 0.5, 'yellow', 1, 'blue'], stroke: 'blue', strokeWidth: 5, draggable: true, }); layer.add(star); stage.add(layer); var ctx = layer.getContext(); var oldCreate = ctx.createRadialGradient; var callCount = 0; ctx.createRadialGradient = function () { callCount += 1; return oldCreate.apply(this, arguments); }; layer.draw(); layer.draw(); assert.equal(callCount, 0); }); it('recache linear gradient on changes', function () { var stage = addStage(); var layer = new Konva.Layer(); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, fillRadialGradientStartPoint: { x: 0, y: 0 }, fillRadialGradientStartRadius: 0, fillRadialGradientEndPoint: { x: 0, y: 0 }, fillRadialGradientEndRadius: 70, fillRadialGradientColorStops: [0, 'red', 0.5, 'yellow', 1, 'blue'], stroke: 'blue', strokeWidth: 5, draggable: true, }); layer.add(star); stage.add(layer); var gradient1 = star._getRadialGradient(); star.fillRadialGradientStartPointX(-10); var gradient2 = star._getRadialGradient(); assert.notEqual(gradient1, gradient2); star.fillRadialGradientStartPointY(-10); var gradient3 = star._getRadialGradient(); assert.notEqual(gradient2, gradient3); star.fillRadialGradientEndPointX(100); var gradient4 = star._getRadialGradient(); assert.notEqual(gradient3, gradient4); star.fillRadialGradientEndPointY(100); var gradient5 = star._getRadialGradient(); assert.notEqual(gradient4, gradient5); star.fillRadialGradientColorStops([0, 'red', 1, 'green']); var gradient6 = star._getRadialGradient(); assert.notEqual(gradient5, gradient6); star.fillRadialGradientStartRadius(10); var gradient7 = star._getRadialGradient(); assert.notEqual(gradient6, gradient7); star.fillRadialGradientEndRadius(200); var gradient8 = star._getRadialGradient(); assert.notEqual(gradient7, gradient8); layer.draw(); }); it('try to add destroyed shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, stroke: 'blue', strokeWidth: 5, draggable: true, }); star.destroy(); var callCount = 0; var oldWarn = Konva.Util.warn; Konva.Util.warn = function () { callCount += 1; }; layer.add(star); layer.draw(); assert.equal(callCount, 1); Konva.Util.warn = oldWarn; }); it('hasFill getter', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Shape({ stroke: 'black', strokeWidth: 4, sceneFunc: function (context) { context.beginPath(); context.moveTo(20, 50); context.quadraticCurveTo(550, 0, 500, 500); context.fillStrokeShape(shape); }, fill: 'red', fillEnabled: false, }); layer.add(shape); assert.equal(shape.hasFill(), false); }); it('test hit of non filled shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var line = new Konva.Shape({ sceneFunc: function (context) { context.beginPath(); context.moveTo(20, 50); context.quadraticCurveTo(550, 0, 500, 500); context.fillStrokeShape(line); }, }); layer.add(line); layer.draw(); // we still should register shape here // like for a non filled rectangle (with just stroke), // we need fill it for full events var shape = layer.getIntersection({ x: 50, y: 70 }); assert.equal(shape, line); }); it('validation on stroke should accept gradients', function () { var callCount = 0; var oldWarn = Konva.Util.warn; Konva.Util.warn = function () { callCount += 1; }; var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var canvas = createCanvas(); var ctx = canvas.getContext('2d'); var gradient = ctx.createLinearGradient(0, 75, 100, 75); gradient.addColorStop(0.0, 'rgba(255,255,255,1)'); gradient.addColorStop(1 / 6, 'rgba(255,255,255,0.8)'); gradient.addColorStop(2 / 6, 'rgba(255,255,255,0.6)'); gradient.addColorStop(3 / 6, 'rgba(255,255,255,0.4)'); gradient.addColorStop(4 / 6, 'rgba(255,255,255,0.3)'); gradient.addColorStop(5 / 6, 'rgba(255,255,255,0.2)'); gradient.addColorStop(1.0, 'rgba(255,255,255, 0)'); var star = new Konva.Star({ x: 200, y: 100, numPoints: 5, innerRadius: 40, outerRadius: 70, stroke: gradient, strokeWidth: 5, draggable: true, }); layer.add(star); layer.draw(); assert.equal(callCount, 0); Konva.Util.warn = oldWarn; }); });
the_stack
declare const enum TWTRAPIErrorCode { CouldNotAuthenticate = 32, PageNotExist = 34, NotAuthorizedForEndpoint = 37, InvalidParameter = 44, AccountSuspended = 64, APIVersionRetired = 68, RateLimitExceeded = 88, InvalidOrExpiredToken = 89, SSLInvalid = 92, OverCapacity = 130, InternalError = 131, CouldNotAuthenticateTimestampOutOfRange = 135, AlreadyFavorited = 139, CannotFollowOverLimit = 161, NotAuthorizedToSeeStatus = 179, OverDailyStatusUpdateLimit = 185, StatusIsDuplicate = 187, BadAuthenticationData = 215, RequestIsAutomated = 226, UserMustVerifyLogin = 231, ChallengeCodeInvalid = 236, BadGuestToken = 239, LoginRateExceeded = 245, EndpointRetired = 251, ApplicationCannotPerformWriteAction = 261, CannotMuteSelf = 271, CannotMuteSpecifiedUser = 272, DeviceRegisterRateExceeded = 299, DeviceCarrierNotSupported = 286, AlreadyRetweeted = 327, TooManyRequests = 429 } declare var TWTRAPIErrorDomain: string; declare class TWTRAuthConfig extends NSObject { static alloc(): TWTRAuthConfig; // inherited from NSObject static new(): TWTRAuthConfig; // inherited from NSObject readonly consumerKey: string; readonly consumerSecret: string; constructor(o: { consumerKey: string; consumerSecret: string; }); initWithConsumerKeyConsumerSecret(consumerKey: string, consumerSecret: string): this; } interface TWTRAuthSession extends TWTRBaseSession { authToken: string; authTokenSecret: string; userID: string; } declare var TWTRAuthSession: { prototype: TWTRAuthSession; }; interface TWTRBaseSession extends NSCoding, NSObjectProtocol { } declare var TWTRBaseSession: { prototype: TWTRBaseSession; }; interface TWTRCoreOAuthSigning extends NSObjectProtocol { OAuthEchoHeadersForRequestMethodURLStringParametersError(method: string, URLString: string, parameters: NSDictionary<any, any>): NSDictionary<any, any>; OAuthEchoHeadersToVerifyCredentials(): NSDictionary<any, any>; } declare var TWTRCoreOAuthSigning: { prototype: TWTRCoreOAuthSigning; }; declare const enum TWTRErrorCode { Unknown = -1, NoAuthentication = 0, NotInitialized = 1, UserDeclinedPermission = 2, UserHasNoEmailAddress = 3, InvalidResourceID = 4, InvalidURL = 5, MismatchedJSONType = 6, KeychainSerializationFailure = 7, DiskSerializationError = 8, WebViewError = 9, MissingParameter = 10 } declare var TWTRErrorDomain: string; declare class TWTRGuestSession extends NSObject implements TWTRBaseSession { static alloc(): TWTRGuestSession; // inherited from NSObject static new(): TWTRGuestSession; // inherited from NSObject readonly accessToken: string; readonly guestToken: string; readonly probablyNeedsRefreshing: boolean; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol constructor(o: { accessToken: string; guestToken: string; }); constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { sessionDictionary: NSDictionary<any, any>; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; encodeWithCoder(coder: NSCoder): void; initWithAccessTokenGuestToken(accessToken: string, guestToken: string): this; initWithCoder(coder: NSCoder): this; initWithSessionDictionary(sessionDictionary: NSDictionary<any, any>): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } interface TWTRGuestSessionStore extends NSObjectProtocol { fetchGuestSessionWithCompletion(completion: (p1: TWTRGuestSession, p2: NSError) => void): void; } declare var TWTRGuestSessionStore: { prototype: TWTRGuestSessionStore; }; declare const enum TWTRLogInErrorCode { LogInErrorCodeUnknown = -1, LogInErrorCodeDenied = 0, LogInErrorCodeCancelled = 1, LogInErrorCodeNoAccounts = 2, LogInErrorCodeReverseAuthFailed = 3, LogInErrorCodeCannotRefreshSession = 4, LogInErrorCodeSessionNotFound = 5, LogInErrorCodeFailed = 6, LogInErrorCodeSystemAccountCredentialsInvalid = 7, LoginErrorNoTwitterApp = 8 } declare var TWTRLogInErrorDomain: string; declare var TWTROAuthEchoAuthorizationHeaderKey: string; declare var TWTROAuthEchoRequestURLStringKey: string; declare class TWTRSession extends NSObject implements TWTRAuthSession { static alloc(): TWTRSession; // inherited from NSObject static new(): TWTRSession; // inherited from NSObject readonly userName: string; readonly authToken: string; // inherited from TWTRAuthSession readonly authTokenSecret: string; // inherited from TWTRAuthSession readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly userID: string; // inherited from TWTRAuthSession readonly // inherited from NSObjectProtocol constructor(o: { authToken: string; authTokenSecret: string; userName: string; userID: string; }); constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { SSOResponse: NSDictionary<any, any>; }); constructor(o: { sessionDictionary: NSDictionary<any, any>; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; encodeWithCoder(coder: NSCoder): void; initWithAuthTokenAuthTokenSecretUserNameUserID(authToken: string, authTokenSecret: string, userName: string, userID: string): this; initWithCoder(coder: NSCoder): this; initWithSSOResponse(authDictionary: NSDictionary<any, any>): this; initWithSessionDictionary(sessionDictionary: NSDictionary<any, any>): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } interface TWTRSessionRefreshingStore extends NSObjectProtocol { isExpiredSessionError(session: any, error: NSError): boolean; isExpiredSessionResponse(session: any, response: NSHTTPURLResponse): boolean; refreshSessionClassSessionIDCompletion(sessionClass: typeof NSObject, sessionID: string, completion: (p1: any, p2: NSError) => void): void; } declare var TWTRSessionRefreshingStore: { prototype: TWTRSessionRefreshingStore; }; declare class TWTRSessionStore extends NSObject implements TWTRSessionStoreProtocol { static alloc(): TWTRSessionStore; // inherited from NSObject static new(): TWTRSessionStore; // inherited from NSObject readonly authConfig: TWTRAuthConfig; // inherited from TWTRSessionStoreProtocol readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; existingUserSessions(): NSArray<any>; fetchGuestSessionWithCompletion(completion: (p1: TWTRGuestSession, p2: NSError) => void): void; hasLoggedInUsers(): boolean; isEqual(object: any): boolean; isExpiredSessionError(session: any, error: NSError): boolean; isExpiredSessionResponse(session: any, response: NSHTTPURLResponse): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; isValidOauthToken(token: string): boolean; logOutUserID(userID: string): void; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; refreshSessionClassSessionIDCompletion(sessionClass: typeof NSObject, sessionID: string, completion: (p1: any, p2: NSError) => void): void; reloadSessionStore(): void; respondsToSelector(aSelector: string): boolean; retainCount(): number; saveOauthToken(token: string): void; saveSessionCompletion(session: TWTRAuthSession, completion: (p1: TWTRAuthSession, p2: NSError) => void): void; saveSessionWithAuthTokenAuthTokenSecretCompletion(authToken: string, authTokenSecret: string, completion: (p1: TWTRAuthSession, p2: NSError) => void): void; self(): this; session(): TWTRAuthSession; sessionForUserID(userID: string): TWTRAuthSession; } interface TWTRSessionStoreProtocol extends TWTRGuestSessionStore, TWTRSessionRefreshingStore, TWTRUserSessionStore { authConfig: TWTRAuthConfig; } declare var TWTRSessionStoreProtocol: { prototype: TWTRSessionStoreProtocol; }; interface TWTRUserSessionStore extends NSObjectProtocol { existingUserSessions(): NSArray<any>; hasLoggedInUsers(): boolean; logOutUserID(userID: string): void; saveSessionCompletion(session: TWTRAuthSession, completion: (p1: TWTRAuthSession, p2: NSError) => void): void; saveSessionWithAuthTokenAuthTokenSecretCompletion(authToken: string, authTokenSecret: string, completion: (p1: TWTRAuthSession, p2: NSError) => void): void; session(): TWTRAuthSession; sessionForUserID(userID: string): TWTRAuthSession; } declare var TWTRUserSessionStore: { prototype: TWTRUserSessionStore; };
the_stack
import Bot from './Bot'; import log from '../lib/logger'; type Job = { type: 'smelt' | 'combine' | 'use' | 'delete' | 'sort'; defindex?: number; assetid?: string; sortType?: number; callback?: (err?: Error) => void; }; export = class TF2GC { private readonly bot: Bot; private processingQueue = false; private startedProcessing = false; private jobs: Job[] = []; constructor(bot: Bot) { this.bot = bot; } smeltMetal(defindex: 5001 | 5002, callback?: (err: Error | null) => void): void { if (![5001, 5002].includes(defindex)) { return; } log.debug('Enqueueing smelt job for ' + defindex); this.newJob({ type: 'smelt', defindex: defindex, callback: callback }); } combineMetal(defindex: 5000 | 5001, callback?: (err: Error | null) => void): void { if (![5000, 5001].includes(defindex)) { return; } log.debug('Enqueueing combine job for ' + defindex); this.newJob({ type: 'combine', defindex: defindex, callback: callback }); } useItem(assetid: string, callback?: (err: Error | null) => void): void { log.debug('Enqueueing use job for ' + assetid); this.newJob({ type: 'use', assetid: assetid, callback: callback }); } deleteItem(assetid: string, callback?: (err: Error | null) => void): void { log.debug('Enqueueing delete job for ' + assetid); this.newJob({ type: 'delete', assetid: assetid, callback: callback }); } sortInventory(type: number, callback?: (err: Error | null) => void): void { log.debug('Enqueueing sort job'); this.newJob({ type: 'sort', sortType: type, callback: callback }); } private newJob(job: Job): void { this.jobs.push(job); this.handleJobQueue(); } private handleJobQueue(): void { if (this.processingQueue) { log.debug('Already handling queue'); return; } if (this.jobs.length === 0) { log.debug('Queue is empty'); if (this.startedProcessing) { log.debug('Done processing queue'); this.startedProcessing = false; this.bot.handler.onTF2QueueCompleted(); } return; } this.processingQueue = true; const job = this.jobs[0]; if (!this.canProcessJob(job)) { log.debug("Can't handle job", { job }); } this.startedProcessing = true; log.debug('Ensuring TF2 GC connection...'); this.connectToGC().asCallback(err => { if (err) { return this.finishedProcessingJob(err); } let func; if (job.type === 'smelt' || job.type === 'combine') { func = this.handleCraftJob.bind(this, job); } else if (job.type === 'use' || job.type === 'delete') { func = this.handleUseOrDeleteJob.bind(this, job); } else if (job.type === 'sort') { func = this.handleSortJob.bind(this, job); } if (func) { func(); } else { this.finishedProcessingJob(new Error('Unknown job type')); } }); } private handleCraftJob(job: Job): void { if (!this.canProcessJob(job)) { return this.finishedProcessingJob(new Error("Can't process job")); } const assetids = this.bot.inventoryManager .getInventory() .findBySKU(job.defindex + ';6', true) .filter(assetid => !this.bot.trades.isInTrade(assetid)); const ids = assetids.splice(0, job.type === 'smelt' ? 1 : 3); log.debug('Sending craft request'); this.bot.tf2.craft(ids); const gainDefindex = job.defindex + (job.type === 'smelt' ? -1 : 1); const gainSKU = gainDefindex + ';6'; this.listenForEvent( 'craftingComplete', (recipe: number, itemsGained: string[]) => { // Remove items used for recipe ids.forEach(assetid => this.bot.inventoryManager.getInventory().removeItem(assetid)); // Add items gained itemsGained.forEach(assetid => this.bot.inventoryManager.getInventory().addItem(gainSKU, assetid)); this.finishedProcessingJob(); }, err => { this.finishedProcessingJob(err); } ); } private handleUseOrDeleteJob(job: Job): void { log.debug('Sending ' + job.type + ' request'); if (job.type === 'use') { this.bot.tf2.useItem(job.assetid); } else if (job.type === 'delete') { this.bot.tf2.deleteItem(job.assetid); } this.listenForEvent( 'itemRemoved', function(item) { return { success: item.id === job.assetid }; }, () => { this.bot.inventoryManager.getInventory().removeItem(job.assetid); this.finishedProcessingJob(); }, err => { this.finishedProcessingJob(err); } ); } private handleSortJob(job: Job): void { log.debug('Sending sort request'); this.bot.tf2.sortBackpack(job.sortType); let timeout; const cancel = this.listenForEvent( 'itemChanged', () => { clearTimeout(timeout); timeout = setTimeout(() => { // 1 second after the last item has changed we will mark the job as finished cancel(); this.finishedProcessingJob(); }, 1000); // Clear fail timeout return { success: false, clearTimeout: true }; }, () => { this.finishedProcessingJob(); }, err => { if (err.message === 'Canceled') { // Was canceled because of timeout this.finishedProcessingJob(); } else { // Job failed this.finishedProcessingJob(err); } } ); } /** * Listens for GC event * * @remarks Calls onSuccess function when event has been emitted. * * @param event - Event to listen for * @param onSuccess - Function to call when the event is emitted * @param onFail - Function to call when canceled, timed out, or disconnected from GC * * @returns Call this function to cancel */ private listenForEvent(event: string, onSuccess: (...args: any[]) => void, onFail: (err: Error) => void): Function; /** * Listens for GC event * * @remarks Calls iterator every time event is emittet, if iterator returns success=true * then onSuccess is called with the values from the event. * * @param event - Event to listen for * @param iterator - Function to call when event is emitted * @param onSuccess - Function to call on success * @param onFail - Function to call when canceled, timed out, or disconnected from GC * * @returns Call this function to cancel */ private listenForEvent( event: string, iterator: (...args: any[]) => { success: boolean; clearTimeout?: boolean }, onSuccess: (...args: any[]) => void, onFail: (err: Error) => void ): Function; private listenForEvent(...args: any[]): Function { const event = args[0]; const iterator = args.length === 4 ? args[1] : function(): { success: boolean; clearTimeout?: boolean; } { return { success: true }; }; const successCallback = args.length === 4 ? args[2] : args[1]; const failCallback = args.length === 4 ? args[3] : args[2]; function onEvent(...args: any[]): void { const response = iterator(...args); if (response.success) { removeListeners(); successCallback(...args); } else if (response.clearTimeout === true) { clearTimeout(timeout); } } function onDisconnected(): void { removeListeners(); failCallback(new Error('Diconnected from TF2 GC')); } function onTimeout(): void { removeListeners(); failCallback(new Error('Timed out')); } function onCancel(): void { removeListeners(); failCallback(new Error('Canceled')); } const removeListeners = (): void => { clearTimeout(timeout); this.bot.tf2.removeListener(event, onEvent); this.bot.tf2.removeListener('disconnectedFromGC', onDisconnected); }; const timeout = setTimeout(onTimeout, 10000); this.bot.tf2.on(event, onEvent); return onCancel; } private finishedProcessingJob(err: Error | null = null): void { const job = this.jobs.splice(0, 1)[0]; if (job !== undefined && job.callback) { job.callback(err); } this.processingQueue = false; this.handleJobQueue(); } private canProcessJob(job: Job): boolean { if (job.type === 'smelt' || job.type === 'combine') { const assetids = this.bot.inventoryManager .getInventory() .findBySKU(job.defindex + ';6', true) .filter(assetid => !this.bot.trades.isInTrade(assetid)); return (job.type === 'smelt' && assetids.length > 0) || (job.type === 'combine' && assetids.length >= 3); } else if (job.type === 'use' || job.type === 'delete') { return this.bot.inventoryManager.getInventory().findByAssetid(job.assetid) !== null; } return true; } private connectToGC(): Promise<void> { return new Promise((resolve, reject) => { if (!this.isConnectedToGC()) { log.debug('Not playing TF2'); this.bot.client.gamesPlayed([440]); } if (this.bot.tf2.haveGCSession) { log.debug('Already connected to TF2 GC'); return resolve(); } this.listenForEvent( 'connectedToGC', function() { return { success: true }; }, function() { resolve(); }, function() { reject(new Error('Could not connect to TF2 GC')); } ); }); } private isConnectedToGC(): boolean { return this.bot.client._playingAppIds.some(game => game == 440); } };
the_stack
import { Component, OnInit, Input, ViewEncapsulation, ViewChild, AfterViewInit, ElementRef, EventEmitter, Output, OnDestroy } from '@angular/core'; import { StixObject } from 'src/app/classes/stix/stix-object'; import {animate, style, transition, trigger} from '@angular/animations'; import {MatSort} from '@angular/material/sort'; import {MatPaginator} from '@angular/material/paginator'; import { Router } from '@angular/router'; import { SelectionModel } from '@angular/cdk/collections'; import { StixDialogComponent } from '../../../views/stix/stix-dialog/stix-dialog.component'; import { MatDialog } from '@angular/material/dialog'; import { fromEvent, Observable, of, Subscription } from 'rxjs'; import { Paginated, RestApiConnectorService } from 'src/app/services/connectors/rest-api/rest-api-connector.service'; import { debounceTime, distinctUntilChanged, filter, tap } from 'rxjs/operators'; @Component({ selector: 'app-stix-list', templateUrl: './stix-list.component.html', styleUrls: ['./stix-list.component.scss'], encapsulation: ViewEncapsulation.None, animations: [ trigger("detailExpand", [ transition(":enter", [ style({ height: '0px', minHeight: '0px'}), animate("100ms cubic-bezier(0.4, 0.0, 0.2, 1)", style({height: '*'})) ]), transition(':leave', [ animate('100ms cubic-bezier(0.4, 0.0, 0.2, 1)', style({ height: '0px', minHeight: '0px' })) ]) ]), trigger("fadeIn", [ transition(":enter", [ style({ opacity: 0 }), animate("500ms cubic-bezier(0.4, 0.0, 0.2, 1)", style({opacity: '1'})) ]) ]) ] }) export class StixListComponent implements OnInit, AfterViewInit, OnDestroy { // @Input() public stixObjects: StixObject[]; //TODO get rid of this in favor of stix list cards loading using filters @Input() public config: StixListConfig = {}; @Output() public onRowAction = new EventEmitter<string>(); @Output() public onSelect = new EventEmitter<StixObject>(); @Output() public refresh = new EventEmitter(); @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild('search') search: ElementRef; public searchQuery: string = ""; private searchSubscription: Subscription; // @ViewChild(MatSort) public sort: MatSort; //objects to render; public objects$: Observable<StixObject[]>; public data$: Observable<Paginated<StixObject>>; public totalObjectCount: number = 0; //view mode public mode: string = "cards"; //options provided to the user for grouping and filtering public filterOptions: FilterGroup[] = []; //current grouping and filtering selections public filter: string[] = []; public groupBy: string[] = []; // search query // TABLE STUFF public tableColumns: string[] = []; public tableColumns_controls: string[]; //including select behavior public tableColumns_settings: Map<string, any> = new Map<string, any>(); // property to display for each displayProperty public tableDetail: any[]; public expandedElement: StixObject | null; // Selection stuff public selection: SelectionModel<string>; // Type map for redirections private typeMap = { "x-mitre-collection": "collection", "attack-pattern": "technique", "malware": "software", "tool": "software", "intrusion-set": "group", "course-of-action": "mitigation", "x-mitre-matrix": "matrix", "x-mitre-tactic": "tactic", "relationship": "relationship" } /** * Add a column to the table * @param {string} label the label to display the field under; column name * @param {string} field the field to display * @param {string} display how to format the column data * @param {boolean} [sticky] is the column sticky? If true, the column will be static in the X scrolling of the view * @param {string[]} [classes] list of css classes to apply to the cell */ private addColumn(label: string, field: string, display: "version" | "list" | "plain" | "timestamp" | "descriptive" | "relationship_name" | "icon", sticky?: boolean, classes?: string[]) { this.tableColumns.push(field); this.tableColumns_settings.set(field, {label, display, sticky, classes}); } /** * Handles row click events. Open the panel, or open a modal depending on object type * @param {StixObject} object of the row that was clicked */ public rowClick(element: StixObject) { if (this.config.clickBehavior && this.config.clickBehavior == "none") return; if (this.config.clickBehavior && this.config.clickBehavior == "dialog") { //open modal let prompt = this.dialog.open(StixDialogComponent, { data: { object: element, editable: this.config.allowEdits, sidebarControl: this.config.allowEdits? "events" : "disable" }, maxHeight: "75vh" }) let subscription = prompt.afterClosed().subscribe({ next: result => { if (prompt.componentInstance.dirty) { //re-fetch values since an edit occurred this.applyControls(); this.refresh.emit(); } }, complete: () => { subscription.unsubscribe(); } }); } else if (this.config.clickBehavior && this.config.clickBehavior == "linkToSourceRef") { let source_ref = element['source_ref']; // Get type to navigate from source_ref let type = this.typeMap[source_ref.split('--')[0]]; this.router.navigateByUrl('/' + type + '/' + source_ref); } else if (this.config.clickBehavior && this.config.clickBehavior == "linkToTargetRef") { let target_ref = element['target_ref']; // Get type to navigate from target_ref let type = this.typeMap[target_ref.split('--')[0]]; this.router.navigateByUrl('/'+ type + '/' + target_ref); } else { //expand this.expandedElement = this.expandedElement === element ? null : element; } } //all possible each type of filter/groupBy // private types: FilterValue[] = [ // {"value": "type.group", "label": "group", "disabled": false}, // {"value": "type.matrix", "label": "matrix", "disabled": false}, // {"value": "type.mitigation", "label": "mitigation", "disabled": false}, // {"value": "type.software", "label": "software", "disabled": false}, // {"value": "type.tactic", "label": "tactic", "disabled": false}, // {"value": "type.technique", "label": "technique", "disabled": false}, // ] // private domains: FilterValue[] = [ // {"value": "domain.enterprise-attack", "label": "enterprise", "disabled": false}, // {"value": "domain.mobile-attack", "label": "mobile", "disabled": false} // ] private statuses: FilterValue[] = [ {"value": "status.work-in-progress", "label": "show only work in progress", "disabled": false}, {"value": "status.awaiting-review", "label": "show only awaiting review", "disabled": false}, {"value": "status.reviewed", "label": "show only reviewed", "disabled": false} ] private states: FilterValue[] = [ {"value": "state.deprecated", "label": "include deprecated", "disabled": false}, {"value": "state.revoked", "label": "include revoked", "disabled": false} ] constructor(public dialog: MatDialog, private restAPIConnectorService: RestApiConnectorService, private router: Router) {} ngOnInit() { this.filterOptions = [] // parse the config let controls_before = [] // control columns which occur before the main columns let controls_after = []; // control columns which occur after the main columns let sticky_allowed = !(this.config.rowAction && this.config.rowAction.position == "start"); if ("type" in this.config) { // this.filter.push("type." + this.config.type); // set columns according to type switch(this.config.type.replace(/_/g, '-')) { case "collection": case "collection-created": this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("version", "version", "version"); this.addColumn("released?", "release", "plain", null, ["text-label"]); this.addColumn("modified", "modified", "timestamp"); this.addColumn("created", "created", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "collection-imported": this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("version", "version", "version"); this.addColumn("imported", "imported", "timestamp"); this.addColumn("modified", "modified", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "mitigation": case "tactic": this.addColumn("", "workflow", "icon"); this.addColumn("", "state", "icon"); this.addColumn("ID", "attackID", "plain", false); this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("domain", "domains", "list"); this.addColumn("version", "version", "version"); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "matrix": this.addColumn("", "workflow", "icon"); this.addColumn("", "state", "icon"); this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("version", "version", "version"); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "group": this.addColumn("", "workflow", "icon"); this.addColumn("", "state", "icon"); this.addColumn("ID", "attackID", "plain", false); this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("associated groups", "aliases", "list"); this.addColumn("version", "version", "version"); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "software": this.addColumn("", "workflow", "icon"); this.addColumn("", "state", "icon"); this.addColumn("ID", "attackID", "plain", false); this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("type", "type", "plain"); this.addColumn("domain", "domains", "list"); this.addColumn("version", "version", "version"); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "data-source": case "technique": this.addColumn("", "workflow", "icon"); this.addColumn("", "state", "icon"); this.addColumn("ID", "attackID", "plain", false); this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("platforms", "platforms", "list"); this.addColumn("domain", "domains", "list"); this.addColumn("version", "version", "version"); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "data-component": this.addColumn("name", "name", "plain", sticky_allowed, ["name"]); this.addColumn("domain", "domains", "list"); this.addColumn("version", "version", "version"); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); this.tableDetail = [{ "field": "description", "display": "descriptive" }] break; case "relationship": this.addColumn("", "state", "icon"); if (this.config.relationshipType && this.config.relationshipType !== "detects") { this.addColumn("source", "source_ID", "plain"); this.addColumn("", "source_name", "plain", this.config.targetRef? sticky_allowed: false, ["relationship-name"]);// ["name", "relationship-left"]); } else this.addColumn("source", "source_name", "plain", this.config.targetRef? sticky_allowed: false, ["relationship-name"]); this.addColumn("type", "relationship_type", "plain", false, ["text-deemphasis", "relationship-joiner"]); this.addColumn("target", "target_ID", "plain"); this.addColumn("", "target_name", "plain", this.config.sourceRef? sticky_allowed: false, ["relationship-name"]);// ["name", "relationship-right"]); if (!(this.config.relationshipType && this.config.relationshipType == "subtechnique-of")) this.addColumn("description", "description", "descriptive", false); // controls_after.push("open-link") break; default: this.addColumn("type", "attackType", "plain"); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); } } else { // this.filterOptions.push({ // "name": "type", //TODO make more extensible to additional types // "disabled": "type" in this.config, // "values": this.types // }) this.groupBy = ["type"]; this.addColumn("type", "attackType", "plain"); this.addColumn("ID", "attackID", "plain", false); this.addColumn("name", "name", "plain", true, ["name"]); this.addColumn("modified","modified", "timestamp"); this.addColumn("created", "created", "timestamp"); } if ("relatedTo" in this.config) { } if ("query" in this.config) { } //controls cols setup //selection setup if ("select" in this.config && this.config.select != "disabled") { if ("selectionModel" in this.config) { this.selection = this.config.selectionModel; } else { this.selection = new SelectionModel<string>(this.config.select == "many"); } controls_before.unshift("select") // add select column to view } // open-link icon setup if (this.config.clickBehavior && this.config.clickBehavior == "dialog") { controls_after.push("open-link") } // row action setup if (this.config.rowAction) { if (this.config.rowAction.position == "start") controls_before.push("start-action"); else controls_after.push("end-action"); } this.tableColumns_controls = controls_before.concat(this.tableColumns, controls_after); // filter setup this.filterOptions.push({ "name": "workflow status", "disabled": "status" in this.config, "values": this.statuses }) this.filterOptions.push({ "name": "state", "disabled": "status" in this.config, "values": this.states }) // get data from config (if we are not connecting to back-end) if ("stixObjects" in this.config && !(this.config.stixObjects instanceof Observable)) { this.totalObjectCount = this.config.stixObjects.length; this.applyControls(); } } ngAfterViewInit() { // get objects from backend if data is not from config if (!("stixObjects" in this.config)) this.applyControls(); // set up listener to search input if (this.config.type && this.config.type != "relationship") { this.searchSubscription = fromEvent(this.search.nativeElement, 'keyup').pipe( filter(Boolean), debounceTime(250), distinctUntilChanged(), tap(_ => { if (this.paginator) this.paginator.pageIndex = 0; this.applyControls(); }) ).subscribe() } } /** * Filter the given objects to those which include the query. Searches all string and string[] properties * @template T the input type * @param {string} query * @param {T[]} objects * @returns {T[]} * @memberof StixListComponent */ private filterObjects<T>(query: string, objects: T[]): T[] { return objects.filter(obj => { return Object.keys(obj).some(key => { if (typeof obj[key] === 'string') return obj[key].toLowerCase().includes(query.toLowerCase()) else if (Array.isArray(obj[key])) { return obj[key].some(val => { if (typeof(val) === 'string') { return val.toLowerCase().includes(query.toLowerCase()); } }) } }) }) } /** * Apply all controls and fetch objects from the back-end if configured */ public applyControls() { if ("stixObjects" in this.config) { if (this.config.stixObjects instanceof Observable) { // pull objects out of observable } else { // no need to pull objects out of observable // set max length for paginator // this.paginator.length = this.config.stixObjects.length; // filter on STIX objects specified in the config let filtered = this.config.stixObjects; // filter to objects matching searchString filtered = this.filterObjects(this.searchQuery, filtered); // sort filtered = filtered.sort((a, b) => { let x = a as any; let y = b as any; return x.hasOwnProperty("name") && y.hasOwnProperty("name")? x.name.localeCompare(y.name) : x.stixID.localeCompare(y.stixID) }) if (this.paginator) this.totalObjectCount = filtered.length; // filter to only ones within the correct index range let startIndex = this.paginator? this.paginator.pageIndex * this.paginator.pageSize : 0 let endIndex = this.paginator? startIndex + this.paginator.pageSize : 10; filtered = filtered.slice(startIndex, endIndex); this.data$ = of({ data: filtered, pagination: { total: this.config.stixObjects.length, offset: startIndex, limit: this.paginator? this.paginator.pageSize : 0 } }); // this.objects$ = of(filtered); } } else { // fetch objects from backend let limit = this.paginator? this.paginator.pageSize : 10; let offset = this.paginator? this.paginator.pageIndex * limit : 0; let deprecated = this.filter.includes("state.deprecated"); let revoked = this.filter.includes("state.revoked"); let state = this.filter.find((x) => x.startsWith("status.")); if (state) { state = state.split("status.")[1]; // disable other states for (let group of this.filterOptions) { for (let option of group.values) { if (option.value.startsWith("status.") && !option.value.endsWith(state)) option.disabled = true; } } } else { // enable all states for (let group of this.filterOptions) { for (let option of group.values) { if (option.value.startsWith("status.")) option.disabled = false; } } } let options = { limit: limit, offset: offset, excludeIDs: this.config.excludeIDs, search: this.searchQuery, state: state, includeRevoked: revoked, includeDeprecated: deprecated } if (this.config.type == "software") this.data$ = this.restAPIConnectorService.getAllSoftware(options); else if (this.config.type == "group") this.data$ = this.restAPIConnectorService.getAllGroups(options); else if (this.config.type == "matrix") this.data$ = this.restAPIConnectorService.getAllMatrices(options); else if (this.config.type == "mitigation") this.data$ = this.restAPIConnectorService.getAllMitigations(options); else if (this.config.type == "tactic") this.data$ = this.restAPIConnectorService.getAllTactics(options); else if (this.config.type == "technique") this.data$ = this.restAPIConnectorService.getAllTechniques(options); else if (this.config.type.includes("collection")) this.data$ = this.restAPIConnectorService.getAllCollections({search: this.searchQuery, versions: "all"}); else if (this.config.type == "relationship") this.data$ = this.restAPIConnectorService.getRelatedTo({sourceRef: this.config.sourceRef, targetRef: this.config.targetRef, sourceType: this.config.sourceType, targetType: this.config.targetType, relationshipType: this.config.relationshipType, excludeSourceRefs: this.config.excludeSourceRefs, excludeTargetRefs: this.config.excludeTargetRefs, limit: limit, offset: offset, includeDeprecated: deprecated}); else if (this.config.type == "data-source") this.data$ = this.restAPIConnectorService.getAllDataSources(options); else if (this.config.type == "data-component") this.data$ = this.restAPIConnectorService.getAllDataComponents(options); let subscription = this.data$.subscribe({ next: (data) => { this.totalObjectCount = data.pagination.total; }, complete: () => { subscription.unsubscribe() } }) } } public showDeprecated(event) { if (event.checked) { this.filter.push("state.deprecated"); } else { let i = this.filter.indexOf("state.deprecated"); if (i >= 0) { this.filter.splice(i, 1); } } this.applyControls(); } public ngOnDestroy() { if (this.searchSubscription) this.searchSubscription.unsubscribe(); } } //allowed types for StixListConfig type type_attacktype = "collection" | "group" | "matrix" | "mitigation" | "software" | "tactic" | "technique" | "relationship" | "data-source" | "data-component"; type selection_types = "one" | "many" | "disabled" export interface StixListConfig { /* if specified, shows the given STIX objects in the table instead of loading from the back-end based on other configurations. */ stixObjects?: Observable<StixObject[]> | StixObject[]; /** STIX ID;s force the list to show relationships with the given source or target. Use with type=='relationship' */ sourceRef?: string; targetRef?: string; /** ATT&CK Types force the list to show relationships only with those types, use with type == 'relationship' */ sourceType?: type_attacktype; targetType?: type_attacktype; /** relationship type to get, use with type=='relationship' */ relationshipType?: string; /** force the list to show only this type */ type?: type_attacktype | "collection-created" | "collection-imported"; /** force the list to show only objects matching this query */ query?: any; /** can the user select in this list? allowed options: * "one": user can select a single element at a time * "many": user can select as many elements as they want * "disabled": do not allow selection (the same as omitting the config field) */ select?: selection_types; /** * If provided, use this selection model of STIX IDs for tracking selection * Only relevant if 'select' is also enabled. Also, will cause problems if multiple constructor pram is set according to 'select'. */ selectionModel?: SelectionModel<string>; /** show links to view/edit pages for relevant objects? */ showLinks?: boolean; /** default true, if false hides the filter dropdown menu */ showFilters?: boolean; /** * How should the table act when the row is clicked? default "expand" * "expand": expand the row to show additional detail * "dialog": open a dialog with the full object definition * "linkToSourceRef": clicking redirects to the source ref object * "linkToTargetRef": clicking redirects user to target ref object * "none": row is not clickable */ clickBehavior?: "expand" | "dialog" | "linkToSourceRef" | "linkToTargetRef" | "none"; /** * Default false. If true, allows for edits of the objects in the table * when in dialog mode */ allowEdits?: boolean; excludeIDs?: string[]; //exclude objects with this ID from the list excludeSourceRefs?: string[]; //exclude relationships with this source_ref from the list excludeTargetRefs?: string[]; //exclude relationships with this target_ref from the list // if specified, adds an action button for each row rowAction?: { icon: string, // material icon for the button tooltip: string, // tooltip or descriptor of action position: "start" | "end" //start: occurs before first column; end: occurs after last column } } export interface FilterValue { value: string; label: string; disabled: boolean; } export interface FilterGroup { disabled?: boolean; //is the entire group disabled name: string; values: FilterValue[]; }
the_stack
import { assert } from "chai"; import UrlRestClient, { UrlRestClientRestClient } from "./generated/urlRest/src"; import { UriColor } from "./generated/url/src"; describe("Integration tests for UrlRest", () => { let client: UrlRestClientRestClient; beforeEach(() => { client = UrlRestClient({ allowInsecureConnection: true }); }); describe("paths", () => { // it("should work when passing null", async () => { // await client.path("/paths/byte/null/{bytePath}", null as any).get() // }); it("should work when path has empty value", async () => { const result = await client .path("/paths/byte/empty/{bytePath}", "") .get(); assert.strictEqual(result.status, "200"); assert.notStrictEqual(result, undefined); }); it("should work when path has multi-byte byte values", async () => { //TODO: Check browser compatibility const byteArrayString = "5ZWK6b2E5LiC54ub54uc76ex76Ss76ex76iM76ip"; const result = await client .path("/paths/byte/multibyte/{bytePath}", byteArrayString) .get(); assert.strictEqual(result.status, "200"); assert.notStrictEqual(result, undefined); }); it("should work when path has string", async () => { const result = await client .path("/paths/string/empty/{stringPath}", "") .get(); assert.strictEqual(result.status, "200"); await client.path("/paths/string/null/{stringPath}", null as any).get(); }); it("should work when path has string unicode", async () => { const result = await client .path("/paths/string/unicode/{stringPath}", "啊齄丂狛狜隣郎隣兀﨩") .get(); assert.strictEqual(result.status, "200"); }); it("should work when path has string URL Encoded", async () => { const result = await client .path( "/paths/string/begin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend/{stringPath}", "begin!*'();:@ &=+$,/?#[]end" ) .get(); assert.strictEqual(result.status, "200"); }); it("should work when path has string URL NOT Encoded", async () => { const result = await client .path( "/paths/string/begin!*'();:@&=+$,end/{stringPath}", "begin!*'();:@&=+$,end" ) .get(); assert.strictEqual(result.status, "200"); }); it("should work when path has base64url encoded string", async () => { //TODO: Check browser compatibility const result = await client .path("/paths/string/bG9yZW0/{base64UrlPath}", "bG9yZW0") .get(); assert.strictEqual(result.status, "200"); }); it("should work when path has a paramaeter in UnixTime format", async () => { const result = await client .path("/paths/int/1460505600/{unixTimeUrlPath}", "1460505600") .get(); assert.strictEqual(result.status, "200"); }); it("should work when path has datetime", async () => { const result = await client .path( "/paths/datetime/2012-01-01T01%3A01%3A01Z/{dateTimePath}", "2012-01-01T01:01:01Z" ) .get(); assert.strictEqual(result.status, "200"); await client .path("/paths/datetime/null/{dateTimePath}", null as any) .get(); }); it("should work when path has date", async function() { const result = await client .path("/paths/date/2012-01-01/{datePath}", "2012-01-01") .get(); assert.strictEqual(result.status, "200"); assert.ok("called dateValid successfully"); }); it("should work when path has enum", async function() { try { await client .path("/paths/enum/green%20color/{enumPath}", <UriColor>"") .get(); } catch (error) { assert.equal( error.message, ` is not a valid value for enumPath. The valid values are: ["red color","green color","blue color"].` ); } try { await client.path("/paths/string/null/{enumPath}", null as any).get(); } catch (error) { assert.equal(error.message, `enumPath cannot be null or undefined.`); } const result = await client .path("/paths/enum/green%20color/{enumPath}", "green color") .get(); assert.strictEqual(result.status, "200"); }); it("should work when path has bool", async function() { const result = await client .path("/paths/bool/true/{boolPath}", true) .get(); const result1 = await client .path("/paths/bool/false/{boolPath}", false) .get(); assert.strictEqual(result.status, "200"); assert.strictEqual(result1.status, "200"); assert.ok("Both calls succeeded"); }); it("should work when path has double decimal values", async function() { const result = await client .path("/paths/double/-9999999.999/{doublePath}", -9999999.999) .get(); const result1 = await client .path("/paths/double/9999999.999/{doublePath}", 9999999.999) .get(); assert.strictEqual(result.status, "200"); assert.strictEqual(result1.status, "200"); assert.ok("Both calls succeeded"); }); it("should work when path has float values", async function() { const result = await client .path("/paths/float/-1.034E-20/{floatPath}", -1.034e-20) .get(); const result1 = await client .path("/paths/float/1.034E+20/{floatPath}", 103400000000000000000) .get(); assert.strictEqual(result.status, "200"); assert.strictEqual(result1.status, "200"); assert.ok("Both calls succeeded"); }); it("should work when path has integer values", async function() { const result = await client .path("/paths/int/-1000000/{intPath}", -1000000) .get(); const result1 = await client .path("/paths/int/1000000/{intPath}", 1000000) .get(); assert.strictEqual(result.status, "200"); assert.strictEqual(result1.status, "200"); assert.ok("Both calls succeeded"); }); it("should work when path has big integer values", async function() { const result = await client .path("/paths/long/-10000000000/{longPath}", -10000000000) .get(); const result1 = await client .path("/paths/long/10000000000/{longPath}", 10000000000) .get(); assert.strictEqual(result.status, "200"); assert.strictEqual(result1.status, "200"); assert.ok("Both calls succeeded"); }); }); describe("pathItems", () => { it("getAllWithValues should work when use values in different portion of url", async function() { const optionalParams = { localStringQuery: "localStringQuery", pathItemStringQuery: "pathItemStringQuery", globalStringQuery: "globalStringQuery" }; const result = await client .path( "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/pathItemStringQuery/localStringQuery", "globalStringPath", "pathItemStringPath", "localStringPath" ) .get({ queryParameters: optionalParams }); assert.strictEqual(result.status, "200"); assert.ok("Call succeeded"); }); it("getGlobalAndLocalQueryNull should work when use null values in different portion of url", async function() { const optionalParams = { localStringQuery: null as any, pathItemStringQuery: "pathItemStringQuery", globalStringQuery: null as any }; const result = await client .path( "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/null/pathItemStringQuery/null", "globalStringPath", "pathItemStringPath", "localStringPath" ) .get({ queryParameters: optionalParams }); assert.strictEqual(result.status, "200"); assert.ok("Call succeeded"); }); it("getGlobalQueryNull should work when use null values in different portion of url", async function() { const optionalParams = { globalStringQuery: null as any, localStringQuery: "localStringQuery", pathItemStringQuery: "pathItemStringQuery" }; const result = await client .path( "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/null/pathItemStringQuery/localStringQuery", "globalStringPath", "pathItemStringPath", "localStringPath" ) .get({ queryParameters: optionalParams }); assert.strictEqual(result.status, "200"); assert.ok("Call succeeded"); }); it("getLocalPathItemQueryNull should work when use null values in different portion of url", async function() { const optionalParams = { localStringQuery: null as any, pathItemStringQuery: null as any, globalStringQuery: "globalStringQuery" }; const result = await client .path( "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/null/null", "globalStringPath", "pathItemStringPath", "localStringPath" ) .get({ queryParameters: optionalParams }); assert.strictEqual(result.status, "200"); assert.ok("Call succeeded"); }); }); describe("queries", () => { it("should work when query has bool", async function() { const result = await client.path("/queries/array/none/string/empty").get({ queryParameters: { arrayQuery: ["hello", "nihao", "bonjour"] } }); assert.strictEqual(result.status, "200"); }); it("should work when query has double values", async function() { const result = await client.path("/queries/double/9999999.999").get({ queryParameters: { doubleQuery: 9999999.999 } }); assert.strictEqual(result.status, "200"); const result1 = await client.path("/queries/double/-9999999.999").get({ queryParameters: { doubleQuery: -9999999.999 } }); assert.strictEqual(result1.status, "200"); }); it("should work when query has date values", async function() { const result = await client.path("/queries/date/2012-01-01").get({ queryParameters: { dateQuery: "2012-01-01" } }); assert.strictEqual(result.status, "200"); }); it("should work when query has bool", async function() { const result = await client.path("/queries/bool/true").get({ queryParameters: { boolQuery: true } }); assert.strictEqual(result.status, "200"); const result1 = await client.path("/queries/bool/false").get({ queryParameters: { boolQuery: false } }); assert.strictEqual(result1.status, "200"); assert.ok("Call succeeded"); }); it("should work when query has float values", async function() { const result = await client.path("/queries/float/1.034E+20").get({ queryParameters: { floatQuery: 103400000000000000000 } }); assert.strictEqual(result.status, "200"); const result1 = await client.path("/queries/float/-1.034E-20").get({ queryParameters: { floatQuery: -1.034e-20 } }); assert.strictEqual(result1.status, "200"); assert.ok("Call succeeded"); }); it("should work when query has int values", async function() { const result = await client.path("/queries/int/1000000").get({ queryParameters: { intQuery: 1000000 } }); assert.strictEqual(result.status, "200"); const result1 = await client.path("/queries/int/-1000000").get({ queryParameters: { intQuery: -1000000 } }); assert.strictEqual(result1.status, "200"); assert.ok("Call succeeded"); }); it("should work when query has billion values", async () => { const result = await client.path("/queries/long/10000000000").get({ queryParameters: { longQuery: 10000000000 } }); assert.strictEqual(result.status, "200"); const result1 = await client.path("/queries/long/-10000000000").get({ queryParameters: { longQuery: -10000000000 } }); assert.strictEqual(result1.status, "200"); assert.ok("Call succeeded"); }); it("should work when query has string values", async () => { const result = await client.path("/queries/string/empty").get({ queryParameters: { stringQuery: "" } }); assert.strictEqual(result.status, "200"); const result1 = await client .path( "/queries/string/begin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend" ) .get({ queryParameters: { stringQuery: "begin!*'();:@ &=+$,/?#[]end" } }); assert.strictEqual(result1.status, "200"); assert.ok("Call succeeded"); }); it("should work when query has datetime", async () => { const result = await client .path("/queries/datetime/2012-01-01T01%3A01%3A01Z") .get({ queryParameters: { dateTimeQuery: "2012-01-01T01:01:01Z" } }); assert.strictEqual(result.status, "200"); assert.ok("Call succeeded"); }); it("should work when query has byte values", async function() { const result = await client.path("/queries/byte/empty").get({ queryParameters: { byteQuery: "" } }); assert.strictEqual(result.status, "200"); const result1 = await client.path("/queries/byte/multibyte").get({ queryParameters: { byteQuery: "5ZWK6b2E5LiC54ub54uc76ex76Ss76ex76iM76ip" } }); assert.strictEqual(result1.status, "200"); }); it("should work when query has enum values", async function() { try { await client.path("/queries/enum/green%20color").get({ queryParameters: { enumQuery: <UriColor>"" } }); } catch (error) { assert.equal( error.message, ` is not a valid value for enumPath. The valid values are: ["red color","green color","blue color"].` ); } const result = await client.path("/queries/enum/null").get({ queryParameters: { enumQuery: null as any } }); assert.strictEqual(result.status, "200"); const result1 = await client.path("/queries/enum/green%20color").get({ queryParameters: { enumQuery: "green color" } }); assert.strictEqual(result1.status, "200"); assert.ok("Call succeeded"); }); it("should work when query has stringUnicode", async function() { const result = await client.path("/queries/string/unicode/").get({ queryParameters: { stringQuery: "啊齄丂狛狜隣郎隣兀﨩" } }); assert.strictEqual(result.status, "200"); }); it("should work when query has string array values", async function() { const testArray = [ "ArrayQuery1", "begin!*'();:@ &=+$,/?#[]end", null as any, "" ] as string[]; const result = await client.path("/queries/array/csv/string/empty").get({ queryParameters: { arrayQuery: [] } }); const result1 = await client.path("/queries/array/csv/string/valid").get({ queryParameters: { arrayQuery: testArray } }); const result2 = await client .path("/queries/array/pipes/string/valid") .get({ queryParameters: { arrayQuery: testArray.join("|") as any } }); const result3 = await client.path("/queries/array/ssv/string/valid").get({ queryParameters: { arrayQuery: testArray.join(" ") as any } }); const result4 = await client.path("/queries/array/tsv/string/valid").get({ queryParameters: { arrayQuery: testArray.join("\t") as any } }); assert.strictEqual(result.status, "200"); assert.strictEqual(result1.status, "200"); assert.strictEqual(result2.status, "200"); assert.strictEqual(result3.status, "200"); assert.strictEqual(result4.status, "200"); assert.ok("Calls succeeded"); }); it("should work when path has string array values", async function() { const result = await client .path( "/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}", ["ArrayPath1", "begin!*'();:@ &=+$,/?#[]end", null as any, ""] ) .get(); assert.strictEqual(result.status, "200"); assert.ok("Call succeeded"); }); it("should work when use null values in url query", async function() { await client.path("/queries/byte/null").get({ queryParameters: { byteQuery: null as any } }); await client.path("/queries/date/null").get({ queryParameters: { dateQuery: null as any } }); await client.path("/queries/double/null").get({ queryParameters: { doubleQuery: null as any } }); await client.path("/queries/float/null").get({ queryParameters: { floatQuery: null as any } }); await client.path("/queries/bool/null").get({ queryParameters: { boolQuery: null as any } }); await client.path("/queries/int/null").get({ queryParameters: { intQuery: null as any } }); await client.path("/queries/long/null").get({ queryParameters: { longQuery: null as any } }); await client.path("/queries/string/null").get({ queryParameters: { stringQuery: null as any } }); await client.path("/queries/array/csv/string/null").get({ queryParameters: { arrayQuery: null as any } }); assert.ok("Calls succeeded"); }).timeout(5000); }); });
the_stack
import { ICarouselConfigProps } from '..'; import { setCss } from '../../../utility/dom/setCss'; import { removeClass } from '../../../utility/dom/removeClass'; import { addClass } from '../../../utility/dom/addClass'; import { getEle } from '../../../utility/dom/getEle'; import { getAllEle } from '../../../utility/dom/getAllEle'; import { getAttr } from '../../../utility/dom/getAttr'; import { throttle } from '../../../utility/dom/throttle'; export class Scroll { private static defaultConfig = { container: 'body', dataSource: [ { text: '面板一', img: { url: '', target: '', }, }, { text: '面板二', img: { url: '', target: '', }, }, { text: '面板三', img: { url: '', target: '', }, }, { text: '面板四', img: { url: '', target: '', }, }, ], autoPlay: false, showDots: false, showArrows: false, easing: 'ease-in-out', effect: 'scroll', vertical: false, duringTime: 1.5, delayTime: 3000, isHoverPause: true, beforeChange: () => null, afterChange: () => null, }; private static MIN_CLICK_DELAY_TIME: number = Scroll.defaultConfig.duringTime * 1000 || 1500; /** * 自动轮播辅助函数 */ private static _aidedAutoScroll( count: number, oList: any, oListWidth: number, oItemLength: number, ): void { setCss(oList, { transition: `all ${Scroll.defaultConfig.duringTime}s ${Scroll.defaultConfig.easing}; `, transform: `translateX(-${oListWidth / (oItemLength) * (count + 1)}px)`, }); } /** * 辅助函数: dot栏改变 * @param oDotsItem 圆点数组 */ private static _aidedChangeDotsStyle( count: number, oItemLength: number, oDotsItem: ArrayLike<HTMLSpanElement>, ): void { for (let i = 0, outer; outer = oDotsItem[i++];) { removeClass(outer, 'yyg-dot-item-active'); } if (count === oItemLength - 1) { addClass(oDotsItem[0], 'yyg-dot-item-active'); } else if (++count === 1) { addClass( oDotsItem[oItemLength - 3], 'yyg-dot-item-active', ); } else { addClass( oDotsItem[count - 2], 'yyg-dot-item-active', ); } } private timer: any = 0; private count: number = 1; private oList: any = null; private oDotsItem: any = null; private oListItem: any = null; private oPrevArrow: any = null; private oNextArrow: any = null; private oListWidth: number = 0; private oItemLength: number = 0; private oItemWidth: number = 0; public constructor( config: ICarouselConfigProps, ) { this.initSettings(config); this.initDOM(); } public initSettings( config: ICarouselConfigProps, ): void { for (const key in config) { if (config.hasOwnProperty(key)) { const value = Reflect.get(config, key); Reflect.set(Scroll.defaultConfig, key, value); } } } public initDOM(): void { const container = getEle(Scroll.defaultConfig.container); if (container) { // 初始化DOM结构 // TODO: 使用appendChild代替innerHTML, 避免替换原有内容. const temp = document.createElement('div'); temp.innerHTML = this.createDOMTree(); container.appendChild(temp); // 初始化样式 this.createStyle(); // 初始化公共对象(优化) this.initCommonEle(); Scroll.defaultConfig.autoPlay && this.handleAutoScroll(); Scroll.defaultConfig.isHoverPause && this.handleImgHover(); Scroll.defaultConfig.showDots && this.handleDotsHover(); Scroll.defaultConfig.showArrows && this.handleArrowClick(); Scroll.defaultConfig.showArrows && this.handleArrowHover(); } } /** * 初始化通用对象 */ public initCommonEle(): void { this.oList = getEle('.yyg-content-list') as HTMLUListElement; this.oListWidth = this.oList.offsetWidth; this.oDotsItem = getAllEle('.yyg-dot-item'); this.oListItem = getAllEle('.yyg-content-item'); this.oPrevArrow = getEle('.yyg-arrow-prev-wrapper'); this.oNextArrow = getEle('.yyg-arrow-next-wrapper'); this.oItemLength = this.oListItem.length; this.oItemWidth = this.oListWidth / this.oItemLength; } public createDOMTree(): string { const dataSource: any[] = Scroll.defaultConfig.dataSource; const { showArrows, showDots } = Scroll.defaultConfig; let dotsSpan: string = ''; let contentLi: string = ''; contentLi += ` <li class="yyg-content-item" data-id=${dataSource.length}> ${ dataSource[dataSource.length - 1].img.url ? `<a href=${dataSource[dataSource.length - 1].img.target} ><img src=${dataSource[dataSource.length - 1].img.url} alt="图片提示" /></a>` : dataSource[dataSource.length - 1].text } </li> `; dataSource.forEach((item: any, index: number) => { dotsSpan += ` <span class="yyg-dot-item${ index === 0 ? ' yyg-dot-item-active' : '' }" data-id=${index + 1} ></span> `; contentLi += ` <li class="yyg-content-item" data-id=${index + 1}> ${ item.img.url ? `<a href=${item.img.target} ><img src=${item.img.url} alt="图片提示" /></a>` : item.text } </li> `; }); // 无缝 contentLi += ` <li class="yyg-content-item" data-id=${1}> ${ dataSource[0].img.url ? `<a href=${dataSource[0].img.target} ><img src=${dataSource[0].img.url} alt="图片提示" /></a>` : dataSource[0].text } </li> `; const final: string = ` <div class="yyg-carousel-container"> <div class="yyg-carousel-main"> <div class="yyg-content-wrapper"> <ul class="yyg-content-list">${contentLi}</ul> </div> ${ showArrows ? ` <div class="yyg-arrow-wrapper yyg-arrow-prev-wrapper"> <i class="yyg-arrow yyg-arrow-prev">&lt;</i> </div> <div class="yyg-arrow-wrapper yyg-arrow-next-wrapper"> <i class="yyg-arrow yyg-arrow-next">&gt;</i> </div> ` : '' } ${ showDots ? `<div class="yyg-dots-wrapper">${dotsSpan}</div>` : '' } </div> </div> `; return final; } public createStyle(): void { let oStyle: HTMLElement | null = getEle('style'); const { dataSource, container, } = Scroll.defaultConfig; // style标签不存在 if (!oStyle) { oStyle = document.createElement('style'); const oHead = getEle('head') as HTMLHeadElement; oHead.appendChild(oStyle); } oStyle.innerText += ` ${container} p, ${container} ul { margin: 0; padding: 0; } ${container} ul { list-style-type: none; } ${container} .yyg-carousel-container { box-sizing: border-box; height: 100%; padding: 10px; border: 5px solid #1890ff; border-radius: 20px; } ${container} .yyg-carousel-main { position: relative; height: 100%; } ${container} .yyg-arrow-wrapper { position: absolute; z-index: 999; top: 50%; width: 30px; heigth: 45px; border-top-right-radius: 15px; border-bottom-right-radius: 15px; background-clip: padding-box; background-color: rgba(0,0,0,.5); color: #fff; opacity: 0; line-height: 45px; font-size: 24px; text-align: center; cursor: pointer; user-select: none; transform: translateY(-50%); transition: all .5s ease-in-out; } ${container} .yyg-arrow-prev-wrapper { left: -10px; } ${container} .yyg-arrow-next-wrapper { right: -10px; } ${container} .yyg-content-wrapper { overflow: hidden; height: 100%; } ${container} .yyg-content-list { width: ${(dataSource.length + 2) * 100}%; height: 100%; // transition: all ${Scroll.defaultConfig.duringTime}s ${Scroll.defaultConfig.easing}; transform: translateX(-${ 100 / (dataSource.length + 2) }%); } ${container} .yyg-content-item { float: left; width: ${100 / (dataSource.length + 2)}%; height: 100%; text-align: center; } ${container} .yyg-content-item a img { display: block; max-width: 100%; // width: 100%; height: 100%; border-radius: 6px; } ${container} .yyg-dots-wrapper { display: none; position: absolute; left: 50%; bottom: 10px; padding: 2px 0; border: 1px solid #ccc; border-radius: 8px; background-color: rgba(0,0,0,.5); font-size: 0; transform: translateX(-50%); } ${container} .yyg-dot-item { display: inline-block; margin-left: 5px; width: 12px; height: 12px; background-color: #fff; border-radius: 50%; transition: all .5s ease-in-out; } ${container} .yyg-dot-item:last-child { margin-right: 5px; } ${container} .yyg-dot-item-active { background-color: #d50; } ${container} .yyg-prev-wrapper-active { left: 15px; opacity: 1; } ${container} .yyg-next-wrapper-active { right: 15px; opacity: 1; } `; } /** * 处理 自动轮播 */ public handleAutoScroll(): void { const oList = this.oList; const oItemLength = this.oItemLength; const oDotsItem = this.oDotsItem; const oItemWidth = this.oItemWidth; const oListWidth = this.oListWidth; this.timer = setInterval(() => { // 执行钩子函数 Scroll.defaultConfig.beforeChange && Scroll.defaultConfig.beforeChange(); // 自动滚动 Scroll._aidedAutoScroll( this.count++, oList, oListWidth, oItemLength, ); // dot栏改变 Scroll._aidedChangeDotsStyle( this.count, oItemLength, oDotsItem, ); }, Scroll.defaultConfig.delayTime); // 无缝检测 oList.addEventListener('transitionend', () => { // 执行钩子函数 Scroll.defaultConfig.afterChange && Scroll.defaultConfig.afterChange(); if (this.count > oItemLength) { this.count = 2; setCss(oList, { transition: null, transform: `translateX(${ -(this.count) * oItemWidth }px)`, }); } }, false); } /** * 处理 图片 hover */ public handleImgHover(): void { const oListItem = this.oListItem; for (const key in oListItem) { if (oListItem.hasOwnProperty(key)) { const element = oListItem[key]; element.addEventListener('mouseenter', () => { clearInterval(this.timer); this.aidedHandleArrowVisible(Scroll.defaultConfig.showArrows); }, false); element.addEventListener('mouseleave', () => { this.handleAutoScroll(); this.aidedHandleArrowVisible(false); }, false); } } } /** * 处理 圆点 hover */ public handleDotsHover(): void { const oList = this.oList; const oItemWidth = this.oItemWidth; const oDotsItem = this.oDotsItem; const oDotsWrapper = getEle('.yyg-dots-wrapper') as HTMLDivElement; setCss(oDotsWrapper, { display: 'block', }); for (let i = 0, outer: any; outer = oDotsItem[i++];) { outer.addEventListener('mouseenter', () => { const signId = getAttr(outer, 'data-id') as string; // 清除定时器 clearInterval(this.timer); // 同步count this.count = Number(signId); // dot栏样式改变 for (let j = 0, inner; inner = oDotsItem[j++];) { removeClass(inner, 'yyg-dot-item-active'); } addClass(outer, 'yyg-dot-item-active'); // 同步轮播 setCss(oList, { transition: `all ${Scroll.defaultConfig.duringTime}s ${Scroll.defaultConfig.easing}; `, transform: `translateX(${-(this.count) * oItemWidth}px)`, }); }); // 移除dot栏重新滚动 outer.addEventListener('mouseleave', () => { this.handleAutoScroll(); }); } } /** * 处理 箭头 点击 */ public handleArrowClick(): void { const oList = this.oList; const oItemWidth = this.oItemWidth; const oItemLength = this.oItemLength; const prevArrow = this.oPrevArrow; const nextArrow = this.oNextArrow; // 左箭头 prevArrow && prevArrow.addEventListener('click', (): void => { this.aidedHandleArrowClick('left'); }, false); // 右箭头 nextArrow && nextArrow.addEventListener('click', () => { this.aidedHandleArrowClick('right'); }, false); oList.addEventListener('transitionend', () => { if (this.count === 0) { this.count = oItemLength - 2; } else if (this.count === oItemLength - 1) { this.count = 1; } setCss(oList, { transition: `null`, transform: `translateX(${ -(this.count) * oItemWidth }px)`, }); }, false); } /** * 悬浮箭头, 箭头显隐(解决bug) */ public handleArrowHover(): void { const oPrevArrow = this.oPrevArrow; const oNextArrow = this.oNextArrow; oPrevArrow && oPrevArrow.addEventListener('mouseenter', () => { this.aidedHandleArrowVisible(true); }, false); oNextArrow && oNextArrow.addEventListener('mouseenter', () => { this.aidedHandleArrowVisible(true); }, false) } /** * 箭头点击切换辅助函数 * @param whichArrow 哪边箭头 */ public aidedHandleArrowClick( whichArrow: string, ): void { const oList = this.oList; const oDotsItem = this.oDotsItem; const oItemWidth = this.oItemWidth; const oItemLength = this.oItemLength; clearInterval(this.timer); // 节流处理 throttle(Scroll.MIN_CLICK_DELAY_TIME, () => { switch (whichArrow) { case 'left': this.count--; break; case 'right': this.count++; break; default: break; } setCss(oList, { transition: `all ${ Scroll.defaultConfig.duringTime }s ${Scroll.defaultConfig.easing}`, transform: `translateX(${ -(this.count) * oItemWidth }px)`, }); Scroll._aidedChangeDotsStyle( this.count, oItemLength, oDotsItem ); }); this.handleAutoScroll(); } /** * 控制箭头显隐 辅助函数 * @param show 箭头显隐 */ public aidedHandleArrowVisible( show: boolean, ): void { const oPrevArrow = this.oPrevArrow; const oNextArrow = this.oNextArrow; if (show) { addClass( oPrevArrow, 'yyg-prev-wrapper-active' ); addClass( oNextArrow, 'yyg-next-wrapper-active' ); } else { removeClass( oPrevArrow, 'yyg-prev-wrapper-active' ); removeClass( oNextArrow, 'yyg-next-wrapper-active', ); } } }
the_stack
import { CRMColumnElement } from '../edit-crm/edit-crm'; import { Polymer } from '../../../../tools/definitions/polymer'; import { I18NKeys } from '../../../_locales/i18n-keys'; namespace EditCrmItemElement { export const editCrmItemProperties: { item: CRM.Node; expanded: boolean; shadow: boolean; itemName: string; isMenu: boolean; hasCodeSettings: boolean; rootNode: boolean; crmTypeHidden: boolean; } = { item: { type: Object, notify: true }, expanded: { type: Boolean, notify: true }, shadow: { type: Boolean, notify: true }, itemName: { type: String, notify: true }, isMenu: { type: Boolean, notify: true }, hasCodeSettings: { type: Boolean, notify: true }, rootNode: { type: Boolean, notify: true }, crmTypeHidden: { type: Boolean, notify: true } } as any; export class ECI { static is: string = 'edit-crm-item'; /** * The type of this item */ static type: string = ''; static properties = editCrmItemProperties; static itemIndex: number; static index: number; /** * The showing animation of the type indicator */ private static _typeIndicatorAnimation: Animation = null; /** * The time of the last mouseover over the type-switcher */ private static _lastTypeSwitchMouseover: number = null; /** * The column this element is currently in */ static currentColumn: CRMColumnElement; /** * Whether the element's attached callback has been called before */ private static _hasBeenAttached: boolean = false; /** * Whether the user is currently hovering over the type switcher */ private static _hoveringTypeSwitcher: boolean = false; /** * Whether this item is being dragged by sortable (is a shdaow copy) */ private static _isDrag: boolean = false; static _openCodeSettings(this: EditCrmItem) { window.app.initCodeOptions(this.item as CRM.ScriptNode|CRM.StylesheetNode); } static getMenuExpandMessage(this: EditCrmItem) { if (!this.item.children) { return this.___(I18NKeys.options.editCrmItem.clickToShowChildren); } if ((this.item as CRM.MenuNode).children.length === 1) { return this.___(I18NKeys.options.editCrmItem.clickToShowChild); } return this.___(I18NKeys.options.editCrmItem.clickToShowXChildren, (this.item as CRM.MenuNode).children.length + ''); }; static update(this: EditCrmItem) { if (!this.classList.contains('id' + this.item.id)) { //Remove old ID and call ready const classes = this.classList; for (let i = 0; i < classes.length; i++) { if (classes[i].indexOf('id') > -1) { this.classList.remove(classes[i]); break; } } this.attached(true); } }; static async updateName(this: EditCrmItem, name: string) { if (name === undefined) { name = window.app.settings.rootName = await this.__async(I18NKeys.options.editCrmItem.rootName);; window.app.upload(); } this.set('itemName', name); this.item.name = name; } static rootNameChange(this: EditCrmItem) { const value = this.$$('#rootNameTitle').value; window.app.settings.rootName = value; window.app.upload(); } private static _initRootNode(this: EditCrmItem) { this.item = window.app.templates.getDefaultDividerNode({ name: 'Custom Menu', id: -1 as CRM.NodeId<CRM.DividerNode>, index: -1, path: [-1], onContentTypes: [true, true, true, true, true, true] }); } static onMouseOver(this: EditCrmItem, e: MouseEvent) { e.preventDefault(); e.stopPropagation(); if (!this._hoveringTypeSwitcher && !this._isDrag) { this._hoveringTypeSwitcher = true; this.typeIndicatorMouseOver(); } } private static _mouseMove(this: EditCrmItem, e: MouseEvent) { if (window.app.editCRM.dragging) { const event = new CustomEvent('dragover', { detail: { isCustom: true, target: window.app.util.getPath(e as any)[0], clientX: e.clientX, clientY: e.clientY } }); //Dispatch it to this node's column this.parentNode.dispatchEvent(event); } } static attached(this: EditCrmItem, force: boolean = false) { if (this._hasBeenAttached && !force) { return; } this._hasBeenAttached = true; if (this.classList.contains('fallbackFiller')) { this.$.itemCont.classList.add('fallbackFiller'); return; } if (this.classList.contains('draggingFiller') || this.getAttribute('draggable')) { //It's a dragging copy this.$.itemCont.classList.add('draggingFiller'); this._isDrag = true; } if (!this._isDrag) { this.addEventListener('mousemove', this._mouseMove.bind(this)); } if (!this._isDrag) { document.body.addEventListener('mousemove', () => { if (this._hoveringTypeSwitcher) { this._hoveringTypeSwitcher = false; this.typeIndicatorMouseLeave(); } }); } window.onExists('app').then(() => { if (this.rootNode) { //Skip initialization, only name is changable this._initRootNode(); return; } else { this.rootNode = false; } this.classList.add('id' + this.item.id); if (this.classList[0] !== 'wait') { this.itemIndex = this.index; this.item = this.item; this.itemName = this.item.name; this.calculateType(); this.itemIndex = this.index; this.$$('#typeSwitcher') && this.$$('#typeSwitcher').ready && this.$$('#typeSwitcher').ready(); if (window.app.editCRM.isSelecting) { this.$.itemCont.classList.add('selecting'); if (window.app.editCRM.selectedElements.indexOf(this.item.id) > -1) { this._onSelect(true, true); } else { this._onDeselect(true, true); } } } }); } static openMenu(this: EditCrmItem) { window.app.editCRM.build({ setItems: this.item.path }); }; private static _getCheckbox(this: EditCrmItem): HTMLPaperCheckboxElement { return this.shadowRoot.querySelector('#checkbox') as HTMLPaperCheckboxElement; } private static _selectThisNode(this: EditCrmItem) { let prevState = this._getCheckbox().checked; this._getCheckbox().checked = !prevState; if (window.app.editCRM.getItemsWithClass('highlighted').length === 0) { this.$.itemCont.classList.add('firstHighlighted'); } prevState ? this._onDeselect() : this._onSelect(); }; static openEditPage(this: EditCrmItem) { if (!this.shadow && !window.app.item && !this.rootNode) { if (!this.$.itemCont.classList.contains('selecting')) { const item = this.item; window.app.item = item; if (item.type === 'script') { window.app.stylesheetItem = null; window.app.scriptItem = item; } else if (item.type === 'stylesheet') { window.app.scriptItem = null; window.app.stylesheetItem = item; } else { window.app.stylesheetItem = null; window.app.scriptItem = null; } window.crmEditPage.init(); } else { this._selectThisNode(); } } }; static getTitle(this: EditCrmItem): string { if (this.rootNode) { return this.___(I18NKeys.options.editCrmItem.clickToEditRoot); } else if (this.hasAttribute('crm-type-hidden')) { return this.___(I18NKeys.options.editCrmItem.nodeHidden); } else { return this.___(I18NKeys.options.editCrmItem.clickToEdit); } } private static _getNextNode(node: CRM.Node): CRM.Node { if (node.children) { return node.children[0]; } const path = Array.prototype.slice.apply(node.path); let currentNodeSiblings = window.app.crm.lookup(path, true); let currentNodeIndex = path.splice(path.length - 1, 1)[0]; while (currentNodeSiblings.length - 1 <= currentNodeIndex) { currentNodeSiblings = window.app.crm.lookup(path, true); currentNodeIndex = path.splice(path.length - 1, 1)[0]; } return currentNodeSiblings[currentNodeIndex + 1]; }; private static _getPreviousNode(node: CRM.Node): CRM.Node { const path = Array.prototype.slice.apply(node.path); const currentNodeSiblings = window.app.crm.lookup(path, true); const currentNodeIndex = path.splice(path.length - 1, 1)[0]; if (currentNodeIndex === 0) { //return parent const parent = window.app.crm.lookup(path) as CRM.Node; return parent; } const possibleParent = currentNodeSiblings[currentNodeIndex - 1]; if (possibleParent.children) { return possibleParent.children[possibleParent.children.length - 1]; } return possibleParent; }; private static _getNodesOrder(this: EditCrmItem, reference: CRM.Node, other: CRM.Node): 'after'|'before'|'same' { let i; const referencePath = reference.path; const otherPath = other.path; //Check if they're the same if (referencePath.length === otherPath.length) { let same = true; for (i = 0; i < referencePath.length; i++) { if (referencePath[i] !== otherPath[i]) { same = false; break; } } if (same) { return 'same'; } } const biggestArray = (referencePath.length > otherPath.length ? referencePath.length : otherPath.length); for (i = 0; i < biggestArray; i++) { if (otherPath[i] !== undefined && referencePath[i] !== undefined) { if (otherPath[i] > referencePath[i]) { return 'after'; } else if (otherPath[i] < referencePath[i]) { return 'before'; } } else { if (otherPath[i] !== undefined) { return 'after'; } else { return 'before'; } } } return 'same'; }; private static _generateShiftSelectionCallback(this: EditCrmItem, node: CRM.Node, wait: number): () => void { return function() { window.setTimeout(function() { window.app.editCRM.getCRMElementFromPath(node.path)._onSelect(true); }, wait); }; }; private static _selectFromXToThis(this: EditCrmItem) { //Get the first highlighted node const firstHighlightedNode = window.app.editCRM.getItemsWithClass('firstHighlighted')[0]; const firstHighlightedItem = firstHighlightedNode.item; //Deselect everything else window.app.editCRM.getItemsWithClass('highlighted').forEach((item) => { item.$.itemCont.classList.remove('highlighted'); }); //Find out if the clicked on node is before, at, or after the first highlighted node const relation = this._getNodesOrder(firstHighlightedItem, this.item); if (relation === 'same') { this.$.itemCont.classList.add('highlighted'); this._getCheckbox().checked = true; window.app.editCRM.selectedElements = [this.item.id]; } else { firstHighlightedNode.$.itemCont.classList.add('highlighted'); (firstHighlightedNode.shadowRoot.getElementById('checkbox') as HTMLPaperCheckboxElement).checked = true; window.app.editCRM.selectedElements = [firstHighlightedNode.item.id]; let wait = 0; const nodeWalker = (relation === 'after' ? this._getNextNode : this._getPreviousNode); let node = nodeWalker(firstHighlightedItem); while (node.id !== this.item.id) { this._generateShiftSelectionCallback(node, wait)(); wait += 35; node = nodeWalker(node); } //Finally select this node window.setTimeout(() => { this.$.itemCont.classList.add('highlighted'); this._getCheckbox().checked = true; window.app.editCRM.selectedElements.push(this.item.id); }, wait); } }; static checkClickType(this: EditCrmItem, e: Polymer.ClickEvent) { if (this.rootNode) { return; } else if (e.detail.sourceEvent.ctrlKey) { window.app.editCRM.cancelAdding(); window.app.editCRM.selectItems(); this._selectThisNode(); } else if (this.$.itemCont.classList.contains('selecting') && e.detail.sourceEvent.shiftKey) { this._selectFromXToThis(); } else { window.app.editCRM.cancelAdding(); this.openEditPage(); } }; static calculateType(this: EditCrmItem) { this.type = this.item.type; this.isMenu = this.item.type === 'menu'; this.hasCodeSettings = (this.item.type === 'script' || this.item.type === 'stylesheet') && window.app.generateCodeOptionsArray(this.item.value.options).length > 0; }; static typeIndicatorMouseOver(this: EditCrmItem) { if (!this.shadow) { const time = Date.now(); this._lastTypeSwitchMouseover = time; this.async(() => { if (this._lastTypeSwitchMouseover === time) { this._lastTypeSwitchMouseover = null; $(this.$$('type-switcher').$$('.TSContainer')).stop().animate({ marginLeft: 0 }, 300); } }, 25); } }; private static _animateOut(this: EditCrmItem) { if (this._typeIndicatorAnimation && this._typeIndicatorAnimation.reverse) { this._typeIndicatorAnimation.reverse(); } else { $(this.$$('type-switcher').$$('.TSContainer')).stop().animate({ marginLeft: '-293px' }, 300); } }; static typeIndicatorMouseLeave(this: EditCrmItem) { this._lastTypeSwitchMouseover = null; if (!this.shadow) { const typeSwitcher = this.$$('#typeSwitcher'); if (typeSwitcher.toggledOpen) { typeSwitcher.closeTypeSwitchContainer(true, () => { typeSwitcher.toggledOpen = false; typeSwitcher.$.typeSwitchChoicesContainer.style.display = 'none'; window.setTransform(typeSwitcher.$.typeSwitchArrow, 'rotate(180deg)'); this._animateOut(); }); } else { this._animateOut(); } } }; private static _getOnSelectFunction(this: EditCrmItem, index: number) { return () => { window.app.editCRM.getCRMElementFromPath((this.item.children as CRM.Node[])[index].path)._onSelect(true); }; }; private static _onSelect(this: EditCrmItem, selectCheckbox: boolean = false, dontSelectChildren: boolean = false) { this.$.itemCont.classList.add('highlighted'); selectCheckbox && (this._getCheckbox().checked = true); if (this.item.children && !dontSelectChildren) { for (let i = 0; i < this.item.children.length; i++) { setTimeout(() => { this._getOnSelectFunction(i) }, (i * 35)); window.app.editCRM.selectedElements.push(this.item.children[i].id); } } }; private static _getOnDeselectFunction(this: EditCrmItem, index: number) { return () => { window.app.editCRM.getCRMElementFromPath((this.item.children as CRM.Node[])[index].path)._onDeselect(true); }; }; private static _onDeselect(this: EditCrmItem, selectCheckbox: boolean = false, dontSelectChildren: boolean = false) { this.$.itemCont.classList.remove('highlighted'); selectCheckbox && (this._getCheckbox().checked = false); if (this.item.children && !dontSelectChildren) { const selectedPaths = window.app.editCRM.selectedElements; for (let i = 0; i < this.item.children.length; i++) { setTimeout(() => { this._getOnDeselectFunction(i) }, (i * 35)); selectedPaths.splice(selectedPaths.indexOf(this.item.children[i].id), 1); } } }; static onToggle(this: EditCrmItem) { setTimeout(() => { if (this._getCheckbox().checked) { this._onSelect(); } else { this._onDeselect(); } }, 0); } } if (window.objectify) { window.register(ECI); } else { window.addEventListener('RegisterReady', () => { window.register(ECI); }); } } export type EditCrmItem = Polymer.El<'edit-crm-item', typeof EditCrmItemElement.ECI & typeof EditCrmItemElement.editCrmItemProperties>;
the_stack
import { CloudWatchLogsClient, CreateLogGroupCommand, CreateLogGroupCommandInput, CreateLogGroupCommandOutput, CreateLogStreamCommand, CreateLogStreamCommandInput, CreateLogStreamCommandOutput, DescribeLogGroupsCommand, DescribeLogGroupsCommandInput, DescribeLogGroupsCommandOutput, DescribeLogStreamsCommand, DescribeLogStreamsCommandInput, DescribeLogStreamsCommandOutput, GetLogEventsCommand, GetLogEventsCommandInput, GetLogEventsCommandOutput, InputLogEvent, LogGroup, LogStream, PutLogEventsCommand, PutLogEventsCommandInput, PutLogEventsCommandOutput, } from '@aws-sdk/client-cloudwatch-logs'; import { AWSCloudWatchProviderOptions, CloudWatchDataTracker, LoggingProvider, } from '../types/types'; import { Credentials } from '../..'; import { ConsoleLogger as Logger } from '../Logger'; import { getAmplifyUserAgent } from '../Platform'; import { parseMobileHubConfig } from '../Parser'; import { AWS_CLOUDWATCH_BASE_BUFFER_SIZE, AWS_CLOUDWATCH_CATEGORY, AWS_CLOUDWATCH_MAX_BATCH_EVENT_SIZE, AWS_CLOUDWATCH_MAX_EVENT_SIZE, AWS_CLOUDWATCH_PROVIDER_NAME, NO_CREDS_ERROR_STRING, RETRY_ERROR_CODES, } from '../Util/Constants'; const logger = new Logger('AWSCloudWatch'); class AWSCloudWatchProvider implements LoggingProvider { static readonly PROVIDER_NAME = AWS_CLOUDWATCH_PROVIDER_NAME; static readonly CATEGORY = AWS_CLOUDWATCH_CATEGORY; private _config: AWSCloudWatchProviderOptions; private _dataTracker: CloudWatchDataTracker; private _currentLogBatch: InputLogEvent[]; private _timer; private _nextSequenceToken: string | undefined; constructor(config?: AWSCloudWatchProviderOptions) { this.configure(config); this._dataTracker = { eventUploadInProgress: false, logEvents: [], }; this._currentLogBatch = []; this._initiateLogPushInterval(); } public getProviderName(): string { return AWSCloudWatchProvider.PROVIDER_NAME; } public getCategoryName(): string { return AWSCloudWatchProvider.CATEGORY; } public getLogQueue(): InputLogEvent[] { return this._dataTracker.logEvents; } public configure( config?: AWSCloudWatchProviderOptions ): AWSCloudWatchProviderOptions { if (!config) return this._config || {}; const conf = Object.assign( {}, this._config, parseMobileHubConfig(config).Logging, config ); this._config = conf; return this._config; } public async createLogGroup( params: CreateLogGroupCommandInput ): Promise<CreateLogGroupCommandOutput> { logger.debug( 'creating new log group in CloudWatch - ', params.logGroupName ); const cmd = new CreateLogGroupCommand(params); try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } const client = this._initCloudWatchLogs(); const output = await client.send(cmd); return output; } catch (error) { logger.error(`error creating log group - ${error}`); throw error; } } public async getLogGroups( params: DescribeLogGroupsCommandInput ): Promise<DescribeLogGroupsCommandOutput> { logger.debug('getting list of log groups'); const cmd = new DescribeLogGroupsCommand(params); try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } const client = this._initCloudWatchLogs(); const output = await client.send(cmd); return output; } catch (error) { logger.error(`error getting log group - ${error}`); throw error; } } public async createLogStream( params: CreateLogStreamCommandInput ): Promise<CreateLogStreamCommandOutput> { logger.debug( 'creating new log stream in CloudWatch - ', params.logStreamName ); const cmd = new CreateLogStreamCommand(params); try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } const client = this._initCloudWatchLogs(); const output = await client.send(cmd); return output; } catch (error) { logger.error(`error creating log stream - ${error}`); throw error; } } public async getLogStreams( params: DescribeLogStreamsCommandInput ): Promise<DescribeLogStreamsCommandOutput> { logger.debug('getting list of log streams'); const cmd = new DescribeLogStreamsCommand(params); try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } const client = this._initCloudWatchLogs(); const output = await client.send(cmd); return output; } catch (error) { logger.error(`error getting log stream - ${error}`); throw error; } } public async getLogEvents( params: GetLogEventsCommandInput ): Promise<GetLogEventsCommandOutput> { logger.debug('getting log events from stream - ', params.logStreamName); const cmd = new GetLogEventsCommand(params); try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } const client = this._initCloudWatchLogs(); const output = await client.send(cmd); return output; } catch (error) { logger.error(`error getting log events - ${error}`); throw error; } } public pushLogs(logs: InputLogEvent[]): void { logger.debug('pushing log events to Cloudwatch...'); this._dataTracker.logEvents = [...this._dataTracker.logEvents, ...logs]; } private async _validateLogGroupExistsAndCreate( logGroupName: string ): Promise<LogGroup> { if (this._dataTracker.verifiedLogGroup) { return this._dataTracker.verifiedLogGroup; } try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } const currGroups = await this.getLogGroups({ logGroupNamePrefix: logGroupName, }); if (!(typeof currGroups === 'string') && currGroups.logGroups) { const foundGroups = currGroups.logGroups.filter( group => group.logGroupName === logGroupName ); if (foundGroups.length > 0) { this._dataTracker.verifiedLogGroup = foundGroups[0]; return foundGroups[0]; } } /** * If we get to this point, it means that the specified log group does not exist * and we should create it. */ await this.createLogGroup({ logGroupName }); return null; } catch (err) { const errString = `failure during log group search: ${err}`; logger.error(errString); throw err; } } private async _validateLogStreamExists( logGroupName: string, logStreamName: string ): Promise<LogStream> { try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } const currStreams = await this.getLogStreams({ logGroupName, logStreamNamePrefix: logStreamName, }); if (currStreams.logStreams) { const foundStreams = currStreams.logStreams.filter( stream => stream.logStreamName === logStreamName ); if (foundStreams.length > 0) { this._nextSequenceToken = foundStreams[0].uploadSequenceToken; return foundStreams[0]; } } /** * If we get to this point, it means that the specified stream does not * exist, and we should create it now. */ await this.createLogStream({ logGroupName, logStreamName, }); return null; } catch (err) { const errString = `failure during log stream search: ${err}`; logger.error(errString); throw err; } } private async _sendLogEvents( params: PutLogEventsCommandInput ): Promise<PutLogEventsCommandOutput> { try { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error(NO_CREDS_ERROR_STRING); } logger.debug('sending log events to stream - ', params.logStreamName); const cmd = new PutLogEventsCommand(params); const client = this._initCloudWatchLogs(); const output = await client.send(cmd); return output; } catch (err) { const errString = `failure during log push: ${err}`; logger.error(errString); } } private _initCloudWatchLogs() { return new CloudWatchLogsClient({ region: this._config.region, credentials: this._config.credentials, customUserAgent: getAmplifyUserAgent(), endpoint: this._config.endpoint, }); } private async _ensureCredentials() { return await Credentials.get() .then(credentials => { if (!credentials) return false; const cred = Credentials.shear(credentials); logger.debug('set credentials for logging', cred); this._config.credentials = cred; return true; }) .catch(error => { logger.warn('ensure credentials error', error); return false; }); } private async _getNextSequenceToken(): Promise<string> { if (this._nextSequenceToken && this._nextSequenceToken.length > 0) { return this._nextSequenceToken; } /** * A sequence token will not exist if any of the following are true: * ...the log group does not exist * ...the log stream does not exist * ...the log stream does exist but has no logs written to it yet */ try { await this._validateLogGroupExistsAndCreate(this._config.logGroupName); this._nextSequenceToken = undefined; const logStream = await this._validateLogStreamExists( this._config.logGroupName, this._config.logStreamName ); if (logStream) { this._nextSequenceToken = logStream.uploadSequenceToken; } return this._nextSequenceToken; } catch (err) { logger.error(`failure while getting next sequence token: ${err}`); throw err; } } private async _safeUploadLogEvents(): Promise<PutLogEventsCommandOutput> { try { /** * CloudWatch has restrictions on the size of the log events that get sent up. * We need to track both the size of each event and the total size of the batch * of logs. * * We also need to ensure that the logs in the batch are sorted in chronological order. * https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html */ const seqToken = await this._getNextSequenceToken(); const logBatch = this._currentLogBatch.length === 0 ? this._getBufferedBatchOfLogs() : this._currentLogBatch; const putLogsPayload: PutLogEventsCommandInput = { logGroupName: this._config.logGroupName, logStreamName: this._config.logStreamName, logEvents: logBatch, sequenceToken: seqToken, }; this._dataTracker.eventUploadInProgress = true; const sendLogEventsResponse = await this._sendLogEvents(putLogsPayload); this._nextSequenceToken = sendLogEventsResponse.nextSequenceToken; this._dataTracker.eventUploadInProgress = false; this._currentLogBatch = []; return sendLogEventsResponse; } catch (err) { logger.error(`error during _safeUploadLogEvents: ${err}`); if (RETRY_ERROR_CODES.includes(err.name)) { this._getNewSequenceTokenAndSubmit({ logEvents: this._currentLogBatch, logGroupName: this._config.logGroupName, logStreamName: this._config.logStreamName, }); } else { this._dataTracker.eventUploadInProgress = false; throw err; } } } private _getBufferedBatchOfLogs(): InputLogEvent[] { /** * CloudWatch has restrictions on the size of the log events that get sent up. * We need to track both the size of each event and the total size of the batch * of logs. * * We also need to ensure that the logs in the batch are sorted in chronological order. * https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html */ let currentEventIdx = 0; let totalByteSize = 0; while (currentEventIdx < this._dataTracker.logEvents.length) { const currentEvent = this._dataTracker.logEvents[currentEventIdx]; const eventSize = currentEvent ? new TextEncoder().encode(currentEvent.message).length + AWS_CLOUDWATCH_BASE_BUFFER_SIZE : 0; if (eventSize > AWS_CLOUDWATCH_MAX_EVENT_SIZE) { const errString = `Log entry exceeds maximum size for CloudWatch logs. Log size: ${eventSize}. Truncating log message.`; logger.warn(errString); currentEvent.message = currentEvent.message.substring(0, eventSize); } if (totalByteSize + eventSize > AWS_CLOUDWATCH_MAX_BATCH_EVENT_SIZE) break; totalByteSize += eventSize; currentEventIdx++; } this._currentLogBatch = this._dataTracker.logEvents.splice( 0, currentEventIdx ); return this._currentLogBatch; } private async _getNewSequenceTokenAndSubmit( payload: PutLogEventsCommandInput ): Promise<PutLogEventsCommandOutput> { try { this._nextSequenceToken = undefined; this._dataTracker.eventUploadInProgress = true; const seqToken = await this._getNextSequenceToken(); payload.sequenceToken = seqToken; const sendLogEventsRepsonse = await this._sendLogEvents(payload); this._dataTracker.eventUploadInProgress = false; this._currentLogBatch = []; return sendLogEventsRepsonse; } catch (err) { logger.error( `error when retrying log submission with new sequence token: ${err}` ); this._dataTracker.eventUploadInProgress = false; throw err; } } private _initiateLogPushInterval(): void { if (this._timer) { clearInterval(this._timer); } this._timer = setInterval(async () => { try { if (this._getDocUploadPermissibility()) { await this._safeUploadLogEvents(); } } catch (err) { logger.error( `error when calling _safeUploadLogEvents in the timer interval - ${err}` ); } }, 2000); } private _getDocUploadPermissibility(): boolean { return ( (this._dataTracker.logEvents.length !== 0 || this._currentLogBatch.length !== 0) && !this._dataTracker.eventUploadInProgress ); } } export { AWSCloudWatchProvider };
the_stack
import { Signer, Utils, Wallet, XrplNetwork } from 'xpring-common-js' import XrpUtils from './shared/xrp-utils' import GrpcNetworkClient from './network-clients/grpc-xrp-network-client' import GrpcNetworkClientWeb from './network-clients/grpc-xrp-network-client.web' import { XRPDropsAmount } from './Generated/web/org/xrpl/rpc/v1/amount_pb' import { AccountRoot } from './Generated/web/org/xrpl/rpc/v1/ledger_objects_pb' import { Account, ClearFlag, LastLedgerSequence, SetFlag, SigningPublicKey, } from './Generated/web/org/xrpl/rpc/v1/common_pb' import { AccountSet, Transaction, } from './Generated/web/org/xrpl/rpc/v1/transaction_pb' import { AccountAddress } from './Generated/web/org/xrpl/rpc/v1/account_pb' import { GetFeeResponse } from './Generated/web/org/xrpl/rpc/v1/get_fee_pb' import TransactionStatus from './shared/transaction-status' import RawTransactionStatus from './shared/raw-transaction-status' import { GrpcNetworkClientInterface } from './network-clients/grpc-network-client-interface' import XrpError, { XrpErrorType } from './shared/xrp-error' import { LedgerSpecifier } from './Generated/web/org/xrpl/rpc/v1/ledger_pb' import TransactionResult from './shared/transaction-result' import isNode from '../Common/utils' import CoreXrplClientInterface from './core-xrpl-client-interface' import TransactionPrefix from './shared/transaction-prefix' async function sleep(milliseconds: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, milliseconds)) } /** A margin to pad the current ledger sequence with when submitting transactions. */ const maxLedgerVersionOffset = 10 /** * CoreXrplClient is a client which supports the core, common functionality for interacting with the XRP Ledger. */ export default class CoreXrplClient implements CoreXrplClientInterface { /** * Creates a new CoreXrplClient. * * The CoreXrplClient will use gRPC to communicate with the given endpoint. * * @param grpcUrl The URL of the gRPC instance to connect to. * @param network The network this XrpClient is connecting to. * @param forceWeb If `true`, then we will use the gRPC-Web client even when on Node. Defaults to false. This is mainly for testing and in the future will be removed when we have browser testing. */ public static coreXrplClientWithEndpoint( grpcUrl: string, network: XrplNetwork, forceWeb = false, ): CoreXrplClient { return isNode() && !forceWeb ? new CoreXrplClient(new GrpcNetworkClient(grpcUrl), network) : new CoreXrplClient(new GrpcNetworkClientWeb(grpcUrl), network) } /** * Creates a new CoreXrplClient with a custom network client implementation. * * @param networkClient A network client which will manage remote RPCs to Rippled. * @param network The network this XrpClient is connecting to. */ public constructor( public readonly networkClient: GrpcNetworkClientInterface, readonly network: XrplNetwork, ) {} /** * Retrieves the sequence number of the current open ledger in this rippled node. * @see https://xrpl.org/ledgers.html#open-closed-and-validated-ledgers */ public async getOpenLedgerSequence(): Promise<number> { const getFeeResponse = await this.getFee() return getFeeResponse.getLedgerCurrentIndex() } /** * Retrieve the latest validated ledger sequence on the XRP Ledger. * * Note: This call will throw if the given account does not exist on the ledger at the current time. It is the * *caller's responsibility* to ensure this invariant is met. * * Note: The input address *must* be in a classic address form. Inputs are not checked to this internal method. * * TODO: The above requirements are onerous, difficult to reason about and the logic of this method is * brittle. Replace this method's implementation when rippled supports a `ledger` RPC via gRPC. * * @param address An address that exists at the current time. The address is unchecked and must be a classic address. * @returns The index of the latest validated ledger. * @throws XrpException If there was a problem communicating with the XRP Ledger. */ public async getLatestValidatedLedgerSequence( address: string, ): Promise<number> { // rippled doesn't support a gRPC call that tells us the latest validated ledger sequence. To get around this, // query the account info for an account which will exist, using a shortcut for the latest validated ledger. The // response will contain the ledger index the information was retrieved at. const accountAddress = new AccountAddress() accountAddress.setAddress(address) const ledgerSpecifier = new LedgerSpecifier() ledgerSpecifier.setShortcut(LedgerSpecifier.Shortcut.SHORTCUT_VALIDATED) const getAccountInfoRequest = this.networkClient.GetAccountInfoRequest() getAccountInfoRequest.setAccount(accountAddress) getAccountInfoRequest.setLedger(ledgerSpecifier) const getAccountInfoResponse = await this.networkClient.getAccountInfo( getAccountInfoRequest, ) return getAccountInfoResponse.getLedgerIndex() } /** * Retrieves the raw transaction status for the given transaction hash. * * @param transactionHash: The hash of the transaction. * @returns The status of the given transaction. */ public async getRawTransactionStatus( transactionHash: string, ): Promise<RawTransactionStatus> { const getTxRequest = this.networkClient.GetTransactionRequest() getTxRequest.setHash(Utils.toBytes(transactionHash)) const getTxResponse = await this.networkClient.getTransaction(getTxRequest) return RawTransactionStatus.fromGetTransactionResponse(getTxResponse) } /** * Retrieves the minimum transaction cost for a reference transaction to be queued for a later ledger, * represented in drops of XRP. * @see https://xrpl.org/rippleapi-reference.html#transaction-fees * @see https://xrpl.org/fee.html#response-format */ public async getMinimumFee(): Promise<XRPDropsAmount> { const getFeeResponse = await this.getFee() const fee = getFeeResponse.getFee()?.getMinimumFee() if (!fee) { throw XrpError.malformedResponse } return fee } /** * Reports the current state of the open-ledger requirements for the transaction cost. * @see https://xrpl.org/rippleapi-reference.html#transaction-fees * @see https://xrpl.org/fee.html#response-format */ public async getFee(): Promise<GetFeeResponse> { const getFeeRequest = this.networkClient.GetFeeRequest() return this.networkClient.getFee(getFeeRequest) } /** * Returns the AccountRoot object containing information about this XRPL account. * @see https://xrpl.org/account_info.html#account_info * * @param address The XRPL account for which to retrieve information. */ public async getAccountData(address: string): Promise<AccountRoot> { const account = this.networkClient.AccountAddress() account.setAddress(address) const request = this.networkClient.GetAccountInfoRequest() request.setAccount(account) const ledger = new LedgerSpecifier() ledger.setShortcut(LedgerSpecifier.Shortcut.SHORTCUT_VALIDATED) request.setLedger(ledger) const accountInfo = await this.networkClient.getAccountInfo(request) if (!accountInfo) { throw XrpError.malformedResponse } const accountData = accountInfo.getAccountData() if (!accountData) { throw XrpError.malformedResponse } return accountData } /** * Populates the required fields common to all transaction types. * * @see https://xrpl.org/transaction-common-fields.html * * Note: The returned Transaction object must still be assigned transaction-specific details. * Some transaction types require a different fee (or no fee), in which case the fee should be overwritten appropriately * when constructing the transaction-specific details. (See https://xrpl.org/transaction-cost.html) * * @param wallet The wallet that will sign and submit this transaction. * @returns A promise which resolves to a Transaction protobuf with the required common fields populated. */ public async prepareBaseTransaction(wallet: Wallet): Promise<Transaction> { const classicAddress = XrpUtils.decodeXAddress(wallet.getAddress()) if (!classicAddress) { throw XrpError.xAddressRequired } const fee = await this.getMinimumFee() const accountData = await this.getAccountData(classicAddress.address) const openLedgerSequence = await this.getOpenLedgerSequence() const senderAccountAddress = new AccountAddress() senderAccountAddress.setAddress(wallet.getAddress()) const account = new Account() account.setValue(senderAccountAddress) const lastLedgerSequence = new LastLedgerSequence() lastLedgerSequence.setValue(openLedgerSequence + maxLedgerVersionOffset) const signingPublicKeyBytes = Utils.toBytes(wallet.publicKey) const signingPublicKey = new SigningPublicKey() signingPublicKey.setValue(signingPublicKeyBytes) const transaction = new Transaction() transaction.setAccount(account) transaction.setFee(fee) transaction.setSequence(accountData.getSequence()) transaction.setLastLedgerSequence(lastLedgerSequence) transaction.setSigningPublicKey(signingPublicKey) return transaction } /** * Signs the provided transaction using the wallet and submits to the XRPL network. * * @param transaction The transaction to be signed and submitted. * @param wallet The wallet that will sign and submit this transaction. * @returns A promise which resolves to a string representing the hash of the submitted transaction. */ public async signAndSubmitTransaction( transaction: Transaction, wallet: Wallet, ): Promise<string> { const signedTransaction = Signer.signTransaction(transaction, wallet) if (!signedTransaction) { throw XrpError.signingError } const submitTransactionRequest = this.networkClient.SubmitTransactionRequest() submitTransactionRequest.setSignedTransaction(signedTransaction) const response = await this.networkClient.submitTransaction( submitTransactionRequest, ) return Utils.toHex(response.getHash_asU8()) } /** * Returns a detailed TransactionResult for a given XRPL transaction hash. * * @param transactionHash The transaction hash to populate a TransactionResult for. * @returns A Promise which resolves to a TransactionResult associated with the given transaction hash. */ public async getTransactionResult( transactionHash: string, ): Promise<TransactionResult> { const rawStatus = await this.getRawTransactionStatus(transactionHash) const isValidated = rawStatus.isValidated const transactionStatus = await this.getTransactionStatus(transactionHash) // TODO: add logic to this method to investigate the transaction's last ledger sequence, // the XRPL latest ledger sequence, and make a more granular distinction in case of yet-unvalidated txn?? return isValidated ? TransactionResult.createFinalTransactionResult( transactionHash, transactionStatus, isValidated, ) : TransactionResult.createPendingTransactionResult( transactionHash, transactionStatus, isValidated, ) } /** * Retrieve the transaction status for a Transaction given a transaction hash. * * Note: This method will only work for Payment type transactions which do not have the tf_partial_payment attribute set. * @see https://xrpl.org/payment.html#payment-flags * * @param transactionHash The hash of the transaction. * @returns A TransactionStatus containing the status of the given transaction. */ public async getTransactionStatus( transactionHash: string, ): Promise<TransactionStatus> { const transactionStatus = await this.getRawTransactionStatus( transactionHash, ) // Return pending if the transaction is not validated. if (!transactionStatus.isValidated) { return TransactionStatus.Pending } const statusCode = transactionStatus.transactionStatusCode const statusPrefix = statusCode.substr(0, 3) switch (statusPrefix) { case TransactionPrefix.Success: return TransactionStatus.Succeeded case TransactionPrefix.MalformedTransaction: return TransactionStatus.MalformedTransaction case TransactionPrefix.Failure: return TransactionStatus.Failed case TransactionPrefix.ClaimedCostOnly: switch (statusCode) { case 'tecPATH_PARTIAL': return TransactionStatus.ClaimedCostOnly_PathPartial case 'tecPATH_DRY': return TransactionStatus.ClaimedCostOnly_PathDry default: return TransactionStatus.ClaimedCostOnly } default: return TransactionStatus.Unknown } } /** * Waits for a transaction to complete and returns a TransactionResult. * * @param transactionHash The transaction to wait for. * @param wallet The wallet sending the transaction. * * @returns A Promise resolving to a TransactionResult containing the results of the transaction associated with * the given transaction hash. */ public async getFinalTransactionResultAsync( transactionHash: string, wallet: Wallet, ): Promise<TransactionResult> { const { rawTransactionStatus, lastLedgerPassed, } = await this.waitForFinalTransactionOutcome(transactionHash, wallet) const finalStatus = lastLedgerPassed ? TransactionStatus.LastLedgerSequenceExpired : this.getFinalTransactionStatus(rawTransactionStatus) return TransactionResult.createFinalTransactionResult( transactionHash, finalStatus, rawTransactionStatus.isValidated, ) } /** * Determines the current TransactionStatus from a RawTransactionStatus (translating from * a rippled transaction status code such as `tesSUCCESS`, in conjunction with validated * status, into a TransactionStatus enum instance) * * @param rawTransactionStatus */ private getFinalTransactionStatus( rawTransactionStatus: RawTransactionStatus, ): TransactionStatus { if (rawTransactionStatus.transactionStatusCode.startsWith('tem')) { return TransactionStatus.MalformedTransaction } if (rawTransactionStatus.transactionStatusCode.includes('tecPATH_DRY')) { return TransactionStatus.ClaimedCostOnly_PathDry } if ( rawTransactionStatus.transactionStatusCode.includes('tecPATH_PARTIAL') ) { return TransactionStatus.ClaimedCostOnly_PathPartial } if (rawTransactionStatus.transactionStatusCode.startsWith('tec')) { return TransactionStatus.ClaimedCostOnly } if (!rawTransactionStatus.isValidated) { throw new XrpError( XrpErrorType.InvalidInput, "The lastLedgerSequence was not passed, but the ledger is not validated either. `getFinalTransactionStatus` shouldn't be called in this case.", ) } else { const transactionStatus = rawTransactionStatus.transactionStatusCode?.startsWith( 'tes', ) ? TransactionStatus.Succeeded : TransactionStatus.Failed return transactionStatus } } private isMalformedTransaction( rawTransactionStatus: RawTransactionStatus, ): boolean { return rawTransactionStatus.transactionStatusCode.startsWith('tem') } /** * The core logic of reliable submission. Polls the ledger until the result of the transaction * can be considered final, meaning it has either been included in a validated ledger, or the * transaction's lastLedgerSequence has been surpassed by the latest ledger sequence (meaning it * will never be included in a validated ledger.) * * @param transactionHash The hash of the transaction being awaited. * @param sender The address used to obtain the latest ledger sequence. */ public async waitForFinalTransactionOutcome( transactionHash: string, sender: Wallet, ): Promise<{ rawTransactionStatus: RawTransactionStatus lastLedgerPassed: boolean }> { const ledgerCloseTimeMs = 4 * 1000 await sleep(ledgerCloseTimeMs) // Get transaction status. let rawTransactionStatus = await this.getRawTransactionStatus( transactionHash, ) const { lastLedgerSequence } = rawTransactionStatus if (!lastLedgerSequence) { return Promise.reject( new Error( 'The transaction did not have a lastLedgerSequence field so transaction status cannot be reliably determined.', ), ) } // Decode the sending address to a classic address for use in determining the last ledger sequence. // An invariant of `getLatestValidatedLedgerSequence` is that the given input address (1) exists when the method // is called and (2) is in a classic address form. // // The sending address should always exist, except in the case where it is deleted. A deletion would supersede the // transaction in flight, either by: // 1) Consuming the nonce sequence number of the transaction, which would effectively cancel the transaction // 2) Occur after the transaction has settled which is an unlikely enough case that we ignore it. // // This logic is brittle and should be replaced when we have an RPC that can give us this data. const classicAddress = XrpUtils.decodeXAddress(sender.getAddress()) if (!classicAddress) { throw new XrpError( XrpErrorType.Unknown, 'The source wallet reported an address which could not be decoded to a classic address', ) } const sourceClassicAddress = classicAddress.address // Retrieve the latest ledger index. let latestLedgerSequence = await this.getLatestValidatedLedgerSequence( sourceClassicAddress, ) // Poll until the transaction is validated, or until the lastLedgerSequence has been passed. /* * In general, performing an await as part of each operation is an indication that the program is not taking full advantage of the parallelization benefits of async/await. * Usually, the code should be refactored to create all the promises at once, then get access to the results using Promise.all(). Otherwise, each successive operation will not start until the previous one has completed. * But here specifically, it is reasonable to await in a loop, because we need to wait for the ledger, and there is no good way to refactor this. * https://eslint.org/docs/rules/no-await-in-loop */ /* eslint-disable no-await-in-loop */ while ( latestLedgerSequence <= lastLedgerSequence && !rawTransactionStatus.isValidated && !this.isMalformedTransaction(rawTransactionStatus) ) { await sleep(ledgerCloseTimeMs) // Update latestLedgerSequence and rawTransactionStatus latestLedgerSequence = await this.getLatestValidatedLedgerSequence( sourceClassicAddress, ) rawTransactionStatus = await this.getRawTransactionStatus(transactionHash) } /* eslint-enable no-await-in-loop */ const lastLedgerPassed = latestLedgerSequence >= lastLedgerSequence return { rawTransactionStatus: rawTransactionStatus, lastLedgerPassed: lastLedgerPassed, } } /** * Helper function. Sets/clears a flag value. * @param flag The desired flag that is being changed. * @param enable Whether the flag is being enabled (true if enabling, false if disabling). * @param wallet The wallet associated with the XRPL account enabling Require Authorization and that will sign the request. * @returns A promise which resolves to a TransactionResult object that represents the result of this transaction. */ public async changeFlag( flag: number, enable: boolean, wallet: Wallet, ): Promise<TransactionResult> { const accountSet = new AccountSet() if (enable) { const setFlag = new SetFlag() setFlag.setValue(flag) accountSet.setSetFlag(setFlag) } else { const clearFlag = new ClearFlag() clearFlag.setValue(flag) accountSet.setClearFlag(clearFlag) } const transaction = await this.prepareBaseTransaction(wallet) transaction.setAccountSet(accountSet) const transactionHash = await this.signAndSubmitTransaction( transaction, wallet, ) return await this.getFinalTransactionResultAsync(transactionHash, wallet) } }
the_stack
import { getPropertyValue, isExtrudedPolygonTechnique, MapEnv, Technique } from "@here/harp-datasource-protocol"; import { TileKey } from "@here/harp-geoutils"; import { ExtrusionFeature, ExtrusionFeatureDefs } from "@here/harp-materials"; import { MathUtils } from "@here/harp-utils"; import { DataSource } from "./DataSource"; import { MapView } from "./MapView"; import { Tile } from "./Tile"; /** * Animation states for extrusion effect */ export enum AnimatedExtrusionState { None, Started, Finished } const DEFAULT_EXTRUSION_DURATION = 750; // milliseconds const DEFAULT_MIN_ZOOM_LEVEL = 1; interface TileExtrusionState { materials: ExtrusionFeature[]; animated: boolean; } // key is tile's morton code. type TileMap = Map<number, TileExtrusionState>; /** * Handles animated extrusion effect of the buildings in {@link MapView}. */ export class AnimatedExtrusionHandler { /** * Animate the extrusion of the buildings if set to `true`. */ enabled: boolean = true; /** * Duration of the building's extrusion in milliseconds */ duration: number = DEFAULT_EXTRUSION_DURATION; private m_minZoomLevel: number = DEFAULT_MIN_ZOOM_LEVEL; private m_forceEnabled: boolean = false; private readonly m_dataSourceMap: Map<DataSource, TileMap> = new Map(); private m_state: AnimatedExtrusionState = AnimatedExtrusionState.None; private m_startTime: number = -1; /** * Creates an {@link AnimatedExtrusionHandler} in {@link MapView}. * * @param m_mapView - Instance of {@link MapView} on which the animation will run. */ constructor(private readonly m_mapView: MapView) {} /** * Returns whether the extrusion animation is force enabled or not. */ get forceEnabled(): boolean { return this.m_forceEnabled; } /** * If `forceEnabled` is set to `true` then `animateExtrusion` and `animateExtrusionDuration` * values from [[extrudedPolygonTechnique]] will be ignored and * `AnimatedExtrusionHandler.enabled` with `AnimatedExtrusionHandler.duration` will be used */ set forceEnabled(force: boolean) { this.m_forceEnabled = force; this.duration = DEFAULT_EXTRUSION_DURATION; } /** * Gets min zoom level at which extruded animation is enabled. */ get minZoomLevel() { return this.m_minZoomLevel; } /** * Sets the extrusion animation properties obtained from a given technique. * @internal * @param technique - The technique where the extrusion animation properties are defined. * @param env - The environment used to evaluate technique properties. * @returns True if the technique has animation enabled (or animation is forced), false * otherwise. */ setAnimationProperties(technique: Technique, env: MapEnv) { if (!isExtrudedPolygonTechnique(technique)) { return false; } if (technique.hasOwnProperty("minZoomLevel")) { this.m_minZoomLevel = (technique as any).minZoomLevel; } if (this.forceEnabled) { return this.enabled; } if (technique.animateExtrusionDuration !== undefined) { this.duration = technique.animateExtrusionDuration; } const animateExtrusionValue = getPropertyValue(technique.animateExtrusion, env); if (animateExtrusionValue === null) { return this.enabled; } return typeof animateExtrusionValue === "boolean" ? animateExtrusionValue : typeof animateExtrusionValue === "number" ? animateExtrusionValue !== 0 : false; } /** * Updates the extrusion animation for every frame. * @internal */ update(zoomLevel: number) { const extrusionVisible = this.m_dataSourceMap.size > 0 && zoomLevel >= this.m_minZoomLevel; if (this.m_state === AnimatedExtrusionState.None && extrusionVisible) { this.m_state = AnimatedExtrusionState.Started; } else if (this.m_state !== AnimatedExtrusionState.None && !extrusionVisible) { this.resetAnimation(true); } this.animateExtrusion(); } /** * Adds a tile to be animated. * @internal * @param tile - The tile to be animated. * @param materials - Extruded materials belonging to the tile. */ add(tile: Tile, materials: ExtrusionFeature[]): void { tile.addDisposeCallback(this.removeTile.bind(this)); let animated = false; if (this.m_state !== AnimatedExtrusionState.None) { animated = this.skipAnimation(tile); if (animated) { // Set extrusion ratio to 1 if the tile skips the animation. this.setTileExtrusionRatio(materials, 1); } else if (this.m_state === AnimatedExtrusionState.Finished) { // Otherwise, if animation was finished, restart animation but leave already // animated tiles untouched. this.resetAnimation(false); } } this.getOrCreateTileMap(tile.dataSource).set(tile.tileKey.mortonCode(), { materials, animated }); } /** * Is `true` if there's any extrusion animation ongoing. */ get isAnimating(): boolean { return ( this.m_state !== AnimatedExtrusionState.Finished && this.m_state !== AnimatedExtrusionState.None ); } private getTileMap(dataSource: DataSource, create: boolean = false): TileMap | undefined { return this.m_dataSourceMap.get(dataSource); } private getOrCreateTileMap(dataSource: DataSource): TileMap { let tileMap = this.m_dataSourceMap.get(dataSource); if (!tileMap) { tileMap = new Map(); this.m_dataSourceMap.set(dataSource, tileMap); } return tileMap; } private skipAnimation(tile: Tile): boolean { return this.wasAnyAncestorAnimated(tile) || this.wasAnyDescendantAnimated(tile); } private wasAnyAncestorAnimated(tile: Tile): boolean { const minLevel = tile.dataSource.getDataZoomLevel(this.m_minZoomLevel); const distanceToMinLevel = Math.max(0, tile.tileKey.level - minLevel); const levelsUp = Math.min( distanceToMinLevel, this.m_mapView.visibleTileSet.options.quadTreeSearchDistanceUp ); const tileMap = this.getTileMap(tile.dataSource); if (!tileMap) { return false; } let lastTileKey = tile.tileKey; for (let deltaUp = 1; deltaUp <= levelsUp; ++deltaUp) { lastTileKey = lastTileKey.parent(); if (tileMap.get(lastTileKey.mortonCode())?.animated ?? false) { return true; } } return false; } private wasAnyDescendantAnimated(tile: Tile): boolean { const distanceToMaxLevel = tile.dataSource.maxDataLevel - tile.tileKey.level; const levelsDown = Math.min( distanceToMaxLevel, this.m_mapView.visibleTileSet.options.quadTreeSearchDistanceDown ); const tileMap = this.getTileMap(tile.dataSource); if (!tileMap) { return false; } const tilingScheme = tile.dataSource.getTilingScheme(); let nextTileKeys = [tile.tileKey]; let childTileKeys: TileKey[] = []; for (let deltaDown = 1; deltaDown <= levelsDown; ++deltaDown) { childTileKeys.length = 0; for (const tileKey of nextTileKeys) { for (const childTileKey of tilingScheme.getSubTileKeys(tileKey)) { if (tileMap.get(childTileKey.mortonCode())?.animated ?? false) { return true; } childTileKeys.push(childTileKey); } } // swap [nextTileKeys, childTileKeys] = [childTileKeys, nextTileKeys]; } return false; } private removeTile(tile: Tile): void { const tileMap = this.getTileMap(tile.dataSource); if (!tileMap) { return; } tileMap.delete(tile.tileKey.mortonCode()); // Remove tile map if it's empty. That way, counting the number of data sources in the // map is enough to know if there's any tile. if (tileMap.size === 0) { this.m_dataSourceMap.delete(tile.dataSource); } } private animateExtrusion() { if (this.m_state !== AnimatedExtrusionState.Started) { return; } const currentTime = Date.now(); if (this.m_startTime < 0) { this.m_startTime = currentTime; } const duration = this.duration; const timeProgress = Math.min(currentTime - this.m_startTime, duration); const extrusionRatio = MathUtils.easeInOutCubic( ExtrusionFeatureDefs.DEFAULT_RATIO_MIN, ExtrusionFeatureDefs.DEFAULT_RATIO_MAX, timeProgress / duration ); this.setExtrusionRatio(extrusionRatio); if (timeProgress >= duration) { this.m_state = AnimatedExtrusionState.Finished; } this.m_mapView.update(); } private resetAnimation(resetTiles: boolean) { this.m_state = AnimatedExtrusionState.None; this.m_startTime = -1; if (resetTiles) { this.m_dataSourceMap.forEach(tileMap => { tileMap.forEach(state => { state.animated = false; }); }); } } private setExtrusionRatio(value: number) { this.m_dataSourceMap.forEach(tileMap => { tileMap.forEach(state => { if (!state.animated) { this.setTileExtrusionRatio(state.materials, value); if (value >= 1) { state.animated = true; } } }); }); } private setTileExtrusionRatio(materials: ExtrusionFeature[], value: number) { materials.forEach(material => { material.extrusionRatio = value; }); } }
the_stack
interface ArtyomWindow extends Window { webkitSpeechRecognition: any; SpeechRecognition: any; SpeechSynthesisUtterance: any; } interface SpeechRecognition extends EventTarget { grammars: SpeechGrammarList; lang: string; continuous: boolean; interimResults: boolean; maxAlternatives: number; serviceURI: string; start(): void; stop(): void; abort(): void; onaudiostart: (ev: Event) => any; onsoundstart: (ev: Event) => any; onspeechstart: (ev: Event) => any; onspeechend: (ev: Event) => any; onsoundend: (ev: Event) => any; onresult: (ev: SpeechRecognitionEvent) => any; onnomatch: (ev: SpeechRecognitionEvent) => any; onerror: (ev: SpeechRecognitionError) => any; onstart: (ev: Event) => any; onend: (ev: Event) => any; } interface SpeechRecognitionStatic { prototype: SpeechRecognition; new (): SpeechRecognition; } declare var SpeechRecognition: SpeechRecognitionStatic; declare var webkitSpeechRecognition: SpeechRecognitionStatic; interface SpeechRecognitionError extends Event { error: string; message: string; } interface SpeechRecognitionAlternative { transcript: string; confidence: number; } interface SpeechRecognitionResult { length: number; item(index: number): SpeechRecognitionAlternative; [index: number]: SpeechRecognitionAlternative; isFinal: boolean; } interface SpeechRecognitionResultList { length: number; item(index: number): SpeechRecognitionResult; [index: number]: SpeechRecognitionResult; } interface SpeechRecognitionEvent extends Event { resultIndex: number; results: SpeechRecognitionResultList; interpretation: any; emma: Document; } interface SpeechGrammar { src: string; weight: number; } interface SpeechGrammarStatic { prototype: SpeechGrammar; new (): SpeechGrammar; } declare var SpeechGrammar: SpeechGrammarStatic; declare var webkitSpeechGrammar: SpeechGrammarStatic; interface SpeechGrammarList { length: number; item(index: number): SpeechGrammar; [index: number]: SpeechGrammar; addFromURI(src: string, weight: number): void; addFromString(string: string, weight: number): void; } interface SpeechGrammarListStatic { prototype: SpeechGrammarList; new (): SpeechGrammarList; } declare var SpeechGrammarList: SpeechGrammarListStatic; declare var webkitSpeechGrammarList: SpeechGrammarListStatic; interface SpeechSynthesis extends EventTarget { pending: boolean; speaking: boolean; paused: boolean; onvoiceschanged: (ev: Event) => any; speak(utterance: SpeechSynthesisUtterance): void; cancel(): void; pause(): void; resume(): void; getVoices(): SpeechSynthesisVoice[]; } interface SpeechSynthesisGetter { speechSynthesis: SpeechSynthesis; } declare var speechSynthesis: SpeechSynthesis; interface SpeechSynthesisUtterance extends EventTarget { text: string; lang: string; voice: SpeechSynthesisVoice; volume: number; rate: number; pitch: number; onstart: (ev: SpeechSynthesisEvent) => any; onend: (ev: SpeechSynthesisEvent) => any; onerror: (ev: SpeechSynthesisErrorEvent) => any; onpause: (ev: SpeechSynthesisEvent) => any; onresume: (ev: SpeechSynthesisEvent) => any; onmark: (ev: SpeechSynthesisEvent) => any; onboundary: (ev: SpeechSynthesisEvent) => any; } interface SpeechSynthesisUtteranceStatic { prototype: SpeechSynthesisUtterance; new (text?: string): SpeechSynthesisUtterance; } declare var SpeechSynthesisUtterance: SpeechSynthesisUtteranceStatic; interface SpeechSynthesisEvent extends Event { utterance: SpeechSynthesisUtterance; charIndex: number; elapsedTime: number; name: string; } interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent { error: string; } interface SpeechSynthesisVoice { voiceURI: string; name: string; lang: string; localService: boolean; default: boolean; } declare namespace Artyom { interface ArtyomDevice { isChrome(): boolean; isMobile(): boolean; } interface ArtyomBrowserVoiceObject { default: boolean; lang: string; localService: false; name: string; voiceURI: string; } interface ArtyomConfigProperties { /** Set the default language of artyom with this property */ lang?: string; recognizing?: boolean; /** Choose if should listen one command and then stops, or listening forever */ continuous?: boolean; /** Moderates the speed with which Artyom talks (0 ~ 1) */ speed?: number; /** Adjust the volume of the voice of artyom */ volume?: number; /** If listen is equal to true the voice recognition will be started otherwise this property can be ignored */ listen: boolean; /** Recognition mode: normal, quick, remote */ mode?: string; /** Displays all the grammars recognized in the console */ debug: boolean; helpers?: { redirectRecognizedTextOutput: any; remoteProcessorHandler: any; lastSay: any; }; /** Set a keyword that allows your command to be executed immediately when you say this word (Useful in noisy environments) */ executionKeyword?: string; /** Set a keyword that allows to enable the command recognition automatically if this word is recognized while artyom is paused (artyom.dontObey) */ obeyKeyword?: string; speaking?: boolean; obeying?: boolean; soundex?: boolean; } interface ArtyomCommand { /** Triggers of the command */ indexes: string[]; /** Logic to execute when the command is triggered */ action: (i: number, wildcard?: string, full?: string) => void; /** Description of the command */ description?: string; /** Flag to specify is a command is either normal or smart */ smart?: boolean; } interface ArtyomFlags { restartRecognition: boolean; } interface ArtyomRecognizer { lang: string; continuous: boolean; interimResults: boolean; start(): void; stop(): void; onstart(): void; onresult(event: any): void; onerror(event: any): void; onend(): void; } export interface ArtyomJS { /** * Contains some basic information that artyom needs to know as the type of device and browser * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/device */ device: ArtyomDevice; /** * Object which provides the speech interface, and set some of its attributes and event handlers */ artyomWSR: ArtyomRecognizer; /** * Artyom can return inmediately the voices available in your browser. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getvoices * @returns {Array} */ getVoices(): SpeechSynthesisVoice[]; /** * Returns an array with all the available commands for artyom. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getavailablecommands * @returns {Array} */ getAvailableCommands(): ArtyomCommand[]; /** * Set up artyom for the application. This function will set the default language used by artyom * or notice the user if artyom is not supported in the actual browser. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/initialize * @param {ArtyomConfigProperties} config * @returns {Boolean} */ initialize(config: ArtyomConfigProperties): boolean; /** * Force artyom to stop listen even if is in continuos mode. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/fatality * @returns {Boolean} */ fatality(): boolean; /** * Add dinamically commands to artyom using. You can even add commands while artyom is active. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/addcommands * @param {ArtyomCommand | Array[ArtyomCommand]} newCommand * @returns {Boolean} */ addCommands(newCommand: ArtyomCommand | ArtyomCommand[]): boolean; /** * Remove the commands of artyom with indexes that matches with the given text. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/removecommands * @param {string} identifier * @returns {Array} */ removeCommands(identifier: string): number[]; /** * Removes all the added commands of artyom. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/emptycommands * @returns {Array} */ emptyCommands(): ArtyomCommand[]; /** * Stops the actual and pendings messages that artyom have to say. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/shutup */ shutUp(): void; /** * Returns an object with the actual properties of artyom. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getproperties * @returns {ArtyomConfigProperties} */ getProperties(): ArtyomConfigProperties; /** * Create a listener when an artyom action is called. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/when */ when(event: any, action: any): any; /** * Returns the code language of artyom according to initialize function. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getlanguage * @returns {String} Language */ getLanguage(): string; /** * Talks a text according to the given parameters (private function). * @param {String} text Text to be spoken * @param {Int} actualChunk Number of chunk of the * @param {Int} totalChunks * @param {any} callbacks */ artyomTalk(text: any, actualChunk: any, totalChunks: any, callbacks: any): any; /** * Splits a string into an array of strings with a limited size (chunk_length). * @param {String} input text to split into chunks * @param {Integer} chunk_length limit of characters in every chunk */ splitStringByChunks(input: any, chunk_length: any): string[]; /** * Process the given text into chunks and execute the private function artyom_talk. * @param {String} message Text to be spoken * @param {Object} callbacks { onStart, onEnd } * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/say */ say(message: any, callbacks?: any): void; /** * Repeats the last sentence that artyom said. Useful in noisy environments. * @param {Boolean} returnObject If set to true, an object with the text and the timestamp when was executed will be returned. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/repeatlastsay */ repeatLastSay(returnObject: any): void; /** * Verify if the browser supports speechSynthesis. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/speechsupported * @returns {Boolean} */ speechSupported(): boolean; /** * Verify if the browser supports webkitSpeechRecognition. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/recognizingsupported * @returns {Boolean} */ recognizingSupported(): boolean; /** * Simulate a voice command via JS. * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/simulateinstruction * @param {string} sentence * @returns {Boolean} */ simulateInstruction(sentence: string): boolean; /** * Returns an object with data of the matched element. * @param {string} voiceCommand * @returns {Object | Function}. There is a result field when the function should return a boolean value. */ artyomExecute(voiceCommand: string): any; /** * Displays a message in the console if the artyom propery DEBUG is set to true. * @param {string} error The error to be debugged * @param {string} traceLevel Error level: { error | warn | info } * @see http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/debug */ debug(stringEvent: string, traceLevel: string): void; /** * Allows to retrieve the recognized spoken text of artyom and do something with it everytime something is recognized. * @param {Function} action * @returns {Boolean} */ redirectRecognizedTextOutput(action: () => void): boolean; /** * Says a random quote and returns it's object. * @param data */ sayRandom(data: any): any; /** * Artyom provide an easy way to create a dictation for your user. Just create an instance and start and stop when you want. */ newDictation(settings: any): any; /** * A voice prompt will be executed. */ newPrompt(config: any): any; /** * Artyom awaits for orders when this function is executed. If artyom gets a first parameter the instance will be stopped. */ artyomHey(resolve: any, reject: any): any; /** * This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some * values, do not make changes directly. */ getNativeApi(): any; /** * This function returns a boolean according to the SpeechRecognition status if artyom is listening, will return true. * Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd * events of the SpeechRecognition * @returns {Boolean} */ isRecognizing(): boolean; /** * This function returns a boolean according to the speechSynthesis status if artyom is speaking, will return true. * Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd * events of the speechSynthesis. * @returns {Boolean} */ isSpeaking(): boolean; /** * The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour * of artyom.say. Use this method to clear all spoken SpeechSynthesisUtterance unused objects. * @returns {Boolean} */ clearGarbageCollection(): any; /** * Returns the SpeechSynthesisUtterance garbageobjects. */ getGarbageCollection(): any; /** * Pause the processing of commands. Artyom still listening in the background and it can be resumed after a couple of seconds. * @returns {Boolean} */ dontObey(): any; /** * Allow artyom to obey commands again. * @returns {Boolean} */ obey(): any; /** * A boolean to check if artyom is obeying commands or not. * @returns {Boolean} */ isObeying(): boolean; /** * Process the recognized text if artyom is active in remote mode. * @returns {Boolean} */ remoteProcessorService(action: any): any; /** * Returns a string with the actual version of Artyom script. * @returns {String} */ getVersion(): string; /** * Add commands like an artisan. If you use artyom for simple * tasks then probably you don't like to write a lot to achieve it. * Use the artisan syntax to write less, but with the same accuracy. * @disclaimer Not a promise-based implementation, just syntax. * @returns {Object} */ on(indexes: any, smart: any): any; } /** * Main class to create the singleton instance of Artyom */ export class ArtyomBuilder { /** * Method to access to the single and unique instance of Artyom engine */ static getInstance(): ArtyomJS } } //tslint:disable-next-line:export-just-namespace export = Artyom; export as namespace Artyom;
the_stack
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- import * as React from 'react'; import { Card, CardTitle, CardBody } from 'reactstrap'; export const DeviceEditFormTutorial = (props: {}) => { return ( <Card> <CardBody> <CardTitle> <span className="h6">Tutorial</span> </CardTitle> <p> Device Mapping is used to normalize the data input from your devices. </p> Note: <br /> <ul> <li>Field with * is required.</li> <li>Patient ID Expression is required when you choose "Create" as Identity Resolution Type.</li> </ul> <p> Let's start with one example. Your data input from a heart rate measuring device is as below and its data type name is "HeartRate". </p> <pre> { JSON.stringify({ "payload": { "heartRate": "78", }, "metadata": { "measuringTime": "2019-02-01T22:46:01.8750000Z", "deviceId": "dsn-9cvb89", "userId": "uid-12hfd8" } }, null, 4) } </pre> <p> You will need to fill in below information: </p> <table className="m-3"> <tbody> <tr> <td className="pr-4">Type Match Expression:</td> <td> <pre className="d-inline-flex m-0">$..[?(@payload.heartRate)]</pre> </td> </tr> <tr> <td className="pr-4">Device ID Expression:</td> <td> <pre className="d-inline-flex m-0">$.metadata.deviceId</pre> </td> </tr> <tr> <td className="pr-4">Timestamp Expression:</td> <td> <pre className="d-inline-flex m-0">$.metadata.measuringTime</pre> </td> </tr> <tr> <td className="pr-4">Patient ID Expression:</td> <td> <pre className="d-inline-flex m-0">$.metadata.userId</pre> </td> </tr> <tr> <td className="pr-4" colSpan={2}>Values:</td> </tr> <tr> <td className="pl-4 pr-4">Value Name:</td> <td> <pre className="d-inline-flex m-0">Heart Rate</pre> </td> </tr> <tr> <td className="pl-4 pr-4">Value Expression:</td> <td> <pre className="d-inline-flex m-0">$.payload.heartRate</pre> </td> </tr> <tr> <td className="pl-4 pr-4">Required:</td> <td> <pre className="d-inline-flex m-0">True</pre> </td> </tr> </tbody> </table> <p> For more information, please visit: <a href="https://github.com/microsoft/iomt-fhir/blob/master/docs/Configuration.md">IoMT Mapping Configuration</a> </p> </CardBody> </Card> ); } export const FhirValueFormTutorial = (props: {}) => { return ( <Card> <CardBody> <CardTitle> <span className="h6">Tutorial</span> </CardTitle> <p> Configure the tranfromation of the normalized device value data to FHIR Resource. <a href="https://www.hl7.org/fhir/observation-definitions.html#Observation.value_x_">Observation.Value</a>. </p> Note: <br /> <ul> <li>You should use this for single value transformation. For multiple values, please consider using FHIR Components.</li> <li>Value Names are referred to Value Expressions defined on the Device Mapping.</li> </ul> <p> Observation Value Mapping with the example HeartRate from the Device Mapping: </p> <table className="m-3"> <tbody> <tr> <td className="pr-4">Value Name:</td> <td> <pre className="d-inline-flex m-0">Heart Rate</pre> </td> </tr> <tr> <td className="pr-4">Value Type:</td> <td> <pre className="d-inline-flex m-0">SampledData</pre> </td> </tr> <tr> <td className="pr-4">Default Period in Millisecond:</td> <td> <pre className="d-inline-flex m-0">30000</pre> </td> </tr> <tr> <td className="pr-4">Unit:</td> <td> <pre className="d-inline-flex m-0">count/min</pre> </td> </tr> </tbody> </table> <p> For more information, please visit: <a href="https://github.com/microsoft/iomt-fhir/blob/master/docs/Configuration.md">IoMT Mapping Configuration</a> </p> </CardBody> </Card> ); } export const FhirComponentsFormTutorial = (props: {}) => { return ( <Card> <CardBody> <CardTitle> <span className="h6">Tutorial</span> </CardTitle> <p> Configure the transformation of the normalized device value data to FHIR Resource: <a href="https://www.hl7.org/fhir/observation-definitions.html#Observation.component">Observation.Components</a> </p> Note: <br /> <ul> <li>You should use this for transformation of multiple values.</li> <li>Value Names are referred to Value Expressions defined on the Device Mapping.</li> <li>Codings of each component should be specified to the value in it.</li> </ul> <p> Please check "Heart Rate - Sampled Data" as an example in <a href="https://github.com/microsoft/iomt-fhir/blob/master/docs/Configuration.md">IoMT Mapping Configuration</a> </p> </CardBody> </Card> ); } export const FhirCodesFormTutorial = (props: {}) => { return ( <Card> <CardBody> <CardTitle> <span className="h6">Tutorial</span> </CardTitle> <p> Add <a href="https://www.hl7.org/fhir/observation-definitions.html#Observation.code">Observation.code</a> to the final FHIR Observation resource. </p> <p> For more information, please visit: <a href="https://github.com/microsoft/iomt-fhir/blob/master/docs/Configuration.md">IoMT Mapping Configuration</a> </p> </CardBody> </Card> ); } export const FhirCategoryFormTutorial = (props: {}) => { return ( <Card> <CardBody> <CardTitle> <span className="h6">Tutorial</span> </CardTitle> <p> Add <a href="https://www.hl7.org/fhir/observation-definitions.html#Observation.category">Observation.category</a> to the final FHIR Observation resource. </p> <p> This is optional information. </p> <p> For more information, please visit: <a href="https://github.com/microsoft/iomt-fhir/blob/master/docs/Configuration.md">IoMT Mapping Configuration</a> </p> </CardBody> </Card> ); } export const FhirGroupingGroupTutorial = (props: {}) => { return ( <Card> <CardBody> <CardTitle> <span className="h6">Tutorial</span> </CardTitle> <p> Choose a grouping logic. This will determine how we merge the data values in a designated time window onto a single FHIR Observation resource. You can also skip grouping, so each data input will be transformed to single observation resource. </p> Available Options: <br /> <ul> <li>No Grouping</li> <li>Correlation ID Grouping</li> <li>1 Hour</li> <li>1 Day</li> </ul> <p> For more information, please check "PeriodInterval" in: <a href="https://github.com/microsoft/iomt-fhir/blob/master/docs/Configuration.md">IoMT Mapping Configuration</a> </p> </CardBody> </Card> ); }
the_stack
import { MersenneTwister19937 } from "../engine/MersenneTwister19937"; import { Distribution, Engine } from "../types"; import { int32 } from "./int32"; import { int53 } from "./int53"; import { int53Full } from "./int53Full"; import { integer } from "./integer"; import { uint32 } from "./uint32"; import { uint53 } from "./uint53"; import { uint53Full } from "./uint53Full"; describe("integer distribution", () => { [-Math.pow(2, 53) - 2, -Infinity, NaN, Infinity].forEach(min => { it(`throws a RangeError if min = ${min}`, () => { expect(() => { integer(min, 0); }).toThrow( new RangeError(`Expected min to be at least ${-0x20000000000000}`) ); }); }); [Math.pow(2, 53) + 2, -Infinity, NaN, Infinity].forEach(max => { it(`throws a RangeError if max = ${max}`, () => { expect(() => { integer(0, max); }).toThrow( new RangeError(`Expected max to be at most ${0x20000000000000}`) ); }); }); let engine!: Engine; beforeEach(() => { engine = MersenneTwister19937.autoSeed(); }); const primeCache = [2, 3]; function primeGenerator() { let index = 0; return () => { const len = primeCache.length; if (index < len) { const result = primeCache[index]; ++index; return result; } else { let current = primeCache[len - 1] + 2; for (; ; current += 2) { let prime = true; for (let i = 0; i < len; ++i) { if (current % primeCache[i] === 0) { prime = false; break; } } if (prime) { primeCache.push(current); ++index; return current; } } } }; } function calculatePrimeFactors(value: number) { const result = []; const nextPrime = primeGenerator(); while (true) { const prime = nextPrime(); if (prime > Math.sqrt(value)) { break; } while (value % prime === 0) { result.push(prime); value /= prime; } } if (value > 1) { result.push(value); } return result; } const fullScaleFactors = [5, 13, 37, 109, 246241, 279073]; function calculatePrimeFactorsOfRange(min: number, max: number) { if (max - min < 0x20000000000000) { return calculatePrimeFactors(max - min + 1); } else if (min === -0x20000000000000 && max === 0x20000000000000) { return fullScaleFactors.slice(); } const sqrt = Math.min(Math.sqrt(max - min), Number.MAX_SAFE_INTEGER); const extra = 0x20000000000000; const rangeMinusExtra = max - extra - min + 1; const nextPrime = primeGenerator(); while (true) { const prime = nextPrime(); if (prime > sqrt) { break; } if (rangeMinusExtra % prime === 0) { return [prime].concat( calculatePrimeFactors( Math.round(rangeMinusExtra / prime + extra / prime) ) ); } } throw new Error("uh oh"); } function returnValue<T>(value: T) { return () => value; } function toCallback<T>( callback: T | ((index: number) => T) ): (index: number) => T { return typeof callback === "function" ? callback : (returnValue(callback) as any); } function times<T>(count: number, callback: T | ((index: number) => T)): T[] { callback = toCallback(callback); const result = []; for (let i = 0; i < count; ++i) { result.push(callback(i)); } return result; } function verifyBucket(bucket: ReadonlyArray<number>, iterationCount: number) { const pdf = 1 / bucket.length; const dividend = Math.sqrt(iterationCount * pdf); for (let i = 0, len = bucket.length; i < len; ++i) { const d = Math.abs(bucket[i] - iterationCount * pdf); const s = d / dividend; if (d > 1) { expect(s).not.toBeGreaterThan(5); } } } function divmod(divisor: number, dividend: number) { let mod = divisor % dividend; if (mod < 0) { mod += dividend; return [Math.floor((divisor - mod) / dividend), mod]; } else { return [Math.floor(divisor / dividend), mod]; } } function testUniformDistribution( min: number, max: number, iterationCount: number ) { const range = max - min + 1; const factors = calculatePrimeFactorsOfRange(min, max); if (factors.length === 1) { it(`is uniformly distributed within [${min}, ${max}] given ${iterationCount} iterations`, () => { const distribution = integer(min, max); const bucket = []; let i; for (i = 0; i < range; ++i) { bucket.push(0); } for (i = 0; i < iterationCount; ++i) { const r = distribution(engine); expect(r).not.toBeLessThan(min); expect(r).not.toBeGreaterThan(max); ++bucket[r - min]; } verifyBucket(bucket, iterationCount); }); } else { it(`is uniformly distributed within [${min}, ${max}] modulo factors {${factors.join( ", " )}} given ${iterationCount} iterations`, () => { const distribution = integer(min, max); const buckets = times(factors.length, i => { return times(factors[i], 0); }); function addToBuckets(value: number) { for (let i = 0, len = factors.length; i < len; ++i) { const factor = factors[i]; const result = divmod(value, factor); ++buckets[i][result[1]]; value = result[0]; } } for (let i = 0; i < iterationCount; ++i) { const r = distribution(engine); expect(r).not.toBeLessThan(min); expect(r).not.toBeGreaterThan(max); addToBuckets(r); } buckets.forEach(bucket => { verifyBucket(bucket, iterationCount); }); }); } } // same min and max testUniformDistribution(1, 1, 10); // fits perfectly into int32 testUniformDistribution(0, 0xffffffff, 1000); testUniformDistribution(1, 0x100000000, 1000); // easily maskable, since range is 2^x testUniformDistribution(0, 15, 1000); testUniformDistribution(0, 255, 1000); // within int32 testUniformDistribution(0, 2, 1000); testUniformDistribution(3, 7, 1000); testUniformDistribution(1, 20, 1000); testUniformDistribution(1, 2, 1000); testUniformDistribution(1, 2 * 3, 1000); testUniformDistribution(1, 2 * 3 * 5, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23, 1000); // lower part of range is evenly int32, high part is easily-maskable. testUniformDistribution(1, 0x200000000, 1000); testUniformDistribution(1, 0x10000000000000, 1000); // fits perfectly into uint53 testUniformDistribution(1, 0x20000000000000, 1000); // within uint53-1 testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29, 1000); testUniformDistribution( 1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31, 1000 ); testUniformDistribution( 1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37, 1000 ); testUniformDistribution( 1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41, 1000 ); testUniformDistribution( 1, 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41 * 43, 1000 ); testUniformDistribution(1, 0x300000000, 1000); // fits perfectly into int53 testUniformDistribution(-0x1fffffffffffff, 0x20000000000000, 1000); testUniformDistribution(-0x20000000000000, 0x1fffffffffffff, 1000); // within int53-1 testUniformDistribution(-0x1fffffffffffff, 0xe7ab3bddafc0e, 1000); testUniformDistribution(-0xe7ab3bddafc0d, 0x20000000000000, 1000); it(`returns int32 if ${-0x80000000} and ${0x7fffffff} are passed in`, () => { const expected = int32; const actual = integer(-0x80000000, 0x7fffffff); expect(actual).toBe(expected); }); it(`returns uint32 if 0 and ${0xffffffff} are passed in`, () => { const expected = uint32; const actual = integer(0, 0xffffffff); expect(actual).toBe(expected); }); it(`returns uint53 if 0 and ${0x1fffffffffffff} are passed in`, () => { const expected = uint53; const actual = integer(0, 0x1fffffffffffff); expect(actual).toBe(expected); }); it(`returns uint53Full if 0 and ${0x20000000000000} are passed in`, () => { const expected = uint53Full; const actual = integer(0, 0x20000000000000); expect(actual).toBe(expected); }); it(`returns int53 if ${-0x20000000000000} and ${0x1fffffffffffff} are passed in`, () => { const expected = int53; const actual = integer(-0x20000000000000, 0x1fffffffffffff); expect(actual).toBe(expected); }); it(`returns int53Full if ${-0x20000000000000} and ${0x20000000000000} are passed in`, () => { const expected = int53Full; const actual = integer(-0x20000000000000, 0x20000000000000); expect(actual).toBe(expected); }); function testFullScale(min: number, max: number, distribution: Distribution) { it(`is uniformly distributed within [${min}, ${max}]`, () => { const iterationCount = 1000; const factors = calculatePrimeFactorsOfRange(min + 1, max); const buckets = times(factors.length, i => { return times(factors[i], 0); }); function addToBuckets(value: number) { for (let i = 0, len = factors.length; i < len; ++i) { const factor = factors[i]; const result = divmod(value, factor); ++buckets[i][result[1]]; value = result[0]; } } for (let i = 0; i < iterationCount; ++i) { let r = 0; do { r = distribution(engine); } while (r === min); expect(r).not.toBeLessThan(min); expect(r).not.toBeGreaterThan(max); addToBuckets(r); } buckets.forEach(bucket => { verifyBucket(bucket, iterationCount); }); }); } testFullScale(-0x20000000000000, 0x20000000000000, int53Full); testFullScale(0, 0x20000000000000, uint53Full); function makeEngine(input: ReadonlyArray<number>) { let index = 0; return { next() { if (index >= input.length) { return 0; } else { return input[index++] | 0; } } }; } it(`can generate ${0x20000000000000} given a distribution of [${-0x20000000000000}, ${0x20000000000000}]`, () => { const distribution = int53Full; const myEngine = makeEngine([0x400000, 0]); const actual = distribution(myEngine); expect(actual).toBe(0x20000000000000); }); it(`can generate ${0x20000000000000} given a distribution of [0, ${0x20000000000000}]`, () => { const distribution = uint53Full; const myEngine = makeEngine([0x200000, 0]); const actual = distribution(myEngine); expect(actual).toBe(0x20000000000000); }); });
the_stack
import { Workbook } from './../src/workbook'; import { Utils } from './../spec/utils.spec'; describe('Demo', () => { it('All-Features', (done) => { let book: Workbook = new Workbook({ builtInProperties: { author: 'Rex', comments: 'Listed the development team members', category: 'Report', company: 'NorthWind Traders', manager: 'John', subject: 'Development Team Members', title: 'Active Development Team Members', createdDate: new Date(), modifiedDate: new Date(), status: "In-Progress", tags: "Excel", }, /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Tahoma', fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true, numberFormat: 'C' }, /*Style ->2*/{ name: 'Custom Heading', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: 'C' }, /*Style ->3*/{ name: 'Custom H2', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: 'C' }, /*Style ->4*/{ name: 'Custom H3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'C' }, ], worksheets: [ { name: 'Sheet', /*grouping-setup*/ pageSetup: { isSummaryRowBelow: false }, columns: [ /*column -> 1*/{ index: 1, width: 100, }, /*column -> 3*/{ index: 2, width: 150, }, /*column -> 3*/{ index: 3, width: 75, }, /*column -> 4*/{ index: 4, width: 150, } ], rows: [ /*row -> 1*/ { index: 1, cells: [{ index: 1, value: 'Hello World' }] }, /*Text*/ /*row -> 2*/ { index: 2, cells: [{ index: 1, value: 10 }] }, /*Number*/ /*row -> 3*/ { index: 3, cells: [{ index: 1, value: new Date() }] }, /*Date without NumberFormat*/ /*row -> 4*/ { index: 4, cells: [{ index: 1, value: new Date(), style: { numberFormat: 'yMd' } }] }, /*Date with NumberFormat*/ /*row -> 5*/ { index: 5, cells: [ /*column -> 1*/{ index: 1, /*Hyperlink with custom display text*/ hyperlink: { target: 'https://www.google.co.in/', displayText: 'Google' } }, /*column -> 2*/{ index: 2, /*Hyperlink default*/ hyperlink: { target: 'https://www.google.co.in/' } } ] }, /*row -> 6*/ { index: 6, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, cells: [ /*column -> 1*/ { index: 1, value: 'Font Style', /*Font Style - FontColor, Size, Bold, Italic, Underline*/ style: { fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true } }] }, /*row -> 7*/ { index: 7, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, cells: [ /*column -> 1*/ { index: 1, value: 'Background Color', /*Cell Style - Background color*/ style: { backColor: '#C67878' } }] }, /*row -> 8*/ { index: 8, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, cells: [ /*column -> 1*/ { index: 1, value: 'Test for wrap text - So text need to long wrapping', /*Cell Style - Wrap text*/ style: { wrapText: true } }] } ], }, { name: 'FreezeTopRow', showGridLines: false, freeze: { row: 2 }, }, { name: 'FreezeFirstColumn', freeze: { column: 2 }, }, { name: 'FreezeRowColumn', freeze: { row: 2, column: 3 }, }, { name: 'PrintTitles', printTitle: { fromRow: 1, toRow: 2, fromColumn: 1, toColumn: 2 }, }, ] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'All-Features-1.xlsx'); } 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(); } } }); }); it('All-Features-2', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'Sheet', /*grouping-setup*/ pageSetup: { isSummaryRowBelow: false }, columns: [ /*column -> 1*/{ index: 1, width: 100, }, /*column -> 3*/{ index: 2, width: 150, }, /*column -> 3*/{ index: 3, width: 75, }, /*column -> 4*/{ index: 4, width: 150, } ], rows: [ /*row -> 10*/ { index: 1, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, cells: [ /*column ->1*/ { index: 1, value: 'Vertical alignment center', /*Cell Style - Vertical alignment Allowed values 'bottom', 'center', 'top' Default value 'bottom' */ style: { vAlign: 'center' } }, /*column ->2*/ { index: 2, value: 'Vertical alignment top', /*Cell Style - Vertical alignment - top*/ style: { vAlign: 'top' } }, /*column ->3*/ { index: 3, value: 'Vertical alignment bottom default', /*Cell Style - Vertical alignment - bottom*/ }] }, /*row -> 11*/ { index: 2, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, cells: [ /*column ->1*/ { index: 1, value: 'all borders', /*Cell Style - All Borders(left, right, top, bottom) Allowed line styles 'thin', 'medium', 'thick' */ style: { borders: { color: '#C67878', lineStyle: 'thick' } } }] }, /*row -> 12*/ { index: 3, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, cells: [ /*column ->1*/ { index: 1, value: 'Separate bottom border', /*Cell Style - All Borders(left, right, top, bottom) Allowed line styles 'thin', 'medium', 'thick' */ style: { bottomBorder: { color: '#C67878', lineStyle: 'thick' } } }, /*column ->2*/ { index: 2, value: 'Separate top border', /*Cell Style - All Borders(left, right, top, bottom) Allowed line styles 'thin', 'medium', 'thick' */ style: { topBorder: { color: '#C67878', lineStyle: 'thick' } } }, /*column ->3*/ { index: 3, value: 'Separate left border', /*Cell Style - All Borders(left, right, top, bottom) Allowed line styles 'thin', 'medium', 'thick' */ style: { leftBorder: { color: '#C67878', lineStyle: 'thick' } } }, /*column ->4*/ { index: 4, value: 'Separate right border', /*Cell Style - All Borders(left, right, top, bottom) Allowed line styles 'thin', 'medium', 'thick' */ style: { rightBorder: { color: '#C67878', lineStyle: 'thick' } } }] }, /*row -> 13*/ { index: 4, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, cells: [ /*column ->1*/ { index: 1, image: { base64: 'data:image/png;base64,/*encoded string*/iVBORw0KGgoAAAANSUhEUgAAABgAAAAXCAYAAAARIY8tAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAIfSURBVEhL7ZTPaxNBHMW9eGlP/h8eLS3Riwq11luFugr1UEERvbRgL94EFQ8VFBREc6k/uxYVsSrSelGSCOpmJS31KJKk3fxaYTd2k908+2Y72KyTNCIeBB88mNmdeZ/5zszulkQigb/p/4BN3REgnU4jl8vBdV34vi/MNp+ZpqmcI90WkEqlkM/nsZkISiaTyoyWAIbbti0CGp6H6sxdlE+OoDC4C9a+GMrHj8CdnhLvqEqlooS0BMiVB9Yyysc0WHt7lLYnTotxFCuJ5igB3HOKqyuNDougwv6dcG5dQ+2TgVrGhBO/jtLRIfhfv4ixUtEzUQK4EqpuXEVxqBdWf99aaAhtUhCsN34qWoUSwBtC+e964D3tQvXOKdHvRI7jNGUpAbyGVP11N+pzW9EoPhd9qT3nnV98Vv8u3nHuxqz2gPmuEFCYFX0pFeDMvd8AyC369nY7SnPb8MScFH2Vzj1aFYDJ2VXR72iL5CF/WLyEAf0A+vRhfLQWxLONWsoF6L8YVvBmKaw6m802ZSkBvGqU59dw6MUYdjw4iJiu4Up6Cu9XMmuwRdzM6Bi8fQO7L9g4Ea+i0RBTYBhGU5YSQMsqVtwitHWIytrjy1i2w/To6umWAH72/PwpL6jh/udnGHk1gdhDTVRz+OU44gszqNbDvedY/l6iOS0BNCGyknbiylXhdFuANM+EIN4QXkOabQZH9zzqjgB/4n8dkMAPcKlEy0IZ6hkAAAAASUVORK5CYII=', width: 200, height: 200, moveWithCell: true, sizeWithCell: true } }] }, /*row -> 14*/ { index: 5, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, height: 100, /*Row height*/ cells: [{ index: 1, value: 'Row height' }] }, /*row -> 15*/ { index: 6, /*grouping*/ grouping: { outlineLevel: 1, isHidden: true }, height: 100, /*Row height*/ cells: [ /*cell with merge*/{ index: 1, rowSpan: 3, colSpan: 4, value: 'Merge text' } ] }, /*row -> 16*/ { index: 7, /*grouping*/ grouping: { isCollapsed: true } }] } ] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'All-Features-2.xlsx'); } 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(); } } }); }); it('All-Features-3', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'Sheet', rows: [ /*row -> 9*/ { index: 1, cells: [ /*column ->1*/ { index: 1, value: 'Horizontal alignment right', /*Cell Style - Horizontal alignment Allowed values 'center', 'justify', 'left', 'right' Default value 'left' */ style: { hAlign: 'right' } }, /*column ->2*/ { index: 2, value: 'Horizontal alignment center', /*Cell Style - Horizontal alignment - Center*/ style: { hAlign: 'center' } }, /*column ->3*/ { index: 3, value: 'Horizontal alignment left', /*Cell Style - Horizontal alignment - left*/ style: { hAlign: 'left' } }] }, ] } ] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'All-Features-3.xlsx'); } 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(); } } }); }); });
the_stack
"use strict"; // Typescript imports import Assert = require("./assert"); import TestFramework = require("./test-framework"); import Blok = require("../blok"); import BlokUserSettings = require("../blok-user-settings"); import BlokContainer = require("../blok-container"); import BlokContainerUserSettings = require("../blok-container-user-settings"); import BlokAdapter = require("../blok-adapter"); import Rect = require("../rect"); import Css = require("../css"); // npm imports var JSON2: any = require("JSON2"); // To run: // connect ExtendScript Toolkit to Illustrator // run function testOneDeepRow() { let pageItem = app.activeDocument.pageItems[0]; let blokContainer = BlokAdapter.getBlokContainer(pageItem); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 250, 200]))); Assert.areEqual(blokContainer.getFlex(), undefined); Assert.areEqual(blokContainer.getAlignSelf(), undefined); Assert.areEqual(blokContainer.getFlexDirection(), Css.FlexDirections.ROW); Assert.areEqual(blokContainer.getJustifyContent(), Css.Justifications.FLEX_START); Assert.areEqual(blokContainer.getAlignItems(), Css.Alignments.FLEX_START); Assert.areEqual(blokContainer.getFlexWrap(), Css.FlexWraps.NOWRAP); let settings = blokContainer.getUserSettings(); Assert.areEqual(settings.alignSelf, undefined); Assert.areEqual(settings.flexDirection, 0); Assert.areEqual(settings.alignItems, 0); Assert.areEqual(settings.flexWrap, 0); let cssNode = blokContainer.computeCssNode(); Assert.areEqual(cssNode.style.width, undefined); Assert.areEqual(cssNode.style.height, undefined); Assert.areEqual(cssNode.style.flex, undefined); Assert.areEqual(cssNode.style.alignSelf, undefined); Assert.areEqual(cssNode.style.flexDirection, "row"); Assert.areEqual(cssNode.style.justifyContent, "flex-start"); Assert.areEqual(cssNode.style.alignItems, "flex-start"); Assert.areEqual(cssNode.style.flexWrap, "nowrap"); Assert.areEqual(cssNode.children.length, 2); Assert.areEqual(cssNode.children[0].style.width, 100); Assert.areEqual(cssNode.children[0].style.height, 100); Assert.areEqual(cssNode.children[0].style.flex, undefined); Assert.areEqual(cssNode.children[1].style.width, 50); Assert.areEqual(cssNode.children[1].style.height, 200); Assert.areEqual(cssNode.children[1].style.flex, undefined); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 150, 200]))); } /** Container set to stretch */ function testOneDeepRowStretch() { let pageItem = app.activeDocument.pageItems[0]; let settings = new BlokContainerUserSettings(); settings.alignItems = Css.Alignments.STRETCH; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); let cssNode = blokContainer.computeCssNode(); Assert.areEqual(cssNode.style.alignItems, "stretch"); Assert.areEqual(cssNode.children.length, 2); Assert.areEqual(cssNode.children[0].style.width, 100); Assert.areEqual(cssNode.children[0].style.height, undefined); Assert.areEqual(cssNode.children[0].style.flex, undefined); Assert.areEqual(cssNode.children[1].style.width, 50); Assert.areEqual(cssNode.children[1].style.height, undefined); Assert.areEqual(cssNode.children[1].style.flex, undefined); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 150, 200]))); } /** Container not set to stretch, but a child is */ function testOneDeepRowChildStretch() { let pageItem = app.activeDocument.pageItems[0]; let blokContainer = BlokAdapter.getBlokContainer(pageItem); let childPageItem = pageItem.pageItems[1]; let childSettings = new BlokUserSettings(); childSettings.alignSelf = Css.Alignments.STRETCH; BlokAdapter.getBlok(childPageItem, childSettings); let cssNode = blokContainer.computeCssNode(); Assert.areEqual(cssNode.children.length, 2); Assert.areEqual(cssNode.children[0].style.width, 100); Assert.areEqual(cssNode.children[0].style.height, undefined); Assert.areEqual(cssNode.children[0].style.flex, undefined); Assert.areEqual(cssNode.children[1].style.width, 50); Assert.areEqual(cssNode.children[1].style.height, 200); Assert.areEqual(cssNode.children[1].style.flex, undefined); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 150, 200]))); } function testOneDeepColumn() { let pageItem = app.activeDocument.pageItems[0]; let settings = new BlokContainerUserSettings(); settings.flexDirection = Css.FlexDirections.COLUMN; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); Assert.areEqual(blokContainer.getFlexDirection(), Css.FlexDirections.COLUMN); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 100, 300]))); } function testOneDeepRowSpaceBetween() { let pageItem = app.activeDocument.pageItems[0]; let settings = new BlokContainerUserSettings(); settings.justifyContent = Css.Justifications.SPACE_BETWEEN; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); blokContainer.invalidate(); } function testOneDeepRowFlex() { let pageItem = app.activeDocument.pageItems[0]; let blokContainer = BlokAdapter.getBlokContainer(pageItem); let firstChild = pageItem.pageItems[2]; let secondChild = pageItem.pageItems[1]; let thirdChild = pageItem.pageItems[0]; let childSettings = new BlokUserSettings(); childSettings.flex = 1; BlokAdapter.getBlok(firstChild, childSettings); BlokAdapter.getBlok(thirdChild, childSettings); blokContainer.invalidate(); // Should not have changed width Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 350, 200]))); Assert.areEqual(firstChild.width, 150); Assert.areEqual(secondChild.width, 50); // This one should not have grown Assert.areEqual(thirdChild.width, 150); } function testTwoDeepRow() { let pageItem = app.activeDocument.pageItems[0]; let blokContainer = BlokAdapter.getBlokContainer(pageItem); blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 200, 200]))); } function testTwoDeepMixed() { let pageItem = app.activeDocument.pageItems[0]; // Set the child group to be column layout let childGroupPageItem = pageItem.pageItems[0]; let childSettings = new BlokContainerUserSettings(); childSettings.flexDirection = Css.FlexDirections.COLUMN; BlokAdapter.getBlokContainer(childGroupPageItem, childSettings); let blokContainer = BlokAdapter.getBlokContainer(pageItem); blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 150, 250]))); } function testTwoDeepRowAlt() { let pageItem = app.activeDocument.pageItems[0]; let blokContainer = BlokAdapter.getBlokContainer(pageItem); blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([144, 71, 332, 231]))); } function testNestedGroups() { // Find the groups, from the inner-most to outer-most let firstGroupItem = app.activeDocument.pageItems[0].pageItems[1].pageItems[1]; let secondGroupItem = app.activeDocument.pageItems[0].pageItems[1]; let thirdGroupItem = app.activeDocument.pageItems[0]; // Inner-most is laid out with defaults let firstBlokContainer = BlokAdapter.getBlokContainer(firstGroupItem); firstBlokContainer.invalidate(); // Next will have flex-end let secondSettings = new BlokContainerUserSettings(); secondSettings.alignItems = Css.Alignments.FLEX_END; let secondBlokContainer = BlokAdapter.getBlokContainer(secondGroupItem, secondSettings); secondBlokContainer.invalidate(); // Last will have vertical layout and center alignment let thirdSettings = new BlokContainerUserSettings(); thirdSettings.flexDirection = Css.FlexDirections.COLUMN; thirdSettings.alignItems = Css.Alignments.CENTER; let thirdBlokContainer = BlokAdapter.getBlokContainer(thirdGroupItem, thirdSettings); thirdBlokContainer.invalidate(); Assert.isTrue(thirdBlokContainer.getRect().equals(new Rect([144, 71, 332, 266]))); } function testStrokes() { let pageItem = app.activeDocument.pageItems[0]; let blokContainer = BlokAdapter.getBlokContainer(pageItem); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([10, 10, 160, 110]))); } function testTextFrameArea() { let pageItem = app.activeDocument.pageItems[0]; let blokContainer = BlokAdapter.getBlokContainer(pageItem); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 294, 200]))); let textFrame = pageItem.pageItems[0]; let textFrameBlok = BlokAdapter.getBlok(textFrame); Assert.isTrue(textFrameBlok.getRect().equals(new Rect([150, 0, 294, 65]))); Assert.areEqual(textFrame.textRange.horizontalScale, 100); Assert.areEqual(textFrame.textRange.size, 12); Assert.areEqual(textFrame.textRange.autoLeading, true); } function testTextFrameAreaStretch() { let pageItem = app.activeDocument.pageItems[0]; let settings = new BlokContainerUserSettings(); settings.alignItems = Css.Alignments.STRETCH; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 294, 200]))); let textFrame = pageItem.pageItems[0]; let textFrameBlok = BlokAdapter.getBlok(textFrame); Assert.isTrue(textFrameBlok.getRect().equals(new Rect([150, 0, 294, 200]))); Assert.areEqual(textFrame.textRange.horizontalScale, 100); Assert.areEqual(textFrame.textRange.size, 12); Assert.areEqual(textFrame.textRange.autoLeading, true); } function testTextFrameAreaMiddle() { let pageItem = app.activeDocument.pageItems[0]; let textFrame = pageItem.pageItems[0]; textFrame.zOrder(ZOrderMethod.SENDBACKWARD); let blokContainer = BlokAdapter.getBlokContainer(pageItem); // Now layout blokContainer.invalidate(); Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 294, 200]))); textFrame = pageItem.pageItems[1]; let textFrameBlok = BlokAdapter.getBlok(textFrame); Assert.isTrue(textFrameBlok.getRect().equals(new Rect([100, 0, 244, 65]))); Assert.areEqual(textFrame.textRange.horizontalScale, 100); Assert.areEqual(textFrame.textRange.size, 12); Assert.areEqual(textFrame.textRange.autoLeading, true); } function testInteractiveResizeRow() { let pageItem = app.activeDocument.pageItems[0]; app.activeDocument.selection = pageItem; // Select it let blokContainer = BlokAdapter.getBlokContainer(pageItem); blokContainer.invalidate(); app.redraw(); // Create undo waypoint 1 pageItem.width = 500; // Resize width app.redraw(); // Create undo waypoint 2 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it didn't change size Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 150, 200]))); Assert.areEqual(pageItem.width, 150); pageItem.height = 300; // Resize height app.redraw(); // Create undo waypoint 3 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it didn't change size Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 150, 200]))); Assert.areEqual(pageItem.width, 150); } function testInteractiveResizeColumn() { let pageItem = app.activeDocument.pageItems[0]; app.activeDocument.selection = pageItem; // Select it let settings = new BlokContainerUserSettings(); settings.flexDirection = Css.FlexDirections.COLUMN; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); blokContainer.invalidate(); app.redraw(); // Create undo waypoint 1 pageItem.width = 500; // Resize width app.redraw(); // Create undo waypoint 2 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it didn't change size Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 100, 300]))); Assert.areEqual(pageItem.height, 300); pageItem.height = 200; // Resize height app.redraw(); // Create undo waypoint 3 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it didn't change size Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 100, 300]))); Assert.areEqual(pageItem.height, 300); } function testInteractiveResizeRowDistributed() { let pageItem = app.activeDocument.pageItems[0]; app.activeDocument.selection = pageItem; // Select it let settings = new BlokContainerUserSettings(); settings.justifyContent = Css.Justifications.SPACE_BETWEEN; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); blokContainer.invalidate(); app.redraw(); // Create undo waypoint 1 // Verify it stayed distributed Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 444, 200]))); pageItem.width = 600; // Resize width app.redraw(); // Create undo waypoint 2 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it is the new width Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 600, 200]))); Assert.areEqual(pageItem.width, 600); // Verify that each item is original size Assert.areEqual(pageItem.pageItems[2].width, 100); Assert.areEqual(pageItem.pageItems[2].height, 100); Assert.areEqual(pageItem.pageItems[1].width, 50); Assert.areEqual(pageItem.pageItems[1].height, 200); Assert.areEqual(pageItem.pageItems[0].width, 144); Assert.areEqual(pageItem.pageItems[0].height, 65); pageItem.height = 300; // Resize height app.redraw(); // Create undo waypoint 3 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it didn't change size Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 600, 200]))); Assert.areEqual(pageItem.height, 200); } function testInteractiveResizeColumnDistributed() { let pageItem = app.activeDocument.pageItems[0]; app.activeDocument.selection = pageItem; // Select it let settings = new BlokContainerUserSettings(); settings.flexDirection = Css.FlexDirections.COLUMN; settings.justifyContent = Css.Justifications.SPACE_BETWEEN; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); blokContainer.invalidate(); app.redraw(); // Create undo waypoint 1 // Verify it stacked with no distribution. // Align to pixel grid is turned on for this file and it has a TextFrameItem, so the numbers get // slightly wonky Assert.isTrue(blokContainer.getRect().equals(new Rect([-0.01171875, 0, 144, 365]))); pageItem.height = 500; // Resize height app.redraw(); // Create undo waypoint 2 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it is the new height. Again, a bit wonky due to TextFrameItem Assert.isTrue(blokContainer.getRect().equals(new Rect([-0.0234375, 0, 143.98828125, 500]))); Assert.areEqual(pageItem.height, 500); // Verify that each item is original size Assert.areEqual(pageItem.pageItems[2].width, 100); Assert.areEqual(pageItem.pageItems[2].height, 100); Assert.areEqual(pageItem.pageItems[1].width, 50); Assert.areEqual(pageItem.pageItems[1].height, 200); Assert.areEqual(pageItem.pageItems[0].width, 144); Assert.areEqual(pageItem.pageItems[0].height, 65); pageItem.width = 200; // Resize width app.redraw(); // Create undo waypoint 3 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it didn't change size Assert.isTrue(blokContainer.getRect().equals(new Rect([-0.0234375, 0, 143.98828125, 500]))); Assert.areEqual(pageItem.width, 144); } function testInteractiveResizeRowDistributedStretch() { let pageItem = app.activeDocument.pageItems[0]; app.activeDocument.selection = pageItem; // Select it let settings = new BlokContainerUserSettings(); settings.justifyContent = Css.Justifications.SPACE_BETWEEN; settings.alignItems = Css.Alignments.STRETCH; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); blokContainer.invalidate(); app.redraw(); // Create undo waypoint 1 // Verify it stayed distributed Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 444, 200]))); pageItem.width = 600; // Resize width app.redraw(); // Create undo waypoint 2 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it is the new width Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 600, 200]))); Assert.areEqual(pageItem.width, 600); // Verify that each item is stretched Assert.areEqual(pageItem.pageItems[2].width, 100); Assert.areEqual(pageItem.pageItems[2].height, 200); Assert.areEqual(pageItem.pageItems[1].width, 50); Assert.areEqual(pageItem.pageItems[1].height, 200); Assert.areEqual(pageItem.pageItems[0].width, 144); Assert.areEqual(pageItem.pageItems[0].height, 200); pageItem.height = 300; // Resize height app.redraw(); // Create undo waypoint 3 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify stretch Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 600, 300]))); Assert.areEqual(pageItem.height, 300); Assert.areEqual(pageItem.pageItems[2].width, 100); Assert.areEqual(pageItem.pageItems[2].height, 300); Assert.areEqual(pageItem.pageItems[1].width, 50); Assert.areEqual(pageItem.pageItems[1].height, 300); Assert.areEqual(pageItem.pageItems[0].width, 144); Assert.areEqual(pageItem.pageItems[0].height, 300); } function testInteractiveResizeRowDistributedChildStretch() { let pageItem = app.activeDocument.pageItems[0]; app.activeDocument.selection = pageItem; // Select it let settings = new BlokContainerUserSettings(); settings.justifyContent = Css.Justifications.SPACE_BETWEEN; let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings); let childSettings = new BlokUserSettings(); childSettings.alignSelf = Css.Alignments.STRETCH; BlokAdapter.getBlok(pageItem.pageItems[0], childSettings); blokContainer.invalidate(); app.redraw(); // Create undo waypoint 1 // Verify it stayed distributed Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 444, 200]))); // Verify that only last item is stretched Assert.areEqual(pageItem.pageItems[2].width, 100); Assert.areEqual(pageItem.pageItems[2].height, 100); Assert.areEqual(pageItem.pageItems[1].width, 50); Assert.areEqual(pageItem.pageItems[1].height, 200); Assert.areEqual(pageItem.pageItems[0].width, 144); Assert.areEqual(pageItem.pageItems[0].height, 200); pageItem.width = 600; // Resize width app.redraw(); // Create undo waypoint 2 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify that it is the new width Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 600, 200]))); Assert.areEqual(pageItem.width, 600); // Verify that only last item is stretched Assert.areEqual(pageItem.pageItems[2].width, 100); Assert.areEqual(pageItem.pageItems[2].height, 100); Assert.areEqual(pageItem.pageItems[1].width, 50); Assert.areEqual(pageItem.pageItems[1].height, 200); Assert.areEqual(pageItem.pageItems[0].width, 144); Assert.areEqual(pageItem.pageItems[0].height, 200); pageItem.height = 300; // Resize height app.redraw(); // Create undo waypoint 3 // Attempt relayout blokContainer.checkForRelayout(app.activeDocument.selection); // Verify stretch Assert.isTrue(blokContainer.getRect().equals(new Rect([0, 0, 600, 300]))); Assert.areEqual(pageItem.height, 300); Assert.areEqual(pageItem.pageItems[2].width, 100); Assert.areEqual(pageItem.pageItems[2].height, 100); Assert.areEqual(pageItem.pageItems[1].width, 50); Assert.areEqual(pageItem.pageItems[1].height, 200); Assert.areEqual(pageItem.pageItems[0].width, 144); Assert.areEqual(pageItem.pageItems[0].height, 300); } function testInteractiveResizeNested() { // Find the groups, from the inner-most to outer-most let firstGroupItem = app.activeDocument.pageItems[0].pageItems[1].pageItems[0]; let secondGroupItem = app.activeDocument.pageItems[0].pageItems[1]; let thirdGroupItem = app.activeDocument.pageItems[0]; let firstSettings = new BlokContainerUserSettings(); firstSettings.alignItems = Css.Alignments.CENTER; let firstBlokContainer = BlokAdapter.getBlokContainer(firstGroupItem, firstSettings); let secondSettings = new BlokContainerUserSettings(); secondSettings.flexDirection = Css.FlexDirections.COLUMN; secondSettings.justifyContent = Css.Justifications.SPACE_BETWEEN; let secondBlokContainer = BlokAdapter.getBlokContainer(secondGroupItem, secondSettings); let thirdSettings = new BlokContainerUserSettings(); thirdSettings.alignItems = Css.Alignments.CENTER; thirdSettings.justifyContent = Css.Justifications.SPACE_BETWEEN; let thirdBlokContainer = BlokAdapter.getBlokContainer(thirdGroupItem, thirdSettings); // Select the root app.activeDocument.selection = thirdGroupItem; thirdBlokContainer.invalidate(); app.redraw(); // Undo waypoint 1 // Verify that it stayed distributed Assert.isTrue(thirdBlokContainer.getRect().equals(new Rect([0, 0, 321, 162]))); app.activeDocument.selection = secondGroupItem; // select the second item secondGroupItem.height = 120; // Make the 2nd group distribute taller app.redraw(); // Undo waypoint 2 secondBlokContainer.checkForRelayout(app.activeDocument.selection); // Verify that the second group doesn't stretch (0.5 is layout rounded after we finish) Assert.isTrue(secondBlokContainer.getRect().equals(new Rect([139.5, 21, 139.5 + 78, 21 + 120]))); // But we do stretch if alignSelf is stretch secondSettings.alignSelf = Css.Alignments.STRETCH; secondBlokContainer = BlokAdapter.getBlokContainer(secondGroupItem, secondSettings); secondBlokContainer.invalidate(); Assert.isTrue(secondBlokContainer.getRect().equals(new Rect([139.5, 0, 139.5 + 78, 162]))); } TestFramework.run("blok-container-layout-one-deep.ai", testOneDeepRow); TestFramework.run("blok-container-layout-one-deep.ai", testOneDeepRowStretch); TestFramework.run("blok-container-layout-one-deep.ai", testOneDeepRowChildStretch); TestFramework.run("blok-container-layout-one-deep.ai", testOneDeepColumn); TestFramework.run("blok-container-layout-one-deep-3.ai", testOneDeepRowSpaceBetween); TestFramework.run("blok-container-layout-one-deep-3.ai", testOneDeepRowFlex); TestFramework.run("blok-container-layout-two-deep.ai", testTwoDeepRow); TestFramework.run("blok-container-layout-two-deep.ai", testTwoDeepMixed); TestFramework.run("blok-container-layout-two-deep-alt.ai", testTwoDeepRowAlt); TestFramework.run("blok-container-layout-nested-groups.ai", testNestedGroups); TestFramework.run("blok-container-layout-strokes.ai", testStrokes); TestFramework.run("blok-container-layout-one-deep-textframearea.ai", testTextFrameArea); TestFramework.run("blok-container-layout-one-deep-textframearea.ai", testTextFrameAreaStretch); TestFramework.run("blok-container-layout-one-deep-textframearea.ai", testTextFrameAreaMiddle); TestFramework.run("blok-container-layout-one-deep.ai", testInteractiveResizeRow); TestFramework.run("blok-container-layout-one-deep.ai", testInteractiveResizeColumn); TestFramework.run("blok-container-layout-one-deep-textframearea.ai", testInteractiveResizeRowDistributed); TestFramework.run("blok-container-layout-one-deep-textframearea.ai", testInteractiveResizeColumnDistributed); TestFramework.run("blok-container-layout-one-deep-textframearea.ai", testInteractiveResizeRowDistributedStretch); TestFramework.run("blok-container-layout-one-deep-textframearea.ai", testInteractiveResizeRowDistributedChildStretch); TestFramework.run("blok-container-layout-nested-groups-alt.ai", testInteractiveResizeNested);
the_stack
import { take, skip, startWith, map, tap, filter, expand, pluck, switchMap, distinctUntilChanged, shareReplay, takeUntil, delay, debounceTime } from 'rxjs/operators'; import { where, orderBy, startAfter, endBefore, snap, pageReverse, onSnapshot, docs } from '@wizdm/connect/database/collection/operators'; import { Component, AfterViewInit, OnDestroy, Inject, NgZone, ViewChildren, QueryList } from '@angular/core'; import { DatabaseCollection, QueryDocumentSnapshot } from '@wizdm/connect/database/collection'; import { ConversationData, ConversationFavorites, MessageData } from './chat-types'; import { Subscription, Observable, BehaviorSubject, of, combineLatest } from 'rxjs'; import { DatabaseDocument } from '@wizdm/connect/database/document'; import { UserProfile, UserData } from 'app/utils/user'; import { DatabaseService } from '@wizdm/connect/database'; import { Router, ActivatedRoute } from '@angular/router'; import { ScrollObservable } from 'app/utils/scrolling'; import { runInZone, zoneStable } from '@wizdm/rxjs'; import { EmojiRegex } from '@wizdm/emoji/utils'; import { $animations } from './chat.animations'; import { Conversation } from './conversation/conversation.component'; import { Message } from './message/message.component'; @Component({ selector: 'wm-chat', templateUrl: './chat.component.html', styleUrls: ['./chat.component.scss'], animations: $animations }) export class ChatComponent extends DatabaseCollection<ConversationData> implements AfterViewInit, OnDestroy { // Conversation(s) @ViewChildren(Conversation) conversationsList: QueryList<Conversation>; private conversation: DatabaseDocument<ConversationData>; /** Conversations observable (from DB) */ readonly conversations$: Observable<QueryDocumentSnapshot<ConversationData>[]>; /** Active converastion Id observable */ readonly conversationId$: Observable<string>; /** Active conversation observable */ readonly activeConversation$: Observable<QueryDocumentSnapshot<ConversationData>>; // Messages thread @ViewChildren(Message) messagesList: QueryList<Message>; private thread: DatabaseCollection<MessageData>; /** Active conversation's messages (from DB) */ readonly messages$: Observable<QueryDocumentSnapshot<MessageData>[]>; private reload$ = new BehaviorSubject<void>(null); public loading: boolean = true; public browse: boolean = true; public get deleting(): boolean { return this.deletingCount > 0; } private deletingCount: number = 0; // Scrolling readonly scrolled$: Observable<boolean>; private autoScroll: boolean = true; // Keys private stats: ConversationFavorites = { "😂": 1, "👋🏻": 1, "👍": 1, "💕": 1, "🙏": 1 }; public keys: string[]; public text = ""; public get me(): string { return this.user.uid; } private recipient: string = ''; constructor(db: DatabaseService, private route: ActivatedRoute, private router: Router, private scroller: ScrollObservable, private user: UserProfile<UserData>, @Inject(EmojiRegex) private regex: RegExp, private zone: NgZone) { super(db, 'conversations'); // Lists all my active conversations this.conversations$ = this.reload$.pipe( switchMap( () => this.pipe( // Selects all the conversations where recipients[] contains my user's id where('recipients', 'array-contains', this.me), orderBy('created', 'desc'), // Combines existing conversations with new comers source => source.pipe( // Gets the list of existing conversations and sort them by updated value. // Note: we set the cursor apart to avoid messing up with the following queries // since the conversation array will be shuffled snap(), map( convs => ({ cursor: convs[0], convs: this.sortByUpdated(convs, 'desc') })), // Appends new comers to the top of the list expand( ({ cursor, convs }) => source.pipe( // Filters out the existing conversation to minimize reads endBefore( cursor ), // Listens to new conversations onSnapshot(zone), // Filters out unwanted emissions. // Note: we exclude snapshots with pending writes to make sure timestamps are up to date filter( snap => snap.size > 0 && !snap.metadata.hasPendingWrites ), // Gets the new documents when available docs(), take(1), // Prepends the new comers to the existing ones map( latest => ({ cursor: latest[0], convs: latest.concat(convs) }) ) )), // Gets rid of the cursor pluck('convs') ), // Replays to all subscribers shareReplay(1) ))); // Resolves the current conversation id from the query parameter this.conversationId$ = route.queryParamMap.pipe( // Extracts the @username from the route map( params => params.get('with') || '' ), distinctUntilChanged(), delay(0), // Resolves the user, if any switchMap( userName => { // Catches an unknown user first. This may be a result of: // 1. a deleted conversation (where the user has been removed from the recipients) // 2. a conversation with a user that no longer exists if(userName.startsWith('unknown-')) { // Resets the recipient this.recipient = ''; // Returns the original conversation id return of(userName.replace(/^unknown-/, '')); } // Go on with a known user return user.fromUserName(userName).pipe( take(1), map( user => { // Skips unexisting users if(!user) { return this.recipient = ''; } // Tracks the new recipient id this.recipient = user.id; // Computes the path for the requested conversation otherwise return (this.me < user.id ? this.me.concat(user.id) : this.recipient.concat(this.me) ); })); }), // Filters unchanged values and replays to all subscribers shareReplay(1) ); // Resolves the active conversation this.activeConversation$ = combineLatest(this.conversations$, this.conversationId$).pipe( map( ([convs, id]) => convs?.find( conv => conv.id === id ) || {} as any) ); // Paging observalbe to load the previous messages while scrolling up const more$ = scroller.pipe( // Triggers the previous page when approaching the top map( scroll => scroll.top < 50 ), // Filters for truthfull changes distinctUntilChanged(), filter( value => value ), // Asks for the next 20 messages map( () => 20 ), // Shows the loading spinner every page tap( () => this.loading = true ) ); // Streams up to page size messages from the selected conversation this.messages$ = this.conversationId$.pipe( // Stores the curernt conversation map( id => this.conversation = id && this.document(id) ), // Gets the message thread map( conv => this.thread = conv && conv.collection<MessageData>('messages') ), // Loads messages from the thread ordered by creation time switchMap( thread => thread ? thread.pipe( orderBy('created'), // Combines existing messages with new ones source => source.pipe( // Let's start by paging some existing messages pageReverse(more$), // Perpare to append new coming messages expand( paged => source.pipe( // Excludes existing messages startAfter( paged[paged.length - 1] ), // Listens for updates onSnapshot(this.db.zone), // Filters out unwanted emissions filter( snap => snap.size > 0 && !snap.metadata.hasPendingWrites ), // Gets the new messages and completes docs(), take(1), // Appends the new messages to the list map( latest => paged.concat(latest) ) )), // Always starts with an empty array to clear up messages when loading a new conversation startWith([]) ) // Reverts to an empty array when no conversation is selected ) : of([]) ), // When done loading.... zoneStable( zone, () => { // Scrolls for the last message to be visible this.autoScroll && this.scrollToBottom(); // Hides the loading spinner this.loading = false; }), // Replays to all subscribers shareReplay(1) ); /** Builds an observable telling if the view has been scrolled */ this.scrolled$ = scroller.pipe( // Measure the scrolling distance from the bottom map( scroll => scroll.bottom >= 50 ), // Distincts the value on changes only distinctUntilChanged(), // Enables/disables the autoScroll accordingly tap( scrolled => this.autoScroll = !scrolled ), // Run within angular zone runInZone(this.zone) ); } ngAfterViewInit() { // Syncronizes the status saved withing the selected conversation keeping track of the // last read message timestamp for unread counting purposes this.sub = this.conversationId$.pipe( // Gets the latest status value from the actiev conversation switchMap( id => this.fromId(id).pipe( take(1) ) ), map( data => data?.status?.[this.me] ), // Loads the status from the active conversation tap( status => { // Debug console.log('Loading', status); // Gets the emoji usage stats from the conversation this.stats = status?.favorites || this.stats; // Updates the favorites emoji based on the new stat this.keys = this.sortFavorites(this.stats); }), // Expands on the last message expand( status => this.lastMessage().pipe( // Stops saving new data when switching to another conversation takeUntil(this.conversationId$.pipe(skip(1))), // Extracts the last message timestamp map( msg => msg?.created ), // Ensures saving only updated data filter( created => !!created && (!(status?.lastRead) || ( created > status.lastRead ))), // Saves the new data switchMap( lastRead => { // Prepares a new status object saving the lastRead timestamp and the conversation favorites const newStatus = { favorites: this.stats, lastRead }; // Debug console.log('Saving data', newStatus); // Saves the new data returning the new value for the next recursion return this.conversation.merge({ status: { [this.me]: newStatus }} ) .then( () => newStatus ); }), // Completes the emission take(1) )) ).subscribe(); } // Disposes of the subscriptions ngOnDestroy() { this.sub.unsubscribe(); } private sub: Subscription; /** Returns the requested conversation observable provided the id falls among the active ones */ private fromId(id: string): Observable<ConversationData> { // Waits until the view has been rendered return this.zone.onStable.pipe( take(1), // Catch the QueryList changes switchMap( () => this.conversationsList.changes.pipe( startWith(null) ) ), // Seeks for the requested conversation map( () => this.conversationsList.find( conv => conv.id === id ) ), // Filters out unwanted emissions filter( conv => !!conv ), distinctUntilChanged( undefined, conv => conv.id ), // Returns the child conversation's data observable switchMap( conv => conv.data$ ) ); } /** Returns the last message currently listed from the active conversation */ private lastMessage(): Observable<MessageData> { // Waits until the view has been rendered return this.zone.onStable.pipe( take(1), // Catch the QueryList changes switchMap( () => this.messagesList.changes.pipe( startWith(null) ) ), // Seeks for the requested message data map( () => this.messagesList.last?.data ), // Filters out duplicates distinctUntilChanged(), ); } /** Tracks the deletion of conversations */ public onDeleting(flag: boolean, id: string) { // Tracks how many conversations are in the proess of deleting this.deletingCount = this.deletingCount + (flag ? 1 : -1); // Once done... if(this.deletingCount <= 0) { // Resets the text this.text = ""; // Reloads the page this.reload(); } } /** Reloads the chat content */ public reload() { // Starts by navigating to this very same route without any queryParameter. // This will update reset the conversationId and the message thread return this.router.navigate(['.'], { relativeTo: this.route, replaceUrl: true }) // Reloads all the conversations from scratch next .then( () => this.reload$.next() ); } /** Scrolls te view to the bottom to make the latest message visible */ public scrollToBottom() { this.scroller.scrollTo({ bottom: 0 }); } /** Forces the view to scroll whenever the keyboard expanded */ public onKeyboardExpand() { // Scrolls to bottom wheneve the autoScroll mode is enabled this.autoScroll && this.scrollToBottom(); } /** Send the current message */ public send(body: string) { // Updates the key usage statistics this.updateFavorites(body); // Sends the message adding it to the current conversation thread this.thread.add({ body, sender: this.me, recipient: this.recipient }).then( () => { // Enables automatic scrolling this.autoScroll = true; // Resets the last message text this.text = ""; }); // Prevents default return false; } /** Sorts the favorite keys based on usage */ private sortFavorites(stats: ConversationFavorites): string[] { return Object.keys(stats).sort( (a,b) => stats[b] - stats[a] ); } /** Updates the favorite statistics upon the given message */ public updateFavorites(body: string) { let match; let emojis = []; while(match = this.regex.exec(body)) { const key = match[0]; if(emojis.findIndex( emoji => emoji === key ) < 0) { emojis.push(match[0]); this.stats[key] = (this.stats[key] || 0) + 1; } } if(emojis.length > 0) { this.keys = this.sortFavorites(this.stats); } } /** ngFor tracking function */ public trackById(data: QueryDocumentSnapshot<any>) { return data.id; } /** Sort conversations based on their updated timestamp */ private sortByUpdated(data: QueryDocumentSnapshot<any>[], dir?: 'asc'|'desc'): QueryDocumentSnapshot<any>[] { const _dir = dir === 'desc' ? -1 : 1; return data.sort((a,b) => { const aDate = a?.data().updated; if(!aDate) { return _dir; } const bDate = b?.data().updated; if(!bDate) { return -_dir; } return bDate < aDate ? _dir : (bDate > aDate ? -_dir : 0); }); } }
the_stack
export = dyo export as namespace dyo declare namespace dyo { type Key = string | number | symbol type Type = Component | PromiseLike<any> | string | null type Collection = any[] | any type Properties<Props> = Readonly<Props & Attributes & {ref?: Ref, [props: string]: any}> type Ref<Value = any> = RefObject<Value> | RefCallback<Value> type RefObject<Value> = {current: Value} type RefCallback<Value> = (value: Value) => () => void | void type SetStateAction<State> = State | ((state: State) => State) type Dispatch<Action> = (value: Action) => void type Reducer<State, Action> = (state: State, action: Action) => State type ReducerState<Reduce extends Reducer<any, any>> = Reduce extends Reducer<infer State, any> ? State : never type ReducerAction<Reduce extends Reducer<any, any>> = Reduce extends Reducer<any, infer Action> ? Action : never type EffectCallback<Dependency, Props> = (deps?: Dependency, props?: Props) => (void | (() => void | undefined)) type MemoCallback<Dependency, Type> = (deps?: Dependency) => Type type DependencyList = ReadonlyArray<any> interface Interface<Props = {}> {key: Key, type: Type, props: Props, children: Collection} interface Attributes {key?: Key} interface Handler<Event, Props = {}> {(event: Event, props?: Props): any} interface Exception<Value> {name: string, type: string, stack: string, message: Value} interface Component<Props = {}> { (props: Properties<Props & {children: Collection}>): Collection} interface Context<Value> extends Component<{value: Value, children: Collection}> {} function useRef<Ref, Props = {}> (value: Ref | ((props: Props) => Ref)): RefObject<Ref> function useState<State, Props = {}> (state: State | ((props: Props) => State)): [State, Dispatch<SetStateAction<State>>] function useReducer<Reduce extends Reducer<State, any>, State = any> (reducer: Reduce, state: State & ReducerState<Reduce>): [ReducerState<Reduce>, Dispatch<ReducerAction<Reduce>>] function useCallback<Value extends (...args: any[]) => any, Dependency extends DependencyList> (callback: Value, deps?: Dependency): Value function useMemo<Dependency extends DependencyList, Value = any> (callback: MemoCallback<Dependency, Value>, deps?: Dependency): Value function useLayout<Dependency extends DependencyList, Props = {}> (callback: EffectCallback<Dependency, Props>, deps?: Dependency): void function useEffect<Dependency extends DependencyList, Props = {}> (callback: EffectCallback<Dependency, Props>, deps?: Dependency): void function useResource<Value, Props = {}> (callback: (props: Props) => PromiseLike<Value> | PromiseLike<Response>): Value function useContext<Value extends Component>(context: Value): ReturnType<Value>['props']['value'] function cloneElement<Props>(value: Interface, props?: Props, ...children: Collection): Interface<Props> function isValidElement<Props>(object: object): object is Interface<Props> function render<Target extends Node>(value: any, target: string | Target, callback?: (target: Target) => any): PromiseLike<Target> function createElement<Props extends (JSX.HTMLAttributes & JSX.SVGAttributes & Record<string, any> | null)> (type: string, props?: Props, ...children: Collection): Interface<Props> function createElement<Type extends Component<Props>, Props> (type: Type, props?: Attributes & Props | null, ...children: Collection): Interface<Props> function h<Props extends (JSX.HTMLAttributes & JSX.SVGAttributes & Record<string, any> | null)> (type: string, props?: Props, ...children: Collection): Interface<Props> function h<Type extends Component<Props>, Props>(type: Type, props?: Attributes & Props | null, ...children: Collection): Interface<Props> function Portal<Props extends {target: string | object, children?: Collection}>(props: Props): Interface<Props> function Context<Props extends {value: any, children?: Collection}> (props: Props): Interface<Props> function Boundary<Props extends {fallback: any, children?: Collection}> (props: Props): Interface<Props> function Suspense<Props extends {fallback: any, children?: Collection}> (props: Props): Interface<Props> function Fragment<Props extends {children?: Collection}> (props: Props): Interface<Props> function memo<Type extends Component<any>> (render: Type, compare?: (prev: Readonly<object>, next: Readonly<object>) => boolean): Type function lazy<Type extends Component<any>> (render: () => PromiseLike<{default: Type}>): Type const Children: { count(children: any): number find<Child>(children: Child | Child[], callback: (Child: Child, index: number) => boolean): Child filter<Child>(children: Child | Child[], callback: (Child: Child, index: number) => boolean): Child[] map<Child>(children: Child | Child[], callback: (child: Child, index: number) => Child): Child[] toArray<Child>(children: Child | Child[]): Child[] forEach<Child>(children: Child | Child[], callback: (child: Child, index: number) => void): void } } declare global { namespace JSX { type ClipboardEventHandler = EventHandler<ClipboardEvent> type CompositionEventHandler = EventHandler<CompositionEvent> type DragEventHandler = EventHandler<DragEvent> type FocusEventHandler = EventHandler<FocusEvent> type KeyboardEventHandler = EventHandler<KeyboardEvent> type MouseEventHandler = EventHandler<MouseEvent> type TouchEventHandler = EventHandler<TouchEvent> type UIEventHandler = EventHandler<UIEvent> type WheelEventHandler = EventHandler<WheelEvent> type AnimationEventHandler = EventHandler<AnimationEvent> type TransitionEventHandler = EventHandler<TransitionEvent> type GenericEventHandler = EventHandler<Event> interface EventHandler<Event> extends dyo.Handler<Event> {} interface Element extends dyo.Interface {} interface ElementClass extends dyo.Component<any> {} interface ElementAttributesProperty {props: any} interface ElementChildrenAttribute {children: any} interface IntrinsicAttributes extends dyo.Properties<{}> {} interface IntrinsicClassAttributes extends dyo.Properties<{}> {} interface PathAttributes {d: string} interface IntrinsicElements { // html a: HTMLAttributes abbr: HTMLAttributes address: HTMLAttributes area: HTMLAttributes article: HTMLAttributes aside: HTMLAttributes audio: HTMLAttributes b: HTMLAttributes base: HTMLAttributes bdi: HTMLAttributes bdo: HTMLAttributes big: HTMLAttributes blockquote: HTMLAttributes body: HTMLAttributes br: HTMLAttributes button: HTMLAttributes canvas: HTMLAttributes caption: HTMLAttributes cite: HTMLAttributes code: HTMLAttributes col: HTMLAttributes colgroup: HTMLAttributes data: HTMLAttributes datalist: HTMLAttributes dd: HTMLAttributes del: HTMLAttributes details: HTMLAttributes dfn: HTMLAttributes dialog: HTMLAttributes div: HTMLAttributes dl: HTMLAttributes dt: HTMLAttributes em: HTMLAttributes embed: HTMLAttributes fieldset: HTMLAttributes figcaption: HTMLAttributes figure: HTMLAttributes footer: HTMLAttributes form: HTMLAttributes h1: HTMLAttributes h2: HTMLAttributes h3: HTMLAttributes h4: HTMLAttributes h5: HTMLAttributes h6: HTMLAttributes head: HTMLAttributes header: HTMLAttributes hr: HTMLAttributes html: HTMLAttributes i: HTMLAttributes iframe: HTMLAttributes img: HTMLAttributes input: HTMLAttributes ins: HTMLAttributes kbd: HTMLAttributes keygen: HTMLAttributes label: HTMLAttributes legend: HTMLAttributes li: HTMLAttributes link: HTMLAttributes main: HTMLAttributes map: HTMLAttributes mark: HTMLAttributes menu: HTMLAttributes menuitem: HTMLAttributes meta: HTMLAttributes meter: HTMLAttributes nav: HTMLAttributes noscript: HTMLAttributes object: HTMLAttributes ol: HTMLAttributes optgroup: HTMLAttributes option: HTMLAttributes output: HTMLAttributes p: HTMLAttributes param: HTMLAttributes picture: HTMLAttributes pre: HTMLAttributes progress: HTMLAttributes q: HTMLAttributes rp: HTMLAttributes rt: HTMLAttributes ruby: HTMLAttributes s: HTMLAttributes samp: HTMLAttributes script: HTMLAttributes section: HTMLAttributes select: HTMLAttributes slot: HTMLAttributes small: HTMLAttributes source: HTMLAttributes span: HTMLAttributes strong: HTMLAttributes style: HTMLAttributes sub: HTMLAttributes summary: HTMLAttributes sup: HTMLAttributes table: HTMLAttributes tbody: HTMLAttributes td: HTMLAttributes textarea: HTMLAttributes tfoot: HTMLAttributes th: HTMLAttributes thead: HTMLAttributes time: HTMLAttributes title: HTMLAttributes tr: HTMLAttributes track: HTMLAttributes u: HTMLAttributes ul: HTMLAttributes var: HTMLAttributes video: HTMLAttributes wbr: HTMLAttributes // svg svg: SVGAttributes animate: SVGAttributes circle: SVGAttributes clipPath: SVGAttributes defs: SVGAttributes ellipse: SVGAttributes feBlend: SVGAttributes feColorMatrix: SVGAttributes feComponentTransfer: SVGAttributes feComposite: SVGAttributes feConvolveMatrix: SVGAttributes feDiffuseLighting: SVGAttributes feDisplacementMap: SVGAttributes feFlood: SVGAttributes feGaussianBlur: SVGAttributes feImage: SVGAttributes feMerge: SVGAttributes feMergeNode: SVGAttributes feMorphology: SVGAttributes feOffset: SVGAttributes feSpecularLighting: SVGAttributes feTile: SVGAttributes feTurbulence: SVGAttributes filter: SVGAttributes foreignObject: SVGAttributes g: SVGAttributes image: SVGAttributes line: SVGAttributes linearGradient: SVGAttributes marker: SVGAttributes mask: SVGAttributes path: SVGAttributes pattern: SVGAttributes polygon: SVGAttributes polyline: SVGAttributes radialGradient: SVGAttributes rect: SVGAttributes stop: SVGAttributes symbol: SVGAttributes text: SVGAttributes tspan: SVGAttributes use: SVGAttributes } interface DOMAttributes extends IntrinsicAttributes { // image events onLoad?: GenericEventHandler // clipboard events onCopy?: ClipboardEventHandler onCut?: ClipboardEventHandler onPaste?: ClipboardEventHandler // composition events onCompositionEnd?: CompositionEventHandler onCompositionStart?: CompositionEventHandler onCompositionUpdate?: CompositionEventHandler // focus events onFocus?: FocusEventHandler onBlur?: FocusEventHandler // form events onChange?: GenericEventHandler onInput?: GenericEventHandler onSearch?: GenericEventHandler onSubmit?: GenericEventHandler // keyboard events onKeyDown?: KeyboardEventHandler onKeyPress?: KeyboardEventHandler onKeyUp?: KeyboardEventHandler // media events onAbort?: GenericEventHandler onCanPlay?: GenericEventHandler onCanPlayThrough?: GenericEventHandler onDurationChange?: GenericEventHandler onEmptied?: GenericEventHandler onEncrypted?: GenericEventHandler onEnded?: GenericEventHandler onLoadedData?: GenericEventHandler onLoadedMetadata?: GenericEventHandler onLoadStart?: GenericEventHandler onPause?: GenericEventHandler onPlay?: GenericEventHandler onPlaying?: GenericEventHandler onProgress?: GenericEventHandler onRateChange?: GenericEventHandler onSeeked?: GenericEventHandler onSeeking?: GenericEventHandler onStalled?: GenericEventHandler onSuspend?: GenericEventHandler onTimeUpdate?: GenericEventHandler onVolumeChange?: GenericEventHandler onWaiting?: GenericEventHandler // mouse events onClick?: MouseEventHandler onContextMenu?: MouseEventHandler onDblClick?: MouseEventHandler onDrag?: DragEventHandler onDragEnd?: DragEventHandler onDragEnter?: DragEventHandler onDragExit?: DragEventHandler onDragLeave?: DragEventHandler onDragOver?: DragEventHandler onDragStart?: DragEventHandler onDrop?: DragEventHandler onMouseDown?: MouseEventHandler onMouseEnter?: MouseEventHandler onMouseLeave?: MouseEventHandler onMouseMove?: MouseEventHandler onMouseOut?: MouseEventHandler onMouseOver?: MouseEventHandler onMouseUp?: MouseEventHandler // selection events onSelect?: GenericEventHandler // touch events onTouchCancel?: TouchEventHandler onTouchEnd?: TouchEventHandler onTouchMove?: TouchEventHandler onTouchStart?: TouchEventHandler // ui events onScroll?: UIEventHandler // wheel events onWheel?: WheelEventHandler // animation events onAnimationStart?: AnimationEventHandler onAnimationEnd?: AnimationEventHandler onAnimationIteration?: AnimationEventHandler // transition events onTransitionEnd?: TransitionEventHandler } interface HTMLAttributes extends DOMAttributes { accept?: string acceptCharset?: string accessKey?: string action?: string allowFullScreen?: boolean allowTransparency?: boolean alt?: string async?: boolean autocomplete?: string autofocus?: boolean autoPlay?: boolean capture?: boolean cellPadding?: number | string cellSpacing?: number | string charSet?: string challenge?: string checked?: boolean class?: string className?: string cols?: number colSpan?: number content?: string contentEditable?: boolean contextMenu?: string controls?: boolean coords?: string crossOrigin?: string data?: string dateTime?: string default?: boolean defer?: boolean dir?: string disabled?: boolean download?: any draggable?: boolean encType?: string form?: string formAction?: string formEncType?: string formMethod?: string formNoValidate?: boolean formTarget?: string frameBorder?: number | string headers?: string height?: number | string hidden?: boolean high?: number href?: string hrefLang?: string for?: string httpEquiv?: string icon?: string id?: string inputMode?: string integrity?: string is?: string keyParams?: string keyType?: string kind?: string label?: string lang?: string list?: string loop?: boolean low?: number manifest?: string marginHeight?: number marginWidth?: number max?: number | string maxLength?: number media?: string mediaGroup?: string method?: string min?: number | string minLength?: number multiple?: boolean muted?: boolean name?: string noValidate?: boolean open?: boolean optimum?: number pattern?: string placeholder?: string poster?: string preload?: string radioGroup?: string readOnly?: boolean rel?: string required?: boolean role?: string rows?: number rowSpan?: number sandbox?: string scope?: string scoped?: boolean scrolling?: string seamless?: boolean selected?: boolean shape?: string size?: number sizes?: string slot?: string span?: number spellCheck?: boolean src?: string srcset?: string srcDoc?: string srcLang?: string srcSet?: string start?: number step?: number | string style?: any summary?: string tabIndex?: number target?: string title?: string type?: string useMap?: string value?: string | string[] | number width?: number | string wmode?: string wrap?: string // rdfa attributes about?: string datatype?: string inlist?: any prefix?: string property?: string resource?: string typeof?: string vocab?: string } interface SVGAttributes extends HTMLAttributes { accentHeight?: number | string accumulate?: 'none' | 'sum' additive?: 'replace' | 'sum' alignmentBaseline?: 'auto' | 'baseline' | 'before-edge' | 'text-before-edge' | 'middle' | 'central' | 'after-edge' | 'text-after-edge' | 'ideographic' | 'alphabetic' | 'hanging' | 'mathematical' | 'inherit' allowReorder?: 'no' | 'yes' alphabetic?: number | string amplitude?: number | string arabicForm?: 'initial' | 'medial' | 'terminal' | 'isolated' ascent?: number | string attributeName?: string attributeType?: string autoReverse?: number | string azimuth?: number | string baseFrequency?: number | string baselineShift?: number | string baseProfile?: number | string bbox?: number | string begin?: number | string bias?: number | string by?: number | string calcMode?: number | string capHeight?: number | string clip?: number | string clipPath?: string clipPathUnits?: number | string clipRule?: number | string colorInterpolation?: number | string colorInterpolationFilters?: 'auto' | 'sRGB' | 'linearRGB' | 'inherit' colorProfile?: number | string colorRendering?: number | string contentScriptType?: number | string contentStyleType?: number | string cursor?: number | string cx?: number | string cy?: number | string d?: string decelerate?: number | string descent?: number | string diffuseConstant?: number | string direction?: number | string display?: number | string divisor?: number | string dominantBaseline?: number | string dur?: number | string dx?: number | string dy?: number | string edgeMode?: number | string elevation?: number | string enableBackground?: number | string end?: number | string exponent?: number | string externalResourcesRequired?: number | string fill?: string fillOpacity?: number | string fillRule?: 'nonzero' | 'evenodd' | 'inherit' filter?: string filterRes?: number | string filterUnits?: number | string floodColor?: number | string floodOpacity?: number | string focusable?: number | string fontFamily?: string fontSize?: number | string fontSizeAdjust?: number | string fontStretch?: number | string fontStyle?: number | string fontVariant?: number | string fontWeight?: number | string format?: number | string from?: number | string fx?: number | string fy?: number | string g1?: number | string g2?: number | string glyphName?: number | string glyphOrientationHorizontal?: number | string glyphOrientationVertical?: number | string glyphRef?: number | string gradientTransform?: string gradientUnits?: string hanging?: number | string horizAdvX?: number | string horizOriginX?: number | string ideographic?: number | string imageRendering?: number | string in2?: number | string in?: string intercept?: number | string k1?: number | string k2?: number | string k3?: number | string k4?: number | string k?: number | string kernelMatrix?: number | string kernelUnitLength?: number | string kerning?: number | string keyPoints?: number | string keySplines?: number | string keyTimes?: number | string lengthAdjust?: number | string letterSpacing?: number | string lightingColor?: number | string limitingConeAngle?: number | string local?: number | string markerEnd?: string markerHeight?: number | string markerMid?: string markerStart?: string markerUnits?: number | string markerWidth?: number | string mask?: string maskContentUnits?: number | string maskUnits?: number | string mathematical?: number | string mode?: number | string numOctaves?: number | string offset?: number | string opacity?: number | string operator?: number | string order?: number | string orient?: number | string orientation?: number | string origin?: number | string overflow?: number | string overlinePosition?: number | string overlineThickness?: number | string paintOrder?: number | string panose1?: number | string pathLength?: number | string patternContentUnits?: string patternTransform?: number | string patternUnits?: string pointerEvents?: number | string points?: string pointsAtX?: number | string pointsAtY?: number | string pointsAtZ?: number | string preserveAlpha?: number | string preserveAspectRatio?: string primitiveUnits?: number | string r?: number | string radius?: number | string refX?: number | string refY?: number | string renderingIntent?: number | string repeatCount?: number | string repeatDur?: number | string requiredExtensions?: number | string requiredFeatures?: number | string restart?: number | string result?: string rotate?: number | string rx?: number | string ry?: number | string scale?: number | string seed?: number | string shapeRendering?: number | string slope?: number | string spacing?: number | string specularConstant?: number | string specularExponent?: number | string speed?: number | string spreadMethod?: string startOffset?: number | string stdDeviation?: number | string stemh?: number | string stemv?: number | string stitchTiles?: number | string stopColor?: string stopOpacity?: number | string strikethroughPosition?: number | string strikethroughThickness?: number | string string?: number | string stroke?: string strokeDasharray?: string | number strokeDashoffset?: string | number strokeLinecap?: 'butt' | 'round' | 'square' | 'inherit' strokeLinejoin?: 'miter' | 'round' | 'bevel' | 'inherit' strokeMiterlimit?: string strokeOpacity?: number | string strokeWidth?: number | string surfaceScale?: number | string systemLanguage?: number | string tableValues?: number | string targetX?: number | string targetY?: number | string textAnchor?: string textDecoration?: number | string textLength?: number | string textRendering?: number | string to?: number | string transform?: string u1?: number | string u2?: number | string underlinePosition?: number | string underlineThickness?: number | string unicode?: number | string unicodeBidi?: number | string unicodeRange?: number | string unitsPerEm?: number | string vAlphabetic?: number | string values?: string vectorEffect?: number | string version?: string vertAdvY?: number | string vertOriginX?: number | string vertOriginY?: number | string vHanging?: number | string vIdeographic?: number | string viewBox?: string viewTarget?: number | string visibility?: number | string vMathematical?: number | string widths?: number | string wordSpacing?: number | string writingMode?: number | string x1?: number | string x2?: number | string x?: number | string xChannelSelector?: string xHeight?: number | string xlinkActuate?: string xlinkArcrole?: string xlinkHref?: string xlinkRole?: string xlinkShow?: string xlinkTitle?: string xlinkType?: string xmlBase?: string xmlLang?: string xmlns?: string xmlnsXlink?: string xmlSpace?: string y1?: number | string y2?: number | string y?: number | string yChannelSelector?: string z?: number | string zoomAndPan?: string } } }
the_stack
import { BigNumber, ethers } from 'ethers'; import { artifacts } from 'hardhat'; import semver from 'semver'; import { bigNumberToHex, fromHexString, remove0x } from './hex-utils'; // Represents the JSON objects outputted by the Solidity compiler that describe the structure of // state within the contract. See // https://docs.soliditylang.org/en/v0.8.3/internals/layout_in_storage.html for more information. interface SolidityStorageObj { astId: number; contract: string; label: string; offset: number; slot: string; type: string; } // Represents the JSON objects outputted by the Solidity compiler that describe the types used for // the various pieces of state in the contract. See // https://docs.soliditylang.org/en/v0.8.3/internals/layout_in_storage.html for more information. interface SolidityStorageType { encoding: string; label: string; numberOfBytes: string; key?: string; value?: string; base?: string; members?: SolidityStorageObj[]; } // Container object returned by the Solidity compiler. See // https://docs.soliditylang.org/en/v0.8.3/internals/layout_in_storage.html for more information. export interface SolidityStorageLayout { storage: SolidityStorageObj[]; types: { [name: string]: SolidityStorageType; }; } interface StorageSlotPair { key: string; val: string; } /** * Retrieves the storageLayout portion of the compiler artifact for a given contract by name. This * function is hardhat specific. * * @param hre HardhatRuntimeEnvironment, required for the readArtifactSync function. * @param name Name of the contract to retrieve the storage layout for. * @return Storage layout object from the compiler output. */ export async function getStorageLayout(name: string): Promise<SolidityStorageLayout> { const { sourceName, contractName } = await artifacts.readArtifactSync(name); const buildInfo = await artifacts.getBuildInfo(`${sourceName}:${contractName}`); if (!buildInfo) throw new Error(`Build info not found for contract ${sourceName}:${contractName}`); const output = buildInfo.output.contracts[sourceName][contractName]; if (!semver.satisfies(buildInfo.solcVersion, '>=0.4.x <0.9.x')) { throw new Error(`Storage layout for Solidity version ${buildInfo.solcVersion} not yet supported. Sorry!`); } if (!('storageLayout' in output)) { throw new Error( `Storage layout for ${name} not found. Did you forget to set the storage layout compiler option in your hardhat config? Read more: https://smock.readthedocs.io/en/latest/getting-started.html#enabling-mocks` ); } return (output as any).storageLayout; } /** * Computes the key/value storage slot pairs that would be used if a given set of variable values * were applied to a given contract. * * @param storageLayout Solidity storage layout to use as a template for determining storage slots. * @param variables Variable values to apply against the given storage layout. * @returns An array of key/value storage slot pairs that would result in the desired state. */ export function computeStorageSlots(storageLayout: SolidityStorageLayout, variables: any = {}): Array<StorageSlotPair> { let slots: StorageSlotPair[] = []; for (const [variableName, variableValue] of Object.entries(variables)) { // Find the entry in the storage layout that corresponds to this variable name. const storageObj = storageLayout.storage.find((entry) => { return entry.label === variableName; }); // Complain very loudly if attempting to set a variable that doesn't exist within this layout. if (!storageObj) { throw new Error(`Variable name not found in storage layout: ${variableName}`); } // Encode this variable as series of storage slot key/value pairs and save it. slots = slots.concat(encodeVariable(variableValue, storageObj, storageLayout.types)); } // Dealing with packed storage slots now. We know that a storage slot is packed when two storage // slots produced by the above encoding have the same key. In this case, we want to merge the two // values into a single bytes32 value. We'll throw an error if the two values overlap (have some // byte where both values are non-zero). slots = slots.reduce((prevSlots: StorageSlotPair[], slot) => { // Find some previous slot where we have the same key. const prevSlot = prevSlots.find((otherSlot) => { return otherSlot.key === slot.key; }); if (prevSlot === undefined) { // Slot doesn't share a key with any other slot so we can just push it and continue. prevSlots.push(slot); } else { // Slot shares a key with some previous slot. // First, we remove the previous slot from the list of slots since we'll be modifying it. prevSlots = prevSlots.filter((otherSlot) => { return otherSlot.key !== prevSlot.key; }); // Now we'll generate a merged value by taking the non-zero bytes from both values. There's // probably a more efficient way to do this, but this is relatively easy and straightforward. let mergedVal = '0x'; const valA = remove0x(slot.val); const valB = remove0x(prevSlot.val); for (let i = 0; i < 64; i += 2) { const byteA = valA.slice(i, i + 2); const byteB = valB.slice(i, i + 2); if (byteA === '00' && byteB === '00') { mergedVal += '00'; } else if (byteA === '00' && byteB !== '00') { mergedVal += byteB; } else if (byteA !== '00' && byteB === '00') { mergedVal += byteA; } else { // Should never happen, means our encoding is broken. Values should *never* overlap. throw new Error('detected badly encoded packed value, should not happen'); } } prevSlots.push({ key: slot.key, val: mergedVal, }); } return prevSlots; }, []); return slots; } /** * Takes number slot value (in hex), left-pads it with zeros or f (when negative), * and displaces it by a given offset. * * @param val Number to pad. * @param offset Number of bytes to offset from the right. * @return Padded hex string. */ function padNumHexSlotValue(val: any, offset: number): string { const bn = BigNumber.from(val); return ( '0x' + bigNumberToHex(bn) .padStart(64 - offset * 2, bn.isNegative() ? 'f' : '0') // Pad the start with 64 - offset bytes .padEnd(64, '0') // Pad the end (up to 64 bytes) with zero bytes. .toLowerCase() // Making this lower case makes assertions more consistent later. ); } /** * Takes bytes slot value (in hex), left-pads it with zeros, and displaces it by a given offset. * * @param val Hex string value to pad. * @param offset Number of bytes to offset from the right. * @return Padded hex string. */ function padBytesHexSlotValue(val: string, offset: number): string { return ( '0x' + remove0x(val) .padStart(64 - offset * 2, '0') // Pad the start with 64 - offset zero bytes. .padEnd(64, '0') // Pad the end (up to 64 bytes) with zero bytes. .toLowerCase() // Making this lower case makes assertions more consistent later. ); } /** * Encodes a single variable as a series of key/value storage slot pairs using some storage layout * as instructions for how to perform this encoding. Works recursively with struct types. * ref: https://docs.soliditylang.org/en/v0.8.4/internals/layout_in_storage.html#layout-of-state-variables-in-storage * * @param variable Variable to encode as key/value slot pairs. * @param storageObj Solidity compiler JSON output describing the layout for this * @param storageTypes Full list of storage types allowed for this encoding. * @param nestedSlotOffset Only used for structs. Since slots for struct members are 0-indexed, we * need to be keeping track of the slot offset of the parent struct to figure out the final slot. * See https://docs.soliditylang.org/en/v0.8.6/internals/layout_in_storage.html#mappings-and-dynamic-arrays for additional info. * @param baseSlotKey Only used for maps. Keeps track of the base slot that other elements of the * mapping need to work off of. * @returns Variable encoded as a series of key/value slot pairs. */ function encodeVariable( variable: any, storageObj: SolidityStorageObj, storageTypes: { [name: string]: SolidityStorageType; }, nestedSlotOffset = 0, baseSlotKey?: string ): StorageSlotPair[] { let slotKey: string = '0x' + remove0x( BigNumber.from(baseSlotKey || nestedSlotOffset) .add(BigNumber.from(parseInt(storageObj.slot, 10))) .toHexString() ).padStart(64, '0'); const variableType = storageTypes[storageObj.type]; if (variableType.encoding === 'inplace') { if (variableType.label === 'address' || variableType.label.startsWith('contract')) { if (!ethers.utils.isAddress(variable)) { throw new Error(`invalid address type: ${variable}`); } return [ { key: slotKey, val: padNumHexSlotValue(variable, storageObj.offset), }, ]; } else if (variableType.label === 'bool') { // Do some light parsing here to make sure "true" and "false" are recognized. if (typeof variable === 'string') { if (variable === 'false') { variable = false; } if (variable === 'true') { variable = true; } } if (typeof variable !== 'boolean') { throw new Error(`invalid bool type: ${variable}`); } return [ { key: slotKey, val: padNumHexSlotValue(variable ? '1' : '0', storageObj.offset), }, ]; } else if (variableType.label.startsWith('bytes')) { if (!ethers.utils.isHexString(variable, parseInt(variableType.numberOfBytes, 10))) { throw new Error(`invalid bytesN type`); } return [ { key: slotKey, val: padBytesHexSlotValue(remove0x(variable).padEnd(parseInt(variableType.numberOfBytes, 10) * 2, '0'), storageObj.offset), }, ]; } else if (variableType.label.startsWith('uint') || variableType.label.startsWith('int')) { if (remove0x(BigNumber.from(variable).toHexString()).length / 2 > parseInt(variableType.numberOfBytes, 10)) { throw new Error(`provided ${variableType.label} is too big: ${variable}`); } return [ { key: slotKey, val: padNumHexSlotValue(variable, storageObj.offset), }, ]; } else if (variableType.label.startsWith('struct')) { // Structs are encoded recursively, as defined by their `members` field. let slots: StorageSlotPair[] = []; for (const [varName, varVal] of Object.entries(variable)) { slots = slots.concat( encodeVariable( varVal, (variableType.members as SolidityStorageObj[]).find((member) => { return member.label === varName; }) as SolidityStorageObj, storageTypes, nestedSlotOffset + parseInt(storageObj.slot as any, 10), baseSlotKey ) ); } return slots; } } else if (variableType.encoding === 'bytes') { if (storageObj.offset !== 0) { // string/bytes types are *not* packed by Solidity. throw new Error(`got offset for string/bytes type, should never happen`); } // `string` types are converted to utf8 bytes, `bytes` are left as-is (assuming 0x prefixed). const bytes = storageObj.type === 'string' ? ethers.utils.toUtf8Bytes(variable) : fromHexString(variable); // ref: https://docs.soliditylang.org/en/v0.8.4/internals/layout_in_storage.html#bytes-and-string if (bytes.length < 32) { // NOTE: Solidity docs (see above) specifies that strings or bytes with a length of 31 bytes // should be placed into a storage slot where the last byte of the storage slot is the length // of the variable in bytes * 2. return [ { key: slotKey, val: ethers.utils.hexlify( ethers.utils.concat([ ethers.utils.concat([bytes, ethers.constants.HashZero]).slice(0, 31), ethers.BigNumber.from(bytes.length * 2).toHexString(), ]) ), }, ]; } else { // TODO: add support for large strings or byte arrays throw new Error( 'large strings (> 31 bytes) not supported. Follow this issue for more info: https://github.com/defi-wonderland/smock/issues/30' ); } } else if (variableType.encoding === 'mapping') { if (variableType.key === undefined || variableType.value === undefined) { // Should never happen in practice but required to maintain proper typing. throw new Error(`variable is a mapping but has no key field or has no value field: ${variableType}`); } let slots: StorageSlotPair[] = []; for (const [varName, varVal] of Object.entries(variable)) { // Mapping keys are encoded depending on the key type. let key: string; if (variableType.key.startsWith('t_uint')) { key = BigNumber.from(varName).toHexString(); } else if (variableType.key.startsWith('t_bytes')) { key = '0x' + remove0x(varName).padEnd(64, '0'); } else { // Seems to work for everything else. key = varName; } // Figure out the base slot key that the mapped values need to work off of. // If baseSlotKey is defined here, then we're inside of a nested mapping and we should work // off of that previous baseSlotKey. Otherwise the base slot will be the slot of this map. const prevBaseSlotKey = baseSlotKey || padNumHexSlotValue(storageObj.slot, 0); const nextBaseSlotKey = ethers.utils.keccak256(padNumHexSlotValue(key, 0) + remove0x(prevBaseSlotKey)); // Encode the value. We need to use a dummy storageObj here because the function expects it. // Of course, we're not mapping to a specific variable. We map to a variable /type/. So we // need a dummy thing to represent a variable of that type. slots = slots.concat( encodeVariable( varVal, { label: varName, offset: 0, slot: '0', type: variableType.value, astId: 0, contract: '', }, storageTypes, nestedSlotOffset + parseInt(storageObj.slot, 10), nextBaseSlotKey ) ); } return slots; } else if (variableType.encoding === 'dynamic_array') { // TODO: add support for array types throw new Error('array types not yet supported. Follow this issue for more info https://github.com/defi-wonderland/smock/issues/31'); } throw new Error(`unknown unsupported type ${variableType.encoding} ${variableType.label}`); }
the_stack
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'; import { Form, Tabs, message, Modal, Spin } from 'antd'; import { history } from 'umi'; import { cloneDeep } from 'lodash'; import TestRestIcon from '@/components/testResultIcon'; import MultiVersionComp from './components/multiVerComp'; import { ExclamationCircleFilled } from '@ant-design/icons'; import type { COMPONENT_TYPE_VALUE } from '@/constant'; import { TABS_TITLE_KEY, COMPONENT_CONFIG_NAME, DEFAULT_COMP_VERSION, COMP_ACTION, DRAWER_MENU_ENUM, } from '@/constant'; import { convertToObj } from '@/utils'; import Api from '@/api'; import { initialScheduling, isViewMode, getModifyComp, isSameVersion, getCompsId, isMultiVersion, getCurrentComp, includesCurrentComp, getSingleTestStatus, isDataCheckBoxs, showDataCheckBox, getCompsName, isSchedulings, } from './help'; import ComponentButton from './components/compsBtn'; import MetaIcon from './components/metaIcon'; import { CommonComponentIcon, SchedulingComponentIcon, StoreComponentIcon, ComputeComponentIcon, } from '@/components/icon'; import SingleVerComp from './components/singleVerComp'; import { FormContext } from './context'; import type { ISaveCompsData, IModifyComp, IEditClusterRefProps, IScheduleComponent, IComponentProps, IScheduleComponentComp, IConfirmComps, IGetLoadTemplateParams, ITestConnectsParams, ITestErrorMsg, ITestStatusProps, IVersionData, } from './interface'; import './index.scss'; const { TabPane } = Tabs; const { confirm } = Modal; const TABS_TITLE = { [TABS_TITLE_KEY.COMMON]: { icon: <CommonComponentIcon style={{ marginRight: 2 }} />, name: '公共组件', }, [TABS_TITLE_KEY.SOURCE]: { icon: <SchedulingComponentIcon style={{ marginRight: 2 }} />, name: '资源调度组件', }, [TABS_TITLE_KEY.STORE]: { icon: <StoreComponentIcon style={{ marginRight: 2 }} />, name: '存储组件', }, [TABS_TITLE_KEY.COMPUTE]: { icon: <ComputeComponentIcon style={{ marginRight: 2 }} />, name: '计算组件', }, }; const TABS_POP_VISIBLE = { [TABS_TITLE_KEY.COMMON]: false, [TABS_TITLE_KEY.SOURCE]: false, [TABS_TITLE_KEY.STORE]: false, [TABS_TITLE_KEY.COMPUTE]: false, }; /** * 测试连通性返回结果类型 */ type ITestStatus = Record<number, ITestStatusProps>; export default forwardRef((_, ref) => { const [form] = Form.useForm(); const [activeKey, setActiveKey] = useState<TABS_TITLE_KEY>(TABS_TITLE_KEY.COMMON); const [schedulingComponent, setScheduling] = useState<IScheduleComponentComp[][]>(() => initialScheduling(), ); const [versionData, setVersion] = useState<IVersionData>({}); const [saveCompsData, setSaveCompsData] = useState<ISaveCompsData[]>([]); const [testStatus, setStatus] = useState<ITestStatus>({}); const [disabledMeta, setDisabledMeta] = useState(false); const [popVisible, setPopVisible] = useState(TABS_POP_VISIBLE); const [loading, setLoading] = useState(false); // 多版本组件的componentTypeCode与对应的versionName数组映射 const [versionMap, setVersionMap] = useState<Record<number, string[]>>({}); const mode = (history.location.query?.mode as string) || 'view'; useImperativeHandle( ref, (): IEditClusterRefProps => ({ testConnects, handleComplete: () => { const showConfirm = (comps: Set<IModifyComp>) => { confirm({ title: `${getCompsName(comps).join('、')} 尚未保存,是否退出编辑?`, content: null, icon: <ExclamationCircleFilled color="#FAAD14" />, okText: '确定', cancelText: '取消', onOk: () => { history.push({ query: { drawer: DRAWER_MENU_ENUM.CLUSTER, }, }); }, onCancel: () => {}, }); }; form.validateFields().then((values) => { const valuesObj = convertToObj(values); const modifyComps = getModifyComp(valuesObj, schedulingComponent, versionMap); if (modifyComps.size) { showConfirm(modifyComps); } else { history.push({ query: { drawer: DRAWER_MENU_ENUM.CLUSTER, }, }); } }); }, }), ); const getDataList = () => { const clusterId = history.location.query?.clusterId; setLoading(true); Api.getClusterInfo({ clusterId: Number(clusterId), }) .then((res) => { if (res.code === 1) { const initData = initialScheduling(); const { scheduling } = res.data; scheduling?.forEach((comps: IScheduleComponent) => { initData[comps.schedulingCode] = comps.components; }); setScheduling(initData); setDisabledMeta(!res.data.canModifyMetadata); return getSaveComponentList(res.data.clusterName); } }) .finally(() => { setLoading(false); }); }; const getSaveComponentList = async (clusterName: string): Promise<number[]> => { const res = await Api.getComponentStore({ clusterName }); if (res.code === 1 && res.data) { const nextSaveCompsData: ISaveCompsData[] = []; res.data.forEach((item: COMPONENT_TYPE_VALUE) => { nextSaveCompsData.push({ key: item, value: COMPONENT_CONFIG_NAME[item], }); }); setSaveCompsData(nextSaveCompsData); return res.data; } return []; }; const getVersionData = () => { Api.getVersionData().then((res) => { if (res.code === 1) { setVersion(res.data); } }); }; // 获取组件模板 const getLoadTemplate = async ( key?: string | number, params?: IGetLoadTemplateParams, nextScheduling?: IScheduleComponentComp[][], ) => { const components = nextScheduling || schedulingComponent; const clusterName = history.location.query?.clusterName; const clusterId = history.location.query?.clusterId; const typeCode = ( typeof key !== 'undefined' ? Number(key) : components[activeKey][0]?.componentTypeCode ) as keyof typeof DEFAULT_COMP_VERSION; const comp = getCurrentComp(components[activeKey], { typeCode, }); const saveParams: Partial<IComponentProps> = { componentTypeCode: Number(typeCode), versionName: params?.compVersion ?? '', }; const fisrtVersionData = versionData?.hadoopVersion?.[0]?.values?.[0]?.key; const versionName = params?.compVersion ?? DEFAULT_COMP_VERSION[typeCode] ?? fisrtVersionData ?? ''; if (isMultiVersion(typeCode) && !params?.compVersion) return; const resLists = await getSaveComponentList(clusterName as string); if ( (!comp?.componentTemplate && components[activeKey]?.length) || params?.compVersion || params?.storeType ) { const res = await Api.getLoadTemplate({ clusterId, componentType: typeCode, versionName, storeType: params?.storeType ?? resLists[0] ?? '', deployType: params?.deployType ?? '', }); if (res.code === 1) { saveParams.componentTemplate = JSON.stringify(res.data); } saveComp(saveParams); } }; const saveComp = (params: Partial<IComponentProps>, type?: string) => { const newCompData = schedulingComponent; schedulingComponent[activeKey] = schedulingComponent[activeKey].map((comp) => { const newComp = { ...comp }; if (newComp.componentTypeCode !== params.componentTypeCode) { return newComp; } if (type === COMP_ACTION.ADD) { newComp.multiVersion.push(undefined); } newComp.multiVersion = newComp.multiVersion.map((vcomp) => { if (!vcomp) { return { ...params }; } if (!isMultiVersion(params.componentTypeCode!)) { return { ...vcomp, ...params }; } if (!vcomp?.versionName || vcomp?.versionName === params.versionName) { return { ...vcomp, ...params }; } return vcomp; }) as IComponentProps[]; return newComp; }); setScheduling(cloneDeep(newCompData)); }; const testConnects = (params?: ITestConnectsParams, callBack?: (bool: boolean) => void) => { const typeCode = params?.typeCode ?? ''; const versionName = params?.versionName ?? ''; const deployType = params?.deployType ?? ''; form.validateFields() .then((rawValues) => { const values = convertToObj(rawValues); if (typeCode || typeCode === 0) { // 只对比当前组件的当前版本 const modifyComps = getModifyComp(values, schedulingComponent, { [typeCode]: [versionName], }); const includesCurrent = includesCurrentComp(Array.from(modifyComps), { typeCode, versionName, }); if (modifyComps.size > 0 && includesCurrent) { let desc = COMPONENT_CONFIG_NAME[typeCode] as string; if (isMultiVersion(typeCode)) { desc = `${desc} ${versionName}`; } message.error(`组件 ${desc} 参数变更未保存,请先保存再测试组件连通性`); return; } callBack?.(true); Api.testConnect({ clusterName: history.location.query?.clusterName as string, deployType, componentType: typeCode, versionName: versionName ?? '', }) .then((res) => { if (res.code === 1) { setTestStatus(res.data, true); } }) .finally(() => { callBack?.(false); }); } else { const modifyComps = getModifyComp(values, schedulingComponent, versionMap); if (modifyComps.size > 0) { const compsName = getCompsName(modifyComps).join('、'); message.error(`组件 ${compsName} 参数变更未保存,请先保存再测试组件连通性`); return; } callBack?.(true); Api.testConnects({ clusterName: history.location.query?.clusterName as string, }) .then((res) => { if (res.code === 1) { setTestStatus(res.data); } }) .finally(() => { callBack?.(false); }); } }) .catch((err) => { // 当前组件错误校验 const currentCompErr = err ? err[String(typeCode)] || {} : {}; const isMultiVers = isMultiVersion(typeCode as number); const inculdesVersErr = Object.keys(currentCompErr).includes(versionName); if (isMultiVers && inculdesVersErr) { message.error('请检查配置'); return; } const includesTypeErr = Object.keys(err).includes(String(typeCode)); if ((err && !typeCode) || (err && !isMultiVers && includesTypeErr)) { message.error('请检查配置'); } }); }; const setTestStatus = (status: ITestStatusProps | ITestStatusProps[], isSingle?: boolean) => { if (Array.isArray(status)) { const nextTestStatus: ITestStatus = {}; status.forEach((temp) => { nextTestStatus[temp.componentTypeCode] = { ...temp }; }); setStatus(nextTestStatus); } else if (isSingle) { const currentComp = schedulingComponent[activeKey].find( (comp) => comp.componentTypeCode === status.componentTypeCode, ); if (!isMultiVersion(status.componentTypeCode)) { setStatus((t) => ({ ...t, [status.componentTypeCode]: { ...status, }, })); return; } let multiVersion = getSingleTestStatus( { typeCode: status.componentTypeCode as number, versionName: status?.componentVersion as string, }, status, testStatus, ); multiVersion = multiVersion.filter((ver) => ver); let sign = false; // 标记是否有测试连通性失败的多版本组件 const errorMsg: ITestErrorMsg[] = []; multiVersion.forEach((mv) => { if (mv && !mv.result) { sign = true; errorMsg.push({ componentVersion: mv.componentVersion, errorMsg: mv.errorMsg, }); } }); const msg: ITestStatusProps = { result: null, errorMsg: [], multiVersion, componentTypeCode: status.componentTypeCode, }; if (!sign && currentComp?.multiVersion?.length === multiVersion.length) { msg.result = true; } if (sign) { msg.result = false; msg.errorMsg = errorMsg; } setStatus((s) => ({ ...s, [status.componentTypeCode]: msg, })); } }; const handleConfirm = async (action: string, comps: IConfirmComps, mulitple?: boolean) => { const newCompData = schedulingComponent; let currentCompArr = newCompData[activeKey]; if (Array.isArray(comps) && comps.length && action !== COMP_ACTION.DELETE) { const initialComp = comps.map((code) => { if (!isMultiVersion(code)) return { componentTypeCode: code, multiVersion: [undefined], }; return { componentTypeCode: code, multiVersion: [] }; }); currentCompArr = currentCompArr.concat(initialComp); } if (action === COMP_ACTION.DELETE) { const { componentTypeCode, versionName, id = '' } = comps as IComponentProps; const componentIds = getCompsId(currentCompArr, id); let res: { code?: number } = {}; if (componentIds.length) { res = await Api.deleteComponent({ componentId: componentIds[0] }); } if (res?.code === 1 || !componentIds.length) { const wrapper = new Set<IScheduleComponentComp>(); currentCompArr.forEach((comp) => { if (isMultiVersion(comp.componentTypeCode) && mulitple) { // eslint-disable-next-line no-param-reassign comp.multiVersion = comp.multiVersion.filter( (vComp) => vComp?.versionName !== versionName, ); wrapper.add(comp); } if (comp.componentTypeCode !== componentTypeCode) wrapper.add(comp); }); currentCompArr = Array.from(wrapper); const multiVersion = getSingleTestStatus( { typeCode: componentTypeCode, versionName }, null, testStatus, ); let fieldValue: Record<string, unknown> = {}; if (isMultiVersion(componentTypeCode)) { fieldValue = { [versionName]: {} }; } form.setFieldsValue({ [componentTypeCode]: fieldValue, }); setStatus((s) => ({ ...s, [componentTypeCode]: { ...s[componentTypeCode], result: null, multiVersion, }, })); } } newCompData[activeKey] = currentCompArr; setScheduling(newCompData); getLoadTemplate(undefined, undefined, newCompData); }; const handlePopVisible = (visible?: boolean) => { setPopVisible((visibles) => ({ ...visibles, [activeKey]: visible ?? true, })); }; const handleCompVersion = (typeCode: number, version: string) => { if (!isSameVersion(Number(typeCode))) { form.setFieldsValue({ [`${typeCode}.versionName`]: version }); getLoadTemplate(typeCode, { compVersion: version }); return; } form.setFieldsValue({ [typeCode]: { versionName: version[version.length - 1], hadoopVersionSelect: version, }, }); getLoadTemplate(typeCode, { compVersion: version[version.length - 1], }); }; const onTabChange = (key: string) => { setActiveKey(Number(key)); setVersionMap({}); }; useEffect(() => { getDataList(); getVersionData(); }, []); const isScheduling = isSchedulings(schedulingComponent); const tabPanelTab = (key: TABS_TITLE_KEY) => { return ( <span className="dt-cluster-component-tab-title"> {TABS_TITLE[key].icon} {TABS_TITLE[key].name} </span> ); }; const tabBarExtraContent = (comps: IScheduleComponentComp[]) => { return !isViewMode(mode) ? ( <ComponentButton comps={comps} popVisible={popVisible[activeKey]} activeKey={activeKey} handleConfirm={handleConfirm} handlePopVisible={handlePopVisible} /> ) : null; }; const handleTabChange = (tabActiveKey: string) => { if (!isMultiVersion(Number(tabActiveKey))) { getLoadTemplate(tabActiveKey); } }; const onVersionChange = (versionName: string, typeCode: COMPONENT_TYPE_VALUE) => { if (typeCode || typeCode === 0) { const versions = versionMap[typeCode] || []; if (versionName && !versions.includes(versionName)) { versions.push(versionName); } setVersionMap({ ...versionMap, [typeCode]: versions }); } }; const renderContent = (comp: IScheduleComponentComp, isCheckBoxs: boolean) => { const clusterInfo = { clusterName: history.location.query?.clusterName as string, clusterId: history.location.query?.clusterId as string, }; return ( <TabPane tab={ <div className="flex items-center"> {COMPONENT_CONFIG_NAME[comp.componentTypeCode]} {showDataCheckBox(comp.componentTypeCode) && ( <MetaIcon comp={comp} isMetadata={form.getFieldValue( `${comp.componentTypeCode}.isMetadata`, )} /> )} <TestRestIcon testStatus={testStatus[comp.componentTypeCode] ?? {}} /> </div> } key={comp.componentTypeCode.toString()} > {isMultiVersion(comp.componentTypeCode) ? ( <MultiVersionComp comp={comp} view={isViewMode(mode)} saveCompsData={saveCompsData} isCheckBoxs={isCheckBoxs} versionData={versionData} testStatus={testStatus[comp.componentTypeCode]?.multiVersion ?? []} clusterInfo={clusterInfo} saveComp={saveComp} getLoadTemplate={getLoadTemplate} testConnects={testConnects} handleConfirm={handleConfirm} onVersionChange={onVersionChange} /> ) : ( comp?.multiVersion?.map((vcomp) => ( <SingleVerComp comp={vcomp!} key={`${vcomp?.versionName || vcomp?.componentTypeCode}`} view={isViewMode(mode)} disabledMeta={disabledMeta} isCheckBoxs={isCheckBoxs} isSchedulings={isScheduling} versionData={versionData} saveCompsData={saveCompsData} clusterInfo={clusterInfo} saveComp={saveComp} handleCompVersion={handleCompVersion} testConnects={testConnects} handleConfirm={handleConfirm} /> )) )} </TabPane> ); }; return ( <FormContext.Provider value={form}> <div className="dt-cluster"> <Tabs tabPosition="top" onChange={onTabChange} activeKey={activeKey.toString()} className="dt-cluster-component" tabBarExtraContent={{ left: <div className="dt-cluster-title">集群配置</div>, }} > {schedulingComponent.map((__, key: TABS_TITLE_KEY) => ( <TabPane tab={tabPanelTab(key)} key={String(key)} /> ))} </Tabs> <Spin spinning={loading}> {schedulingComponent.map((comps, key) => { if (key !== activeKey) { return <div key={key} />; } // 存在HiveServer、SparkThrift两个组件 const isCheckBoxs = isDataCheckBoxs(comps); return ( <div className="relative" key={String(key)}> <Tabs tabPosition="left" tabBarExtraContent={tabBarExtraContent(comps)} className="c-editCluster__container__componentTabs" onChange={handleTabChange} destroyInactiveTabPane > {comps?.map((comp) => renderContent(comp, isCheckBoxs))} </Tabs> {comps?.length === 0 && ( <div key={activeKey} className="empty-logo"> <img src="images/emptyLogo.svg" /> </div> )} </div> ); })} </Spin> </div> </FormContext.Provider> ); });
the_stack
namespace analysis { import CallNode = data.CallNode; import SolverCall = data.SolverCall; type AnalysisCallback = (d: ProfileData) => void; type ZoomCallback = (d: CallNode) => void; export interface ProfileData { root: CallNode; solverCalls: SolverCall[]; rows: AnalysisRow[]; currentZoom: CallNode; aggregate: boolean; maxScore: number; } export interface AnalysisRow { function: string; node: CallNode; allNodes: CallNode[]; score: number; columns: number[]; } export interface AnalysisColumn { type: string; column: string; name: string; score: boolean; description?: string; } var options = { aggregate: false, signatures: false, collapseRosette: false, collapseSolver: false, columns: <AnalysisColumn[]>[], contextDepth: 0, histogramBins: 100 }; var analysisCallbacks: AnalysisCallback[] = []; var zoomCallbacks: ZoomCallback[] = []; var columnDenominators: Map<number> = {}; var currentState: data.ProfileState = null; var currentZoom: CallNode = null; // init export function init() { data.registerUpdateCallback(receiveDataCallback); } export function registerAnalysisCallback(cb: AnalysisCallback): void { analysisCallbacks.push(cb); } export function registerZoomCallback(cb: ZoomCallback): void { zoomCallbacks.push(cb); } export function setAggregate(x: boolean): void { options.aggregate = x; refresh(); } export function setColumns(x: AnalysisColumn[]): void { options.columns = x; refresh(); } export function setContextDepth(x: number): void { options.contextDepth = x; refresh(); } export function setHistogramBins(x: number): void { options.histogramBins = x; refresh(); } export function setSignatures(x: boolean): void { options.signatures = x; refresh(); } export function setCollapseRosette(x: boolean): void { options.collapseRosette = x; refresh(); } export function setCollapseSolver(x: boolean): void { options.collapseSolver = x; refresh(); } export function refresh(): void { if (currentState) receiveDataCallback(currentState); } function receiveDataCallback(d: data.ProfileState): void { // save the state for reuse when options are changed currentState = d; // which data to actually use let root: CallNode = d.root; if (options.collapseRosette) { root = collapseRosetteCalls(root); } if (options.collapseSolver) { root = collapseSolverTime(root, d.solverCalls); } // compute scores for the data let maxScore = computeScores(root); // compute rows for the table let rows = computeTableRows(root); if (!currentZoom) { currentZoom = root; } let a: ProfileData = { root: root, solverCalls: d.solverCalls, rows: rows, currentZoom: currentZoom, aggregate: options.aggregate, maxScore: maxScore }; for (let cb of analysisCallbacks) { cb(a); } } export function zoomTo(root: CallNode) { currentZoom = root; for (let cb of zoomCallbacks) { cb(currentZoom); } } function computeScores(root: CallNode): number { if (root === null) return 0.0; // first pass: compute denominators let maxValues: Map<number> = {}; let nodes = [root]; while (nodes.length > 0) { let n = nodes.pop()!; for (let c of options.columns) { if (n.hasOwnProperty(c.type)) { let k = c.type + ":" + c.column; maxValues[k] = Math.max(maxValues[k] || 0, n[c.type][c.column] || 0); } } for (let c of n.children) nodes.push(c); } // second pass: compute scores for each node nodes.push(root); let maxScore = 0; while (nodes.length > 0) { let n = nodes.pop()!; let score = 0.0; for (let c of options.columns) { if (c.score && n.hasOwnProperty(c.type)) { let k = c.type + ":" + c.column; if (maxValues[k] > 0) { score += (n[c.type][c.column] || 0) / maxValues[k]; } } } n.score = score; if (score > maxScore) { maxScore = score; } for (let c of n.children) nodes.push(c); } return maxScore; } // compute scores for aggregated table rows function updateScoresForRows(rows: AnalysisRow[]) { if (rows.length == 0) return rows; // first pass: compute denominators let maxValues: number[] = []; for (let r of rows) { for (let i = 0; i < r.columns.length; i++) { if (r.columns[i] >= (maxValues[i] || 0)) { maxValues[i] = r.columns[i]; } } } // second pass: compute scores for each row for (let r of rows) { let score = 0.0; for (let i = 0; i < r.columns.length; i++) { if (options.columns[i].score && maxValues[i] > 0) { score += r.columns[i] / maxValues[i]; } } r.score = score; } } // get the key used for aggregating nodes together according to context function getAggregateKeyForNode(node: CallNode): string { var context = options.contextDepth; var key = node.name + "(" + node.source + ")"; while (context-- != 0 && node.parent) { node = node.parent; key = key + "\\" + node.name + "(" + node.source + ")"; } if (options.signatures) { key = (node.inputs["signature"] || []).join("->") + "|" + (node.outputs["signature"] || []).join("->") + "|" + key; } return key; } // compute the analysis rows by aggregating and scoring them function computeTableRows(root: CallNode): AnalysisRow[] { if (root === null) return []; if (options.aggregate) { // group rows by the aggregate key (wrt context) let nodes = [root]; let ctxs: Map<CallNode[]> = {}; while (nodes.length > 0) { let n = nodes.pop()!; if (n) { let k = getAggregateKeyForNode(n); if (!ctxs.hasOwnProperty(k)) ctxs[k] = []; ctxs[k].push(n); for (let c of n.children) nodes.push(c); } } // create row for each node let allRows: AnalysisRow[] = []; for (let k in ctxs) { let rows = ctxs[k]; if (rows.length > 0) { let first = rows[0]!; // compute the row's data as the total within let maxScore = 0.0; let totalValues: Map<number> = {}; for (let n of rows) { for (let c of options.columns) { if (n.hasOwnProperty(c.type)) { let k = c.type + ":" + c.column; totalValues[k] = (totalValues[k] || 0) + (n[c.type][c.column] || 0); } } maxScore = Math.max(maxScore, n.score); } let columns = []; for (let k of options.columns) { columns.push(totalValues[k.type + ":" + k.column]); } let row: AnalysisRow = { function: first.name, node: first, allNodes: rows, score: maxScore, columns: columns }; allRows.push(row); } } updateScoresForRows(allRows); // this should really be an option return allRows; } else { // create a row for each call let nodes = [root]; let rows: AnalysisRow[] = []; while (nodes.length > 0) { let n = nodes.pop()!; if (!n) continue; let values: Map<number> = {}; for (let c of options.columns) { if (n.hasOwnProperty(c.type)) { let k = c.type + ":" + c.column; values[k] = n[c.type][c.column] || 0; } } let columns = []; for (let k of options.columns) { columns.push(values[k.type + ":" + k.column]); } let row: AnalysisRow = { function: n.name, node: n, allNodes: [n], score: n.score, columns: columns }; rows.push(row); for (let c of n.children) nodes.push(c); } return rows; } } function collapseRosetteCalls(root: CallNode): CallNode { let rec = (node: CallNode): CallNode => { let newExcl = undefined; let newChildren = []; let modified = false; for (let c of node.children) { let newC = rec(c); // recurse to collapse children if (newC.name[0] == "@") { if (typeof newExcl === "undefined") { newExcl = {}; for (let k of Object.keys(node.excl)) { newExcl[k] = node.excl[k]; } } for (let k of Object.keys(newC.excl)) { newExcl[k] = (newExcl[k] || 0) + newC.excl[k]; // add all c's children } for (let cc of newC.children) { newChildren.push(cc); } modified = true; } else { if (newC !== c) { modified = true; } newChildren.push(newC); // recurse } } if (modified) { let newNode = {}; for (let k of Object.keys(node)) { newNode[k] = node[k]; } if (typeof newExcl !== "undefined") { (<CallNode>newNode).excl = newExcl; } (<CallNode>newNode).children = newChildren; return <CallNode>newNode; } else { return node; } } let newRoot = rec(root); return newRoot; } // remove all solver time from exclusive time function collapseSolverTime(root: CallNode, solverCalls: SolverCall[]): CallNode { let rec = (node: CallNode) => { let exclDt = 0; let newChildren = []; let modified = false; let start = node.start; // do the spaces before each child for (let c of node.children) { let finish = c.start; for (let sc of solverCalls) { let scfinish = typeof sc.finish === "undefined" ? root.finish : sc.finish; if (scfinish < start) continue; if (finish < sc.start) break; // todo make not quadratic let delta = Math.min(finish, scfinish) - Math.max(start, sc.start); exclDt += delta; } let ret = rec(c); newChildren.push(ret); if (ret !== c) modified = true; start = c.finish; } // do the space between last child and my end let finish = node.finish; for (let sc of solverCalls) { let scfinish = typeof sc.finish === "undefined" ? root.finish : sc.finish; if (scfinish < start) continue; if (finish < sc.start) break; let delta = Math.min(finish, scfinish) - Math.max(start, sc.start); exclDt += delta; } if (exclDt > 0 || modified) { let newNode = {}; for (let k of Object.keys(node)) { newNode[k] = node[k]; } let newExcl = {}; for (let k of Object.keys(node.excl)) { newExcl[k] = node.excl[k]; } (<CallNode>newNode).excl = newExcl; (<CallNode>newNode).excl["time"] -= exclDt; (<CallNode>newNode).children = newChildren; node = (<CallNode>newNode); } return node; } return rec(root); } }
the_stack
import * as cp from "child_process"; import { NodeConnectionRequestMessage, NodeConnectionResponseMessage } from "../types/NodeConnectionMessages"; import { NodeConnectionInterfaceSpec, NodeConnectionDomainSpec } from "../types/NodeConnectionInterfaceSpec"; define((require, exports, module) => { const EventDispatcher = require("utils/EventDispatcher"); const fork = node.require("child_process").fork; const getLogger = node.require("./utils").getLogger; const log = getLogger("NodeConnection"); const CONNECTION_TIMEOUT = 10000; // 10 seconds const MAX_COUNTER_VALUE = 4294967295; // 2^32 - 1 function setDeferredTimeout(deferred: JQueryDeferred<any>, delay = CONNECTION_TIMEOUT) { const timer = setTimeout(() => deferred.reject("timeout"), delay); deferred.always(() => clearTimeout(timer)); } function waitFor(condition: Function, delay = CONNECTION_TIMEOUT) { const deferred = $.Deferred(); setDeferredTimeout(deferred, delay); // periodically check condition function doCheck() { return condition() ? deferred.resolve() : setTimeout(doCheck, 10); } doCheck(); return deferred.promise(); } class NodeConnection { /* eslint-disable */ public domains: any; // TODO: better define structure public domainEvents: any; // TODO: better define structure private _autoReconnect: boolean; private _commandCount: number; private _name: string; private _nodeProcess: cp.ChildProcess | null; private _pendingCommandDeferreds: Array<JQueryDeferred<any>>; private _registeredDomains: { [domainPath: string]: { loaded: boolean, autoReload: boolean } }; /* eslint-enable */ constructor() { this.domains = {}; this.domainEvents = {}; this._registeredDomains = {}; this._nodeProcess = null; this._pendingCommandDeferreds = []; this._name = ""; this._commandCount = 1; this._autoReconnect = false; } public getName(): string { return this._name; } public connect(autoReconnect: boolean = false) { this._autoReconnect = autoReconnect; const deferred = $.Deferred(); // Start the connection process this._cleanup(); // Fork the process base as a child const nodeProcessPath = node.require.resolve("./node-process/base.js"); this._nodeProcess = fork(nodeProcessPath); if (this._nodeProcess == null) { throw new Error(`Unable to fork ${nodeProcessPath}`); } this._nodeProcess.on("error", (err: Error) => { log.error(`[node-process-${this.getName()}] error: ${err.stack}`); }); this._nodeProcess.on("exit", (code: number, signal: string) => { log.error(`[node-process-${this.getName()}] exit code: ${code}, signal: ${signal}`); }); this._nodeProcess.on("message", (obj: any) => { const _type: string = obj.type; switch (_type) { case "log": log[obj.level](`[node-process-${this.getName()}]`, obj.msg); break; case "receive": this._receive(obj.msg); break; case "refreshInterface": this._refreshInterfaceCallback(obj.spec); break; default: log.warn(`unhandled message: ${JSON.stringify(obj)}`); } }); // Called if we succeed at the final setup const success = () => { if (this._nodeProcess == null) { throw new Error(`Unable to fork ${nodeProcessPath}`); } this._nodeProcess.on("disconnect", () => { this._cleanup(); if (this._autoReconnect) { (this as any).trigger("close", this.connect(true)); } else { (this as any).trigger("close", ); } }); deferred.resolve(); }; // Called if we fail at the final setup const fail = (err: Error) => { this._cleanup(); deferred.reject(err); }; // refresh the current domains, then re-register any "autoregister" modules waitFor(() => this.connected() && this.domains.base && typeof this.domains.base.loadDomainModulesFromPaths === "function" ).then(() => { const toReload = Object.keys(this._registeredDomains) .filter((_path) => this._registeredDomains[_path].autoReload === true); return toReload.length > 0 ? this._loadDomains(toReload).then(success, fail) : success(); }); return deferred.promise(); } public connected(): boolean { return !!(this._nodeProcess && this._nodeProcess.connected); } public disconnect() { this._autoReconnect = false; this._cleanup(); } public loadDomains(paths: string | string[], autoReload: boolean) { const pathArray: string[] = Array.isArray(paths) ? paths : [paths]; pathArray.forEach((_path) => { if (this._registeredDomains[_path]) { throw new Error(`Domain path already registered: ${_path}`); } this._registeredDomains[_path] = { loaded: false, autoReload }; }); return this._loadDomains(pathArray); } private _refreshName(): void { const domainNames = Object.keys(this.domains); if (domainNames.length > 1) { // remove "base" const io = domainNames.indexOf("base"); if (io !== -1) { domainNames.splice(io, 1); } this._name = domainNames.join(","); return; } if (this._nodeProcess) { this._name = this._nodeProcess.pid.toString(); return; } this._name = this._name || ""; } private _cleanup(): void { // shut down the old process if there is one if (this._nodeProcess) { try { this._nodeProcess.kill(); } finally { this._nodeProcess = null; } } // clear out the domains, since we may get different ones on the next connection this.domains = {}; // reject all the commands that are to be resolved this._pendingCommandDeferreds.forEach((d) => d.reject("cleanup")); this._pendingCommandDeferreds = []; // need to call _refreshName because this.domains has been modified this._refreshName(); } private _getNextCommandID(): number { return this._commandCount > MAX_COUNTER_VALUE ? this._commandCount = 0 : this._commandCount++; } private _loadDomains(pathArray: string[]) { const deferred = $.Deferred(); setDeferredTimeout(deferred, CONNECTION_TIMEOUT); if (this.domains.base && this.domains.base.loadDomainModulesFromPaths) { this.domains.base.loadDomainModulesFromPaths(pathArray).then( function (success: boolean) { // command call succeeded if (!success) { // response from commmand call was "false" so we know // the actual load failed. deferred.reject("loadDomainModulesFromPaths failed"); } // if the load succeeded, we wait for the API refresh to // resolve the deferred. }, function (reason: string) { // command call failed deferred.reject( "Unable to load one of the modules: " + pathArray + (reason ? ", reason: " + reason : "") ); } ); waitFor(() => { const loadedCount = pathArray .map((_path) => this._registeredDomains[_path].loaded) .filter((x) => x === true) .length; return loadedCount === pathArray.length; }).then(deferred.resolve); } else { deferred.reject("this.domains.base is undefined"); } return deferred.promise(); } private _send(m: NodeConnectionRequestMessage) { if (this._nodeProcess && this.connected()) { // Convert the message to a string let messageString: string | null = null; if (typeof m === "string") { messageString = m; } else { try { messageString = JSON.stringify(m); } catch (stringifyError) { log.error("Unable to stringify message in order to send: " + stringifyError.message); } } // If we succeded in making a string, try to send it if (messageString) { try { this._nodeProcess.send({ type: "message", message: messageString }); } catch (sendError) { log.error(`Error sending message: ${sendError.message}`); } } } else { log.error(`Not connected to node, unable to send`); } } private _receive(messageString: string) { let responseDeferred: JQueryDeferred<any> | null = null; let ipcMessage: any; try { ipcMessage = JSON.parse(messageString); } catch (err) { log.error(`Received malformed message: ${messageString}`, err.message); return; } const message: NodeConnectionResponseMessage = ipcMessage.message; switch (ipcMessage.type) { case "event": if (message.domain === "base" && message.event === "newDomains") { const newDomainPaths: string[] = message.parameters; newDomainPaths.forEach((newDomainPath: string) => { this._registeredDomains[newDomainPath].loaded = true; }); } // Event type "domain:event" EventDispatcher.triggerWithArray( this, message.domain + ":" + message.event, message.parameters ); break; case "commandResponse": responseDeferred = this._pendingCommandDeferreds[message.id]; if (responseDeferred) { responseDeferred.resolveWith(this, [message.response]); delete this._pendingCommandDeferreds[message.id]; } break; case "commandProgress": responseDeferred = this._pendingCommandDeferreds[message.id]; if (responseDeferred) { responseDeferred.notifyWith(this, [message.message]); } break; case "commandError": responseDeferred = this._pendingCommandDeferreds[message.id]; if (responseDeferred) { responseDeferred.rejectWith( this, [message.message, message.stack] ); delete this._pendingCommandDeferreds[message.id]; } break; case "error": log.error(`Received error: ${message.message}`); break; default: log.error(`Unknown event type: ${ipcMessage.type}`); } } private _refreshInterfaceCallback(spec: NodeConnectionInterfaceSpec) { const self = this; function makeCommandFunction(domain: string, command: string) { return function () { const deferred = $.Deferred(); const parameters = Array.prototype.slice.call(arguments, 0); const id = self._getNextCommandID(); self._pendingCommandDeferreds[id] = deferred; self._send({ id, domain, command, parameters }); return deferred; }; } this.domains = {}; this.domainEvents = {}; Object.keys(spec).forEach(function (domainKey) { const domainSpec: NodeConnectionDomainSpec = spec[domainKey]; self.domains[domainKey] = {}; Object.keys(domainSpec.commands).forEach(function (commandKey) { self.domains[domainKey][commandKey] = makeCommandFunction(domainKey, commandKey); }); self.domainEvents[domainKey] = {}; Object.keys(domainSpec.events).forEach(function (eventKey) { const eventSpec = domainSpec.events[eventKey]; const parameters = eventSpec.parameters; self.domainEvents[domainKey][eventKey] = parameters; }); }); // need to call _refreshName because this.domains has been modified this._refreshName(); } } EventDispatcher.makeEventDispatcher(NodeConnection.prototype); module.exports = NodeConnection; });
the_stack
import { IStorage } from "../interfaces/IStorage"; import { ContractMetadata } from "./contract-metadata"; import { IERC20, IERC20Metadata, SignatureDrop } from "contracts"; import { BigNumber, constants, ethers } from "ethers"; import { isNativeToken } from "../../common/currency"; import { ContractWrapper } from "./contract-wrapper"; import { Amount, ClaimCondition, ClaimConditionInput } from "../../types"; import { ClaimEligibility } from "../../enums"; import { TransactionResult } from "../types"; import { getClaimerProofs, processClaimConditionInputs, transformResultToClaimCondition, } from "../../common/claim-conditions"; import { detectContractFeature } from "../../common/feature-detection"; import { PriceSchema } from "../../schema"; import { includesErrorMessage } from "../../common"; import ERC20Abi from "../../../abis/IERC20.json"; import { isNode } from "../../common/utils"; import deepEqual from "fast-deep-equal"; import { IClaimCondition } from "contracts/SignatureDrop"; /** * Manages claim conditions for NFT Drop contracts * @public */ export class DropSingleClaimConditions<TContract extends SignatureDrop> { private contractWrapper; private metadata; private storage: IStorage; constructor( contractWrapper: ContractWrapper<TContract>, metadata: ContractMetadata<TContract, any>, storage: IStorage, ) { this.storage = storage; this.contractWrapper = contractWrapper; this.metadata = metadata; } /** *************************************** * READ FUNCTIONS *****************************************/ /** * Get the currently active claim condition * * @returns the claim condition metadata */ public async get(): Promise<ClaimCondition> { const claimCondition = await this.contractWrapper.readContract.claimCondition(); const metadata = await this.metadata.get(); return await transformResultToClaimCondition( claimCondition, await this.getTokenDecimals(), this.contractWrapper.getProvider(), metadata.merkle, this.storage, ); } /** * Can Claim * * @remarks Check if the drop can currently be claimed. * * @example * ```javascript * // Quantity of tokens to check claimability of * const quantity = 1; * const canClaim = await contract.canClaim(quantity); * ``` */ public async canClaim( quantity: Amount, addressToCheck?: string, ): Promise<boolean> { // TODO switch to use verifyClaim return ( (await this.getClaimIneligibilityReasons(quantity, addressToCheck)) .length === 0 ); } /** * For any claim conditions that a particular wallet is violating, * this function returns human readable information about the * breaks in the condition that can be used to inform the user. * * @param quantity - The desired quantity that would be claimed. * @param addressToCheck - The wallet address, defaults to the connected wallet. * */ public async getClaimIneligibilityReasons( quantity: Amount, addressToCheck?: string, ): Promise<ClaimEligibility[]> { const reasons: ClaimEligibility[] = []; let claimCondition: IClaimCondition.ClaimConditionStructOutput; const decimals = await this.getTokenDecimals(); const quantityWithDecimals = ethers.utils.parseUnits( PriceSchema.parse(quantity), decimals, ); if (addressToCheck === undefined) { try { addressToCheck = await this.contractWrapper.getSignerAddress(); } catch (err) { console.warn("failed to get signer address", err); } } // if we have been unable to get a signer address, we can't check eligibility, so return a NoWallet error reason if (!addressToCheck) { return [ClaimEligibility.NoWallet]; } try { claimCondition = await this.contractWrapper.readContract.claimCondition(); } catch (err: any) { if ( includesErrorMessage(err, "!CONDITION") || includesErrorMessage(err, "no active mint condition") ) { reasons.push(ClaimEligibility.NoClaimConditionSet); return reasons; } reasons.push(ClaimEligibility.Unknown); return reasons; } if (claimCondition.maxClaimableSupply) { const supplyWithDecimals = claimCondition.maxClaimableSupply; if (supplyWithDecimals.lt(quantityWithDecimals)) { reasons.push(ClaimEligibility.NotEnoughSupply); } } // check for merkle root inclusion const merkleRootArray = ethers.utils.stripZeros(claimCondition.merkleRoot); if (merkleRootArray.length > 0) { const merkleLower = claimCondition.merkleRoot.toString(); const metadata = await this.metadata.get(); const proofs = await getClaimerProofs( addressToCheck, merkleLower, await this.getTokenDecimals(), metadata.merkle, this.storage, ); try { const [validMerkleProof] = await this.contractWrapper.readContract.verifyClaimMerkleProof( addressToCheck, quantity, { proof: proofs.proof, maxQuantityInAllowlist: proofs.maxClaimable, }, ); if (!validMerkleProof) { reasons.push(ClaimEligibility.AddressNotAllowed); return reasons; } } catch (e) { reasons.push(ClaimEligibility.AddressNotAllowed); return reasons; } } // check for claim timestamp between claims const [lastClaimedTimestamp, timestampForNextClaim] = await this.contractWrapper.readContract.getClaimTimestamp(addressToCheck); const now = BigNumber.from(Date.now()).div(1000); if (lastClaimedTimestamp.gt(0) && now.lt(timestampForNextClaim)) { // contract will return MaxUint256 if user has already claimed and cannot claim again if (timestampForNextClaim.eq(constants.MaxUint256)) { reasons.push(ClaimEligibility.AlreadyClaimed); } else { reasons.push(ClaimEligibility.WaitBeforeNextClaimTransaction); } } // if not within a browser conetext, check for wallet balance. // In browser context, let the wallet do that job if (claimCondition.pricePerToken.gt(0) && isNode()) { const totalPrice = claimCondition.pricePerToken.mul( BigNumber.from(quantity), ); const provider = this.contractWrapper.getProvider(); if (isNativeToken(claimCondition.currency)) { const balance = await provider.getBalance(addressToCheck); if (balance.lt(totalPrice)) { reasons.push(ClaimEligibility.NotEnoughTokens); } } else { const erc20 = new ContractWrapper<IERC20>( provider, claimCondition.currency, ERC20Abi, {}, ); const balance = await erc20.readContract.balanceOf(addressToCheck); if (balance.lt(totalPrice)) { reasons.push(ClaimEligibility.NotEnoughTokens); } } } return reasons; } /** *************************************** * WRITE FUNCTIONS *****************************************/ /** * Set public mint conditions * * @remarks Sets the public mint conditions that need to be fullfiled by users to claim NFTs. * * @example * ```javascript * const presaleStartTime = new Date(); * const publicSaleStartTime = new Date(Date.now() + 60 * 60 * 24 * 1000); * const claimConditions = [ * { * startTime: presaleStartTime, // start the presale now * maxQuantity: 2, // limit how many mints for this presale * price: 0.01, // presale price * snapshot: ['0x...', '0x...'], // limit minting to only certain addresses * }, * { * startTime: publicSaleStartTime, // 24h after presale, start public sale * price: 0.08, // public sale price * } * ]); * * await dropContract.claimConditions.set(claimConditions); * ``` * * @param claimConditionInput - The claim condition * @param resetClaimEligibilityForAll - Whether to reset the state of who already claimed NFTs previously */ public async set( claimConditionInput: ClaimConditionInput, resetClaimEligibilityForAll = false, ): Promise<TransactionResult> { // process inputs const { snapshotInfos, sortedConditions } = await processClaimConditionInputs( [claimConditionInput], await this.getTokenDecimals(), this.contractWrapper.getProvider(), this.storage, ); const merkleInfo: { [key: string]: string } = {}; snapshotInfos.forEach((s) => { merkleInfo[s.merkleRoot] = s.snapshotUri; }); const metadata = await this.metadata.get(); const encoded = []; // upload new merkle roots to snapshot URIs if updated if (!deepEqual(metadata.merkle, merkleInfo)) { const mergedMetadata = this.metadata.parseInputMetadata({ ...metadata, merkle: merkleInfo, }); // using internal method to just upload, avoids one contract call const contractURI = await this.metadata._parseAndUploadMetadata( mergedMetadata, ); encoded.push( this.contractWrapper.readContract.interface.encodeFunctionData( "setContractURI", [contractURI], ), ); } encoded.push( this.contractWrapper.readContract.interface.encodeFunctionData( "setClaimConditions", [sortedConditions[0], resetClaimEligibilityForAll], ), ); return { receipt: await this.contractWrapper.multiCall(encoded), }; } /** *************************************** * PRIVATE FUNCTIONS *****************************************/ private async getTokenDecimals(): Promise<number> { if (detectContractFeature<IERC20Metadata>(this.contractWrapper, "ERC20")) { return this.contractWrapper.readContract.decimals(); } else { return Promise.resolve(0); } } }
the_stack
import { Vector3, Quaternion, Matrix4, Matrix3, Object3D } from "three"; import * as helpers from "@ff/three/helpers"; import { Node, types } from "@ff/graph/Component"; import { IPointerEvent } from "@ff/scene/RenderView"; import Annotation from "../models/Annotation"; import NVNode from "../nodes/NVNode"; import CVDocument from "./CVDocument"; import CVTask from "./CVTask"; import CVModel2 from "./CVModel2"; import CVAnnotationView, { IAnnotationsUpdateEvent, IAnnotationClickEvent } from "./CVAnnotationView"; import AnnotationsTaskView from "../ui/story/AnnotationsTaskView"; import CVScene from "client/components/CVScene"; import { ELanguageStringType, ELanguageType, DEFAULT_LANGUAGE } from "client/schema/common"; //////////////////////////////////////////////////////////////////////////////// const _position = new Vector3(); const _scaling = new Vector3(); const _quat = new Quaternion(); const _mat4 = new Matrix4(); const _mat3 = new Matrix3(); export enum EAnnotationsTaskMode { Off, Move, Create } export default class CVAnnotationsTask extends CVTask { static readonly typeName: string = "CVAnnotationsTask"; static readonly text: string = "Annotations"; static readonly icon: string = "comment"; protected static readonly ins = { mode: types.Enum("Mode", EAnnotationsTaskMode, EAnnotationsTaskMode.Off), language: types.Option("Task.Language", Object.keys(ELanguageStringType).map(key => ELanguageStringType[key]), ELanguageStringType[ELanguageType.EN]), }; protected static readonly outs = { language: types.Enum("Interface.Language", ELanguageType, ELanguageType.EN), }; ins = this.addInputs<CVTask, typeof CVAnnotationsTask.ins>(CVAnnotationsTask.ins); outs = this.addOutputs<CVTask, typeof CVAnnotationsTask.outs>(CVAnnotationsTask.outs); private _activeAnnotations: CVAnnotationView = null; private _defaultScale = 1; constructor(node: Node, id: string) { super(node, id); const configuration = this.configuration; configuration.annotationsVisible = true; configuration.gridVisible = false; configuration.interfaceVisible = true; configuration.bracketsVisible = false; } get activeAnnotations() { return this._activeAnnotations; } set activeAnnotations(annotations: CVAnnotationView) { if (annotations !== this._activeAnnotations) { this._activeAnnotations = annotations; this.emitUpdateEvent(); } } createView() { return new AnnotationsTaskView(this); } activateTask() { this.startObserving(); super.activateTask(); this.synchLanguage(); //this.selection.selectedComponents.on(CVAnnotationView, this.onSelectAnnotations, this); //this.system.on<IPointerEvent>("pointer-up", this.onPointerUp, this); } deactivateTask() { //this.selection.selectedComponents.off(CVAnnotationView, this.onSelectAnnotations, this); //this.system.off<IPointerEvent>("pointer-up", this.onPointerUp, this); this.stopObserving(); super.deactivateTask(); } update(context) { const {ins, outs} = this; if(!this.activeDocument) { return false; } const languageManager = this.activeDocument.setup.language; if (ins.mode.changed) { this.emitUpdateEvent(); } if(ins.language.changed) { const newLanguage = ELanguageType[ELanguageType[ins.language.value]]; languageManager.addLanguage(newLanguage); // add in case this is a currently inactive language languageManager.ins.language.setValue(newLanguage); outs.language.setValue(newLanguage); return true; } this.synchLanguage(); return true; } removeAnnotation() { const annotations = this.activeAnnotations; if (annotations) { const annotation = annotations.activeAnnotation; if (annotation) { annotations.removeAnnotation(annotation); } } } protected onPointerUp(event: IPointerEvent) { // do not handle event if user is dragging (the camera) if (event.isDragging) { return; } const annotations = this.activeAnnotations; if (!annotations) { return; } const model = annotations.getComponent(CVModel2); // user clicked on model if (event.component === model) { // get click position and normal in annotation space = pose transform * model space _position.fromArray(model.ins.position.value); helpers.degreesToQuaternion(model.ins.rotation.value, CVModel2.rotationOrder, _quat); _scaling.setScalar(1); _mat4.compose(_position, _quat, _scaling); // add mesh parent transforms in this branch _mat4.copy(_mat4.multiply(this.getMeshTransform(model.object3D, event.object3D).invert())); _mat3.getNormalMatrix(_mat4); const position = event.view.pickPosition(event).applyMatrix4(_mat4).toArray(); const normal = event.view.pickNormal(event).applyMatrix3(_mat3).toArray(); const mode = this.ins.mode.getValidatedValue(); if (mode === EAnnotationsTaskMode.Create) { this.createAnnotation(position, normal); event.stopPropagation = true; } else if (mode === EAnnotationsTaskMode.Move) { this.moveAnnotation(position, normal); event.stopPropagation = true; } } } protected createAnnotation(position: number[], direction: number[]) { const annotations = this.activeAnnotations; if (!annotations) { return; } const activeAnnotation = annotations.activeAnnotation; let template = undefined; if (activeAnnotation) { template = activeAnnotation.toJSON(); template.id = Annotation.generateId(); } const model = annotations.getComponent(CVModel2); const annotation = new Annotation(template); const data = annotation.data; data.position = position; data.direction = direction; if (!template) { data.scale = this._defaultScale * (1 / model.outs.unitScale.value); } annotations.addAnnotation(annotation); annotations.activeAnnotation = annotation; this.activeDocument.setup.language.ins.language.setValue(ELanguageType[DEFAULT_LANGUAGE]); } protected moveAnnotation(position: number[], direction: number[]) { const annotations = this.activeAnnotations; if (annotations) { const annotation = annotations.activeAnnotation; if (annotation) { annotation.data.position = position; annotation.data.direction = direction; annotation.update(); annotations.updateAnnotation(annotation); this.emitUpdateEvent(); } } } protected onActiveDocument(previous: CVDocument, next: CVDocument) { super.onActiveDocument(previous, next); if(previous) { previous.setup.language.outs.language.off("value", this.update, this); } if (next) { const scene = next.getInnerComponent(CVScene); this._defaultScale = scene.outs.boundingRadius.value * 0.05; next.setup.language.outs.language.on("value", this.update, this); } } protected onActiveNode(previous: NVNode, next: NVNode) { const prevAnnotations = previous ? previous.getComponent(CVAnnotationView, true) : null; const nextAnnotations = next ? next.getComponent(CVAnnotationView, true) : null; if (prevAnnotations) { prevAnnotations.off<IAnnotationsUpdateEvent>("annotation-update", this.emitUpdateEvent, this); prevAnnotations.off<IAnnotationClickEvent>("click", this.onAnnotationClick, this); } if (nextAnnotations) { nextAnnotations.on<IAnnotationClickEvent>("click", this.onAnnotationClick, this); nextAnnotations.on<IAnnotationsUpdateEvent>("annotation-update", this.emitUpdateEvent, this); } const prevModel = previous ? previous.getComponent(CVModel2, true) : null; const nextModel = next ? next.getComponent(CVModel2, true) : null; if (prevModel) { prevModel.off<IPointerEvent>("pointer-up", this.onPointerUp, this); } if (nextModel) { nextModel.on<IPointerEvent>("pointer-up", this.onPointerUp, this); } this.activeAnnotations = nextAnnotations; } protected emitUpdateEvent() { this.emit("update"); } // Handles annotation selection in outside of task. protected onAnnotationClick(event: IAnnotationClickEvent) { // HACK to blur potentially selected textboxes when an annotation // is clicked outside of the task UI and is consumed before getting here. const textboxes = document.getElementsByClassName("ff-text-edit"); for(let box of textboxes) { (box as HTMLElement).blur(); } } /** Accumulates transforms from current object to root. */ protected getMeshTransform(root : Object3D, current: Object3D) { var result = new Matrix4(); var tempMatrix = new Matrix4(); result.identity(); do { tempMatrix.compose(current.position, current.quaternion, current.scale); result.multiply(tempMatrix.invert()); current = current.parent; } while (root !== current) return result; } // Make sure this task language matches document protected synchLanguage() { const {ins} = this; const languageManager = this.activeDocument.setup.language; if(ins.language.value !== languageManager.outs.language.value) { ins.language.setValue(languageManager.outs.language.value, true); } } }
the_stack