text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { createToolbarFactory, SessionContext, Toolbar, ToolbarRegistry, ToolbarWidgetRegistry } from '@jupyterlab/apputils'; import { ISettingRegistry, SettingRegistry } from '@jupyterlab/settingregistry'; import { IDataConnector } from '@jupyterlab/statedb'; import { createSessionContext, framePromise, JupyterServer } from '@jupyterlab/testutils'; import { ITranslator } from '@jupyterlab/translation'; import { Widget } from '@lumino/widgets'; const server = new JupyterServer(); beforeAll(async () => { await server.start(); }); afterAll(async () => { await server.shutdown(); }); describe('@jupyterlab/apputils', () => { describe('Toolbar', () => { describe('Kernel buttons', () => { let sessionContext: SessionContext; beforeEach(async () => { sessionContext = await createSessionContext(); }); afterEach(async () => { await sessionContext.shutdown(); sessionContext.dispose(); }); describe('.createInterruptButton()', () => { it("should add an inline svg node with the 'stop' icon", async () => { const button = Toolbar.createInterruptButton(sessionContext); Widget.attach(button, document.body); await framePromise(); expect( button.node.querySelector("[data-icon$='stop']") ).toBeDefined(); }); }); describe('.createRestartButton()', () => { it("should add an inline svg node with the 'refresh' icon", async () => { const button = Toolbar.createRestartButton(sessionContext); Widget.attach(button, document.body); await framePromise(); expect( button.node.querySelector("[data-icon$='refresh']") ).toBeDefined(); }); }); describe('.createKernelNameItem()', () => { it("should display the `'display_name'` of the kernel", async () => { const item = Toolbar.createKernelNameItem(sessionContext); await sessionContext.initialize(); Widget.attach(item, document.body); await framePromise(); const node = item.node.querySelector( '.jp-ToolbarButtonComponent-label' )!; expect(node.textContent).toBe(sessionContext.kernelDisplayName); }); }); describe('.createKernelStatusItem()', () => { beforeEach(async () => { await sessionContext.initialize(); await sessionContext.session?.kernel?.info; }); it('should display a busy status if the kernel status is busy', async () => { const item = Toolbar.createKernelStatusItem(sessionContext); let called = false; sessionContext.statusChanged.connect((_, status) => { if (status === 'busy') { // eslint-disable-next-line jest/no-conditional-expect expect( item.node.querySelector("[data-icon$='circle']") ).toBeDefined(); called = true; } }); const future = sessionContext.session!.kernel!.requestExecute({ code: 'a = 109\na' })!; await future.done; expect(called).toBe(true); }); it('should show the current status in the node title', async () => { const item = Toolbar.createKernelStatusItem(sessionContext); const status = sessionContext.session?.kernel?.status; expect(item.node.title.toLowerCase()).toContain(status); let called = false; const future = sessionContext.session!.kernel!.requestExecute({ code: 'a = 1' })!; future.onIOPub = msg => { if (sessionContext.session?.kernel?.status === 'busy') { // eslint-disable-next-line jest/no-conditional-expect expect(item.node.title.toLowerCase()).toContain('busy'); called = true; } }; await future.done; expect(called).toBe(true); }); it('should handle a starting session', async () => { await sessionContext.session?.kernel?.info; await sessionContext.shutdown(); sessionContext = await createSessionContext(); await sessionContext.initialize(); const item = Toolbar.createKernelStatusItem(sessionContext); expect(item.node.title).toBe('Kernel Connecting'); expect( item.node.querySelector("[data-icon$='circle-empty']") ).toBeDefined(); await sessionContext.initialize(); await sessionContext.session?.kernel?.info; }); }); }); }); describe('ToolbarWidgetRegistry', () => { describe('#constructor', () => { it('should set a default factory', () => { const dummy = jest.fn(); const registry = new ToolbarWidgetRegistry({ defaultFactory: dummy }); expect(registry.defaultFactory).toBe(dummy); }); }); describe('#defaultFactory', () => { it('should set a default factory', () => { const dummy = jest.fn(); const dummy2 = jest.fn(); const registry = new ToolbarWidgetRegistry({ defaultFactory: dummy }); registry.defaultFactory = dummy2; expect(registry.defaultFactory).toBe(dummy2); }); }); describe('#createWidget', () => { it('should call the default factory as fallback', () => { const documentWidget = new Widget(); const dummyWidget = new Widget(); const dummy = jest.fn().mockReturnValue(dummyWidget); const registry = new ToolbarWidgetRegistry({ defaultFactory: dummy }); const item: ToolbarRegistry.IWidget = { name: 'test' }; const widget = registry.createWidget('factory', documentWidget, item); expect(widget).toBe(dummyWidget); expect(dummy).toBeCalledWith('factory', documentWidget, item); }); it('should call the registered factory', () => { const documentWidget = new Widget(); const dummyWidget = new Widget(); const defaultFactory = jest.fn().mockReturnValue(dummyWidget); const dummy = jest.fn().mockReturnValue(dummyWidget); const registry = new ToolbarWidgetRegistry({ defaultFactory }); const item: ToolbarRegistry.IWidget = { name: 'test' }; registry.registerFactory('factory', item.name, dummy); const widget = registry.createWidget('factory', documentWidget, item); expect(widget).toBe(dummyWidget); expect(dummy).toBeCalledWith(documentWidget); expect(defaultFactory).toBeCalledTimes(0); }); }); describe('#registerFactory', () => { it('should return the previous registered factory', () => { const defaultFactory = jest.fn(); const dummy = jest.fn(); const dummy2 = jest.fn(); const registry = new ToolbarWidgetRegistry({ defaultFactory }); const item: ToolbarRegistry.IWidget = { name: 'test' }; expect( registry.registerFactory('factory', item.name, dummy) ).toBeUndefined(); expect(registry.registerFactory('factory', item.name, dummy2)).toBe( dummy ); }); }); }); describe('createToolbarFactory', () => { it('should return the toolbar items', async () => { const factoryName = 'dummyFactory'; const pluginId = 'test-plugin:settings'; const toolbarRegistry = new ToolbarWidgetRegistry({ defaultFactory: jest.fn() }); const bar: ISettingRegistry.IPlugin = { data: { composite: {}, user: {} }, id: pluginId, raw: '{}', schema: { 'jupyter.lab.toolbars': { dummyFactory: [ { name: 'insert', command: 'notebook:insert-cell-below', rank: 20 }, { name: 'spacer', type: 'spacer', rank: 100 }, { name: 'cut', command: 'notebook:cut-cell', rank: 21 } ] }, 'jupyter.lab.transform': true, properties: { toolbar: { type: 'array' } }, type: 'object' }, version: 'test' }; const connector: IDataConnector< ISettingRegistry.IPlugin, string, string, string > = { fetch: jest.fn().mockImplementation((id: string) => { switch (id) { case bar.id: return bar; default: return {}; } }), list: jest.fn(), save: jest.fn(), remove: jest.fn() }; const settingRegistry = new SettingRegistry({ connector }); const translator: ITranslator = { load: jest.fn() }; const factory = createToolbarFactory( toolbarRegistry, settingRegistry, factoryName, pluginId, translator ); await settingRegistry.load(bar.id); // Trick push this test after all other promise in the hope they get resolve // before going further - in particular we are looking at the update of the items // factory in `createToolbarFactory` await Promise.resolve(); const items = factory(null as any); expect(items).toHaveLength(3); }); it('should update the toolbar items with late settings load', async () => { const factoryName = 'dummyFactory'; const pluginId = 'test-plugin:settings'; const toolbarRegistry = new ToolbarWidgetRegistry({ defaultFactory: jest.fn() }); const foo: ISettingRegistry.IPlugin = { data: { composite: {}, user: {} }, id: 'foo', raw: '{}', schema: { 'jupyter.lab.toolbars': { dummyFactory: [ { name: 'cut', command: 'notebook:cut-cell', rank: 21 } ] }, type: 'object' }, version: 'test' }; const bar: ISettingRegistry.IPlugin = { data: { composite: {}, user: {} }, id: pluginId, raw: '{}', schema: { 'jupyter.lab.toolbars': { dummyFactory: [ { name: 'insert', command: 'notebook:insert-cell-below', rank: 20 } ] }, 'jupyter.lab.transform': true, properties: { toolbar: { type: 'array' } }, type: 'object' }, version: 'test' }; const connector: IDataConnector< ISettingRegistry.IPlugin, string, string, string > = { fetch: jest.fn().mockImplementation((id: string) => { switch (id) { case bar.id: return bar; case foo.id: return foo; default: return {}; } }), list: jest.fn(), save: jest.fn(), remove: jest.fn() }; const settingRegistry = new SettingRegistry({ connector }); const translator: ITranslator = { load: jest.fn() }; const factory = createToolbarFactory( toolbarRegistry, settingRegistry, factoryName, pluginId, translator ); await settingRegistry.load(bar.id); // Trick push this test after all other promise in the hope they get resolve // before going further - in particular we are looking at the update of the items // factory in `createToolbarFactory` await Promise.resolve(); await settingRegistry.load(foo.id); const items = factory(null as any); expect(items).toHaveLength(2); }); }); });
the_stack
import BitArray from '../../../../common/BitArray'; import FormatException from '../../../../FormatException'; import IllegalStateException from '../../../../IllegalStateException'; import StringBuilder from '../../../../util/StringBuilder'; import BlockParsedResult from './BlockParsedResult'; import CurrentParsingState from './CurrentParsingState'; import DecodedChar from './DecodedChar'; import DecodedInformation from './DecodedInformation'; import DecodedNumeric from './DecodedNumeric'; import FieldParser from './FieldParser'; export default class GeneralAppIdDecoder { private readonly information: BitArray; private readonly current: CurrentParsingState; private readonly buffer = new StringBuilder(); constructor(information: BitArray) { this.information = information; } decodeAllCodes(buff: StringBuilder, initialPosition: number): string { let currentPosition = initialPosition; let remaining = null; do { let info = this.decodeGeneralPurposeField(currentPosition, remaining); let parsedFields = FieldParser.parseFieldsInGeneralPurpose(info.getNewString()); if (parsedFields != null) { buff.append(parsedFields); } if (info.isRemaining()) { remaining = '' + info.getRemainingValue(); } else { remaining = null; } if (currentPosition === info.getNewPosition()) { // No step forward! break; } currentPosition = info.getNewPosition(); } while (true); return buff.toString(); } private isStillNumeric(pos: number): boolean { // It's numeric if it still has 7 positions // and one of the first 4 bits is "1". if (pos + 7 > this.information.getSize()) { return pos + 4 <= this.information.getSize(); } for (let i = pos; i < pos + 3; ++i) { if (this.information.get(i)) { return true; } } return this.information.get(pos + 3); } private decodeNumeric(pos: number): DecodedNumeric { if (pos + 7 > this.information.getSize()) { let numeric = this.extractNumericValueFromBitArray(pos, 4); if (numeric === 0) { return new DecodedNumeric(this.information.getSize(), DecodedNumeric.FNC1, DecodedNumeric.FNC1); } return new DecodedNumeric(this.information.getSize(), numeric - 1, DecodedNumeric.FNC1); } let numeric = this.extractNumericValueFromBitArray(pos, 7); let digit1 = (numeric - 8) / 11; let digit2 = (numeric - 8) % 11; return new DecodedNumeric(pos + 7, digit1, digit2); } extractNumericValueFromBitArray(pos: number, bits: number): number { return GeneralAppIdDecoder.extractNumericValueFromBitArray(this.information, pos, bits); } static extractNumericValueFromBitArray(information: BitArray, pos: number, bits: number): number { let value = 0; for (let i = 0; i < bits; ++i) { if (information.get(pos + i)) { value |= 1 << (bits - i - 1); } } return value; } decodeGeneralPurposeField(pos: number, remaining: string): DecodedInformation { // this.buffer.setLength(0); this.buffer.setLengthToZero(); if (remaining != null) { this.buffer.append(remaining); } this.current.setPosition(pos); let lastDecoded = this.parseBlocks(); if (lastDecoded != null && lastDecoded.isRemaining()) { return new DecodedInformation(this.current.getPosition(), this.buffer.toString(), lastDecoded.getRemainingValue()); } return new DecodedInformation(this.current.getPosition(), this.buffer.toString()); } private parseBlocks(): DecodedInformation { let isFinished: boolean; let result: BlockParsedResult; do { let initialPosition = this.current.getPosition(); if (this.current.isAlpha()) { result = this.parseAlphaBlock(); isFinished = result.isFinished(); } else if (this.current.isIsoIec646()) { result = this.parseIsoIec646Block(); isFinished = result.isFinished(); } else { // it must be numeric result = this.parseNumericBlock(); isFinished = result.isFinished(); } let positionChanged: boolean = initialPosition !== this.current.getPosition(); if (!positionChanged && !isFinished) { break; } } while (!isFinished); return result.getDecodedInformation(); } private parseNumericBlock(): BlockParsedResult { while (this.isStillNumeric(this.current.getPosition())) { let numeric: DecodedNumeric = this.decodeNumeric(this.current.getPosition()); this.current.setPosition(numeric.getNewPosition()); if (numeric.isFirstDigitFNC1()) { let information: DecodedInformation; if (numeric.isSecondDigitFNC1()) { information = new DecodedInformation(this.current.getPosition(), this.buffer.toString()); } else { information = new DecodedInformation(this.current.getPosition(), this.buffer.toString(), numeric.getSecondDigit()); } return new BlockParsedResult(true, information); } this.buffer.append(numeric.getFirstDigit()); if (numeric.isSecondDigitFNC1()) { let information = new DecodedInformation(this.current.getPosition(), this.buffer.toString()); return new BlockParsedResult(true, information); } this.buffer.append(numeric.getSecondDigit()); } if (this.isNumericToAlphaNumericLatch(this.current.getPosition())) { this.current.setAlpha(); this.current.incrementPosition(4); } return new BlockParsedResult(false); } private parseIsoIec646Block(): BlockParsedResult { while (this.isStillIsoIec646(this.current.getPosition())) { let iso = this.decodeIsoIec646(this.current.getPosition()); this.current.setPosition(iso.getNewPosition()); if (iso.isFNC1()) { let information = new DecodedInformation(this.current.getPosition(), this.buffer.toString()); return new BlockParsedResult(true, information); } this.buffer.append(iso.getValue()); } if (this.isAlphaOr646ToNumericLatch(this.current.getPosition())) { this.current.incrementPosition(3); this.current.setNumeric(); } else if (this.isAlphaTo646ToAlphaLatch(this.current.getPosition())) { if (this.current.getPosition() + 5 < this.information.getSize()) { this.current.incrementPosition(5); } else { this.current.setPosition(this.information.getSize()); } this.current.setAlpha(); } return new BlockParsedResult(false); } private parseAlphaBlock(): BlockParsedResult { while (this.isStillAlpha(this.current.getPosition())) { let alpha = this.decodeAlphanumeric(this.current.getPosition()); this.current.setPosition(alpha.getNewPosition()); if (alpha.isFNC1()) { let information = new DecodedInformation(this.current.getPosition(), this.buffer.toString()); return new BlockParsedResult(true, information); // end of the char block } this.buffer.append(alpha.getValue()); } if (this.isAlphaOr646ToNumericLatch(this.current.getPosition())) { this.current.incrementPosition(3); this.current.setNumeric(); } else if (this.isAlphaTo646ToAlphaLatch(this.current.getPosition())) { if (this.current.getPosition() + 5 < this.information.getSize()) { this.current.incrementPosition(5); } else { this.current.setPosition(this.information.getSize()); } this.current.setIsoIec646(); } return new BlockParsedResult(false); } private isStillIsoIec646(pos: number): boolean { if (pos + 5 > this.information.getSize()) { return false; } let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5); if (fiveBitValue >= 5 && fiveBitValue < 16) { return true; } if (pos + 7 > this.information.getSize()) { return false; } let sevenBitValue = this.extractNumericValueFromBitArray(pos, 7); if (sevenBitValue >= 64 && sevenBitValue < 116) { return true; } if (pos + 8 > this.information.getSize()) { return false; } let eightBitValue = this.extractNumericValueFromBitArray(pos, 8); return eightBitValue >= 232 && eightBitValue < 253; } private decodeIsoIec646(pos: number): DecodedChar { let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5); if (fiveBitValue === 15) { return new DecodedChar(pos + 5, DecodedChar.FNC1); } if (fiveBitValue >= 5 && fiveBitValue < 15) { return new DecodedChar(pos + 5, ('0' + (fiveBitValue - 5))); } let sevenBitValue = this.extractNumericValueFromBitArray(pos, 7); if (sevenBitValue >= 64 && sevenBitValue < 90) { return new DecodedChar(pos + 7, ('' + (sevenBitValue + 1))); } if (sevenBitValue >= 90 && sevenBitValue < 116) { return new DecodedChar(pos + 7, ('' + (sevenBitValue + 7))); } let eightBitValue = this.extractNumericValueFromBitArray(pos, 8); let c; switch (eightBitValue) { case 232: c = '!'; break; case 233: c = '"'; break; case 234: c = '%'; break; case 235: c = '&'; break; case 236: c = '\''; break; case 237: c = '('; break; case 238: c = ')'; break; case 239: c = '*'; break; case 240: c = '+'; break; case 241: c = ','; break; case 242: c = '-'; break; case 243: c = '.'; break; case 244: c = '/'; break; case 245: c = ':'; break; case 246: c = ';'; break; case 247: c = '<'; break; case 248: c = '='; break; case 249: c = '>'; break; case 250: c = '?'; break; case 251: c = '_'; break; case 252: c = ' '; break; default: throw new FormatException(); } return new DecodedChar(pos + 8, c); } private isStillAlpha(pos: number): boolean { if (pos + 5 > this.information.getSize()) { return false; } // We now check if it's a valid 5-bit value (0..9 and FNC1) let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5); if (fiveBitValue >= 5 && fiveBitValue < 16) { return true; } if (pos + 6 > this.information.getSize()) { return false; } let sixBitValue = this.extractNumericValueFromBitArray(pos, 6); return sixBitValue >= 16 && sixBitValue < 63; // 63 not included } private decodeAlphanumeric(pos: number): DecodedChar { let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5); if (fiveBitValue === 15) { return new DecodedChar(pos + 5, DecodedChar.FNC1); } if (fiveBitValue >= 5 && fiveBitValue < 15) { return new DecodedChar(pos + 5, ('0' + (fiveBitValue - 5))); } let sixBitValue = this.extractNumericValueFromBitArray(pos, 6); if (sixBitValue >= 32 && sixBitValue < 58) { return new DecodedChar(pos + 6, ('' + (sixBitValue + 33))); } let c; switch (sixBitValue) { case 58: c = '*'; break; case 59: c = ','; break; case 60: c = '-'; break; case 61: c = '.'; break; case 62: c = '/'; break; default: throw new IllegalStateException('Decoding invalid alphanumeric value: ' + sixBitValue); } return new DecodedChar(pos + 6, c); } private isAlphaTo646ToAlphaLatch(pos: number): boolean { if (pos + 1 > this.information.getSize()) { return false; } for (let i = 0; i < 5 && i + pos < this.information.getSize(); ++i) { if (i === 2) { if (!this.information.get(pos + 2)) { return false; } } else if (this.information.get(pos + i)) { return false; } } return true; } private isAlphaOr646ToNumericLatch(pos: number): boolean { // Next is alphanumeric if there are 3 positions and they are all zeros if (pos + 3 > this.information.getSize()) { return false; } for (let i = pos; i < pos + 3; ++i) { if (this.information.get(i)) { return false; } } return true; } private isNumericToAlphaNumericLatch(pos: number): boolean { // Next is alphanumeric if there are 4 positions and they are all zeros, or // if there is a subset of this just before the end of the symbol if (pos + 1 > this.information.getSize()) { return false; } for (let i = 0; i < 4 && i + pos < this.information.getSize(); ++i) { if (this.information.get(pos + i)) { return false; } } return true; } }
the_stack
import { Buffer } from 'buffer'; import * as fs from 'fs'; import * as crypto from 'crypto'; import * as Minio from 'minio'; import * as uuid from 'uuid'; import * as sharp from 'sharp'; import { publishMainStream, publishDriveStream } from '../stream'; import { deleteFile } from './delete-file'; import { fetchMeta } from '../../misc/fetch-meta'; import { GenerateVideoThumbnail } from './generate-video-thumbnail'; import { driveLogger } from './logger'; import { IImage, convertToJpeg, convertToWebp, convertToPng, convertToGif, convertToApng } from './image-processor'; import { contentDisposition } from '../../misc/content-disposition'; import { detectMine } from '../../misc/detect-mine'; import { DriveFiles, DriveFolders, Users, Instances, UserProfiles } from '../../models'; import { InternalStorage } from './internal-storage'; import { DriveFile } from '../../models/entities/drive-file'; import { IRemoteUser, User } from '../../models/entities/user'; import { driveChart, perUserDriveChart, instanceChart } from '../chart'; import { genId } from '../../misc/gen-id'; import { isDuplicateKeyValueError } from '../../misc/is-duplicate-key-value-error'; const logger = driveLogger.createSubLogger('register', 'yellow'); /*** * Save file * @param path Path for original * @param name Name for original * @param type Content-Type for original * @param hash Hash for original * @param size Size for original */ async function save(file: DriveFile, path: string, name: string, type: string, hash: string, size: number): Promise<DriveFile> { // thunbnail, webpublic を必要なら生成 const alts = await generateAlts(path, type, !file.uri); const meta = await fetchMeta(); if (meta.useObjectStorage) { //#region ObjectStorage params let [ext] = (name.match(/\.([a-zA-Z0-9_-]+)$/) || ['']); if (ext === '') { if (type === 'image/jpeg') ext = '.jpg'; if (type === 'image/png') ext = '.png'; if (type === 'image/webp') ext = '.webp'; } const baseUrl = meta.objectStorageBaseUrl || `${ meta.objectStorageUseSSL ? 'https' : 'http' }://${ meta.objectStorageEndpoint }${ meta.objectStoragePort ? `:${meta.objectStoragePort}` : '' }/${ meta.objectStorageBucket }`; // for original const key = `${meta.objectStoragePrefix}/${uuid.v4()}${ext}`; const url = `${ baseUrl }/${ key }`; // for alts let webpublicKey: string | null = null; let webpublicUrl: string | null = null; let thumbnailKey: string | null = null; let thumbnailUrl: string | null = null; //#endregion //#region Uploads logger.info(`uploading original: ${key}`); const uploads = [ upload(key, fs.createReadStream(path), type, name) ]; if (alts.webpublic) { webpublicKey = `${meta.objectStoragePrefix}/${uuid.v4()}.${alts.webpublic.ext}`; webpublicUrl = `${ baseUrl }/${ webpublicKey }`; logger.info(`uploading webpublic: ${webpublicKey}`); uploads.push(upload(webpublicKey, alts.webpublic.data, alts.webpublic.type, name)); } if (alts.thumbnail) { thumbnailKey = `${meta.objectStoragePrefix}/${uuid.v4()}.${alts.thumbnail.ext}`; thumbnailUrl = `${ baseUrl }/${ thumbnailKey }`; logger.info(`uploading thumbnail: ${thumbnailKey}`); uploads.push(upload(thumbnailKey, alts.thumbnail.data, alts.thumbnail.type)); } await Promise.all(uploads); //#endregion file.url = url; file.thumbnailUrl = thumbnailUrl; file.webpublicUrl = webpublicUrl; file.accessKey = key; file.thumbnailAccessKey = thumbnailKey; file.webpublicAccessKey = webpublicKey; file.name = name; file.type = type; file.md5 = hash; file.size = size; file.storedInternal = false; return await DriveFiles.save(file); } else { // use internal storage const accessKey = uuid.v4(); const thumbnailAccessKey = uuid.v4(); const webpublicAccessKey = uuid.v4(); const url = InternalStorage.saveFromPath(accessKey, path); let thumbnailUrl: string | null = null; let webpublicUrl: string | null = null; if (alts.thumbnail) { thumbnailUrl = InternalStorage.saveFromBuffer(thumbnailAccessKey, alts.thumbnail.data); logger.info(`thumbnail stored: ${thumbnailAccessKey}`); } if (alts.webpublic) { webpublicUrl = InternalStorage.saveFromBuffer(webpublicAccessKey, alts.webpublic.data); logger.info(`web stored: ${webpublicAccessKey}`); } file.storedInternal = true; file.url = url; file.thumbnailUrl = thumbnailUrl; file.webpublicUrl = webpublicUrl; file.accessKey = accessKey; file.thumbnailAccessKey = thumbnailAccessKey; file.webpublicAccessKey = webpublicAccessKey; file.name = name; file.type = type; file.md5 = hash; file.size = size; return await DriveFiles.save(file); } } /** * Generate webpublic, thumbnail, etc * @param path Path for original * @param type Content-Type for original * @param generateWeb Generate webpublic or not */ export async function generateAlts(path: string, type: string, generateWeb: boolean) { // #region webpublic let webpublic: IImage | null = null; if (generateWeb) { logger.info(`creating web image`); if (['image/jpeg'].includes(type)) { webpublic = await convertToJpeg(path, 2048, 2048); } else if (['image/webp'].includes(type)) { webpublic = await convertToWebp(path, 2048, 2048); } else if (['image/png'].includes(type)) { webpublic = await convertToPng(path, 2048, 2048); } else if (['image/apng', 'image/vnd.mozilla.apng'].includes(type)) { webpublic = await convertToApng(path); } else if (['image/gif'].includes(type)) { webpublic = await convertToGif(path); } else { logger.info(`web image not created (not an image)`); } } else { logger.info(`web image not created (from remote)`); } // #endregion webpublic // #region thumbnail let thumbnail: IImage | null = null; if (['image/jpeg', 'image/webp'].includes(type)) { thumbnail = await convertToJpeg(path, 498, 280); } else if (['image/png'].includes(type)) { thumbnail = await convertToPng(path, 498, 280); } else if (['image/gif'].includes(type)) { thumbnail = await convertToGif(path); } else if (type.startsWith('video/')) { try { thumbnail = await GenerateVideoThumbnail(path); } catch (e) { logger.error(`GenerateVideoThumbnail failed: ${e}`); } } // #endregion thumbnail return { webpublic, thumbnail, }; } /** * Upload to ObjectStorage */ async function upload(key: string, stream: fs.ReadStream | Buffer, type: string, filename?: string) { const meta = await fetchMeta(); const minio = new Minio.Client({ endPoint: meta.objectStorageEndpoint!, region: meta.objectStorageRegion ? meta.objectStorageRegion : undefined, port: meta.objectStoragePort ? meta.objectStoragePort : undefined, useSSL: meta.objectStorageUseSSL, accessKey: meta.objectStorageAccessKey!, secretKey: meta.objectStorageSecretKey!, }); const metadata = { 'Content-Type': type, 'Cache-Control': 'max-age=31536000, immutable' } as Minio.ItemBucketMetadata; if (filename) metadata['Content-Disposition'] = contentDisposition('inline', filename); await minio.putObject(meta.objectStorageBucket!, key, stream, undefined, metadata); } async function deleteOldFile(user: IRemoteUser) { const q = DriveFiles.createQueryBuilder('file') .where('file.userId = :userId', { userId: user.id }); if (user.avatarId) { q.andWhere('file.id != :avatarId', { avatarId: user.avatarId }); } if (user.bannerId) { q.andWhere('file.id != :bannerId', { bannerId: user.bannerId }); } q.orderBy('file.id', 'ASC'); const oldFile = await q.getOne(); if (oldFile) { deleteFile(oldFile, true); } } /** * Add file to drive * * @param user User who wish to add file * @param path File path * @param name Name * @param comment Comment * @param folderId Folder ID * @param force If set to true, forcibly upload the file even if there is a file with the same hash. * @param isLink Do not save file to local * @param url URL of source (URLからアップロードされた場合(ローカル/リモート)の元URL) * @param uri URL of source (リモートインスタンスのURLからアップロードされた場合の元URL) * @param sensitive Mark file as sensitive * @return Created drive file */ export default async function( user: User, path: string, name: string | null = null, comment: string | null = null, folderId: any = null, force: boolean = false, isLink: boolean = false, url: string | null = null, uri: string | null = null, sensitive: boolean | null = null ): Promise<DriveFile> { // Calc md5 hash const calcHash = new Promise<string>((res, rej) => { const readable = fs.createReadStream(path); const hash = crypto.createHash('md5'); const chunks: Buffer[] = []; readable .on('error', rej) .pipe(hash) .on('error', rej) .on('data', chunk => chunks.push(chunk)) .on('end', () => { const buffer = Buffer.concat(chunks); res(buffer.toString('hex')); }); }); // Get file size const getFileSize = new Promise<number>((res, rej) => { fs.stat(path, (err, stats) => { if (err) return rej(err); res(stats.size); }); }); const [hash, [mime, ext], size] = await Promise.all([calcHash, detectMine(path), getFileSize]); logger.info(`hash: ${hash}, mime: ${mime}, ext: ${ext}, size: ${size}`); // detect name const detectedName = name || (ext ? `untitled.${ext}` : 'untitled'); if (!force) { // Check if there is a file with the same hash const much = await DriveFiles.findOne({ md5: hash, userId: user.id, }); if (much) { logger.info(`file with same hash is found: ${much.id}`); return much; } } //#region Check drive usage if (!isLink) { const usage = await DriveFiles.clacDriveUsageOf(user); const instance = await fetchMeta(); const driveCapacity = 1024 * 1024 * (Users.isLocalUser(user) ? instance.localDriveCapacityMb : instance.remoteDriveCapacityMb); logger.debug(`drive usage is ${usage} (max: ${driveCapacity})`); // If usage limit exceeded if (usage + size > driveCapacity) { if (Users.isLocalUser(user)) { throw new Error('no-free-space'); } else { // (アバターまたはバナーを含まず)最も古いファイルを削除する deleteOldFile(user as IRemoteUser); } } } //#endregion const fetchFolder = async () => { if (!folderId) { return null; } const driveFolder = await DriveFolders.findOne({ id: folderId, userId: user.id }); if (driveFolder == null) throw new Error('folder-not-found'); return driveFolder; }; const properties: {[key: string]: any} = {}; let propPromises: Promise<void>[] = []; const isImage = ['image/jpeg', 'image/gif', 'image/png', 'image/webp'].includes(mime); if (isImage) { const img = sharp(path); // Calc width and height const calcWh = async () => { logger.debug('calculating image width and height...'); // Calculate width and height const meta = await img.metadata(); logger.debug(`image width and height is calculated: ${meta.width}, ${meta.height}`); properties['width'] = meta.width; properties['height'] = meta.height; }; // Calc average color const calcAvg = async () => { logger.debug('calculating average color...'); try { const info = await (img as any).stats(); const r = Math.round(info.channels[0].mean); const g = Math.round(info.channels[1].mean); const b = Math.round(info.channels[2].mean); logger.debug(`average color is calculated: ${r}, ${g}, ${b}`); properties['avgColor'] = `rgb(${r},${g},${b})`; } catch (e) { } }; propPromises = [calcWh(), calcAvg()]; } const profile = await UserProfiles.findOne(user.id); const [folder] = await Promise.all([fetchFolder(), Promise.all(propPromises)]); let file = new DriveFile(); file.id = genId(); file.createdAt = new Date(); file.userId = user.id; file.userHost = user.host; file.folderId = folder !== null ? folder.id : null; file.comment = comment; file.properties = properties; file.isLink = isLink; file.isSensitive = Users.isLocalUser(user) && profile!.alwaysMarkNsfw ? true : (sensitive !== null && sensitive !== undefined) ? sensitive : false; if (url !== null) { file.src = url; if (isLink) { file.url = url; file.thumbnailUrl = url; file.webpublicUrl = url; } } if (uri !== null) { file.uri = uri; } if (isLink) { try { file.size = 0; file.md5 = hash; file.name = detectedName; file.type = mime; file.storedInternal = false; file = await DriveFiles.save(file); } catch (e) { // duplicate key error (when already registered) if (isDuplicateKeyValueError(e)) { logger.info(`already registered ${file.uri}`); file = await DriveFiles.findOne({ uri: file.uri, userId: user.id }) as DriveFile; } else { logger.error(e); throw e; } } } else { file = await (save(file, path, detectedName, mime, hash, size)); } logger.succ(`drive file has been created ${file.id}`); DriveFiles.pack(file).then(packedFile => { // Publish driveFileCreated event publishMainStream(user.id, 'driveFileCreated', packedFile); publishDriveStream(user.id, 'fileCreated', packedFile); }); // 統計を更新 driveChart.update(file, true); perUserDriveChart.update(file, true); if (file.userHost !== null) { instanceChart.updateDrive(file, true); Instances.increment({ host: file.userHost }, 'driveUsage', file.size); Instances.increment({ host: file.userHost }, 'driveFiles', 1); } return file; }
the_stack
import { browser, Tabs, WebNavigation, Runtime, Storage, WebRequest, Cookies, ContextualIdentities, History, ExtensionTypes } from "webextension-polyfill-ts"; import { assert } from "chai"; import { createSpy, clone, SpyData } from "./testHelpers"; // @ts-ignore // tslint:disable-next-line:no-var-requires const parseUrl = require("url").parse; // @ts-ignore // tslint:disable-next-line:function-constructor const glob = (function () { return this; }()) || Function("return this")(); glob.URL = function (url: string) { const parsed = parseUrl(url); for (const key in parsed) { if (parsed.hasOwnProperty(key)) this[key] = parsed[key]; } }; type ListenerCallback = (...args: any[]) => any; // tslint:disable-next-line:ban-types class ListenerMock<T extends Function> { private listeners: ListenerCallback[] = []; public emit: T; public readonly mock: { [s: string]: SpyData }; public constructor() { // @ts-ignore this.emit = (...args) => { const results = []; for (const listener of this.listeners) { results.push(listener.apply(null, args)); } return results; }; this.mock = { addListener: createSpy((listener: ListenerCallback) => { this.listeners.push(listener); }), removeListener: createSpy((listener: ListenerCallback) => { this.listeners = this.listeners.filter((cb) => listener !== cb); }), hasListener: createSpy((listener: ListenerCallback) => { return this.listeners.indexOf(listener) >= 0; }), hasListeners: createSpy(() => { return this.listeners.length > 0; }) }; } public reset() { this.listeners.length = 0; for (const key in this.mock) this.mock[key].reset(); } } class BrowsingDataMock { public remove = createSpy(); public reset() { this.remove.reset(); } } class BrowserContextualIdentitiesMock { public contextualIdentities: ContextualIdentities.ContextualIdentity[] = []; public reset() { this.contextualIdentities = []; } public query(details: ContextualIdentities.QueryDetailsType): Promise<ContextualIdentities.ContextualIdentity[]> { return Promise.resolve(clone(this.contextualIdentities)); } } const DOMAIN_PATH_SPLIT = /\/(.*)/; class BrowserCookiesMock { private readonly cookies: Cookies.Cookie[] = []; public remove = createSpy(this._remove); public set = createSpy(this._set); public getAll = createSpy(this._getAll); public getAllCookieStores = createSpy(this._getAllCookieStores); public cookieStores: Cookies.CookieStore[] = []; public onChanged = new ListenerMock<(changeInfo: Cookies.OnChangedChangeInfoType) => void>(); public reset() { this.cookies.length = 0; this.remove.reset(); this.set.reset(); this.getAll.reset(); this.getAllCookieStores.reset(); this.cookieStores = []; this.onChanged.reset(); } public resetCookies() { this.cookies.length = 0; } private findCookie(name: string, secure: boolean, domain: string, path: string, storeId: string, firstPartyDomain?: string) { let cookies = firstPartyDomain ? this.cookies.filter((c) => c.firstPartyDomain === firstPartyDomain) : this.cookies; cookies = cookies.filter((c) => c.secure === secure && c.path === path && c.storeId === storeId && c.name === name && c.domain === domain); if (cookies.length === 1) return cookies[0]; return null; } private _set(details: Cookies.SetDetailsType) { let cookie = this.findCookie(details.name || "", details.secure || false, details.domain || "", details.path || "", details.storeId || "firefox-default", details.firstPartyDomain); if (cookie) { cookie.value = details.value || ""; } else { cookie = { name: details.name || "", value: details.value || "", domain: details.domain || "", hostOnly: false, path: details.path || "", secure: details.secure || false, httpOnly: false, session: false, storeId: details.storeId || "firefox-default", firstPartyDomain: details.firstPartyDomain || "", sameSite: "no_restriction" }; this.cookies.push(cookie); } this.onChanged.emit({ removed: false, cookie: clone(cookie), cause: "explicit" }); return Promise.resolve(clone(cookie)); } private _remove(details: Cookies.RemoveDetailsType) { const secure = details.url.startsWith("https://"); const withoutProtocol = details.url.substr(secure ? 8 : 7); const parts = withoutProtocol.split(DOMAIN_PATH_SPLIT); const domain = parts[0].toLowerCase(); const path = parts[1] || ""; const cookie = this.findCookie(details.name || "", secure, domain, path, details.storeId || "firefox-default", details.firstPartyDomain); if (cookie) { const index = this.cookies.indexOf(cookie); this.cookies.splice(index, 1); this.onChanged.emit({ removed: true, cookie: clone(cookie), cause: "explicit" }); return Promise.resolve({ url: details.url, name: details.name, storeId: cookie.storeId, firstPartyDomain: cookie.firstPartyDomain }); } else { return Promise.reject(null); } } private _getAll(details: Cookies.GetAllDetailsType) { // Mocking only supports limited functionality right now assert.isNull(details.firstPartyDomain); assert.isNotNull(details.storeId); assert.hasAllKeys(details, ["firstPartyDomain", "storeId"]); const cookies = this.cookies.filter((c) => c.storeId === details.storeId); return Promise.resolve(clone(cookies)); } private _getAllCookieStores() { return Promise.resolve(clone(this.cookieStores)); } } class BrowserHistoryMock { public onVisited = new ListenerMock<(result: History.HistoryItem) => void>(); public deleteUrl = createSpy(); public search = createSpy(this._search.bind(this)); public readonly items: History.HistoryItem[] = []; public reset() { this.onVisited.reset(); this.deleteUrl.reset(); this.search.reset(); this.items.length = 0; } private _search(query: History.SearchQueryType): Promise<History.HistoryItem[]> { return Promise.resolve(clone(this.items)); } } class BrowserTabsMock { private idCount = 0; private tabs: Tabs.Tab[] = []; public onRemoved = new ListenerMock<(tabId: number, removeInfo: Tabs.OnRemovedRemoveInfoType) => void>(); public onCreated = new ListenerMock<(tab: Tabs.Tab) => void>(); public executeScriptSuccess = false; public executeScript = createSpy(this._executeScript); public reset() { this.tabs.length = 0; this.onRemoved.reset(); this.onCreated.reset(); this.executeScriptSuccess = false; } public get(tabId: number) { const tab = this.tabs.find((t) => t.id === tabId); if (tab) { return Promise.resolve(clone(tab)); } else { return Promise.reject("Tab doesn't exist"); } } public getTabs(): Tabs.Tab[] { return this.tabs; } public byId(tabId: number): Tabs.Tab | undefined { return this.tabs.find((ti) => ti.id === tabId); } public create(url: string, cookieStoreId: string, incognito = false) { const id = ++this.idCount; const tab: Tabs.Tab = { active: true, cookieStoreId, highlighted: false, id, incognito, index: this.tabs.length, isArticle: false, isInReaderMode: false, lastAccessed: Date.now(), pinned: false, url, windowId: 1 }; this.tabs.push(tab); browserMock.tabs.onCreated.emit(tab); return id; } public remove(tabId: number) { let i = 0; while (i < this.tabs.length) { if (this.tabs[i].id === tabId) { this.onRemoved.emit(tabId, { windowId: this.tabs[i].windowId || -1, isWindowClosing: false }); this.tabs.splice(i, 1); break; } i++; } while (i < this.tabs.length) this.tabs[i].index = i++; } public query(queryInfo: Tabs.QueryQueryInfoType) { return { then(resolve: (tabs: Tabs.Tab[]) => void) { resolve(browserMock.tabs.getTabs()); } }; } public _executeScript(tabId: number | undefined, details: ExtensionTypes.InjectDetails) { if (this.executeScriptSuccess) { return Promise.resolve([]); } else { return Promise.reject({}); } } } class BrowserWebNavigationMock { public onBeforeNavigate = new ListenerMock<(details: WebNavigation.OnBeforeNavigateDetailsType) => void>(); public onCommitted = new ListenerMock<(details: WebNavigation.OnCommittedDetailsType) => void>(); public onCompleted = new ListenerMock<(details: WebNavigation.OnCompletedDetailsType) => void>(); public reset() { this.onBeforeNavigate.reset(); this.onCommitted.reset(); this.onCompleted.reset(); } public beforeNavigate(tabId: number, url: string) { const tab = browserMock.tabs.byId(tabId); assert.isDefined(tab); if (tab) { this.onBeforeNavigate.emit({ tabId, url, timeStamp: Date.now(), frameId: 0, parentFrameId: 0 }); } } public commit(tabId: number, url: string) { const tab = browserMock.tabs.byId(tabId); assert.isDefined(tab); if (tab) { tab.url = url; this.onCommitted.emit({ tabId, url, timeStamp: Date.now(), frameId: 0 }); } } public complete(tabId: number, url: string) { const tab = browserMock.tabs.byId(tabId); assert.isDefined(tab); if (tab) { tab.url = url; this.onCompleted.emit({ tabId, url, timeStamp: Date.now(), frameId: 0 }); } } } class BrowserWebRequestMock { public onHeadersReceived = new ListenerMock<(details: WebRequest.OnHeadersReceivedDetailsType) => Array<WebRequest.BlockingResponse | undefined>>(); public onBeforeRedirect = new ListenerMock<(details: WebRequest.OnBeforeRedirectDetailsType) => void>(); public reset() { this.onHeadersReceived.reset(); this.onBeforeRedirect.reset(); } public headersReceived(details: WebRequest.OnHeadersReceivedDetailsType) { return this.onHeadersReceived.emit(details); } public beforeRedirect(details: WebRequest.OnBeforeRedirectDetailsType) { return this.onBeforeRedirect.emit(details); } } class BrowserRuntimeMock { public onMessage = new ListenerMock<(message: any | undefined, sender: Runtime.MessageSender, sendResponse: () => void) => void>(); public reset() { this.onMessage.reset(); } public sendMessage(message: any, options?: Runtime.SendMessageOptionsType): Promise<any> { this.onMessage.emit(message, { id: "mock" }, () => undefined); return Promise.resolve(); } public getManifest() { return { version: "2.0.0" }; } } class StorageAreaMock { public readonly QUOTA_BYTES: 5242880 = 5242880; private readonly data: any = {}; public get(keys?: null | string | string[] | { [s: string]: any }) { assert.isNull(keys); // only null supported for now return Promise.resolve(clone(this.data)); } private setInternal(key: string, newValue: any, changes: { [key: string]: Storage.StorageChange }) { if (!this.data.hasOwnProperty(key)) { this.data[key] = clone(newValue); changes[key] = { newValue: clone(newValue) }; } else if (JSON.stringify(this.data[key]) !== JSON.stringify(newValue)) { const oldValue = this.data[key]; this.data[key] = clone(newValue); changes[key] = { oldValue: clone(oldValue), newValue: clone(newValue) }; } } public set(items: Storage.StorageAreaSetItemsType) { const changes: { [s: string]: Storage.StorageChange } = {}; for (const key in items) { // @ts-ignore const value = items[key]; this.setInternal(key, value, changes); } browserMock.storage.onChanged.emit(changes, "local"); return Promise.resolve(); } private removeInternal(key: string, changes: { [key: string]: Storage.StorageChange }) { if (this.data.hasOwnProperty(key)) { const oldValue = this.data[key]; changes[key] = { oldValue: clone(oldValue) }; delete this.data[key]; } } public remove(keys: string | string[]) { const changes: { [s: string]: Storage.StorageChange } = {}; if (typeof (keys) === "string") this.removeInternal(keys, changes); else { for (const key of keys) this.removeInternal(key, changes); } browserMock.storage.onChanged.emit(changes, "local"); return Promise.resolve(); } public clear() { return this.remove(Object.getOwnPropertyNames(this.data)); } public reset() { for (const key in this.data) delete this.data[key]; } } export const browserMock = { browsingData: new BrowsingDataMock(), cookies: new BrowserCookiesMock(), history: new BrowserHistoryMock(), contextualIdentities: new BrowserContextualIdentitiesMock(), tabs: new BrowserTabsMock(), webNavigation: new BrowserWebNavigationMock(), webRequest: new BrowserWebRequestMock(), runtime: new BrowserRuntimeMock(), storage: { local: new StorageAreaMock(), onChanged: new ListenerMock<(changes: { [s: string]: Storage.StorageChange }, areaName: string) => void>() }, reset: () => { browserMock.browsingData.reset(); browserMock.cookies.reset(); browserMock.history.reset(); browserMock.contextualIdentities.reset(); browserMock.tabs.reset(); browserMock.webNavigation.reset(); browserMock.webRequest.reset(); browserMock.runtime.reset(); browserMock.storage.local.reset(); } }; function bindMocks<DT>(destination: DT, source: any, keys: Array<keyof DT>) { if (!destination) destination = {} as any; for (const key of keys) { let mock = source[key]; if (typeof (mock) === "function") mock = mock.bind(source); else if (mock.constructor.name === "ListenerMock") mock = mock.mock; (destination as any)[key] = mock; } return destination; } browser.browsingData = bindMocks(browser.browsingData, browserMock.browsingData, ["remove"]); browser.cookies = bindMocks(browser.cookies, browserMock.cookies, ["getAll", "set", "remove", "getAllCookieStores", "onChanged"]); browser.history = bindMocks(browser.history, browserMock.history, ["onVisited", "deleteUrl", "search"]); browser.contextualIdentities = bindMocks(browser.contextualIdentities, browserMock.contextualIdentities, ["query"]); browser.tabs = bindMocks(browser.tabs, browserMock.tabs, ["get", "query", "onRemoved", "onCreated", "executeScript"]); browser.webNavigation = bindMocks(browser.webNavigation, browserMock.webNavigation, ["onBeforeNavigate", "onCommitted", "onCompleted"]); browser.webRequest = bindMocks(browser.webRequest, browserMock.webRequest, ["onHeadersReceived", "onBeforeRedirect"]); browser.runtime = bindMocks(browser.runtime, browserMock.runtime, ["onMessage", "sendMessage", "getManifest"]); browser.webRequest = bindMocks(browser.webRequest, browserMock.webRequest, ["onHeadersReceived"]); browser.storage = bindMocks(browser.storage, browserMock.storage, ["onChanged", "local"]);
the_stack
import { dew as _readerForDewDew } from "./reader/readerFor.dew.js"; import { dew as _utilsDewDew } from "./utils.dew.js"; import { dew as _compressedObjectDewDew } from "./compressedObject.dew.js"; import { dew as _crc32DewDew } from "./crc32.dew.js"; import { dew as _utf8DewDew } from "./utf8.dew.js"; import { dew as _compressionsDewDew } from "./compressions.dew.js"; import { dew as _supportDewDew } from "./support.dew.js"; var exports = {}, _dewExec = false; export function dew() { if (_dewExec) return exports; _dewExec = true; var readerFor = _readerForDewDew(); var utils = _utilsDewDew(); var CompressedObject = _compressedObjectDewDew(); var crc32fn = _crc32DewDew(); var utf8 = _utf8DewDew(); var compressions = _compressionsDewDew(); var support = _supportDewDew(); var MADE_BY_DOS = 0x00; var MADE_BY_UNIX = 0x03; /** * Find a compression registered in JSZip. * @param {string} compressionMethod the method magic to find. * @return {Object|null} the JSZip compression object, null if none found. */ var findCompression = function (compressionMethod) { for (var method in compressions) { if (!compressions.hasOwnProperty(method)) { continue; } if (compressions[method].magic === compressionMethod) { return compressions[method]; } } return null; }; // class ZipEntry {{{ /** * An entry in the zip file. * @constructor * @param {Object} options Options of the current file. * @param {Object} loadOptions Options for loading the stream. */ function ZipEntry(options, loadOptions) { this.options = options; this.loadOptions = loadOptions; } ZipEntry.prototype = { /** * say if the file is encrypted. * @return {boolean} true if the file is encrypted, false otherwise. */ isEncrypted: function () { // bit 1 is set return (this.bitFlag & 0x0001) === 0x0001; }, /** * say if the file has utf-8 filename/comment. * @return {boolean} true if the filename/comment is in utf-8, false otherwise. */ useUTF8: function () { // bit 11 is set return (this.bitFlag & 0x0800) === 0x0800; }, /** * Read the local part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readLocalPart: function (reader) { var compression, localExtraFieldsLength; // we already know everything from the central dir ! // If the central dir data are false, we are doomed. // On the bright side, the local part is scary : zip64, data descriptors, both, etc. // The less data we get here, the more reliable this should be. // Let's skip the whole header and dash to the data ! reader.skip(22); // in some zip created on windows, the filename stored in the central dir contains \ instead of /. // Strangely, the filename here is OK. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... // Search "unzip mismatching "local" filename continuing with "central" filename version" on // the internet. // // I think I see the logic here : the central directory is used to display // content and the local directory is used to extract the files. Mixing / and \ // may be used to display \ to windows users and use / when extracting the files. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 this.fileNameLength = reader.readInt(2); localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding. this.fileName = reader.readData(this.fileNameLength); reader.skip(localExtraFieldsLength); if (this.compressedSize === -1 || this.uncompressedSize === -1) { throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); } compression = findCompression(this.compressionMethod); if (compression === null) { // no compression found throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); } this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); }, /** * Read the central part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readCentralPart: function (reader) { this.versionMadeBy = reader.readInt(2); reader.skip(2); // this.versionNeeded = reader.readInt(2); this.bitFlag = reader.readInt(2); this.compressionMethod = reader.readString(2); this.date = reader.readDate(); this.crc32 = reader.readInt(4); this.compressedSize = reader.readInt(4); this.uncompressedSize = reader.readInt(4); var fileNameLength = reader.readInt(2); this.extraFieldsLength = reader.readInt(2); this.fileCommentLength = reader.readInt(2); this.diskNumberStart = reader.readInt(2); this.internalFileAttributes = reader.readInt(2); this.externalFileAttributes = reader.readInt(4); this.localHeaderOffset = reader.readInt(4); if (this.isEncrypted()) { throw new Error("Encrypted zip are not supported"); } // will be read in the local part, see the comments there reader.skip(fileNameLength); this.readExtraFields(reader); this.parseZIP64ExtraField(reader); this.fileComment = reader.readData(this.fileCommentLength); }, /** * Parse the external file attributes and get the unix/dos permissions. */ processAttributes: function () { this.unixPermissions = null; this.dosPermissions = null; var madeBy = this.versionMadeBy >> 8; // Check if we have the DOS directory flag set. // We look for it in the DOS and UNIX permissions // but some unknown platform could set it as a compatibility flag. this.dir = this.externalFileAttributes & 0x0010 ? true : false; if (madeBy === MADE_BY_DOS) { // first 6 bits (0 to 5) this.dosPermissions = this.externalFileAttributes & 0x3F; } if (madeBy === MADE_BY_UNIX) { this.unixPermissions = this.externalFileAttributes >> 16 & 0xFFFF; // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8); } // fail safe : if the name ends with a / it probably means a folder if (!this.dir && this.fileNameStr.slice(-1) === '/') { this.dir = true; } }, /** * Parse the ZIP64 extra field and merge the info in the current ZipEntry. * @param {DataReader} reader the reader to use. */ parseZIP64ExtraField: function (reader) { if (!this.extraFields[0x0001]) { return; } // should be something, preparing the extra reader var extraReader = readerFor(this.extraFields[0x0001].value); // I really hope that these 64bits integer can fit in 32 bits integer, because js // won't let us have more. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { this.uncompressedSize = extraReader.readInt(8); } if (this.compressedSize === utils.MAX_VALUE_32BITS) { this.compressedSize = extraReader.readInt(8); } if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { this.localHeaderOffset = extraReader.readInt(8); } if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { this.diskNumberStart = extraReader.readInt(4); } }, /** * Read the central part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readExtraFields: function (reader) { var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue; if (!this.extraFields) { this.extraFields = {}; } while (reader.index + 4 < end) { extraFieldId = reader.readInt(2); extraFieldLength = reader.readInt(2); extraFieldValue = reader.readData(extraFieldLength); this.extraFields[extraFieldId] = { id: extraFieldId, length: extraFieldLength, value: extraFieldValue }; } reader.setIndex(end); }, /** * Apply an UTF8 transformation if needed. */ handleUTF8: function () { var decodeParamType = support.uint8array ? "uint8array" : "array"; if (this.useUTF8()) { this.fileNameStr = utf8.utf8decode(this.fileName); this.fileCommentStr = utf8.utf8decode(this.fileComment); } else { var upath = this.findExtraFieldUnicodePath(); if (upath !== null) { this.fileNameStr = upath; } else { // ASCII text or unsupported code page var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); } var ucomment = this.findExtraFieldUnicodeComment(); if (ucomment !== null) { this.fileCommentStr = ucomment; } else { // ASCII text or unsupported code page var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); } } }, /** * Find the unicode path declared in the extra field, if any. * @return {String} the unicode path, null otherwise. */ findExtraFieldUnicodePath: function () { var upathField = this.extraFields[0x7075]; if (upathField) { var extraReader = readerFor(upathField.value); // wrong version if (extraReader.readInt(1) !== 1) { return null; } // the crc of the filename changed, this field is out of date. if (crc32fn(this.fileName) !== extraReader.readInt(4)) { return null; } return utf8.utf8decode(extraReader.readData(upathField.length - 5)); } return null; }, /** * Find the unicode comment declared in the extra field, if any. * @return {String} the unicode comment, null otherwise. */ findExtraFieldUnicodeComment: function () { var ucommentField = this.extraFields[0x6375]; if (ucommentField) { var extraReader = readerFor(ucommentField.value); // wrong version if (extraReader.readInt(1) !== 1) { return null; } // the crc of the comment changed, this field is out of date. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { return null; } return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); } return null; } }; exports = ZipEntry; return exports; }
the_stack
import { Color, PageContent, StatePages, } from "../pageModel"; import { SENTINEL_INDEX, EMPTY_TREE_ROOT } from "../tree/tree"; import { SENTINEL_STRUCTURE } from "./tree"; import { SENTINEL_CONTENT } from "../contentTree/tree"; import pageReducer from "../reducer"; import { insertStructure } from "./actions"; import { TagType } from "./structureModel"; export const getBigTree = (): PageContent => ({ buffers: [], content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 2, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 2 color: Color.Black, id: "helloWorld", left: 1, leftSubTreeLength: 1, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 3 color: Color.Black, id: "helloWorld", left: 2, leftSubTreeLength: 2, length: 0, parent: 5, right: 4, tag: "span", tagType: TagType.StartEndTag, }, { // 4 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 5 color: Color.Black, id: "helloWorld", left: 3, leftSubTreeLength: 4, length: 0, parent: SENTINEL_INDEX, right: 7, tag: "span", tagType: TagType.StartEndTag, }, { // 6 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 7, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 7 color: Color.Black, id: "helloWorld", left: 6, leftSubTreeLength: 1, length: 0, parent: 5, right: 10, tag: "span", tagType: TagType.StartEndTag, }, { // 8 color: Color.Black, id: "helloWorld", left: 14, leftSubTreeLength: 1, length: 0, parent: 10, right: 9, tag: "span", tagType: TagType.StartEndTag, }, { // 9 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 8, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 10 color: Color.Red, id: "helloWorld", left: 8, leftSubTreeLength: 3, length: 0, parent: 7, right: 12, tag: "span", tagType: TagType.StartEndTag, }, { // 11 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 12 color: Color.Black, id: "helloWorld", left: 11, leftSubTreeLength: 1, length: 0, parent: 10, right: 13, tag: "span", tagType: TagType.StartEndTag, }, { // 13 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 14 color: Color.Red, id: "newNode", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 8, right: SENTINEL_INDEX, tag: "img", tagType: TagType.StartEndTag, }, ], root: 5, }, }); describe("structureTree insert tests", (): void => { test("Less than insertion - left side", (): void => { const page: PageContent = { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 2, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 2 color: Color.Black, id: "helloWorld", left: 1, leftSubTreeLength: 1, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 3 color: Color.Black, id: "helloWorld", left: 2, leftSubTreeLength: 2, length: 0, parent: 5, right: 4, tag: "span", tagType: TagType.StartEndTag, }, { // 4 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 5 color: Color.Black, id: "helloWorld", left: 3, leftSubTreeLength: 4, length: 0, parent: SENTINEL_INDEX, right: 7, tag: "span", tagType: TagType.StartEndTag, }, { // 6 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 7, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 7 color: Color.Black, id: "helloWorld", left: 6, leftSubTreeLength: 1, length: 0, parent: 5, right: 10, tag: "span", tagType: TagType.StartEndTag, }, { // 8 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 10, right: 9, tag: "span", tagType: TagType.StartEndTag, }, { // 9 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 8, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 10 color: Color.Red, id: "helloWorld", left: 8, leftSubTreeLength: 2, length: 0, parent: 7, right: 12, tag: "span", tagType: TagType.StartEndTag, }, { // 11 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 12 color: Color.Black, id: "helloWorld", left: 11, leftSubTreeLength: 1, length: 0, parent: 10, right: 13, tag: "span", tagType: TagType.StartEndTag, }, { // 13 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, ], root: 5, }, }; const state: StatePages = { pageId: page, }; const expectedState: StatePages = { pageId: getBigTree(), }; const resultState = pageReducer( state, insertStructure("pageId", 8, 0, "img", TagType.StartEndTag, "newNode"), ); expect(resultState).toStrictEqual(expectedState); }); test("Less than insertion - right side", (): void => { const page: PageContent = { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 2, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 2 color: Color.Black, id: "helloWorld", left: 1, leftSubTreeLength: 1, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 3 color: Color.Black, id: "helloWorld", left: 2, leftSubTreeLength: 2, length: 0, parent: 5, right: 4, tag: "span", tagType: TagType.StartEndTag, }, { // 4 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 5 color: Color.Black, id: "helloWorld", left: 3, leftSubTreeLength: 4, length: 0, parent: SENTINEL_INDEX, right: 7, tag: "span", tagType: TagType.StartEndTag, }, { // 6 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 7, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 7 color: Color.Black, id: "helloWorld", left: 6, leftSubTreeLength: 1, length: 0, parent: 5, right: 10, tag: "span", tagType: TagType.StartEndTag, }, { // 8 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 9, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 9 color: Color.Black, id: "helloWorld", left: 8, leftSubTreeLength: 1, length: 0, parent: 10, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 10 color: Color.Red, id: "helloWorld", left: 9, leftSubTreeLength: 2, length: 0, parent: 7, right: 12, tag: "span", tagType: TagType.StartEndTag, }, { // 11 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 12 color: Color.Black, id: "helloWorld", left: 11, leftSubTreeLength: 1, length: 0, parent: 10, right: 13, tag: "span", tagType: TagType.StartEndTag, }, { // 13 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, ], root: 5, }, }; const state: StatePages = { pageId: page, }; const expectedPage: PageContent = { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 2, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 2 color: Color.Black, id: "helloWorld", left: 1, leftSubTreeLength: 1, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 3 color: Color.Black, id: "helloWorld", left: 2, leftSubTreeLength: 2, length: 0, parent: 5, right: 4, tag: "span", tagType: TagType.StartEndTag, }, { // 4 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 5 color: Color.Black, id: "helloWorld", left: 3, leftSubTreeLength: 4, length: 0, parent: SENTINEL_INDEX, right: 7, tag: "span", tagType: TagType.StartEndTag, }, { // 6 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 7, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 7 color: Color.Black, id: "helloWorld", left: 6, leftSubTreeLength: 1, length: 0, parent: 5, right: 10, tag: "span", tagType: TagType.StartEndTag, }, { // 8 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 9, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 9 color: Color.Black, id: "helloWorld", left: 8, leftSubTreeLength: 1, length: 0, parent: 10, right: 14, tag: "span", tagType: TagType.StartEndTag, }, { // 10 color: Color.Red, id: "helloWorld", left: 9, leftSubTreeLength: 3, length: 0, parent: 7, right: 12, tag: "span", tagType: TagType.StartEndTag, }, { // 11 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 12 color: Color.Black, id: "helloWorld", left: 11, leftSubTreeLength: 1, length: 0, parent: 10, right: 13, tag: "span", tagType: TagType.StartEndTag, }, { // 13 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 14 color: Color.Red, id: "newNode", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 9, right: SENTINEL_INDEX, tag: "img", tagType: TagType.StartEndTag, }, ], root: 5, }, }; const expectedState: StatePages = { pageId: expectedPage, }; const resultState = pageReducer( state, insertStructure( "pageId", 10, 0, "img", TagType.StartEndTag, "newNode", undefined, undefined, ), ); expect(resultState).toStrictEqual(expectedState); }); test("Greater than insertion", (): void => { const page: PageContent = { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 2, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 2 color: Color.Black, id: "helloWorld", left: 1, leftSubTreeLength: 1, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 3 color: Color.Black, id: "helloWorld", left: 2, leftSubTreeLength: 2, length: 0, parent: 5, right: 4, tag: "span", tagType: TagType.StartEndTag, }, { // 4 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 5 color: Color.Black, id: "helloWorld", left: 3, leftSubTreeLength: 4, length: 0, parent: SENTINEL_INDEX, right: 7, tag: "span", tagType: TagType.StartEndTag, }, { // 6 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 7, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 7 color: Color.Black, id: "helloWorld", left: 6, leftSubTreeLength: 1, length: 0, parent: 5, right: 10, tag: "span", tagType: TagType.StartEndTag, }, { // 8 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 9, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 9 color: Color.Black, id: "helloWorld", left: 8, leftSubTreeLength: 1, length: 0, parent: 10, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 10 color: Color.Red, id: "helloWorld", left: 9, leftSubTreeLength: 2, length: 0, parent: 7, right: 12, tag: "span", tagType: TagType.StartEndTag, }, { // 11 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 12 color: Color.Black, id: "helloWorld", left: 11, leftSubTreeLength: 1, length: 0, parent: 10, right: 13, tag: "span", tagType: TagType.StartEndTag, }, { // 13 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, ], root: 5, }, }; const state: StatePages = { pageId: page, }; const expectedPage: PageContent = { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 2, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 2 color: Color.Black, id: "helloWorld", left: 1, leftSubTreeLength: 1, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 3 color: Color.Black, id: "helloWorld", left: 2, leftSubTreeLength: 2, length: 0, parent: 5, right: 4, tag: "span", tagType: TagType.StartEndTag, }, { // 4 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 5 color: Color.Black, id: "helloWorld", left: 3, leftSubTreeLength: 4, length: 0, parent: SENTINEL_INDEX, right: 10, tag: "span", tagType: TagType.StartEndTag, }, { // 6 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 7, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 7 color: Color.Red, id: "helloWorld", left: 6, leftSubTreeLength: 1, length: 0, parent: 10, right: 9, tag: "span", tagType: TagType.StartEndTag, }, { // 8 color: Color.Red, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 9, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 9 color: Color.Black, id: "helloWorld", left: 8, leftSubTreeLength: 1, length: 0, parent: 7, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 10 color: Color.Black, id: "helloWorld", left: 7, leftSubTreeLength: 4, length: 0, parent: 5, right: 12, tag: "span", tagType: TagType.StartEndTag, }, { // 11 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: SENTINEL_INDEX, tag: "span", tagType: TagType.StartEndTag, }, { // 12 color: Color.Red, id: "helloWorld", left: 11, leftSubTreeLength: 1, length: 0, parent: 10, right: 13, tag: "span", tagType: TagType.StartEndTag, }, { // 13 color: Color.Black, id: "helloWorld", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 12, right: 14, tag: "span", tagType: TagType.StartEndTag, }, { // 14 color: Color.Red, id: "newNode", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 13, right: SENTINEL_INDEX, tag: "img", tagType: TagType.StartEndTag, }, ], root: 5, }, }; const expectedState: StatePages = { pageId: expectedPage, }; const resultState = pageReducer( state, insertStructure("pageId", 14, 0, "img", TagType.StartEndTag, "newNode"), ); expect(resultState).toStrictEqual(expectedState); }); test("Insert the root of the tree", (): void => { const state: StatePages = { pageId: { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: EMPTY_TREE_ROOT }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [SENTINEL_STRUCTURE], root: EMPTY_TREE_ROOT }, }, }; const expectedState: StatePages = { pageId: { buffers: [], content: { nodes: [SENTINEL_CONTENT], root: EMPTY_TREE_ROOT }, previouslyInsertedContentNodeIndex: null, previouslyInsertedContentNodeOffset: null, structure: { nodes: [ SENTINEL_STRUCTURE, { color: Color.Black, id: "id", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: SENTINEL_INDEX, right: SENTINEL_INDEX, tag: "p", tagType: TagType.StartEndTag, }, ], root: 1, }, }, }; const resultState = pageReducer( state, insertStructure("pageId", 1, 0, "p", TagType.StartEndTag, "id"), ); expect(resultState).toStrictEqual(expectedState); }); });
the_stack
var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g; function parse(css, options?) { options = options || {}; /** * Positional. */ var lineno = 1; var column = 1; /** * Update lineno and column based on `str`. */ function updatePosition(str) { var lines = str.match(/\n/g); if (lines) lineno += lines.length; var i = str.lastIndexOf('\n'); column = ~i ? str.length - i : column + str.length; } /** * Mark position and patch `node.position`. */ function position() { var start = { line: lineno, column: column }; return function (node) { node.position = new Position(start); whitespace(); return node; }; } /** * Store position information for a node */ function Position(start) { this.start = start; this.end = { line: lineno, column: column }; this.source = options.source; } /** * Non-enumerable source string */ Position.prototype.content = css; /** * Error `msg`. */ var errorsList = []; function error(msg) { var err: any = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg); err.reason = msg; err.filename = options.source; err.line = lineno; err.column = column; err.source = css; if (options.silent) { errorsList.push(err); } else { throw err; } } /** * Parse stylesheet. */ function stylesheet() { var rulesList = rules(); return { type: 'stylesheet', stylesheet: { source: options.source, rules: rulesList, parsingErrors: errorsList, }, }; } /** * Opening brace. */ function open() { return match(/^{\s*/); } /** * Closing brace. */ function close() { return match(/^}/); } /** * Parse ruleset. */ function rules() { var node; var rules = []; whitespace(); comments(rules); while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) { if (node !== false) { rules.push(node); comments(rules); } } return rules; } /** * Match `re` and return captures. */ function match(re) { var m = re.exec(css); if (!m) return; var str = m[0]; updatePosition(str); css = css.slice(str.length); return m; } /** * Parse whitespace. */ function whitespace() { match(/^\s*/); } /** * Parse comments; */ function comments(rules?) { var c; rules = rules || []; while ((c = comment())) { if (c !== false) { rules.push(c); } } return rules; } /** * Parse comment. */ function comment() { var pos = position(); if ('/' != css.charAt(0) || '*' != css.charAt(1)) return; var i = 2; while ('' != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i; i += 2; if ('' === css.charAt(i - 1)) { return error('End of comment missing'); } var str = css.slice(2, i - 2); column += 2; updatePosition(str); css = css.slice(i); column += 2; return pos({ type: 'comment', comment: str, }); } /** * Parse selector. */ function selector() { var m = match(/^([^{]+)/); if (!m) return; /* @fix Remove all comments from selectors * http://ostermiller.org/findcomment.html */ return trim(m[0]) .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '') .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function (m) { return m.replace(/,/g, '\u200C'); }) .split(/\s*(?![^(]*\)),\s*/) .map(function (s) { return s.replace(/\u200C/g, ','); }); } /** * Parse declaration. */ function declaration() { var pos = position(); // prop var prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/); if (!prop) return; prop = trim(prop[0]); // : if (!match(/^:\s*/)) return error("property missing ':'"); // val var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/); var ret = pos({ type: 'declaration', property: prop.replace(commentre, ''), value: val ? trim(val[0]).replace(commentre, '') : '', }); // ; match(/^[;\s]*/); return ret; } /** * Parse declarations. */ function declarations() { var decls = []; if (!open()) return error("missing '{'"); comments(decls); // declarations var decl; while ((decl = declaration())) { if (decl !== false) { decls.push(decl); comments(decls); } } if (!close()) return error("missing '}'"); return decls; } /** * Parse keyframe. */ function keyframe() { var m; var vals = []; var pos = position(); while ((m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/))) { vals.push(m[1]); match(/^,\s*/); } if (!vals.length) return; return pos({ type: 'keyframe', values: vals, declarations: declarations(), }); } /** * Parse keyframes. */ function atkeyframes() { var pos = position(); var m = match(/^@([-\w]+)?keyframes\s*/); if (!m) return; var vendor = m[1]; // identifier var m = match(/^([-\w]+)\s*/); if (!m) return error('@keyframes missing name'); var name = m[1]; if (!open()) return error("@keyframes missing '{'"); var frame; var frames = comments(); while ((frame = keyframe())) { frames.push(frame); frames = frames.concat(comments()); } if (!close()) return error("@keyframes missing '}'"); return pos({ type: 'keyframes', name: name, vendor: vendor, keyframes: frames, }); } /** * Parse supports. */ function atsupports() { var pos = position(); var m = match(/^@supports *([^{]+)/); if (!m) return; var supports = trim(m[1]); if (!open()) return error("@supports missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@supports missing '}'"); return pos({ type: 'supports', supports: supports, rules: style, }); } /** * Parse host. */ function athost() { var pos = position(); var m = match(/^@host\s*/); if (!m) return; if (!open()) return error("@host missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@host missing '}'"); return pos({ type: 'host', rules: style, }); } /** * Parse media. */ function atmedia() { var pos = position(); var m = match(/^@media *([^{]+)/); if (!m) return; var media = trim(m[1]); if (!open()) return error("@media missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@media missing '}'"); return pos({ type: 'media', media: media, rules: style, }); } /** * Parse custom-media. */ function atcustommedia() { var pos = position(); var m = match(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/); if (!m) return; return pos({ type: 'custom-media', name: trim(m[1]), media: trim(m[2]), }); } /** * Parse paged media. */ function atpage() { var pos = position(); var m = match(/^@page */); if (!m) return; var sel = selector() || []; if (!open()) return error("@page missing '{'"); var decls = comments(); // declarations var decl; while ((decl = declaration())) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) return error("@page missing '}'"); return pos({ type: 'page', selectors: sel, declarations: decls, }); } /** * Parse document. */ function atdocument() { var pos = position(); var m = match(/^@([-\w]+)?document *([^{]+)/); if (!m) return; var vendor = trim(m[1]); var doc = trim(m[2]); if (!open()) return error("@document missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@document missing '}'"); return pos({ type: 'document', document: doc, vendor: vendor, rules: style, }); } /** * Parse font-face. */ function atfontface() { var pos = position(); var m = match(/^@font-face\s*/); if (!m) return; if (!open()) return error("@font-face missing '{'"); var decls = comments(); // declarations var decl; while ((decl = declaration())) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) return error("@font-face missing '}'"); return pos({ type: 'font-face', declarations: decls, }); } /** * Parse import */ var atimport = _compileAtrule('import'); /** * Parse charset */ var atcharset = _compileAtrule('charset'); /** * Parse namespace */ var atnamespace = _compileAtrule('namespace'); /** * Parse non-block at-rules */ function _compileAtrule(name) { var re = new RegExp('^@' + name + '\\s*([^;]+);'); return function () { var pos = position(); var m = match(re); if (!m) return; var ret = { type: name }; ret[name] = m[1].trim(); return pos(ret); }; } /** * Parse at rule. */ function atrule() { if (css[0] != '@') return; return ( atkeyframes() || atmedia() || atcustommedia() || atsupports() || atimport() || atcharset() || atnamespace() || atdocument() || atpage() || athost() || atfontface() ); } /** * Parse rule. */ function rule() { var pos = position(); var sel = selector(); if (!sel) return error('selector missing'); comments(); return pos({ type: 'rule', selectors: sel, declarations: declarations(), }); } return addParent(stylesheet()); } /** * Trim `str`. */ function trim(str) { return str ? str.replace(/^\s+|\s+$/g, '') : ''; } /** * Adds non-enumerable parent node reference to each node. */ function addParent(obj, parent?) { var isNode = obj && typeof obj.type === 'string'; var childParent = isNode ? obj : parent; for (var k in obj) { var value = obj[k]; if (Array.isArray(value)) { value.forEach(function (v) { addParent(v, childParent); }); } else if (value && typeof value === 'object') { addParent(value, childParent); } } if (isNode) { Object.defineProperty(obj, 'parent', { configurable: true, writable: true, enumerable: false, value: parent || null, }); } return obj; } export default parse;
the_stack
import * as fs from "fs"; import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; import { CONFIG, CONSTANTS, DialogResponses, GLOBAL_ENV_VARS, HELPER_FILES, TelemetryEventName, VERSIONS, } from "../constants"; import { checkConfig, createEscapedPath, exec, getConfig, getPathToScript, showPrivacyModal, } from "../extension_utils/utils"; import TelemetryAI from "../telemetry/telemetryAI"; export class SetupService { private telemetryAI: TelemetryAI; constructor(telemetryAI: TelemetryAI) { this.telemetryAI = telemetryAI; } public setupEnv = async ( context: vscode.ExtensionContext, needsResponse: boolean = false ) => { const originalPythonExecutablePath = await this.getCurrentPythonExecutablePath(); if (originalPythonExecutablePath === "") { return; } let pythonExecutablePath = originalPythonExecutablePath; const pythonExecutableName: string = os.platform() === "win32" ? HELPER_FILES.PYTHON_EXE : HELPER_FILES.PYTHON; if ( !(await this.areDependenciesInstalled( context, pythonExecutablePath )) ) { // environment needs to install dependencies if (!(await this.checkIfVenv(context, pythonExecutablePath))) { const pythonExecutablePathVenv = await this.getPythonVenv( context, pythonExecutableName ); if (await this.hasVenv(context)) { // venv in extention exists with wrong dependencies if ( !(await this.areDependenciesInstalled( context, pythonExecutablePathVenv )) ) { pythonExecutablePath = await this.installDependenciesWrapper( context, pythonExecutablePathVenv, pythonExecutablePath ); } else { pythonExecutablePath = pythonExecutablePathVenv; } } else { pythonExecutablePath = await this.promptInstallVenv( context, originalPythonExecutablePath, pythonExecutableName ); this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_INSTALL_VENV ); } if (pythonExecutablePath === pythonExecutablePathVenv) { vscode.window.showInformationMessage( CONSTANTS.INFO.UPDATED_TO_EXTENSION_VENV ); vscode.workspace .getConfiguration() .update(CONFIG.PYTHON_PATH, pythonExecutablePath); } } else { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_HAS_VENV ); } if (pythonExecutablePath === originalPythonExecutablePath) { // going with original interpreter, either because // already in venv or error in creating custom venv if (checkConfig(CONFIG.SHOW_DEPENDENCY_INSTALL)) { await vscode.window .showInformationMessage( CONSTANTS.INFO.INSTALL_PYTHON_DEPS, DialogResponses.INSTALL_NOW, DialogResponses.DONT_INSTALL ) .then( async ( installChoice: vscode.MessageItem | undefined ) => { if ( installChoice === DialogResponses.INSTALL_NOW ) { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_ORIGINAL_INTERPRETER_DEP_INSTALL ); await this.installDependenciesWrapper( context, pythonExecutablePath ); } else { await vscode.window .showInformationMessage( CONSTANTS.INFO.ARE_YOU_SURE, DialogResponses.INSTALL_NOW, DialogResponses.DONT_INSTALL ) .then( async ( installChoice2: | vscode.MessageItem | undefined ) => { if ( installChoice2 === DialogResponses.INSTALL_NOW ) { await this.installDependenciesWrapper( context, pythonExecutablePath ); } else { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_NO_DEPS_INSTALLED ); } } ); } } ); } } } else if (needsResponse) { vscode.window.showInformationMessage( CONSTANTS.INFO.ALREADY_SUCCESSFUL_INSTALL ); } return pythonExecutablePath; }; public getCurrentPythonExecutablePath = async ( isTryingPython3: boolean = false ) => { let originalPythonExecutablePath = ""; const systemPythonVar = isTryingPython3 ? GLOBAL_ENV_VARS.PYTHON3 : GLOBAL_ENV_VARS.PYTHON; // try to get name from interpreter try { originalPythonExecutablePath = getConfig(CONFIG.PYTHON_PATH); } catch (err) { originalPythonExecutablePath = systemPythonVar; } if ( originalPythonExecutablePath === GLOBAL_ENV_VARS.PYTHON3 || originalPythonExecutablePath === GLOBAL_ENV_VARS.PYTHON || originalPythonExecutablePath === "" ) { // catching any instance where the python path needs to be resolved // from an system variable this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_AUTO_RESOLVE_PYTHON_PATH ); try { const { stdout } = await this.executePythonCommand( systemPythonVar, `-c "import sys; print(sys.executable)"` ); originalPythonExecutablePath = stdout.trim(); } catch (err) { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_NO_PYTHON_PATH ); if (isTryingPython3) { // if trying python3 failed, that means that BOTH // python and python3 failed as system variables // so that means that there is no python vscode.window .showErrorMessage( CONSTANTS.ERROR.NO_PYTHON_PATH, DialogResponses.INSTALL_PYTHON ) .then((selection: vscode.MessageItem | undefined) => { if (selection === DialogResponses.INSTALL_PYTHON) { const okAction = () => { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_DOWNLOAD_PYTHON ); open(CONSTANTS.LINKS.DOWNLOAD_PYTHON); }; showPrivacyModal( okAction, CONSTANTS.INFO.THIRD_PARTY_WEBSITE_PYTHON ); } }); // no python installed, cannot get path return ""; } else { // "python" didn't resolve to anything, trying "python3" return this.getCurrentPythonExecutablePath(true); } } if ( !(await this.validatePythonVersion( originalPythonExecutablePath )) ) { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_INVALID_PYTHON_VER ); if (isTryingPython3) { // if we're trying python3, it means we already tried python and it // all doesn't seem to work, but it got this far, so it means that // their system python3 version is still not above 3.7, but they // don't have a path selected. vscode.window .showInformationMessage( CONSTANTS.ERROR.INVALID_PYTHON_PATH, DialogResponses.INSTALL_PYTHON ) .then( (installChoice: vscode.MessageItem | undefined) => { if ( installChoice === DialogResponses.INSTALL_PYTHON ) { const okAction = () => { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_DOWNLOAD_PYTHON ); open(CONSTANTS.LINKS.DOWNLOAD_PYTHON); }; showPrivacyModal( okAction, CONSTANTS.INFO .THIRD_PARTY_WEBSITE_PYTHON ); } } ); return ""; } else { // otherwise, we ran the "python" system variable // and we can try python3 return this.getCurrentPythonExecutablePath(true); } } } else { // should only be applicable if the user defined their own path // fix path to be absolute if (!path.isAbsolute(originalPythonExecutablePath)) { originalPythonExecutablePath = path.join( vscode.workspace.rootPath, originalPythonExecutablePath ); } if (!fs.existsSync(originalPythonExecutablePath)) { await vscode.window.showErrorMessage( CONSTANTS.ERROR.BAD_PYTHON_PATH ); this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_INVALID_PYTHON_INTERPRETER_PATH ); return ""; } if ( !(await this.validatePythonVersion( originalPythonExecutablePath )) ) { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_INVALID_PYTHON_VER ); vscode.window .showInformationMessage( CONSTANTS.ERROR.INVALID_PYTHON_PATH, DialogResponses.INSTALL_PYTHON ) .then((installChoice: vscode.MessageItem | undefined) => { if (installChoice === DialogResponses.INSTALL_PYTHON) { const okAction = () => { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_DOWNLOAD_PYTHON ); open(CONSTANTS.LINKS.DOWNLOAD_PYTHON); }; showPrivacyModal( okAction, CONSTANTS.INFO.THIRD_PARTY_WEBSITE_PYTHON ); } }); return ""; } } return originalPythonExecutablePath; }; public isPipInstalled = async (pythonExecutablePath: string) => { try { await this.executePythonCommand(pythonExecutablePath, " -m pip"); return true; } catch (err) { vscode.window .showErrorMessage( `We found that you may not have Pip installed on your interpreter at ${pythonExecutablePath}, please install it and try again.`, DialogResponses.INSTALL_PIP ) .then((selection: vscode.MessageItem | undefined) => { if (selection === DialogResponses.INSTALL_PIP) { const okAction = () => { open(CONSTANTS.LINKS.DOWNLOAD_PIP); }; showPrivacyModal( okAction, CONSTANTS.INFO.THIRD_PARTY_WEBSITE_PIP ); } }); return false; } }; public checkIfVenv = async ( context: vscode.ExtensionContext, pythonExecutablePath: string ) => { const venvCheckerPath: string = getPathToScript( context, CONSTANTS.FILESYSTEM.OUTPUT_DIRECTORY, HELPER_FILES.CHECK_IF_VENV_PY ); const { stdout } = await this.executePythonCommand( pythonExecutablePath, `"${venvCheckerPath}"` ); return stdout.trim() === "1"; }; public executePythonCommand = async ( pythonExecutablePath: string, command: string ) => { return exec(`${createEscapedPath(pythonExecutablePath)} ${command}`); }; public validatePythonVersion = async (pythonExecutablePath: string) => { const { stdout } = await this.executePythonCommand( pythonExecutablePath, "--version" ); if (stdout < VERSIONS.MIN_PY_VERSION) { return false; } else { return true; } }; public hasVenv = async (context: vscode.ExtensionContext) => { const pathToEnv: string = getPathToScript( context, CONSTANTS.FILESYSTEM.PYTHON_VENV_DIR ); return fs.existsSync(pathToEnv); }; public promptInstallVenv = ( context: vscode.ExtensionContext, pythonExecutable: string, pythonExecutableName: string ) => { return vscode.window .showInformationMessage( CONSTANTS.INFO.INSTALL_PYTHON_VENV, DialogResponses.YES, DialogResponses.NO ) .then((selection: vscode.MessageItem | undefined) => { if (selection === DialogResponses.YES) { return this.installPythonVenv( context, pythonExecutable, pythonExecutableName ); } else { // return pythonExecutable, notifying the caller // that the user was unwilling to create venv // and by default, this will trigger the extension to // try using pythonExecutable return pythonExecutable; } }); }; public getPythonVenv = async ( context: vscode.ExtensionContext, pythonExecutableName: string ) => { const subFolder = os.platform() === "win32" ? "Scripts" : "bin"; return getPathToScript( context, path.join(CONSTANTS.FILESYSTEM.PYTHON_VENV_DIR, subFolder), pythonExecutableName ); }; public installPythonVenv = async ( context: vscode.ExtensionContext, pythonExecutable: string, pythonExecutableName: string ) => { const pathToEnv: string = getPathToScript( context, CONSTANTS.FILESYSTEM.PYTHON_VENV_DIR ); vscode.window.showInformationMessage( CONSTANTS.INFO.INSTALLING_PYTHON_VENV ); const pythonPath: string = await this.getPythonVenv( context, pythonExecutableName ); try { // make venv // run command to download dependencies to out/python_libs await this.executePythonCommand( pythonExecutable, `-m venv "${pathToEnv}"` ); } catch (err) { this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_VENV_CREATION_ERR ); vscode.window .showErrorMessage( `Virtual environment for download could not be completed. Using original interpreter at: ${pythonExecutable}. If you're on Linux, try running "sudo apt-get install python3-venv".`, DialogResponses.READ_INSTALL_MD ) .then((selection: vscode.MessageItem | undefined) => { if (selection === DialogResponses.READ_INSTALL_MD) { open(CONSTANTS.LINKS.INSTALL); } }); console.error(err); return pythonExecutable; } return this.installDependenciesWrapper( context, pythonPath, pythonExecutable ); }; public areDependenciesInstalled = async ( context: vscode.ExtensionContext, pythonPath: string ) => { const dependencyCheckerPath: string = getPathToScript( context, CONSTANTS.FILESYSTEM.OUTPUT_DIRECTORY, HELPER_FILES.CHECK_PYTHON_DEPENDENCIES ); try { // python script will throw exception // if not all dependencies are downloaded const { stdout } = await this.executePythonCommand( pythonPath, `"${dependencyCheckerPath}"` ); // output for debugging purposes console.info(stdout); return true; } catch (err) { return false; } }; public installDependencies = async ( context: vscode.ExtensionContext, pythonPath: string ) => { const requirementsPyInstallPath: string = getPathToScript( context, CONSTANTS.FILESYSTEM.OUTPUT_DIRECTORY, "install_dependencies.py" ); if (!this.isPipInstalled(pythonPath)) { this.telemetryAI.trackFeatureUsage(TelemetryEventName.SETUP_NO_PIP); return false; } try { const { stdout } = await this.executePythonCommand( pythonPath, `"${requirementsPyInstallPath}"` ); console.log(`DSE ${stdout}`); vscode.window.showInformationMessage( CONSTANTS.INFO.SUCCESSFUL_INSTALL ); return true; } catch (err) { console.log(`DSE ${err}`); return false; } }; public installDependenciesWrapper = async ( context: vscode.ExtensionContext, pythonPath: string, backupPythonPath: string = "" ) => { let errMessage = CONSTANTS.ERROR.DEPENDENCY_DOWNLOAD_ERROR; if (backupPythonPath !== "") { errMessage = `${errMessage} Using original interpreter at: ${backupPythonPath}.`; } if (!(await this.installDependencies(context, pythonPath))) { vscode.window .showErrorMessage( CONSTANTS.ERROR.DEPENDENCY_DOWNLOAD_ERROR, DialogResponses.READ_INSTALL_MD ) .then((selection: vscode.MessageItem | undefined) => { if (selection === DialogResponses.READ_INSTALL_MD) { open(CONSTANTS.LINKS.INSTALL); } }); this.telemetryAI.trackFeatureUsage( TelemetryEventName.SETUP_DEP_INSTALL_FAIL ); return backupPythonPath; } return pythonPath; }; }
the_stack
function main(workbook: ExcelScript.Workbook) { let HappyXmasTree = workbook.getWorksheet('HappyXmasTree') OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow FlashingStarandSmileFF0000(workbook) //red FlashingStarandSmileFFFF00(workbook) //yellow //FlashingStarandSmileFF0000(workbook) //red //FlashingStarandSmileFFFF00(workbook) //yellow //FlashingStarandSmileFF0000(workbook) //red //FlashingStarandSmileFFFF00(workbook) //yellow //FlashingStarandSmileFF0000(workbook) //red //FlashingStarandSmileFFFF00(workbook) //yellow //FlashingStarandSmileFF0000(workbook) //red //FlashingStarandSmileFFFF00(workbook) //yellow //FlashingStarandSmileFF0000(workbook) //red //FlashingStarandSmileFFFF00(workbook) //yellow //FlashingStarandSmileFF0000(workbook) //red //FlashingStarandSmileFFFF00(workbook) //yellow OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow FlashingStarandSmileFF0000(workbook) //red FlashingStarandSmileFFFF00(workbook) //yellow Blink(workbook) OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow //Unblink(workbook) //Blink(workbook) OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow //Unblink(workbook) //Blink(workbook) OuterEdgeFF0000(workbook) //red OuterEdgeFFFF00(workbook) //yellow Unblink(workbook) //Blink(workbook) //Unblink(workbook) function Blink(workbook: ExcelScript.Workbook) { //blink let selectedSheet = workbook.getWorksheet('HappyXmasTree'); // Set fill color to C65911 for range HappyXmasTree!N16:Q17 selectedSheet.getRange("N16:Q17") .getFormat() .getFill() .setColor("C65911"); // Set fill color to C65911 for range HappyXmasTree!G16:J17 selectedSheet.getRange("G16:J17") .getFormat() .getFill() .setColor("C65911"); } function Unblink(workbook: ExcelScript.Workbook) { let selectedSheet = workbook.getWorksheet('HappyXmasTree'); // Set fill color to FFFFFF for range HappyXmasTree!N16:N17 selectedSheet.getRange("N16:N17") .getFormat() .getFill() .setColor("FFFFFF"); // Set fill color to FFFFFF for range HappyXmasTree!O16:Q16 selectedSheet.getRange("O16:Q16") .getFormat() .getFill() .setColor("FFFFFF"); // Set fill color to FFFFFF for range HappyXmasTree!G16:H17 selectedSheet.getRange("G16:H17") .getFormat() .getFill() .setColor("FFFFFF"); // Set fill color to FFFFFF for range HappyXmasTree!I16:J16 selectedSheet.getRange("I16:J16") .getFormat() .getFill() .setColor("FFFFFF"); // Set fill color to FFFFFF for range HappyXmasTree!P17:Q17 selectedSheet.getRange("P17:Q17") .getFormat() .getFill() .setColor("FFFFFF"); // Set fill color to FFFFFF for range HappyXmasTree!J17 selectedSheet.getRange("J17") .getFormat() .getFill() .setColor("FFFFFF"); } function FlashingStarandSmileFF0000(workbook: ExcelScript.Workbook) { //red let selectedSheet = workbook.getWorksheet('HappyXmasTree'); // Set fill color to FF0000 for range HappyXmasTree!L2:L6 selectedSheet.getRange("L2:L6") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range HappyXmasTree!K3:K5 selectedSheet.getRange("K3:K5") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range HappyXmasTree!M3:M5 selectedSheet.getRange("M3:M5") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range HappyXmasTree!N4 selectedSheet.getRange("N4") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range HappyXmasTree!J4 selectedSheet.getRange("J4") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to 000000 for range HappyXmasTree!O26 selectedSheet.getRange("O26") .getFormat() .getFill() .setColor("000000"); // Set fill color to 000000 for range HappyXmasTree!I26 selectedSheet.getRange("I26") .getFormat() .getFill() .setColor("000000") //black } function FlashingStarandSmileFFFF00(workbook: ExcelScript.Workbook) { //yellow let selectedSheet = workbook.getWorksheet('HappyXmasTree'); // Set fill color to FF0000 for range HappyXmasTree!L2:L6 selectedSheet.getRange("L2:L6") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FF0000 for range HappyXmasTree!K3:K5 selectedSheet.getRange("K3:K5") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FF0000 for range HappyXmasTree!M3:M5 selectedSheet.getRange("M3:M5") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FF0000 for range HappyXmasTree!N4 selectedSheet.getRange("N4") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FF0000 for range HappyXmasTree!J4 selectedSheet.getRange("J4") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to 000000 for range HappyXmasTree!O26 selectedSheet.getRange("O26") .getFormat() .getFill().clear //.setColor("000000"); // Set fill color to 000000 for range HappyXmasTree!I26 selectedSheet.getRange("I26") .getFormat() .getFill().clear //.setColor("000000") } //OuterEdgeClearFill() console.log('Routine finished') } function OuterEdgeFFFF00(workbook: ExcelScript.Workbook) { // Set fill color to FFFF00 for range sheet!Q11 let sheet = workbook.getWorksheet('HappyXmasTree') sheet.getRange("Q11") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!G11 sheet.getRange("G11") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!R12 sheet.getRange("R12") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!F12 sheet.getRange("F12") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!S13 sheet.getRange("S13") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!E13 sheet.getRange("E13") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!T14 sheet.getRange("T14") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!D14 sheet.getRange("D14") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!C15 sheet.getRange("C15") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!U15 sheet.getRange("U15") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!T16:T17 sheet.getRange("T16:T17") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!D16:D17 sheet.getRange("D16:D17") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!C18 sheet.getRange("C18") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!U18 sheet.getRange("U18") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!T19 sheet.getRange("T19") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!D19 sheet.getRange("D19") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!L2:L6 sheet.getRange("L2:L6") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!C21 sheet.getRange("C21") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!U21 sheet.getRange("U21") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!C23 sheet.getRange("C23") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!U23 sheet.getRange("U23") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!C25 sheet.getRange("C25") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!U25 sheet.getRange("U25") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!C27 sheet.getRange("C27") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!U27 sheet.getRange("U27") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!C29 sheet.getRange("C29") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!U29 sheet.getRange("U29") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!T30 sheet.getRange("T30") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!D30 sheet.getRange("D30") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!K3:K5 sheet.getRange("K3:K5") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!M3:M5 sheet.getRange("M3:M5") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!S31 sheet.getRange("S31") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!E31 sheet.getRange("E31") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!R32 sheet.getRange("R32") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!F32 sheet.getRange("F32") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!Q33 sheet.getRange("Q33") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!G33 sheet.getRange("G33") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!P34 sheet.getRange("P34") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!H34 sheet.getRange("H34") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!O35 sheet.getRange("O35") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!I35 sheet.getRange("I35") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!N36:N37 sheet.getRange("N36:N37") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!J36:J37 sheet.getRange("J36:J37") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!K37:M37 sheet.getRange("K37:M37") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!N4 sheet.getRange("N4") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!J4 sheet.getRange("J4") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!K7 sheet.getRange("K7") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!M7 sheet.getRange("M7") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!N8 sheet.getRange("N8") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!J8 sheet.getRange("J8") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!O9 sheet.getRange("O9") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!I9 sheet.getRange("I9") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!P10 sheet.getRange("P10") .getFormat() .getFill() .setColor("FFFF00"); // Set fill color to FFFF00 for range sheet!H10 sheet.getRange("H10") .getFormat() .getFill() .setColor("FFFF00"); } function OuterEdgeFF0000(workbook: ExcelScript.Workbook) { // Set fill color to FFFF00 for range sheet!Q11 let sheet = workbook.getWorksheet('HappyXmasTree') sheet.getRange("Q11") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!G11 sheet.getRange("G11") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!R12 sheet.getRange("R12") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!F12 sheet.getRange("F12") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!S13 sheet.getRange("S13") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!E13 sheet.getRange("E13") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!T14 sheet.getRange("T14") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!D14 sheet.getRange("D14") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!C15 sheet.getRange("C15") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!U15 sheet.getRange("U15") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!T16:T17 sheet.getRange("T16:T17") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!D16:D17 sheet.getRange("D16:D17") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!C18 sheet.getRange("C18") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!U18 sheet.getRange("U18") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!T19 sheet.getRange("T19") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!D19 sheet.getRange("D19") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!L2:L6 sheet.getRange("L2:L6") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!C21 sheet.getRange("C21") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!U21 sheet.getRange("U21") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!C23 sheet.getRange("C23") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!U23 sheet.getRange("U23") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!C25 sheet.getRange("C25") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!U25 sheet.getRange("U25") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!C27 sheet.getRange("C27") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!U27 sheet.getRange("U27") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!C29 sheet.getRange("C29") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!U29 sheet.getRange("U29") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!T30 sheet.getRange("T30") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!D30 sheet.getRange("D30") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!K3:K5 sheet.getRange("K3:K5") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!M3:M5 sheet.getRange("M3:M5") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!S31 sheet.getRange("S31") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!E31 sheet.getRange("E31") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!R32 sheet.getRange("R32") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!F32 sheet.getRange("F32") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!Q33 sheet.getRange("Q33") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!G33 sheet.getRange("G33") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!P34 sheet.getRange("P34") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!H34 sheet.getRange("H34") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!O35 sheet.getRange("O35") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!I35 sheet.getRange("I35") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!N36:N37 sheet.getRange("N36:N37") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!J36:J37 sheet.getRange("J36:J37") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!K37:M37 sheet.getRange("K37:M37") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!N4 sheet.getRange("N4") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!J4 sheet.getRange("J4") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!K7 sheet.getRange("K7") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!M7 sheet.getRange("M7") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!N8 sheet.getRange("N8") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!J8 sheet.getRange("J8") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!O9 sheet.getRange("O9") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!I9 sheet.getRange("I9") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!P10 sheet.getRange("P10") .getFormat() .getFill() .setColor("FF0000"); // Set fill color to FF0000 for range sheet!H10 sheet.getRange("H10") .getFormat() .getFill() .setColor("FF0000"); }
the_stack
import { contrastRatio, parseColor } from "@microsoft/fast-colors"; import { accentFill as accentFillAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/accent-fill"; import { accentForeground as accentForegroundAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/accent-foreground"; import { foregroundOnAccent as foregroundOnAccentAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/foreground-on-accent"; import { neutralFill as neutralFillAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-fill"; import { neutralFillLayer as neutralFillLayerAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-fill-layer"; import { neutralFillInput as neutralFillInputAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-fill-input"; import { neutralFillStealth as neutralFillStealthAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-fill-stealth"; import { neutralFillContrast as neutralFillContrastAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-fill-contrast"; import { focusStrokeInner as focusStrokeInnerAlgorithm, focusStrokeOuter as focusStrokeOuterAlgorithm, } from "@microsoft/fast-components/dist/esm/color/recipes/focus-stroke"; import { neutralForeground as neutralForegroundAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-foreground"; import { neutralForegroundHint as neutralForegroundHintAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-foreground-hint"; import { neutralLayerCardContainer as neutralLayerCardContainerAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-layer-card-container"; import { neutralLayerFloating as neutralLayerFloatingAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-layer-floating"; import { neutralLayer1 as neutralLayer1Algorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-layer-1"; import { neutralLayer2 as neutralLayer2Algorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-layer-2"; import { neutralLayer3 as neutralLayer3Algorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-layer-3"; import { neutralLayer4 as neutralLayer4Algorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-layer-4"; import { neutralStroke as neutralStrokeAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-stroke"; import { neutralStrokeDivider as neutralStrokeDividerAlgorithm } from "@microsoft/fast-components/dist/esm/color/recipes/neutral-stroke-divider"; import { ColorsDesignSystem, swatchToSwatchRGB } from "./design-system"; export type Swatch = string; export type DesignSystemResolver<T, Y = ColorsDesignSystem> = (d: Y) => T; export type SwatchResolver = DesignSystemResolver<Swatch>; /** * A function type that resolves a Swatch from a SwatchResolver * and applies it to the backgroundColor property of the design system * of the returned DesignSystemResolver * @internal */ export type DesignSystemResolverFromSwatchResolver<T> = ( resolver: SwatchResolver ) => DesignSystemResolver<T>; /** * A function type that resolves a Swatch from a string literal * and applies it to the backgroundColor property of the design system * of the returned DesignSystemResolver */ export type DesignSystemResolverFromSwatch<T> = ( colorLiteral: string ) => DesignSystemResolver<T>; /** * The states that a swatch can have * @internal */ export enum SwatchFamilyType { rest = "rest", hover = "hover", active = "active", focus = "focus", } /** * A function that resolves a color when provided a design system * or resolves a ColorRecipe when provided a SwatchResolver */ export type ColorRecipe<T> = DesignSystemResolver<T> & DesignSystemResolverFromSwatchResolver<T> & DesignSystemResolverFromSwatch<T>; export type SwatchRecipe = ColorRecipe<Swatch>; // This file exists as an interop between the new color recipes and the legacy design system support. // TODO: Migrate the Color Explorer to web components. You get to celebrate by deleting this file! :D const accentFill = (d?: ColorsDesignSystem): any => { return accentFillAlgorithm( d?.accentPaletteRGB, d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), foregroundOnAccentAlgorithm(swatchToSwatchRGB(d?.backgroundColor as string), 4.5), 4.5, d?.accentFillHoverDelta, d?.accentFillActiveDelta, d?.accentFillFocusDelta, 0, d?.neutralFillRestDelta, d?.neutralFillHoverDelta, d?.neutralFillActiveDelta ); }; export const accentFillRest = (d?: ColorsDesignSystem): string => { return accentFill(d).rest.toColorString().toUpperCase(); }; export const accentFillHover = (d?: ColorsDesignSystem): string => { return accentFill(d).hover.toColorString().toUpperCase(); }; export const accentFillActive = (d?: ColorsDesignSystem): string => { return accentFill(d).active.toColorString().toUpperCase(); }; export const accentFillFocus = (d?: ColorsDesignSystem): string => { return accentFill(d).focus.toColorString().toUpperCase(); }; const accentForeground = (d?: ColorsDesignSystem): any => { return accentForegroundAlgorithm( d?.accentPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), 4.5, d?.accentForegroundRestDelta, d?.accentForegroundHoverDelta, d?.accentForegroundActiveDelta, d?.accentForegroundFocusDelta ); }; export const accentForegroundRest = (d?: ColorsDesignSystem): string => { return accentForeground(d).rest.toColorString().toUpperCase(); }; export const accentForegroundHover = (d?: ColorsDesignSystem): string => { return accentForeground(d).hover.toColorString().toUpperCase(); }; export const accentForegroundActive = (d?: ColorsDesignSystem): string => { return accentForeground(d).active.toColorString().toUpperCase(); }; export const accentForegroundFocus = (d?: ColorsDesignSystem): string => { return accentForeground(d).focus.toColorString().toUpperCase(); }; export const foregroundOnAccent = (d?: ColorsDesignSystem): string => { return foregroundOnAccentAlgorithm(swatchToSwatchRGB(accentFillHover(d)), 4.5) .toColorString() .toUpperCase(); }; export const neutralStrokeDividerRest = (d?: ColorsDesignSystem): string => { return neutralStrokeDividerAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), d?.neutralStrokeDividerRestDelta ) .toColorString() .toUpperCase(); }; const neutralFill = (d?: ColorsDesignSystem): any => { return neutralFillAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), d?.neutralFillRestDelta, d?.neutralFillHoverDelta, d?.neutralFillActiveDelta, d?.neutralFillFocusDelta, 0 ); }; export const neutralFillRest = (d?: ColorsDesignSystem): string => { return neutralFill(d).rest.toColorString().toUpperCase(); }; export const neutralFillHover = (d?: ColorsDesignSystem): string => { return neutralFill(d).hover.toColorString().toUpperCase(); }; export const neutralFillActive = (d?: ColorsDesignSystem): string => { return neutralFill(d).active.toColorString().toUpperCase(); }; export const neutralFillFocus = (d?: ColorsDesignSystem): string => { return neutralFill(d).focus.toColorString().toUpperCase(); }; export const neutralFillLayerRest = (d?: ColorsDesignSystem): string => { return neutralFillLayerAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), d?.neutralFillLayerDelta ) .toColorString() .toUpperCase(); }; const neutralFillInput = (d?: ColorsDesignSystem): any => { return neutralFillInputAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), d?.neutralFillInputRestDelta, d?.neutralFillInputHoverDelta, d?.neutralFillInputActiveDelta, d?.neutralFillInputFocusDelta, 0 ); }; export const neutralFillInputRest = (d?: ColorsDesignSystem): string => { return neutralFillInput(d).rest.toColorString().toUpperCase(); }; export const neutralFillInputHover = (d?: ColorsDesignSystem): string => { return neutralFillInput(d).hover.toColorString().toUpperCase(); }; export const neutralFillInputActive = (d?: ColorsDesignSystem): string => { return neutralFillInput(d).active.toColorString().toUpperCase(); }; export const neutralFillInputFocus = (d?: ColorsDesignSystem): string => { return neutralFillInput(d).focus.toColorString().toUpperCase(); }; const neutralFillStealth = (d?: ColorsDesignSystem): any => { return neutralFillStealthAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), d?.neutralFillStealthRestDelta, d?.neutralFillStealthHoverDelta, d?.neutralFillStealthActiveDelta, d?.neutralFillStealthFocusDelta, 0 ); }; export const neutralFillStealthRest = (d?: ColorsDesignSystem): string => { return neutralFillStealth(d).rest.toColorString().toUpperCase(); }; export const neutralFillStealthHover = (d?: ColorsDesignSystem): string => { return neutralFillStealth(d).hover.toColorString().toUpperCase(); }; export const neutralFillStealthActive = (d?: ColorsDesignSystem): string => { return neutralFillStealth(d).active.toColorString().toUpperCase(); }; export const neutralFillStealthFocus = (d?: ColorsDesignSystem): string => { return neutralFillStealth(d).focus.toColorString().toUpperCase(); }; const neutralFillStrong = (d?: ColorsDesignSystem): any => { return neutralFillContrastAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), 0, d?.neutralFillStrongHoverDelta, d?.neutralFillStrongActiveDelta, d?.neutralFillStrongFocusDelta ); }; export const neutralFillStrongRest = (d?: ColorsDesignSystem): string => { return neutralFillStrong(d).rest.toColorString().toUpperCase(); }; export const neutralFillStrongHover = (d?: ColorsDesignSystem): string => { return neutralFillStrong(d).hover.toColorString().toUpperCase(); }; export const neutralFillStrongActive = (d?: ColorsDesignSystem): string => { return neutralFillStrong(d).active.toColorString().toUpperCase(); }; export const neutralFillStrongFocus = (d?: ColorsDesignSystem): string => { return neutralFillStrong(d).focus.toColorString().toUpperCase(); }; export const focusStrokeOuter = (d?: ColorsDesignSystem): string => { return focusStrokeOuterAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string) ) .toColorString() .toUpperCase(); }; export const focusStrokeInner = (d?: ColorsDesignSystem): string => { return focusStrokeInnerAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), focusStrokeOuterAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string) ) ) .toColorString() .toUpperCase(); }; export const neutralForegroundHint = (d?: ColorsDesignSystem): string => { return neutralForegroundHintAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string) ) .toColorString() .toUpperCase(); }; export const neutralForegroundRest = (d?: ColorsDesignSystem): string => { return neutralForegroundAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string) ) .toColorString() .toUpperCase(); }; const neutralStroke = (d?: ColorsDesignSystem): any => { return neutralStrokeAlgorithm( d?.neutralPaletteRGB, swatchToSwatchRGB(d?.backgroundColor as string), d?.neutralStrokeRestDelta, d?.neutralStrokeHoverDelta, d?.neutralStrokeActiveDelta, d?.neutralStrokeFocusDelta ); }; export const neutralStrokeRest = (d?: ColorsDesignSystem): string => { return neutralStroke(d).rest.toColorString().toUpperCase(); }; export const neutralStrokeHover = (d?: ColorsDesignSystem): string => { return neutralStroke(d).hover.toColorString().toUpperCase(); }; export const neutralStrokeActive = (d?: ColorsDesignSystem): string => { return neutralStroke(d).active.toColorString().toUpperCase(); }; export const neutralStrokeFocus = (d?: ColorsDesignSystem): string => { return neutralStroke(d).focus.toColorString().toUpperCase(); }; export const neutralLayerCardContainer = (d?: ColorsDesignSystem): string => { return neutralLayerCardContainerAlgorithm( d?.neutralPaletteRGB, d?.baseLayerLuminance, d?.neutralFillLayerDelta ) .toColorString() .toUpperCase(); }; export const neutralLayerFloating = (d?: ColorsDesignSystem): string => { return neutralLayerFloatingAlgorithm( d?.neutralPaletteRGB, d?.baseLayerLuminance, d?.neutralFillLayerDelta ) .toColorString() .toUpperCase(); }; export const neutralLayer1 = (d?: ColorsDesignSystem): string => { return neutralLayer1Algorithm(d?.neutralPaletteRGB, d?.baseLayerLuminance) .toColorString() .toUpperCase(); }; export const neutralLayer2 = (d?: ColorsDesignSystem): string => { return neutralLayer2Algorithm( d?.neutralPaletteRGB, d?.baseLayerLuminance, d?.neutralFillLayerDelta, d?.neutralFillRestDelta, d?.neutralFillHoverDelta, d?.neutralFillActiveDelta ) .toColorString() .toUpperCase(); }; export const neutralLayer3 = (d?: ColorsDesignSystem): string => { return neutralLayer3Algorithm( d?.neutralPaletteRGB, d?.baseLayerLuminance, d?.neutralFillLayerDelta, d?.neutralFillRestDelta, d?.neutralFillHoverDelta, d?.neutralFillActiveDelta ) .toColorString() .toUpperCase(); }; export const neutralLayer4 = (d?: ColorsDesignSystem): string => { return neutralLayer4Algorithm( d?.neutralPaletteRGB, d?.baseLayerLuminance, d?.neutralFillLayerDelta, d?.neutralFillRestDelta, d?.neutralFillHoverDelta, d?.neutralFillActiveDelta ) .toColorString() .toUpperCase(); }; export function backgroundColor(d?: ColorsDesignSystem): string { return d?.backgroundColor || "#FFFFFF"; } /** * Returns the contrast value between two color strings. * Supports #RRGGBB and rgb(r, g, b) formats. * @internal */ export function contrast(a: string, b: string): number { /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ return contrastRatio(parseColor(a)!, parseColor(b)!); }
the_stack
import { message } from "antd"; import axios, { CancelTokenSource } from "axios"; import BaseEntity from "../base/BaseEntity"; import Filter from "../base/filter/Filter"; import HttpUtil from "../../util/HttpUtil"; import FileUtil from "../../util/FileUtil"; import ImageUtil from "../../util/ImageUtil"; import EnvUtil from "../../util/EnvUtil"; import InputFilter from "../base/filter/InputFilter"; import CheckFilter from "../base/filter/CheckFilter"; import SortFilter from "../base/filter/SortFilter"; import MimeUtil from "../../util/MimeUtil"; import StringUtil from "../../util/StringUtil"; import NumberUtil from "../../util/NumberUtil"; import SafeUtil from "../../util/SafeUtil"; import ImagePreviewer from "../../../pages/widget/previewer/ImagePreviewer"; import MessageBoxUtil from "../../util/MessageBoxUtil"; import PreviewerHelper from "../../../pages/widget/previewer/PreviewerHelper"; export default class Matter extends BaseEntity { puuid: string = ""; userUuid: string = ""; dir: boolean = false; alien: boolean = false; name: string = ""; md5: string | null = null; size: number = 0; privacy: boolean = true; path: string | null = null; times: number = 0; //上次访问时间 visitTime: Date | null = null; parent: Matter | null = null; // 文件是否被软删除 deleted: boolean = false; deleteTime: Date | null = null; /* 这部分是辅助UI的字段信息 */ //作为勾选变量 check: boolean = false; editMode: boolean = false; //允许用户选择的文件类型 filter: string = "*"; //本地字段 //给用户的提示文字 uploadHint: string | null = null; //浏览器中选择好的原生file,未作任何处理。 file: File | null = null; //当前上传进度的数值 0-1之间 progress: number = 0; //实时上传速度 byte/s speed: number = 0; //取消上传source cancelSource: CancelTokenSource = axios.CancelToken.source(); static URL_MATTER_CREATE_DIRECTORY = "/api/matter/create/directory"; static URL_MATTER_SOFT_DELETE = "/api/matter/soft/delete"; static URL_MATTER_SOFT_DELETE_BATCH = "/api/matter/soft/delete/batch"; static URL_MATTER_RECOVERY = "/api/matter/recovery"; static URL_MATTER_RECOVERY_BATCH = "/api/matter/recovery/batch"; static URL_MATTER_DELETE = "/api/matter/delete"; static URL_MATTER_DELETE_BATCH = "/api/matter/delete/batch"; static URL_MATTER_RENAME = "/api/matter/rename"; static URL_CHANGE_PRIVACY = "/api/matter/change/privacy"; static URL_MATTER_MOVE = "/api/matter/move"; static URL_MATTER_DOWNLOAD = "/api/matter/download"; static URL_MATTER_UPLOAD = "/api/matter/upload"; static URL_MATTER_ZIP = "/api/matter/zip"; static MATTER_ROOT = "root"; //下载zip包 static downloadZip(uuidsString: string) { window.open( EnvUtil.currentHost() + Matter.URL_MATTER_ZIP + "?uuids=" + uuidsString ); } constructor(reactComponent?: React.Component) { super(reactComponent); } assign(obj: any) { super.assign(obj); this.assignEntity("parent", Matter); this.assignEntity("visitTime", Date); this.assignEntity("deleteTime", Date); } getForm(): any { return { userUuid: this.userUuid, puuid: this.puuid, uuid: this.uuid ? this.uuid : null, dir: this.dir, alien: this.alien, name: this.name, md5: this.md5, size: this.size, privacy: this.privacy, path: this.path, times: this.times, parent: this.parent, }; } getFilters(): Filter[] { return [ ...super.getFilters(), new InputFilter("父级菜单uuid", "puuid", null, false), new InputFilter("用户", "userUuid", null, false), new InputFilter("关键字", "name"), new CheckFilter("文件夹", "dir"), new CheckFilter("应用数据", "alien"), new CheckFilter("删除", "deleted"), new SortFilter("文件夹", "orderDir"), new SortFilter("下载次数", "orderTimes"), new SortFilter("大小", "orderSize"), new SortFilter("名称", "orderName"), new InputFilter("后缀名", "extensions"), new InputFilter("分享uuid", "shareUuid"), new InputFilter("提取码", "shareCode"), new InputFilter("分享根目录", "shareRootUuid"), new SortFilter("删除时间排序", "orderDeleteTime"), ]; } getUrlPrefix() { return "/api/matter"; } isImage() { return FileUtil.isImage(this.name); } isPdf() { return FileUtil.isPdf(this.name); } isText() { return FileUtil.isText(this.name); } isDoc() { return FileUtil.isDoc(this.name); } isPpt() { return FileUtil.isPpt(this.name); } isXls() { return FileUtil.isXls(this.name); } isAudio() { return FileUtil.isAudio(this.name); } isVideo() { return FileUtil.isVideo(this.name); } isPsd() { return FileUtil.isPsd(this.name); } getIcon() { if (FileUtil.isImage(this.name)) { return ImageUtil.handleImageUrl(this.getPreviewUrl(), false, 100, 100); } else { return FileUtil.getIcon(this.name, this.dir); } } //下载文件 download(downloadUrl?: string | null) { if (!downloadUrl) { downloadUrl = this.getDownloadUrl(); } window.open(downloadUrl); } //预览文件 在分享的预览中才主动传入previewUrl. preview(previewUrl?: string | null) { let shareMode = true; if (previewUrl) { shareMode = true; } else { shareMode = false; previewUrl = this.getPreviewUrl(); } if (this.isImage()) { ImagePreviewer.showSinglePhoto(previewUrl); } else { if (shareMode) { PreviewerHelper.preview(this, previewUrl); } else { PreviewerHelper.preview(this); } } } httpCreateDirectory( successCallback?: any, errorCallback?: any, finallyCallback?: any ) { let that = this; let form = { userUuid: that.userUuid, name: that.name, puuid: that.puuid }; return this.httpPost( Matter.URL_MATTER_CREATE_DIRECTORY, form, function (response: any) { that.assign(response.data.data); typeof successCallback === "function" && successCallback(response); }, errorCallback, finallyCallback ); } httpSoftDelete(successCallback?: any, errorCallback?: any) { this.httpPost( Matter.URL_MATTER_SOFT_DELETE, { uuid: this.uuid }, function (response: any) { typeof successCallback === "function" && successCallback(response); }, errorCallback ); } httpSoftDeleteBatch( uuids: string, successCallback?: any, errorCallback?: any ) { this.httpPost( Matter.URL_MATTER_SOFT_DELETE_BATCH, { uuids: uuids }, function (response: any) { typeof successCallback === "function" && successCallback(response); }, errorCallback ); } httpDelete(successCallback?: any, errorCallback?: any) { this.httpPost( Matter.URL_MATTER_DELETE, { uuid: this.uuid }, function (response: any) { typeof successCallback === "function" && successCallback(response); }, errorCallback ); } httpDeleteBatch(uuids: string, successCallback?: any, errorCallback?: any) { this.httpPost( Matter.URL_MATTER_DELETE_BATCH, { uuids: uuids }, function (response: any) { typeof successCallback === "function" && successCallback(response); }, errorCallback ); } httpRecovery(successCallback?: any, errorCallback?: any) { this.httpPost( Matter.URL_MATTER_RECOVERY, { uuid: this.uuid }, function (response: any) { typeof successCallback === "function" && successCallback(response); }, errorCallback ); } httpRecoveryBatch(uuids: string, successCallback?: any, errorCallback?: any) { this.httpPost( Matter.URL_MATTER_RECOVERY_BATCH, { uuids: uuids }, function (response: any) { typeof successCallback === "function" && successCallback(response); }, errorCallback ); } httpRename( name: string, successCallback?: any, errorCallback?: any, finallyCallback?: any ) { let that = this; this.httpPost( Matter.URL_MATTER_RENAME, { uuid: this.uuid, name: name }, function (response: any) { that.assign(response.data.data); typeof successCallback === "function" && successCallback(response); }, errorCallback, finallyCallback ); } httpChangePrivacy( privacy: boolean, successCallback?: any, errorCallback?: any ) { let that = this; this.httpPost( Matter.URL_CHANGE_PRIVACY, { uuid: this.uuid, privacy: privacy }, function (response: any) { that.privacy = privacy; if (typeof successCallback === "function") { successCallback(response); message.success(response.data.msg); } else { message.success(response.data.msg); } }, errorCallback ); } httpMove( srcUuids: string, destUuid: string, successCallback?: any, errorCallback?: any ) { let form: any = { srcUuids: srcUuids }; if (destUuid) { form.destUuid = destUuid; } else { form.destUuid = "root"; } this.httpPost( Matter.URL_MATTER_MOVE, form, function (response: any) { typeof successCallback === "function" && successCallback(response); }, errorCallback ); } /* 以下是和上传相关的内容。 */ //从file中装填metaData validate() { if (!this.file) { this.errorMessage = "请选择上传文件"; return false; } this.name = this.file.name; if (!this.name) { this.errorMessage = "请选择上传文件"; return false; } this.size = this.file.size; this.errorMessage = null; return true; } //验证过滤器有没有误填写,这个方法主要给开发者使用。 validateFilter() { let filter = this.filter; if (filter === null || filter === "") { this.errorMessage = "过滤器设置错误,请检查-1"; console.error("过滤器设置错误,请检查.-1"); return false; } if (filter !== "*") { let regex1 = /^(image|audio|video|text)(\|(image|audio|video|text))*$/g; let regex2 = /^(\.[\w]+)(\|\.[\w]+)*$/; // 测试几种特殊类型 image|audio|video|text if (!regex1.test(filter)) { //测试后缀名 if (!regex2.test(filter)) { this.errorMessage = "过滤器设置错误,请检查-2"; console.error("过滤器设置错误,请检查.-2"); return false; } } } //validate privacy let privacy = this.privacy; if (!privacy) { if (privacy !== false) { this.errorMessage = "privacy属性为Boolean类型"; console.error("privacy属性为Boolean类型."); return false; } } return true; } //验证用户上传的文件是否符合过滤器 validateFileType() { if (!this.filter) { this.errorMessage = "该过滤条件有问题"; return false; } if (this.filter === "*") { this.errorMessage = null; return true; } let type = MimeUtil.getMimeType(this.name); let extension = MimeUtil.getExtension(this.name); let simpleType = type.substring(0, type.indexOf("/")); //专门解决android微信浏览器中名字乱命名的bug. if (StringUtil.startWith(this.name, "image%3A")) { extension = "jpg"; simpleType = "image"; } else if (StringUtil.startWith(this.name, "video%3A")) { extension = "mp4"; simpleType = "video"; } else if (StringUtil.startWith(this.name, "audio%3A")) { extension = "mp3"; simpleType = "audio"; } if (StringUtil.containStr(this.filter, extension)) { this.errorMessage = null; return true; } if (simpleType) { if (StringUtil.containStr(this.filter, simpleType)) { this.errorMessage = null; return true; } } this.errorMessage = "您上传的文件格式不符合要求"; return false; } //文件上传 httpUpload(successCallback?: any, failureCallback?: any) { let that = this; //验证是否装填好 if (!this.validate()) { return; } //验证用户填写的过滤条件是否正确 if (!this.validateFilter()) { return; } //验证是否满足过滤器 if (!this.validateFileType()) { MessageBoxUtil.error("文件类型不满足,请重试"); return; } //(兼容性:chrome,ff,IE9及以上) let formData = new FormData(); formData.append("userUuid", that.userUuid); formData.append("puuid", that.puuid); formData.append("file", that.file!); formData.append("alien", that.alien.toString()); formData.append("privacy", that.privacy.toString()); //闭包 let lastTimeStamp = new Date().getTime(); let lastSize = 0; that.loading = true; HttpUtil.httpPostFile( Matter.URL_MATTER_UPLOAD, formData, function (response: any) { that.uuid = response.data.data.uuid; SafeUtil.safeCallback(successCallback)(response); }, function (err: any) { if (axios.isCancel(err)) { that.clear(); SafeUtil.safeCallback(failureCallback)(); return; } const response = err.response; that.errorMessage = response; that.clear(); that.defaultErrorHandler(response); SafeUtil.safeCallback(failureCallback)(that.getErrorMessage(response)); }, function () { that.loading = false; }, function (event) { //上传进度。 that.progress = event.loaded / event.total; let currentTime = new Date().getTime(); let deltaTime = currentTime - lastTimeStamp; //每1s计算一次速度 if (deltaTime > 1000) { lastTimeStamp = currentTime; let currentSize = event.loaded; let deltaSize = currentSize - lastSize; lastSize = currentSize; that.speed = NumberUtil.parseInt( (deltaSize / (deltaTime / 1000)).toFixed(0) ); } that.updateUI(); }, { cancelToken: that.cancelSource.token, } ); } cancelUpload() { this.cancelSource.cancel(); } //清除文件 clear() { //filter,privacy不变 let matter = new Matter(); matter.filter = this.filter; matter.privacy = this.privacy; matter.errorMessage = this.errorMessage; matter.uploadHint = this.uploadHint; this.assign(matter); } getPreviewUrl(downloadTokenUuid?: string): string { return `${EnvUtil.currentHost()}/api/alien/preview/${this.uuid}/${ this.name }${downloadTokenUuid ? "?downloadTokenUuid=" + downloadTokenUuid : ""}`; } getDownloadUrl(downloadTokenUuid?: string): string { return `${EnvUtil.currentHost()}/api/alien/download/${this.uuid}/${ this.name }${downloadTokenUuid ? "?downloadTokenUuid=" + downloadTokenUuid : ""}`; } getShareDownloadUrl( shareUuid: string, shareCode: string, shareRootUuid: string ): string { return `${EnvUtil.currentHost()}/api/alien/download/${this.uuid}/${ this.name }?shareUuid=${shareUuid}&shareCode=${shareCode}&shareRootUuid=${shareRootUuid}`; } getSharePreviewUrl( shareUuid: string, shareCode: string, shareRootUuid: string ): string { return `${EnvUtil.currentHost()}/api/alien/preview/${this.uuid}/${ this.name }?shareUuid=${shareUuid}&shareCode=${shareCode}&shareRootUuid=${shareRootUuid}`; } }
the_stack
import React, { useState } from 'react'; import { View, StyleSheet, Text, TouchableOpacity, TouchableWithoutFeedback, } from 'react-native'; import { BlurView } from '@react-native-community/blur'; import { DEVICE_LARGE } from '@/utils/deviceConstants'; import { useDispatch, useSelector } from '@/store'; import { connection_levels } from '@/utils/constants'; import { ORANGE, BLACK, WHITE, GREEN, DARKER_GREY } from '@/theme/colors'; import { fontSize } from '@/theme/fonts'; import { types } from '@/utils/sorting'; import { setFilters, setConnectionsSort } from '@/actions'; import { StackScreenProps } from '@react-navigation/stack'; import Chevron from '../Icons/Chevron'; /** CONSTANTS */ const trustLevels = [ connection_levels.SUSPICIOUS, connection_levels.JUST_MET, connection_levels.ALREADY_KNOWN, connection_levels.RECOVERY, connection_levels.REPORTED, ]; const ascending = [ types.byNameAscending, types.byDateAddedAscending, types.byTrustLevelAscending, ]; const byName = [types.byNameDescending, types.byNameAscending]; const byDate = [types.byDateAddedDescending, types.byDateAddedAscending]; const byTrust = [types.byTrustLevelDescending, types.byTrustLevelAscending]; /** COMPONENT */ type props = StackScreenProps<ModalStackParamList, 'SortConnections'>; const SortConnectionsModal = ({ navigation }: props) => { const dispatch = useDispatch(); const filters = useSelector((state: State) => state.connections.filters); const connectionsSort = useSelector((state: State) => state.connections.connectionsSort) || types.byDateAddedDescending; const [newFilters, setNewFilters] = useState<ConnectionLevel[]>( filters || [], ); const [newConnectionsSort, setNewConnectionsSort] = useState(connectionsSort); const onSubmit = () => { dispatch(setFilters(newFilters)); dispatch(setConnectionsSort(newConnectionsSort)); navigation.goBack(); }; const renderFilterRadioBtn = (trustLevel: ConnectionLevel) => { // const active = btnReason === reason; const active = newFilters.includes(trustLevel); const updateFilters = () => { // start with a new filter array to prevent mutating state let updatedFilters = []; if (active) { // remove filter updatedFilters = newFilters.filter((filter) => filter !== trustLevel); } else { // add filter updatedFilters = newFilters.concat(trustLevel); } setNewFilters(updatedFilters); }; return ( <TouchableOpacity testID={`${trustLevel}-RadioBtn`} key={trustLevel} onPress={updateFilters} style={styles.radioButton} > <View style={styles.radioSquare}> {active && <View style={styles.radioInnerSquare} />} </View> <View style={styles.radioLabel}> <Text style={styles.radioLabelText}>{trustLevel}</Text> </View> </TouchableOpacity> ); }; return ( <View style={styles.container} testID="SortConnectionsModal"> <BlurView style={styles.blurView} blurType="dark" blurAmount={5} reducedTransparencyFallbackColor={BLACK} /> <TouchableWithoutFeedback onPress={() => { navigation.goBack(); }} > <View style={styles.blurView} /> </TouchableWithoutFeedback> <View style={styles.modalContainer}> <View style={styles.header}> <Text style={styles.headerText}>Sort By</Text> </View> <View style={styles.divider} /> <View style={styles.sortContainer}> <TouchableOpacity style={styles.sortButton} onPress={() => { // toggles sort method const sortMethod = byDate .filter((n) => n !== newConnectionsSort) .shift(); setNewConnectionsSort(sortMethod); }} > <Text style={[ styles.sortButtonText, byDate.includes(newConnectionsSort) ? styles.activeButtonText : {}, ]} > Date </Text> <Chevron width={16} height={16} strokeWidth={byDate.includes(newConnectionsSort) ? 3 : 1.5} color={byDate.includes(newConnectionsSort) ? ORANGE : BLACK} direction={ byDate.includes(newConnectionsSort) && ascending.includes(newConnectionsSort) ? 'up' : 'down' } /> </TouchableOpacity> <TouchableOpacity style={styles.sortButton} onPress={() => { const sortMethod = byName .filter((n) => n !== newConnectionsSort) .shift(); setNewConnectionsSort(sortMethod); }} > <Text style={[ styles.sortButtonText, byName.includes(newConnectionsSort) ? styles.activeButtonText : {}, ]} > Name </Text> <Chevron width={16} height={16} strokeWidth={byName.includes(newConnectionsSort) ? 3 : 1.5} color={byName.includes(newConnectionsSort) ? ORANGE : BLACK} direction={ byName.includes(newConnectionsSort) && ascending.includes(newConnectionsSort) ? 'up' : 'down' } /> </TouchableOpacity> <TouchableOpacity style={styles.sortButton} onPress={() => { const sortMethod = byTrust .filter((n) => n !== newConnectionsSort) .shift(); setNewConnectionsSort(sortMethod); }} > <Text style={[ styles.sortButtonText, byTrust.includes(newConnectionsSort) ? styles.activeButtonText : {}, ]} > Trust Level </Text> <Chevron width={16} height={16} strokeWidth={byTrust.includes(newConnectionsSort) ? 3 : 1.5} color={byTrust.includes(newConnectionsSort) ? ORANGE : BLACK} direction={ byTrust.includes(newConnectionsSort) && ascending.includes(newConnectionsSort) ? 'up' : 'down' } /> </TouchableOpacity> </View> <View style={styles.header}> <Text style={styles.headerText}>Filter By Trust Level</Text> </View> <View style={styles.divider} /> <View style={styles.radioButtonsContainer}> {trustLevels.map(renderFilterRadioBtn)} </View> <View style={styles.modalButtons}> <TouchableOpacity testID="SubmitReportBtn" style={[styles.modalButton, styles.submitButton]} onPress={onSubmit} > <Text style={styles.submitButtonText}>Submit</Text> </TouchableOpacity> </View> </View> </View> ); }; const styles = StyleSheet.create({ blurView: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, }, container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, modalContainer: { alignItems: 'center', justifyContent: 'center', backgroundColor: WHITE, width: '90%', borderRadius: 25, padding: DEVICE_LARGE ? 30 : 25, }, header: { // marginTop: 5, }, headerText: { fontFamily: 'Poppins-Bold', fontSize: fontSize[16], }, divider: { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: ORANGE, width: '105%', height: 1, marginTop: DEVICE_LARGE ? 10 : 8, marginBottom: DEVICE_LARGE ? 10 : 8, }, sortContainer: { flexDirection: 'row', width: '100%', justifyContent: 'space-evenly', marginBottom: DEVICE_LARGE ? 25 : 12, }, sortButton: { // borderWidth: 1, // borderLeftWidth: 1, minHeight: 36, borderRadius: 0, alignItems: 'center', justifyContent: 'center', flexDirection: 'row', flexGrow: 1, }, sortButtonText: { color: BLACK, fontFamily: 'Poppins-Regular', fontSize: fontSize[14], marginRight: DEVICE_LARGE ? 5 : 4, }, activeButtonText: { color: ORANGE, fontFamily: 'Poppins-Bold', }, radioButtonsContainer: { marginLeft: 10, marginBottom: 20, alignItems: 'flex-start', justifyContent: 'flex-start', width: '100%', }, radioButton: { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', marginTop: 4, marginBottom: 4, }, radioSquare: { height: 16, width: 16, borderRadius: 0.5, borderWidth: 3, borderColor: ORANGE, alignItems: 'center', // To center the checked circle… justifyContent: 'center', }, radioInnerSquare: { height: 7.5, width: 7.5, // borderRadius: 10, backgroundColor: ORANGE, }, radioLabel: { marginLeft: DEVICE_LARGE ? 12 : 10, marginRight: DEVICE_LARGE ? 12 : 10, }, radioLabelText: { fontFamily: 'Poppins-Medium', fontSize: fontSize[15], color: BLACK, textTransform: 'capitalize', }, modalButtons: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 10, }, modalButton: { flex: 1, paddingTop: 10, paddingBottom: 10, marginLeft: 10, marginRight: 10, alignItems: 'center', justifyContent: 'center', }, submitButton: { backgroundColor: GREEN, borderRadius: 50, borderColor: GREEN, borderWidth: 1, }, submitButtonText: { fontFamily: 'Poppins-Bold', fontSize: fontSize[15], color: BLACK, }, submitButtonDisabledText: { fontFamily: 'Poppins-Bold', fontSize: fontSize[15], color: DARKER_GREY, }, }); export default SortConnectionsModal;
the_stack
import * as c from "./constants"; import * as childProcess from "child_process"; import * as p from "vscode-languageserver-protocol"; import * as path from "path"; import * as t from "vscode-languageserver-types"; import { RequestMessage, ResponseMessage, } from "vscode-languageserver-protocol"; import fs from "fs"; import * as os from "os"; let tempFilePrefix = "rescript_format_file_" + process.pid + "_"; let tempFileId = 0; export let createFileInTempDir = (extension = "") => { let tempFileName = tempFilePrefix + tempFileId + extension; tempFileId = tempFileId + 1; return path.join(os.tmpdir(), tempFileName); }; // TODO: races here? // TODO: this doesn't handle file:/// scheme export let findProjectRootOfFile = ( source: p.DocumentUri ): null | p.DocumentUri => { let dir = path.dirname(source); if (fs.existsSync(path.join(dir, c.bsconfigPartialPath))) { return dir; } else { if (dir === source) { // reached top return null; } else { return findProjectRootOfFile(dir); } } }; // TODO: races here? // TODO: this doesn't handle file:/// scheme // We need to recursively search for bs-platform/{platform}/bsc.exe upward from // the project's root, because in some setups, such as yarn workspace/monorepo, // the node_modules/bs-platform package might be hoisted up instead of alongside // the project root. // Also, if someone's ever formatting a regular project setup's dependency // (which is weird but whatever), they'll at least find an upward bs-platform // from the dependent. export let findBscNativeOfFile = ( source: p.DocumentUri ): null | p.DocumentUri => { let dir = path.dirname(source); // The rescript package's rescript command is a JS wrapper. `rescript format` // also invokes another JS wrapper. _That_ JS wrapper ultimately calls the // (unexposed) bsc -format anyway. let bscNativeReScriptPath = path.join(dir, c.bscNativeReScriptPartialPath); let bscNativePath = path.join(dir, c.bscNativePartialPath); if (fs.existsSync(bscNativeReScriptPath)) { return bscNativeReScriptPath; } else if (fs.existsSync(bscNativePath)) { return bscNativePath; } else if (dir === source) { // reached the top return null; } else { return findBscNativeOfFile(dir); } }; // TODO: this doesn't handle file:/// scheme export let findNodeBuildOfProjectRoot = ( projectRootPath: p.DocumentUri ): null | { buildPath: p.DocumentUri; isReScript: boolean } => { let rescriptNodePath = path.join(projectRootPath, c.rescriptNodePartialPath); let bsbNodePath = path.join(projectRootPath, c.bsbNodePartialPath); if (fs.existsSync(rescriptNodePath)) { return { buildPath: rescriptNodePath, isReScript: true }; } else if (fs.existsSync(bsbNodePath)) { return { buildPath: bsbNodePath, isReScript: false }; } return null; }; type execResult = | { kind: "success"; result: string; } | { kind: "error"; error: string; }; export let formatUsingValidBscNativePath = ( code: string, bscNativePath: p.DocumentUri, isInterface: boolean ): execResult => { let extension = isInterface ? c.resiExt : c.resExt; let formatTempFileFullPath = createFileInTempDir(extension); fs.writeFileSync(formatTempFileFullPath, code, { encoding: "utf-8", }); try { let result = childProcess.execFileSync(bscNativePath, [ "-color", "never", "-format", formatTempFileFullPath, ]); return { kind: "success", result: result.toString(), }; } catch (e) { return { kind: "error", error: e.message, }; } finally { // async close is fine. We don't use this file name again fs.unlink(formatTempFileFullPath, () => null); } }; export let runAnalysisAfterSanityCheck = ( filePath: p.DocumentUri, args: Array<any> ) => { let binaryPath; if (fs.existsSync(c.analysisDevPath)) { binaryPath = c.analysisDevPath; } else if (fs.existsSync(c.analysisProdPath)) { binaryPath = c.analysisProdPath; } else { return null; } let projectRootPath = findProjectRootOfFile(filePath); if (projectRootPath == null) { return null; } let stdout = childProcess.execFileSync(binaryPath, args, { cwd: projectRootPath, }); return JSON.parse(stdout.toString()); }; export let runAnalysisCommand = ( filePath: p.DocumentUri, args: Array<any>, msg: RequestMessage ) => { let result = runAnalysisAfterSanityCheck(filePath, args); let response: ResponseMessage = { jsonrpc: c.jsonrpcVersion, id: msg.id, result, }; return response; }; export let getReferencesForPosition = ( filePath: p.DocumentUri, position: p.Position ) => runAnalysisAfterSanityCheck(filePath, [ "references", filePath, position.line, position.character, ]); export let replaceFileExtension = (filePath: string, ext: string): string => { let name = path.basename(filePath, path.extname(filePath)); return path.format({ dir: path.dirname(filePath), name, ext }); }; export let createInterfaceFileUsingValidBscExePath = ( filePath: string, cmiPath: string, bscExePath: p.DocumentUri ): execResult => { try { let resiString = childProcess.execFileSync(bscExePath, [ "-color", "never", cmiPath, ]); let resiPath = replaceFileExtension(filePath, c.resiExt); fs.writeFileSync(resiPath, resiString, { encoding: "utf-8" }); return { kind: "success", result: "Interface successfully created.", }; } catch (e) { return { kind: "error", error: e.message, }; } }; export let runBuildWatcherUsingValidBuildPath = ( buildPath: p.DocumentUri, isRescript: boolean, projectRootPath: p.DocumentUri ) => { let cwdEnv = { cwd: projectRootPath, }; if (process.platform === "win32") { /* - a node.js script in node_modules/.bin on windows is wrapped in a batch script wrapper (there's also a regular binary of the same name on windows, but that one's a shell script wrapper for cygwin). More info: https://github.com/npm/cmd-shim/blob/c5118da34126e6639361fe9706a5ff07e726ed45/index.js#L1 - a batch script adds the suffix .cmd to the script - you can't call batch scripts through the regular `execFile`: https://nodejs.org/api/child_process.html#child_process_spawning_bat_and_cmd_files_on_windows - So you have to use `exec` instead, and make sure you quote the path (since the path might have spaces), which `execFile` would have done for you under the hood */ if (isRescript) { return childProcess.exec(`"${buildPath}".cmd build -w`, cwdEnv); } else { return childProcess.exec(`"${buildPath}".cmd -w`, cwdEnv); } } else { if (isRescript) { return childProcess.execFile(buildPath, ["build", "-w"], cwdEnv); } else { return childProcess.execFile(buildPath, ["-w"], cwdEnv); } } }; // Logic for parsing .compiler.log /* example .compiler.log content: #Start(1600519680823) Syntax error! /Users/chenglou/github/reason-react/src/test.res:1:8-2:3 1 │ let a = 2 │ let b = 3 │ This let-binding misses an expression Warning number 8 /Users/chenglou/github/reason-react/src/test.res:3:5-8 1 │ let a = j`😀` 2 │ let b = `😀` 3 │ let None = None 4 │ let bla: int = " 5 │ hi You forgot to handle a possible case here, for example: Some _ We've found a bug for you! /Users/chenglou/github/reason-react/src/test.res:3:9 1 │ let a = 1 2 │ let b = "hi" 3 │ let a = b + 1 This has type: string Somewhere wanted: int #Done(1600519680836) */ // parser helpers let pathToURI = (file: string) => { return process.platform === "win32" ? `file:\\\\\\${file}` : `file://${file}`; }; let parseFileAndRange = (fileAndRange: string) => { // https://github.com/rescript-lang/rescript-compiler/blob/0a3f4bb32ca81e89cefd5a912b8795878836f883/jscomp/super_errors/super_location.ml#L15-L25 /* The file + location format can be: a/b.res <- fallback, no location available (usually due to bad ppx...) a/b.res:10:20 a/b.res:10:20-21 <- last number here is the end char of line 10 a/b.res:10:20-30:11 */ let regex = /(.+)\:(\d+)\:(\d+)(-(\d+)(\:(\d+))?)?$/; /* ^^ file ^^^ start line ^^^ start character ^ optional range ^^^ end line or chararacter ^^^ end character */ // for the trimming, see https://github.com/rescript-lang/rescript-vscode/pull/71#issuecomment-769160576 let trimmedFileAndRange = fileAndRange.trim(); let match = trimmedFileAndRange.match(regex); if (match === null) { // no location! Though LSP insist that we provide at least a dummy location return { file: pathToURI(trimmedFileAndRange), range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 }, }, }; } let [ _source, file, startLine, startChar, optionalEndGroup, endLineOrChar, _colonPlusEndCharOrNothing, endCharOrNothing, ] = match; // language-server position is 0-based. Ours is 1-based. Convert // also, our end character is inclusive. Language-server's is exclusive let range; if (optionalEndGroup == null) { let start = { line: parseInt(startLine) - 1, character: parseInt(startChar), }; range = { start: start, end: start, }; } else { let isSingleLine = endCharOrNothing == null; let [endLine, endChar] = isSingleLine ? [startLine, endLineOrChar] : [endLineOrChar, endCharOrNothing]; range = { start: { line: parseInt(startLine) - 1, character: parseInt(startChar) - 1, }, end: { line: parseInt(endLine) - 1, character: parseInt(endChar) }, }; } return { file: pathToURI(file), range, }; }; // main parsing logic type filesDiagnostics = { [key: string]: p.Diagnostic[]; }; type parsedCompilerLogResult = { done: boolean; result: filesDiagnostics; }; export let parseCompilerLogOutput = ( content: string ): parsedCompilerLogResult => { type parsedDiagnostic = { code: number | undefined; severity: t.DiagnosticSeverity; tag: t.DiagnosticTag | undefined; content: string[]; }; let parsedDiagnostics: parsedDiagnostic[] = []; let lines = content.split(os.EOL); let done = false; for (let i = 0; i < lines.length; i++) { let line = lines[i]; if (line.startsWith(" We've found a bug for you!")) { parsedDiagnostics.push({ code: undefined, severity: t.DiagnosticSeverity.Error, tag: undefined, content: [], }); } else if (line.startsWith(" Warning number ")) { let warningNumber = parseInt(line.slice(" Warning number ".length)); let tag: t.DiagnosticTag | undefined = undefined; switch (warningNumber) { case 11: case 20: case 26: case 27: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 60: case 66: case 67: case 101: tag = t.DiagnosticTag.Unnecessary; break; case 3: tag = t.DiagnosticTag.Deprecated; break; } parsedDiagnostics.push({ code: Number.isNaN(warningNumber) ? undefined : warningNumber, severity: t.DiagnosticSeverity.Warning, tag: tag, content: [], }); } else if (line.startsWith(" Syntax error!")) { parsedDiagnostics.push({ code: undefined, severity: t.DiagnosticSeverity.Error, tag: undefined, content: [], }); } else if (line.startsWith("#Start(")) { // do nothing for now } else if (line.startsWith("#Done(")) { done = true; } else if (/^ +([0-9]+| +|\.) (│|┆)/.test(line)) { // ^^ indent // ^^^^^^^^^^^^^^^ gutter // ^^^^^ separator // swallow code display. Examples: // 10 │ // . │ // │ // 10 ┆ } else if (line.startsWith(" ")) { // part of the actual diagnostics message parsedDiagnostics[parsedDiagnostics.length - 1].content.push( line.slice(2) ); } else if (line.trim() != "") { // We'll assume that everything else is also part of the diagnostics too. // Most of these should have been indented 2 spaces; sadly, some of them // aren't (e.g. outcome printer printing badly, and certain old ocaml type // messages not printing with indent). We used to get bug reports and fix // the messages, but that strategy turned out too slow. One day we should // revert to not having this branch... parsedDiagnostics[parsedDiagnostics.length - 1].content.push(line); } } let result: filesDiagnostics = {}; parsedDiagnostics.forEach((parsedDiagnostic) => { let [fileAndRangeLine, ...diagnosticMessage] = parsedDiagnostic.content; let { file, range } = parseFileAndRange(fileAndRangeLine); if (result[file] == null) { result[file] = []; } result[file].push({ severity: parsedDiagnostic.severity, tags: parsedDiagnostic.tag === undefined ? [] : [parsedDiagnostic.tag], code: parsedDiagnostic.code, range, source: "ReScript", // remove start and end whitespaces/newlines message: diagnosticMessage.join("\n").trim() + "\n", }); }); return { done, result }; };
the_stack
import {EditorPosition, editorViewField, KeymapContext, MarkdownView, Plugin, TFile,} from "obsidian"; import SnippetManager from "./snippet_manager"; import SuggestionPopup, {SelectionDirection} from "./popup"; import {CompletrSettings, DEFAULT_SETTINGS} from "./settings"; import {WordList} from "./provider/word_list_provider"; import {FileScanner} from "./provider/scanner_provider"; import CompletrSettingsTab from "./settings_tab"; import {EditorView, ViewUpdate} from "@codemirror/view"; import {editorToCodeMirrorState, posFromIndex} from "./editor_helpers"; import {markerStateField} from "./marker_state_field"; import {FrontMatter} from "./provider/front_matter_provider"; import {Latex} from "./provider/latex_provider"; import {SuggestionBlacklist} from "./provider/blacklist"; export default class CompletrPlugin extends Plugin { settings: CompletrSettings; private snippetManager: SnippetManager; private _suggestionPopup: SuggestionPopup; async onload() { await this.loadSettings(); this.snippetManager = new SnippetManager(); this._suggestionPopup = new SuggestionPopup(this.app, this.settings, this.snippetManager); this.registerEditorSuggest(this._suggestionPopup); this.registerEvent(this.app.workspace.on('file-open', this.onFileOpened, this)); this.registerEvent(this.app.metadataCache.on('changed', FrontMatter.onCacheChange, FrontMatter)); this.app.workspace.onLayoutReady(() => FrontMatter.loadYAMLKeyCompletions(this.app.metadataCache, this.app.vault.getMarkdownFiles())); this.registerEditorExtension(markerStateField); this.registerEditorExtension(EditorView.updateListener.of(new CursorActivityListener(this.snippetManager, this._suggestionPopup).listener)); this.addSettingTab(new CompletrSettingsTab(this.app, this)); this.setupCommands(); if ((this.app.vault as any).config?.legacyEditor) { console.log("Completr: Without Live Preview enabled, most features of Completr will not work properly!"); } } private setupCommands() { //This replaces the default handler for commands. This is needed because the default handler always consumes // the event if the command exists. const app = this.app as any; app.scope.keys = []; const isHotkeyMatch = (hotkey: any, context: KeymapContext, id: string): boolean => { //Copied from original isMatch function, modified to not require exactly the same modifiers for // completr-bypass commands. This allows triggering for example Ctrl+Enter even when // pressing Ctrl+Shift+Enter. The additional modifier is then passed to the editor. /* Original isMatch function: var n = e.modifiers , i = e.key; return (null === n || n === t.modifiers) && (!i || (i === t.vkey || !(!t.key || i.toLowerCase() !== t.key.toLowerCase()))) */ const modifiers = hotkey.modifiers, key = hotkey.key; if (modifiers !== null && (id.contains("completr-bypass") ? !context.modifiers.contains(modifiers) : modifiers !== context.modifiers)) return false; return (!key || (key === context.vkey || !(!context.key || key.toLowerCase() !== context.key.toLowerCase()))) } this.app.scope.register(null, null, (e: KeyboardEvent, t: KeymapContext) => { const hotkeyManager = app.hotkeyManager; hotkeyManager.bake(); for (let bakedHotkeys = hotkeyManager.bakedHotkeys, bakedIds = hotkeyManager.bakedIds, r = 0; r < bakedHotkeys.length; r++) { const hotkey = bakedHotkeys[r]; const id = bakedIds[r]; if (isHotkeyMatch(hotkey, t, id)) { const command = app.commands.findCommand(id); //HACK: Hide our commands when to popup is not visible to allow the keybinds to execute their default action. if (!command || (command.isVisible && !command.isVisible())) { continue; } else if (id.contains("completr-bypass")) { this._suggestionPopup.close(); const validMods = t.modifiers.replace(new RegExp(`${hotkey.modifiers},*`), "").split(","); //Sends the event again, only keeping the modifiers which didn't activate this command let event = new KeyboardEvent("keydown", { key: hotkeyManager.defaultKeys[id][0].key, ctrlKey: validMods.contains("Ctrl"), shiftKey: validMods.contains("Shift"), altKey: validMods.contains("Alt"), metaKey: validMods.contains("Meta") }); e.target.dispatchEvent(event); return false; } if (app.commands.executeCommandById(id)) return false } } }); this.addCommand({ id: 'completr-open-suggestion-popup', name: 'Open suggestion popup', hotkeys: [ { key: " ", modifiers: ["Mod"] } ], editorCallback: (editor) => { //This is the same function that is called by obsidian when you type a character (this._suggestionPopup as any).trigger(editor, this.app.workspace.getActiveFile(), true); }, }); this.addCommand({ id: 'completr-select-next-suggestion', name: 'Select next suggestion', hotkeys: [ { key: "ArrowDown", modifiers: [] } ], editorCallback: (editor) => { this.suggestionPopup.selectNextItem(SelectionDirection.NEXT); }, // @ts-ignore isVisible: () => this._suggestionPopup.isVisible(), }); this.addCommand({ id: 'completr-select-previous-suggestion', name: 'Select previous suggestion', hotkeys: [ { key: "ArrowUp", modifiers: [] } ], editorCallback: (editor) => { this.suggestionPopup.selectNextItem(SelectionDirection.PREVIOUS); }, // @ts-ignore isVisible: () => this._suggestionPopup.isVisible(), }); this.addCommand({ id: 'completr-insert-selected-suggestion', name: 'Insert selected suggestion', hotkeys: [ { key: "Enter", modifiers: [] } ], editorCallback: (editor) => { this.suggestionPopup.applySelectedItem(); }, // @ts-ignore isVisible: () => this._suggestionPopup.isVisible(), }); this.addCommand({ id: 'completr-bypass-enter-key', name: 'Bypass the popup and press Enter', hotkeys: [ { key: "Enter", modifiers: ["Ctrl"] } ], editorCallback: (editor) => { }, // @ts-ignore isVisible: () => this._suggestionPopup.isVisible(), }); this.addCommand({ id: 'completr-bypass-tab-key', name: 'Bypass the popup and press Tab', hotkeys: [ { key: "Tab", modifiers: ["Ctrl"] } ], editorCallback: (editor) => { }, // @ts-ignore isVisible: () => this._suggestionPopup.isVisible(), }); this.addCommand({ id: 'completr-blacklist-current-word', name: 'Add the currently selected word to the blacklist', hotkeys: [ { key: "D", modifiers: ["Shift"] } ], editorCallback: (editor) => { SuggestionBlacklist.add(this._suggestionPopup.getSelectedItem()); SuggestionBlacklist.saveData(this.app.vault); (this._suggestionPopup as any).trigger(editor, this.app.workspace.getActiveFile(), true); }, // @ts-ignore isVisible: () => this._suggestionPopup.isVisible(), }); this.addCommand({ id: 'completr-close-suggestion-popup', name: 'Close suggestion popup', hotkeys: [ { key: "Escape", modifiers: [] } ], editorCallback: (editor) => { this.suggestionPopup.close(); }, // @ts-ignore isVisible: () => this._suggestionPopup.isVisible(), }); this.addCommand({ id: 'completr-jump-to-next-snippet-placeholder', name: 'Jump to next snippet placeholder', hotkeys: [ { key: "Enter", modifiers: [] } ], editorCallback: (editor, view) => { const placeholder = this.snippetManager.placeholderAtPos(editor.getCursor()); //Sanity check if (!placeholder) return; const placeholderEnd = posFromIndex(editorToCodeMirrorState(placeholder.editor).doc, placeholder.marker.to); if (!this.snippetManager.consumeAndGotoNextMarker(editor)) { editor.setSelections([{ anchor: { ...placeholderEnd, ch: Math.min(editor.getLine(placeholderEnd.line).length, placeholderEnd.ch + 1) } }]); } }, // @ts-ignore isVisible: () => { const view = this.app.workspace.getActiveViewOfType(MarkdownView); if (!view) return false; const placeholder = this.snippetManager.placeholderAtPos(view.editor.getCursor()); return placeholder != null; }, }); } async onunload() { this.snippetManager.onunload(); await FileScanner.saveData(this.app.vault); } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); SuggestionBlacklist.loadData(this.app.vault).then(() => { WordList.loadFromFiles(this.app.vault, this.settings); FileScanner.loadData(this.app.vault); Latex.loadCommands(this.app.vault); }); } get suggestionPopup() { return this._suggestionPopup; } async saveSettings() { await this.saveData(this.settings); } private readonly onFileOpened = (file: TFile) => { if (!this.settings.fileScannerScanCurrent || !file) return; FileScanner.scanFile(this.settings, file, true); } } class CursorActivityListener { private readonly snippetManager: SnippetManager; private readonly suggestionPopup: SuggestionPopup; private cursorTriggeredByChange = false; private lastCursorLine = -1; constructor(snippetManager: SnippetManager, suggestionPopup: SuggestionPopup) { this.snippetManager = snippetManager; this.suggestionPopup = suggestionPopup; } readonly listener = (update: ViewUpdate) => { if (update.docChanged) { this.handleDocChange(); } if (update.selectionSet) { this.handleCursorActivity(posFromIndex(update.state.doc, update.state.selection.main.head)) } }; private readonly handleDocChange = () => { this.cursorTriggeredByChange = true; }; private readonly handleCursorActivity = (cursor: EditorPosition) => { //This prevents the popup from opening when switching to the previous line if (this.lastCursorLine == cursor.line + 1) this.suggestionPopup.preventNextTrigger(); this.lastCursorLine = cursor.line; //Clear all placeholders when moving cursor outside of them if (!this.snippetManager.placeholderAtPos(cursor)) { this.snippetManager.clearAllPlaceholders(); } //Prevents the suggestion popup from flickering when typing if (this.cursorTriggeredByChange) { this.cursorTriggeredByChange = false; return; } this.suggestionPopup.close(); }; }
the_stack
import objectValues from '../polyfills/objectValues.js'; import inspect from '../jsutils/inspect.js'; import devAssert from '../jsutils/devAssert.js'; import keyValMap from '../jsutils/keyValMap.js'; import isObjectLike from '../jsutils/isObjectLike.js'; import { parseValue } from '../language/parser.js'; import { GraphQLDirective } from '../type/directives.js'; import { specifiedScalarTypes } from '../type/scalars.js'; import { introspectionTypes, TypeKind } from '../type/introspection.js'; import { GraphQLSchema } from '../type/schema.js'; import { isInputType, isOutputType, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, assertNullableType, assertObjectType, assertInterfaceType } from '../type/definition.js'; import { valueFromAST } from './valueFromAST.js'; /** * Build a GraphQLSchema for use by client tools. * * Given the result of a client running the introspection query, creates and * returns a GraphQLSchema instance which can be then used with all graphql-js * tools, but cannot be used to execute a query, as introspection does not * represent the "resolver", "parse" or "serialize" functions or any other * server-internal mechanisms. * * This function expects a complete introspection result. Don't forget to check * the "errors" field of a server response before calling this function. */ export function buildClientSchema(introspection, options) { devAssert(isObjectLike(introspection) && isObjectLike(introspection.__schema), `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${inspect(introspection)}.`); // Get the schema from the introspection result. const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. const typeMap = keyValMap(schemaIntrospection.types, typeIntrospection => typeIntrospection.name, typeIntrospection => buildType(typeIntrospection)); // Include standard types only if they are used. for (const stdType of [...specifiedScalarTypes, ...introspectionTypes]) { if (typeMap[stdType.name]) { typeMap[stdType.name] = stdType; } } // Get the root Query, Mutation, and Subscription types. const queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; const mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; const subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if // directives were not queried for. const directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. return new GraphQLSchema({ description: schemaIntrospection.description, query: queryType, mutation: mutationType, subscription: subscriptionType, types: objectValues(typeMap), directives, assumeValid: options?.assumeValid }); // Given a type reference in introspection, return the GraphQLType instance. // preferring cached instances before building new instances. function getType(typeRef) { if (typeRef.kind === TypeKind.LIST) { const itemRef = typeRef.ofType; if (!itemRef) { throw new Error('Decorated type deeper than introspection query.'); } return GraphQLList(getType(itemRef)); } if (typeRef.kind === TypeKind.NON_NULL) { const nullableRef = typeRef.ofType; if (!nullableRef) { throw new Error('Decorated type deeper than introspection query.'); } const nullableType = getType(nullableRef); return GraphQLNonNull(assertNullableType(nullableType)); } return getNamedType(typeRef); } function getNamedType(typeRef) { const typeName = typeRef.name; if (!typeName) { throw new Error(`Unknown type reference: ${inspect(typeRef)}.`); } const type = typeMap[typeName]; if (!type) { throw new Error(`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`); } return type; } function getObjectType(typeRef) { return assertObjectType(getNamedType(typeRef)); } function getInterfaceType(typeRef) { return assertInterfaceType(getNamedType(typeRef)); } // Given a type's introspection result, construct the correct // GraphQLType instance. function buildType(type) { if (type != null && type.name != null && type.kind != null) { switch (type.kind) { case TypeKind.SCALAR: return buildScalarDef(type); case TypeKind.OBJECT: return buildObjectDef(type); case TypeKind.INTERFACE: return buildInterfaceDef(type); case TypeKind.UNION: return buildUnionDef(type); case TypeKind.ENUM: return buildEnumDef(type); case TypeKind.INPUT_OBJECT: return buildInputObjectDef(type); } } const typeStr = inspect(type); throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`); } function buildScalarDef(scalarIntrospection) { return new GraphQLScalarType({ name: scalarIntrospection.name, description: scalarIntrospection.description }); } function buildImplementationsList(implementingIntrospection) { // TODO: Temporary workaround until GraphQL ecosystem will fully support // 'interfaces' on interface types. if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === TypeKind.INTERFACE) { return []; } if (!implementingIntrospection.interfaces) { const implementingIntrospectionStr = inspect(implementingIntrospection); throw new Error(`Introspection result missing interfaces: ${implementingIntrospectionStr}.`); } return implementingIntrospection.interfaces.map(getInterfaceType); } function buildObjectDef(objectIntrospection) { return new GraphQLObjectType({ name: objectIntrospection.name, description: objectIntrospection.description, interfaces: () => buildImplementationsList(objectIntrospection), fields: () => buildFieldDefMap(objectIntrospection) }); } function buildInterfaceDef(interfaceIntrospection) { return new GraphQLInterfaceType({ name: interfaceIntrospection.name, description: interfaceIntrospection.description, interfaces: () => buildImplementationsList(interfaceIntrospection), fields: () => buildFieldDefMap(interfaceIntrospection) }); } function buildUnionDef(unionIntrospection) { if (!unionIntrospection.possibleTypes) { const unionIntrospectionStr = inspect(unionIntrospection); throw new Error(`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`); } return new GraphQLUnionType({ name: unionIntrospection.name, description: unionIntrospection.description, types: () => unionIntrospection.possibleTypes.map(getObjectType) }); } function buildEnumDef(enumIntrospection) { if (!enumIntrospection.enumValues) { const enumIntrospectionStr = inspect(enumIntrospection); throw new Error(`Introspection result missing enumValues: ${enumIntrospectionStr}.`); } return new GraphQLEnumType({ name: enumIntrospection.name, description: enumIntrospection.description, values: keyValMap(enumIntrospection.enumValues, valueIntrospection => valueIntrospection.name, valueIntrospection => ({ description: valueIntrospection.description, deprecationReason: valueIntrospection.deprecationReason })) }); } function buildInputObjectDef(inputObjectIntrospection) { if (!inputObjectIntrospection.inputFields) { const inputObjectIntrospectionStr = inspect(inputObjectIntrospection); throw new Error(`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`); } return new GraphQLInputObjectType({ name: inputObjectIntrospection.name, description: inputObjectIntrospection.description, fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields) }); } function buildFieldDefMap(typeIntrospection) { if (!typeIntrospection.fields) { throw new Error(`Introspection result missing fields: ${inspect(typeIntrospection)}.`); } return keyValMap(typeIntrospection.fields, fieldIntrospection => fieldIntrospection.name, buildField); } function buildField(fieldIntrospection) { const type = getType(fieldIntrospection.type); if (!isOutputType(type)) { const typeStr = inspect(type); throw new Error(`Introspection must provide output type for fields, but received: ${typeStr}.`); } if (!fieldIntrospection.args) { const fieldIntrospectionStr = inspect(fieldIntrospection); throw new Error(`Introspection result missing field args: ${fieldIntrospectionStr}.`); } return { description: fieldIntrospection.description, deprecationReason: fieldIntrospection.deprecationReason, type, args: buildInputValueDefMap(fieldIntrospection.args) }; } function buildInputValueDefMap(inputValueIntrospections) { return keyValMap(inputValueIntrospections, inputValue => inputValue.name, buildInputValue); } function buildInputValue(inputValueIntrospection) { const type = getType(inputValueIntrospection.type); if (!isInputType(type)) { const typeStr = inspect(type); throw new Error(`Introspection must provide input type for arguments, but received: ${typeStr}.`); } const defaultValue = inputValueIntrospection.defaultValue != null ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) : undefined; return { description: inputValueIntrospection.description, type, defaultValue }; } function buildDirective(directiveIntrospection) { if (!directiveIntrospection.args) { const directiveIntrospectionStr = inspect(directiveIntrospection); throw new Error(`Introspection result missing directive args: ${directiveIntrospectionStr}.`); } if (!directiveIntrospection.locations) { const directiveIntrospectionStr = inspect(directiveIntrospection); throw new Error(`Introspection result missing directive locations: ${directiveIntrospectionStr}.`); } return new GraphQLDirective({ name: directiveIntrospection.name, description: directiveIntrospection.description, isRepeatable: directiveIntrospection.isRepeatable, locations: directiveIntrospection.locations.slice(), args: buildInputValueDefMap(directiveIntrospection.args) }); } }
the_stack
import type { Dispatch } from 'redux'; import type { TFlags } from '@flopflip/types'; import type { NormalizedCacheObject } from '@apollo/client'; import type { ApolloError } from '@apollo/client/errors'; import type { TApplicationContext } from '@commercetools-frontend/application-shell-connectors'; import type { TAsyncLocaleDataProps } from '@commercetools-frontend/i18n'; import type { TApplicationsMenu } from '../../types/generated/proxy'; import type { TrackingList } from '../../utils/gtm'; import { ReactNode, SyntheticEvent, useEffect } from 'react'; import { Redirect, Route, Switch, useLocation } from 'react-router-dom'; import { ApolloClient } from '@apollo/client'; import { Global, css } from '@emotion/react'; import styled from '@emotion/styled'; import { DOMAINS, LOGOUT_REASONS } from '@commercetools-frontend/constants'; import { reportErrorToSentry, SentryUserTracker, } from '@commercetools-frontend/sentry'; import { ApplicationContextProvider, useApplicationContext, } from '@commercetools-frontend/application-shell-connectors'; import { PortalsContainer } from '@commercetools-frontend/application-components'; import { NotificationsList } from '@commercetools-frontend/react-notifications'; import { AsyncLocaleData } from '@commercetools-frontend/i18n'; import version from '../../version'; import internalReduxStore from '../../configure-store'; import { selectProjectKeyFromUrl, getPreviousProjectKey } from '../../utils'; import ProjectDataLocale from '../project-data-locale'; import ApplicationShellProvider from '../application-shell-provider'; import { getBrowserLocale } from '../application-shell-provider/utils'; import FetchUser from '../fetch-user'; import VersionTracker from '../version-tracker'; import FetchProject from '../fetch-project'; import ConfigureIntlProvider from '../configure-intl-provider'; import AppBar from '../app-bar'; import ProjectContainer from '../project-container'; import SetupFlopFlipProvider from '../setup-flop-flip-provider'; import RequestsInFlightLoader from '../requests-in-flight-loader'; import GtmUserTracker from '../gtm-user-tracker'; import GtmApplicationTracker from '../gtm-application-tracker'; import NavBar, { LoadingNavBar } from '../navbar'; import ApplicationLoader from '../application-loader'; import ErrorApologizer from '../error-apologizer'; import RouteCatchAll from '../route-catch-all'; import RedirectToProjectCreate from '../redirect-to-project-create'; import QuickAccess from '../quick-access'; import RedirectToLogin from './redirect-to-login'; import RedirectToLogout from './redirect-to-logout'; type Props<AdditionalEnvironmentProperties extends {}> = { apolloClient?: ApolloClient<NormalizedCacheObject>; /** * NOTE: the environment value passed here is usually `window.app`. * This object usually contains values as string and will be "transformed" * to a real object with proper scalar values in the ApplicationShell. * To keep the types simple, we assign here the already coerced type object. * This should be fine, as consumers of the application can use the * `ApplicationWindow` type from the `@commercetools-frontend/constants` package * to type cast it: * * ```tsx * import { ApplicationWindow } from '@commercetools-frontend/constants'; * * declare let window: ApplicationWindow; * * <ApplicationShell environment={window.app} /> * ``` */ environment: TApplicationContext<AdditionalEnvironmentProperties>['environment']; featureFlags?: TFlags; defaultFeatureFlags?: TFlags; trackingEventList?: TrackingList; applicationMessages: TAsyncLocaleDataProps['applicationMessages']; onRegisterErrorListeners: (args: { dispatch: Dispatch }) => void; onMenuItemClick?: <TrackFn>( event: SyntheticEvent<HTMLAnchorElement>, track: TrackFn ) => void; render?: () => JSX.Element; children?: ReactNode; // Only available in development mode DEV_ONLY__loadAppbarMenuConfig?: () => Promise<TApplicationsMenu['appBar']>; DEV_ONLY__loadNavbarMenuConfig?: () => Promise<TApplicationsMenu['navBar']>; }; /** * This component is rendered whenever the user is considered "authenticated" * and contains the "restricted" application part. */ const getHasUnauthorizedError = (graphQLErrors: ApolloError['graphQLErrors']) => graphQLErrors.find( (gqlError) => gqlError.extensions && gqlError.extensions.code && gqlError.extensions.code === 'UNAUTHENTICATED' ); const getHasUserBeenDeletedError = ( graphQLErrors: ApolloError['graphQLErrors'] ) => graphQLErrors.find( (gqlError) => gqlError.message && // NOTE: The CTP API does not provide an error code in this case. gqlError.message.includes('was not found.') ); export const MainContainer = styled.main` grid-column: 2; grid-row: 3; /* Allow the this flex child to grow smaller than its smallest content. This is needed when there is a really wide text inside that would stretch this node to be wider than the parent. */ min-width: 0; overflow-x: hidden; overflow-y: scroll; /* layout the children. There will always be the page and side notification about the actual content. The content should stretch to fill the rest of the page. */ display: flex; flex-direction: column; /* set position to relative to layout notifications and modals */ position: relative; `; export const RestrictedApplication = < AdditionalEnvironmentProperties extends {} >( props: Omit< Props<AdditionalEnvironmentProperties>, 'environment' | 'onRegisterErrorListeners' > ) => { const applicationEnvironment = useApplicationContext( (context) => context.environment ) as TApplicationContext<AdditionalEnvironmentProperties>['environment']; // TODO: using this hook will subscribe the component to route updates. // This is currently useful for detecting a change in the project key // from URL ("/" --> "/:projectKey"). // However, every route change will trigger a re-render. This is probably // ok-ish but we might want to look into a more performant solution. const location = useLocation(); return ( <FetchUser> {({ isLoading: isLoadingUser, user, error }) => { if (error) { // In case there is an unauthorized error, we redirect to the login page if (error.graphQLErrors && Array.isArray(error.graphQLErrors)) { const hasUnauthorizedError = getHasUnauthorizedError( error.graphQLErrors ); const hasUserBeenDeletedError = getHasUserBeenDeletedError( error.graphQLErrors ); if (hasUnauthorizedError || hasUserBeenDeletedError) { let logoutReason: | typeof LOGOUT_REASONS[keyof typeof LOGOUT_REASONS] | undefined; if (hasUnauthorizedError) logoutReason = LOGOUT_REASONS.UNAUTHORIZED; else if (hasUserBeenDeletedError) logoutReason = LOGOUT_REASONS.DELETED; return <RedirectToLogout reason={logoutReason} />; } } // Since we do not know the locale of the user, we pick it from the // user's browser to attempt to match the language for the correct translations. const userLocale = getBrowserLocale(window); return ( <AsyncLocaleData locale={userLocale} applicationMessages={props.applicationMessages} > {({ locale, messages }) => { reportErrorToSentry(error, {}); return ( <ConfigureIntlProvider locale={locale} messages={messages}> <ErrorApologizer /> </ConfigureIntlProvider> ); }} </AsyncLocaleData> ); } const projectKeyFromUrl = selectProjectKeyFromUrl(location.pathname); return ( <ApplicationContextProvider<AdditionalEnvironmentProperties> user={user} environment={applicationEnvironment} > {/* NOTE: we do not want to load the locale data as long as we do not know the user setting. This is important in order to avoid flashing of translated content on subsequent re-renders. Therefore, as long as there is no locale, the children should consider using the `isLoading` prop to decide what to render. */} <AsyncLocaleData locale={user?.language} applicationMessages={props.applicationMessages} > {({ isLoading: isLoadingLocaleData, locale, messages }) => ( <ConfigureIntlProvider // We do not want to pass the language as long as the locale data // is not loaded. {...(isLoadingLocaleData ? {} : { locale, messages })} > <SetupFlopFlipProvider user={user} projectKey={projectKeyFromUrl} ldClientSideId={applicationEnvironment.ldClientSideId} flags={props.featureFlags} defaultFlags={props.defaultFeatureFlags} > <> <VersionTracker /> {/* NOTE: the requests in flight loader will render a loading spinner into the AppBar. */} <RequestsInFlightLoader /> <SentryUserTracker user={user ?? undefined} /> <GtmUserTracker user={user} /> <GtmApplicationTracker applicationName={applicationEnvironment.applicationName} projectKey={projectKeyFromUrl} userBusinessRole={user?.businessRole ?? undefined} /> <div role="application-layout" css={css` height: 100vh; display: grid; grid-template-rows: auto 43px 1fr; grid-template-columns: auto 1fr; `} > <div role="global-notifications" css={css` grid-row: 1; grid-column: 1/3; `} > <NotificationsList domain={DOMAINS.GLOBAL} /> </div> <Route> {() => { if (!projectKeyFromUrl) return <QuickAccess />; return ( <FetchProject projectKey={projectKeyFromUrl}> {({ isLoading: isProjectLoading, project }) => { if (isProjectLoading || !project) return null; // when used outside of a project context, // or when the project is expired or supsended const shouldUseProjectContext = !( (project.suspension && project.suspension.isActive) || (project.expiry && project.expiry.isActive) ); if (!shouldUseProjectContext) return <QuickAccess />; return ( <ProjectDataLocale locales={project.languages} > {({ locale: dataLocale, setProjectDataLocale, }) => ( <ApplicationContextProvider<AdditionalEnvironmentProperties> user={user} project={project} projectDataLocale={dataLocale} environment={applicationEnvironment} > <QuickAccess onChangeProjectDataLocale={ setProjectDataLocale } /> </ApplicationContextProvider> )} </ProjectDataLocale> ); }} </FetchProject> ); }} </Route> <header role="header" css={css` grid-row: 2; grid-column: 1/3; `} > <AppBar user={user} projectKeyFromUrl={projectKeyFromUrl} DEV_ONLY__loadAppbarMenuConfig={ props.DEV_ONLY__loadAppbarMenuConfig } /> </header> <aside role="aside" css={css` position: relative; grid-row: 3; display: flex; flex-direction: column; `} > {(() => { // The <NavBar> should only be rendered within a project // context, therefore when there is a `projectKey`. // If there is no `projectKey` in the URL (e.g. `/account` // routes), we don't render it. // NOTE: we also "cache" the `projectKey` in localStorage // but this should only be used to "re-hydrate" the URL // location (e.g when you go to `/`, there should be a // redirect to `/:projectKey`). Therefore, we should not // rely on the value in localStorage to determine which // `projectKey` is currently used. if (!projectKeyFromUrl) return null; return ( <FetchProject projectKey={projectKeyFromUrl}> {({ isLoading: isLoadingProject, project }) => { // Render the loading navbar as long as all the data // hasn't been loaded, or if the project does not exist. if ( isLoadingUser || isLoadingLocaleData || isLoadingProject || !locale || !project ) return <LoadingNavBar />; return ( <ApplicationContextProvider<AdditionalEnvironmentProperties> user={user} environment={applicationEnvironment} // NOTE: do not pass the `project` into the application context. // The permissions for the Navbar are resolved separately, within // a different React context. > <NavBar<AdditionalEnvironmentProperties> applicationLocale={locale} projectKey={projectKeyFromUrl} project={project} environment={applicationEnvironment} DEV_ONLY__loadNavbarMenuConfig={ props.DEV_ONLY__loadNavbarMenuConfig } onMenuItemClick={props.onMenuItemClick} /> </ApplicationContextProvider> ); }} </FetchProject> ); })()} </aside> {isLoadingUser || isLoadingLocaleData ? ( <MainContainer role="main"> <ApplicationLoader /> </MainContainer> ) : ( <MainContainer role="main"> <NotificationsList domain={DOMAINS.PAGE} /> <NotificationsList domain={DOMAINS.SIDE} /> <div css={css` flex-grow: 1; display: flex; flex-direction: column; position: relative; /* This is only necessary because we have an intermediary <div> wrapping the <View> component that is used to wrap every content-view. This intermediary <div> is solely used for adding the tracking context to the content-view. However, this could be done by passing the tracking context to the <View> and let it do the layout, so we can avoid laying our from the outside as we do here. */ > *:not(:first-of-type) { flex-grow: 1; display: flex; flex-direction: column; } `} > <PortalsContainer /> <Switch> <Redirect from="/profile" to="/account/profile" /> <Route path="/account"> { /** * In case the AppShell uses the `render` function, we assume it's one of two cases: * 1. The application does not use `children` and therefore implements the routes including * the <RouteCatchAll> (this is the "legacy" behavior). * 2. It's the account application, which always uses `render` and therefore should render as normal. * * In case the AppShell uses the `children` function, we can always assume that * it's a normal Custom Application and that it should trigger a force reload. */ props.render ? ( <>{props.render()}</> ) : ( <RouteCatchAll /> ) } </Route> {/* Project routes */} <Route exact={true} path="/" render={() => { const previousProjectKey = getPreviousProjectKey( user?.defaultProjectKey ?? undefined ); /** * NOTE: * Given the user has not been loaded a loading spinner is shown. * Given the user was not working on a project previously nor has a default * project, the user will be prompted to create one. * Given the user was working on a project previously or has a default * project, the application will redirect to that project. */ if (!user) return <ApplicationLoader />; if (!previousProjectKey) return <RedirectToProjectCreate />; return ( <Redirect to={`/${previousProjectKey}`} /> ); }} /> <Route exact={false} path="/:projectKey" render={(routerProps) => ( <ProjectContainer<AdditionalEnvironmentProperties> user={user} match={routerProps.match} location={routerProps.location} environment={applicationEnvironment} // This effectively renders the // children, which is the application // specific part render={props.render} > {props.children} </ProjectContainer> )} /> </Switch> </div> </MainContainer> )} </div> </> </SetupFlopFlipProvider> </ConfigureIntlProvider> )} </AsyncLocaleData> </ApplicationContextProvider> ); }} </FetchUser> ); }; RestrictedApplication.displayName = 'RestrictedApplication'; const ApplicationShell = <AdditionalEnvironmentProperties extends {}>( props: Props<AdditionalEnvironmentProperties> ) => { useEffect(() => { props.onRegisterErrorListeners({ dispatch: internalReduxStore.dispatch, }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // <-- run only once, when component mounts return ( <> <Global styles={css` #app { height: 100%; } .ReactModal__Body--open main { /* When a modal is open, we should prevent the content to be scrollable */ overflow: hidden; } `} /> <ApplicationShellProvider<AdditionalEnvironmentProperties> apolloClient={props.apolloClient} environment={props.environment} trackingEventList={props.trackingEventList} applicationMessages={props.applicationMessages} > {({ isAuthenticated }) => { if (isAuthenticated) { return ( <Switch> <Route path="/logout"> <RedirectToLogout /> </Route> <Route> <RestrictedApplication<AdditionalEnvironmentProperties> defaultFeatureFlags={props.defaultFeatureFlags} featureFlags={props.featureFlags} render={props.render} applicationMessages={props.applicationMessages} onMenuItemClick={props.onMenuItemClick} DEV_ONLY__loadAppbarMenuConfig={ props.DEV_ONLY__loadAppbarMenuConfig } DEV_ONLY__loadNavbarMenuConfig={ props.DEV_ONLY__loadNavbarMenuConfig } > {props.children} </RestrictedApplication> </Route> </Switch> ); } return <RedirectToLogin />; }} </ApplicationShellProvider> </> ); }; ApplicationShell.displayName = 'ApplicationShell'; ApplicationShell.version = version; export default ApplicationShell;
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Subscriptions } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ServiceBusManagementClient } from "../serviceBusManagementClient"; import { SBSubscription, SubscriptionsListByTopicNextOptionalParams, SubscriptionsListByTopicOptionalParams, SubscriptionsListByTopicResponse, SubscriptionsCreateOrUpdateOptionalParams, SubscriptionsCreateOrUpdateResponse, SubscriptionsDeleteOptionalParams, SubscriptionsGetOptionalParams, SubscriptionsGetResponse, SubscriptionsListByTopicNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Subscriptions operations. */ export class SubscriptionsImpl implements Subscriptions { private readonly client: ServiceBusManagementClient; /** * Initialize a new instance of the class Subscriptions class. * @param client Reference to the service client */ constructor(client: ServiceBusManagementClient) { this.client = client; } /** * List all the subscriptions under a specified topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param options The options parameters. */ public listByTopic( resourceGroupName: string, namespaceName: string, topicName: string, options?: SubscriptionsListByTopicOptionalParams ): PagedAsyncIterableIterator<SBSubscription> { const iter = this.listByTopicPagingAll( resourceGroupName, namespaceName, topicName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByTopicPagingPage( resourceGroupName, namespaceName, topicName, options ); } }; } private async *listByTopicPagingPage( resourceGroupName: string, namespaceName: string, topicName: string, options?: SubscriptionsListByTopicOptionalParams ): AsyncIterableIterator<SBSubscription[]> { let result = await this._listByTopic( resourceGroupName, namespaceName, topicName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByTopicNext( resourceGroupName, namespaceName, topicName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByTopicPagingAll( resourceGroupName: string, namespaceName: string, topicName: string, options?: SubscriptionsListByTopicOptionalParams ): AsyncIterableIterator<SBSubscription> { for await (const page of this.listByTopicPagingPage( resourceGroupName, namespaceName, topicName, options )) { yield* page; } } /** * List all the subscriptions under a specified topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param options The options parameters. */ private _listByTopic( resourceGroupName: string, namespaceName: string, topicName: string, options?: SubscriptionsListByTopicOptionalParams ): Promise<SubscriptionsListByTopicResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, options }, listByTopicOperationSpec ); } /** * Creates a topic subscription. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param subscriptionName The subscription name. * @param parameters Parameters supplied to create a subscription resource. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, namespaceName: string, topicName: string, subscriptionName: string, parameters: SBSubscription, options?: SubscriptionsCreateOrUpdateOptionalParams ): Promise<SubscriptionsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, subscriptionName, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes a subscription from the specified topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param subscriptionName The subscription name. * @param options The options parameters. */ delete( resourceGroupName: string, namespaceName: string, topicName: string, subscriptionName: string, options?: SubscriptionsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, subscriptionName, options }, deleteOperationSpec ); } /** * Returns a subscription description for the specified topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param subscriptionName The subscription name. * @param options The options parameters. */ get( resourceGroupName: string, namespaceName: string, topicName: string, subscriptionName: string, options?: SubscriptionsGetOptionalParams ): Promise<SubscriptionsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, subscriptionName, options }, getOperationSpec ); } /** * ListByTopicNext * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param nextLink The nextLink from the previous successful call to the ListByTopic method. * @param options The options parameters. */ private _listByTopicNext( resourceGroupName: string, namespaceName: string, topicName: string, nextLink: string, options?: SubscriptionsListByTopicNextOptionalParams ): Promise<SubscriptionsListByTopicNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, nextLink, options }, listByTopicNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByTopicOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBSubscriptionListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.skip, Parameters.top], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SBSubscription }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters13, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName, Parameters.subscriptionName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName, Parameters.subscriptionName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBSubscription }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName, Parameters.subscriptionName ], headerParameters: [Parameters.accept], serializer }; const listByTopicNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBSubscriptionListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.skip, Parameters.top], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.nextLink, Parameters.topicName ], headerParameters: [Parameters.accept], serializer };
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * locale info of decimal, thousands, grouping and currency. */ export const localeInfo = { 'ar-MA': { currency: ['\u062f.\u0645. ', ''], decimal: ',', thousands: '.', grouping: [3], }, 'en-IN': { currency: ['\u20b9', ''], decimal: '.', thousands: ',', grouping: [3, 2, 2, 2, 2, 2, 2, 2, 2, 2], }, 'ar-BH': { currency: ['', ' \u062f.\u0628.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-PS': { currency: ['\u20aa ', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'en-IE': { currency: ['\u20ac', ''], decimal: '.', thousands: ',', grouping: [3], }, 'it-IT': { currency: ['\u20ac', ''], decimal: ',', thousands: '.', grouping: [3], }, 'ar-EG': { currency: ['', ' \u062c.\u0645.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-IQ': { currency: ['', ' \u062f.\u0639.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-EH': { currency: ['\u062f.\u0645. ', ''], decimal: '.', thousands: ',', grouping: [3], }, 'ar-AE': { currency: ['', ' \u062f.\u0625.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-MR': { currency: ['', ' \u0623.\u0645.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'uk-UA': { currency: ['', '\u00a0\u20b4.'], decimal: ',', thousands: '\u00a0', grouping: [3], }, 'ca-ES': { currency: ['', '\u00a0\u20ac'], decimal: ',', thousands: '.', grouping: [3], }, 'sv-SE': { currency: ['', ' kr'], decimal: ',', thousands: '\u00a0', grouping: [3], }, 'ja-JP': { currency: ['', '\u5186'], decimal: '.', thousands: ',', grouping: [3], }, 'es-ES': { currency: ['', '\u00a0\u20ac'], decimal: ',', thousands: '.', grouping: [3], }, 'fi-FI': { currency: ['', '\u00a0\u20ac'], decimal: ',', thousands: '\u00a0', grouping: [3], }, 'ar-DZ': { currency: ['\u062f.\u062c. ', ''], decimal: ',', thousands: '.', grouping: [3], }, 'en-GB': { currency: ['\u00a3', ''], decimal: '.', thousands: ',', grouping: [3], }, 'cs-CZ': { currency: ['', '\u00a0K\u010d'], decimal: ',', thousands: '\u00a0', grouping: [3], }, 'ar-TD': { currency: ['\u200fFCFA ', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'de-CH': { currency: ['', '\u00a0CHF'], decimal: ',', thousands: "'", grouping: [3], }, 'nl-NL': { currency: ['\u20ac\u00a0', ''], decimal: ',', thousands: '.', grouping: [3], }, 'es-BO': { currency: ['Bs\u00a0', ''], decimal: ',', percent: '\u202f%', thousands: '.', grouping: [3], }, 'ar-SY': { currency: ['', ' \u0644.\u0633.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-JO': { currency: ['', ' \u062f.\u0623.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'en-CA': { currency: ['$', ''], decimal: '.', thousands: ',', grouping: [3], }, 'ar-ER': { currency: ['Nfk ', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-LB': { currency: ['', ' \u0644.\u0644.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'fr-CA': { currency: ['', '$'], decimal: ',', thousands: '\u00a0', grouping: [3], }, 'ar-TN': { currency: ['\u062f.\u062a. ', ''], decimal: ',', thousands: '.', grouping: [3], }, 'ar-YE': { currency: ['', ' \u0631.\u0649.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ru-RU': { currency: ['', '\u00a0\u0440\u0443\u0431.'], decimal: ',', thousands: '\u00a0', grouping: [3], }, 'en-US': { currency: ['$', ''], decimal: '.', thousands: ',', grouping: [3], }, 'ar-SS': { currency: ['\u00a3 ', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-SO': { currency: ['\u200fS ', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'hu-HU': { currency: ['', '\u00a0Ft'], decimal: ',', thousands: '\u00a0', grouping: [3], }, 'pt-BR': { currency: ['R$', ''], decimal: ',', thousands: '.', grouping: [3], }, 'ar-DJ': { currency: ['\u200fFdj ', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-SD': { currency: ['', ' \u062c.\u0633.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-001': { currency: ['', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-LY': { currency: ['\u062f.\u0644. ', ''], decimal: ',', thousands: '.', grouping: [3], }, 'ar-SA': { currency: ['', ' \u0631.\u0633.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'ar-KW': { currency: ['', ' \u062f.\u0643.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'pl-PL': { currency: ['', 'z\u0142'], decimal: ',', thousands: '.', grouping: [3], }, 'ar-QA': { currency: ['', ' \u0631.\u0642.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'mk-MK': { currency: ['', '\u00a0\u0434\u0435\u043d.'], decimal: ',', thousands: '.', grouping: [3], }, 'ko-KR': { currency: ['\u20a9', ''], decimal: '.', thousands: ',', grouping: [3], }, 'es-MX': { currency: ['$', ''], decimal: '.', thousands: ',', grouping: [3], }, 'ar-IL': { currency: ['\u20aa ', ''], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'zh-CN': { currency: ['\u00a5', ''], decimal: '.', thousands: ',', grouping: [3], }, 'de-DE': { currency: ['', '\u00a0\u20ac'], decimal: ',', thousands: '.', grouping: [3], }, 'ar-OM': { currency: ['', ' \u0631.\u0639.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'fr-FR': { currency: ['', '\u00a0\u20ac'], decimal: ',', percent: '\u202f%', thousands: '\u00a0', grouping: [3], }, 'ar-KM': { currency: ['', ' \u0641.\u062c.\u0642.'], decimal: '\u066b', thousands: '\u066c', numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], grouping: [3], }, 'he-IL': { currency: ['\u20aa', ''], decimal: '.', thousands: ',', grouping: [3], }, };
the_stack
import MdlElement from "../element/mdl_element"; export default class MdlMenu extends MdlElement{ userDefinedHeight: string; outline_: HTMLElement; container_: HTMLElement; Keycodes_: Object; handleForClick_: Function; handleForKeyboardEvent_: Function; handleItemKeyboardEvent_: Function; handleItemClick_: Function; applyClip_: Function; removeAnimationEndListener_: Function; addAnimationEndListener_: Function; show: Function; hide: Function; toggle: Function; constructor(el: HTMLElement){ super(el) } } MdlMenu.prototype.Constant_ = { // Total duration of the menu animation. TRANSITION_DURATION_SECONDS: 0.3, // The fraction of the total duration we want to use for menu item animations. TRANSITION_DURATION_FRACTION: 0.8, // How long the menu stays open after choosing an option (so the user can see // the ripple). CLOSE_TIMEOUT: 150 }; /** * Keycodes, for code readability. */ MdlMenu.prototype.Keycodes_ = { ENTER: 13, ESCAPE: 27, SPACE: 32, UP_ARROW: 38, DOWN_ARROW: 40 }; MdlMenu.prototype.CssClasses_ = { CONTAINER: 'mdl-menu__container', OUTLINE: 'mdl-menu__outline', ITEM: 'mdl-menu__item', ITEM_RIPPLE_CONTAINER: 'mdl-menu__item-ripple-container', RIPPLE_EFFECT: 'mdl-js-ripple-effect', RIPPLE_IGNORE_EVENTS: 'mdl-js-ripple-effect--ignore-events', RIPPLE: 'mdl-ripple', // Statuses IS_UPGRADED: 'is-upgraded', IS_VISIBLE: 'is-visible', IS_ANIMATING: 'is-animating', // Alignment options BOTTOM_LEFT: 'mdl-menu--bottom-left', // This is the default. BOTTOM_RIGHT: 'mdl-menu--bottom-right', TOP_LEFT: 'mdl-menu--top-left', TOP_RIGHT: 'mdl-menu--top-right', UNALIGNED: 'mdl-menu--unaligned' }; MdlMenu.prototype.init = function () { if (this.element_) { // Create container for the menu. var container = document.createElement('div'); container.classList.add(this.CssClasses_.CONTAINER); this.element_.parentElement.insertBefore(container, this.element_); this.element_.parentElement.removeChild(this.element_); container.appendChild(this.element_); this.container_ = container; // Create outline for the menu (shadow and background). var outline = document.createElement('div'); outline.classList.add(this.CssClasses_.OUTLINE); this.outline_ = outline; container.insertBefore(outline, this.element_); // Find the "for" element and bind events to it. var forElId = this.element_.getAttribute('for') || this.element_.getAttribute('data-mdl-for'); var forEl: any; if (forElId) { forEl = document.getElementById(forElId); if (forEl) { this.forElement_ = forEl; forEl.addEventListener('click', this.handleForClick_.bind(this)); forEl.addEventListener('keydown', this.handleForKeyboardEvent_.bind(this)); } } var items = this.element_.querySelectorAll('.' + this.CssClasses_.ITEM); this.boundItemKeydown_ = this.handleItemKeyboardEvent_.bind(this); this.boundItemClick_ = this.handleItemClick_.bind(this); for (var i = 0; i < items.length; i++) { // Add a listener to each menu item. items[i].addEventListener('click', this.boundItemClick_); // Add a tab index to each menu item. items[i].tabIndex = '-1'; // Add a keyboard listener to each menu item. items[i].addEventListener('keydown', this.boundItemKeydown_); } // Add ripple classes to each item, if the user has enabled ripples. if (this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)) { this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS); for (i = 0; i < items.length; i++) { var item = items[i]; var rippleContainer = document.createElement('span'); rippleContainer.classList.add(this.CssClasses_.ITEM_RIPPLE_CONTAINER); var ripple = document.createElement('span'); ripple.classList.add(this.CssClasses_.RIPPLE); rippleContainer.appendChild(ripple); item.appendChild(rippleContainer); item.classList.add(this.CssClasses_.RIPPLE_EFFECT); } } // Copy alignment classes to the container, so the outline can use them. if (this.element_.classList.contains(this.CssClasses_.BOTTOM_LEFT)) { this.outline_.classList.add(this.CssClasses_.BOTTOM_LEFT); } if (this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)) { this.outline_.classList.add(this.CssClasses_.BOTTOM_RIGHT); } if (this.element_.classList.contains(this.CssClasses_.TOP_LEFT)) { this.outline_.classList.add(this.CssClasses_.TOP_LEFT); } if (this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)) { this.outline_.classList.add(this.CssClasses_.TOP_RIGHT); } if (this.element_.classList.contains(this.CssClasses_.UNALIGNED)) { this.outline_.classList.add(this.CssClasses_.UNALIGNED); } container.classList.add(this.CssClasses_.IS_UPGRADED); } }; /** * Handles a click on the "for" element, by positioning the menu and then * toggling it. * @param {Event} evt The event that fired. */ MdlMenu.prototype.handleForClick_ = function (evt: any) { if (this.element_ && this.forElement_) { var rect = this.forElement_.getBoundingClientRect(); var forRect = this.forElement_.parentElement.getBoundingClientRect(); if (this.element_.classList.contains(this.CssClasses_.UNALIGNED)) { } else if (this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)) { // Position below the "for" element, aligned to its right. this.container_.style.right = forRect.right - rect.right + 'px'; this.container_.style.top = this.forElement_.offsetTop + this.forElement_.offsetHeight + 'px'; } else if (this.element_.classList.contains(this.CssClasses_.TOP_LEFT)) { // Position above the "for" element, aligned to its left. this.container_.style.left = this.forElement_.offsetLeft + 'px'; this.container_.style.bottom = forRect.bottom - rect.top + 'px'; } else if (this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)) { // Position above the "for" element, aligned to its right. this.container_.style.right = forRect.right - rect.right + 'px'; this.container_.style.bottom = forRect.bottom - rect.top + 'px'; } else { // Default: position below the "for" element, aligned to its left. this.container_.style.left = this.forElement_.offsetLeft + 'px'; this.container_.style.top = this.forElement_.offsetTop + this.forElement_.offsetHeight + 'px'; } } this.toggle(evt); }; /** * Handles a keyboard event on the "for" element. * @param {Event} evt The event that fired. */ MdlMenu.prototype.handleForKeyboardEvent_ = function (evt: any) { if (this.element_ && this.container_ && this.forElement_) { var items = this.element_.querySelectorAll('.' + this.CssClasses_.ITEM + ':not([disabled])'); if (items && items.length > 0 && this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)) { if (evt.keyCode === this.Keycodes_.UP_ARROW) { evt.preventDefault(); items[items.length - 1].focus(); } else if (evt.keyCode === this.Keycodes_.DOWN_ARROW) { evt.preventDefault(); items[0].focus(); } } } }; /** * Handles a keyboard event on an item. * @param {Event} evt The event that fired. */ MdlMenu.prototype.handleItemKeyboardEvent_ = function (evt: any) { if (this.element_ && this.container_) { var items = this.element_.querySelectorAll('.' + this.CssClasses_.ITEM + ':not([disabled])'); if (items && items.length > 0 && this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)) { var currentIndex = Array.prototype.slice.call(items).indexOf(evt.target); if (evt.keyCode === this.Keycodes_.UP_ARROW) { evt.preventDefault(); if (currentIndex > 0) { items[currentIndex - 1].focus(); } else { items[items.length - 1].focus(); } } else if (evt.keyCode === this.Keycodes_.DOWN_ARROW) { evt.preventDefault(); if (items.length > currentIndex + 1) { items[currentIndex + 1].focus(); } else { items[0].focus(); } } else if (evt.keyCode === this.Keycodes_.SPACE || evt.keyCode === this.Keycodes_.ENTER) { evt.preventDefault(); // Send mousedown and mouseup to trigger ripple. var e = new MouseEvent('mousedown'); evt.target.dispatchEvent(e); e = new MouseEvent('mouseup'); evt.target.dispatchEvent(e); // Send click. evt.target.click(); } else if (evt.keyCode === this.Keycodes_.ESCAPE) { evt.preventDefault(); this.hide(); } } } }; /** * Handles a click event on an item. * @param {any} evt The event that fired. */ MdlMenu.prototype.handleItemClick_ = function (evt: any) { if (evt.target.hasAttribute('disabled')) { evt.stopPropagation(); } else { // Wait some time before closing menu, so the user can see the ripple. this.closing_ = true; window.setTimeout(function (evt: any) { this.hide(); this.closing_ = false; }.bind(this), this.Constant_.CLOSE_TIMEOUT); } }; /** * Calculates the initial clip (for opening the menu) or final clip (for closing * it), and applies it. This allows us to animate from or to the correct point, * that is, the point it's aligned to in the "for" element. * * @param {number} height Height of the clip rectangle * @param {number} width Width of the clip rectangle */ MdlMenu.prototype.applyClip_ = function (height: any, width: any) { if (this.element_.classList.contains(this.CssClasses_.UNALIGNED)) { // Do not clip. this.element_.style.clip = ''; } else if (this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)) { // Clip to the top right corner of the menu. this.element_.style.clip = 'rect(0 ' + width + 'px ' + '0 ' + width + 'px)'; } else if (this.element_.classList.contains(this.CssClasses_.TOP_LEFT)) { // Clip to the bottom left corner of the menu. this.element_.style.clip = 'rect(' + height + 'px 0 ' + height + 'px 0)'; } else if (this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)) { // Clip to the bottom right corner of the menu. this.element_.style.clip = 'rect(' + height + 'px ' + width + 'px ' + height + 'px ' + width + 'px)'; } else { // Default: do not clip (same as clipping to the top left corner). this.element_.style.clip = ''; } }; /** * Cleanup function to remove animation listeners. * * @param {any} evt */ MdlMenu.prototype.removeAnimationEndListener_ = function (evt: any) { evt.target.classList.remove(MdlMenu.prototype.CssClasses_.IS_ANIMATING); }; /** * Adds an event listener to clean up after the animation ends. */ MdlMenu.prototype.addAnimationEndListener_ = function () { this.element_.addEventListener('transitionend', this.removeAnimationEndListener_); this.element_.addEventListener('webkitTransitionEnd', this.removeAnimationEndListener_); }; /** * Displays the menu. */ MdlMenu.prototype.show = function (evt: any) { if (this.element_ && this.container_ && this.outline_) { // Measure the inner element. var height = this.element_.getBoundingClientRect().height; var width = this.element_.getBoundingClientRect().width; // Apply the inner element's size to the container and outline. this.container_.style.width = width + 'px'; /* modifications */ if (this.userDefinedHeight){ this.container_.style.height = this.userDefinedHeight; } else { this.container_.style.height = height + 'px'; } /* /modifications */ this.outline_.style.width = width + 'px'; this.outline_.style.height = height + 'px'; var transitionDuration = this.Constant_.TRANSITION_DURATION_SECONDS * this.Constant_.TRANSITION_DURATION_FRACTION; // Calculate transition delays for individual menu items, so that they fade // in one at a time. var items = this.element_.querySelectorAll('.' + this.CssClasses_.ITEM); for (var i = 0; i < items.length; i++) { var itemDelay: any = null; if (this.element_.classList.contains(this.CssClasses_.TOP_LEFT) || this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)) { itemDelay = (height - items[i].offsetTop - items[i].offsetHeight) / height * transitionDuration + 's'; } else { itemDelay = items[i].offsetTop / height * transitionDuration + 's'; } items[i].style.transitionDelay = itemDelay; } // Apply the initial clip to the text before we start animating. this.applyClip_(height, width); // Wait for the next frame, turn on animation, and apply the final clip. // Also make it visible. This triggers the transitions. window.requestAnimationFrame(function () { this.element_.classList.add(this.CssClasses_.IS_ANIMATING); this.element_.style.clip = 'rect(0 ' + width + 'px ' + height + 'px 0)'; this.container_.classList.add(this.CssClasses_.IS_VISIBLE); }.bind(this)); // Clean up after the animation is complete. this.addAnimationEndListener_(); // Add a click listener to the document, to close the menu. var callback = function (e: any) { // Check to see if the document is processing the same event that // displayed the menu in the first place. If so, do nothing. // Also check to see if the menu is in the process of closing itself, and // do nothing in that case. // Also check if the clicked element is a menu item // if so, do nothing. if (e !== evt && !this.closing_ && e.target.parentNode !== this.element_) { document.removeEventListener('click', callback); this.hide(); } }.bind(this); document.addEventListener('click', callback); } }; /** * Hides the menu. */ MdlMenu.prototype.hide = function () { if (this.element_ && this.container_ && this.outline_) { var items = this.element_.querySelectorAll('.' + this.CssClasses_.ITEM); // Remove all transition delays; menu items fade out concurrently. for (var i = 0; i < items.length; i++) { items[i].style.removeProperty('transition-delay'); } // Measure the inner element. var rect = this.element_.getBoundingClientRect(); var height = rect.height; var width = rect.width; // Turn on animation, and apply the final clip. Also make invisible. // This triggers the transitions. this.element_.classList.add(this.CssClasses_.IS_ANIMATING); this.applyClip_(height, width); this.container_.classList.remove(this.CssClasses_.IS_VISIBLE); // Clean up after the animation is complete. this.addAnimationEndListener_(); } }; /** * Displays or hides the menu, depending on current state. */ MdlMenu.prototype.toggle = function (evt: any) { if (this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)) { this.hide(); } else { this.show(evt); } };
the_stack
* Autogenerated by @creditkarma/thrift-typescript v3.7.2 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING */ import Int64 from 'node-int64'; import * as thrift from 'thrift'; import * as CompressionCodec from './CompressionCodec'; import * as Encoding from './Encoding'; import * as KeyValue from './KeyValue'; import * as PageEncodingStats from './PageEncodingStats'; import * as Statistics from './Statistics'; import * as Type from './Type'; export interface IColumnMetaDataArgs { type: Type.Type; encodings: Array<Encoding.Encoding>; path_in_schema: Array<string>; codec: CompressionCodec.CompressionCodec; num_values: number | Int64; total_uncompressed_size: number | Int64; total_compressed_size: number | Int64; key_value_metadata?: Array<KeyValue.KeyValue>; data_page_offset: number | Int64; index_page_offset?: number | Int64; dictionary_page_offset?: number | Int64; statistics?: Statistics.Statistics; encoding_stats?: Array<PageEncodingStats.PageEncodingStats>; } export class ColumnMetaData { public type: Type.Type; public encodings: Array<Encoding.Encoding>; public path_in_schema: Array<string>; public codec: CompressionCodec.CompressionCodec; public num_values: Int64; public total_uncompressed_size: Int64; public total_compressed_size: Int64; public key_value_metadata?: Array<KeyValue.KeyValue>; public data_page_offset: Int64; public index_page_offset?: Int64; public dictionary_page_offset?: Int64; public statistics?: Statistics.Statistics; public encoding_stats?: Array<PageEncodingStats.PageEncodingStats>; constructor(args: IColumnMetaDataArgs) { if (args != null && args.type != null) { this.type = args.type; } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[type] is unset!' ); } if (args != null && args.encodings != null) { this.encodings = args.encodings; } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[encodings] is unset!' ); } if (args != null && args.path_in_schema != null) { this.path_in_schema = args.path_in_schema; } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[path_in_schema] is unset!' ); } if (args != null && args.codec != null) { this.codec = args.codec; } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[codec] is unset!' ); } if (args != null && args.num_values != null) { if (typeof args.num_values === 'number') { this.num_values = new Int64(args.num_values); } else { this.num_values = args.num_values; } } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[num_values] is unset!' ); } if (args != null && args.total_uncompressed_size != null) { if (typeof args.total_uncompressed_size === 'number') { this.total_uncompressed_size = new Int64(args.total_uncompressed_size); } else { this.total_uncompressed_size = args.total_uncompressed_size; } } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[total_uncompressed_size] is unset!' ); } if (args != null && args.total_compressed_size != null) { if (typeof args.total_compressed_size === 'number') { this.total_compressed_size = new Int64(args.total_compressed_size); } else { this.total_compressed_size = args.total_compressed_size; } } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[total_compressed_size] is unset!' ); } if (args != null && args.key_value_metadata != null) { this.key_value_metadata = args.key_value_metadata; } if (args != null && args.data_page_offset != null) { if (typeof args.data_page_offset === 'number') { this.data_page_offset = new Int64(args.data_page_offset); } else { this.data_page_offset = args.data_page_offset; } } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Required field[data_page_offset] is unset!' ); } if (args != null && args.index_page_offset != null) { if (typeof args.index_page_offset === 'number') { this.index_page_offset = new Int64(args.index_page_offset); } else { this.index_page_offset = args.index_page_offset; } } if (args != null && args.dictionary_page_offset != null) { if (typeof args.dictionary_page_offset === 'number') { this.dictionary_page_offset = new Int64(args.dictionary_page_offset); } else { this.dictionary_page_offset = args.dictionary_page_offset; } } if (args != null && args.statistics != null) { this.statistics = args.statistics; } if (args != null && args.encoding_stats != null) { this.encoding_stats = args.encoding_stats; } } public write(output: thrift.TProtocol): void { output.writeStructBegin('ColumnMetaData'); if (this.type != null) { output.writeFieldBegin('type', thrift.Thrift.Type.I32, 1); output.writeI32(this.type); output.writeFieldEnd(); } if (this.encodings != null) { output.writeFieldBegin('encodings', thrift.Thrift.Type.LIST, 2); output.writeListBegin(thrift.Thrift.Type.I32, this.encodings.length); this.encodings.forEach((value_1: Encoding.Encoding): void => { output.writeI32(value_1); }); output.writeListEnd(); output.writeFieldEnd(); } if (this.path_in_schema != null) { output.writeFieldBegin('path_in_schema', thrift.Thrift.Type.LIST, 3); output.writeListBegin(thrift.Thrift.Type.STRING, this.path_in_schema.length); this.path_in_schema.forEach((value_2: string): void => { output.writeString(value_2); }); output.writeListEnd(); output.writeFieldEnd(); } if (this.codec != null) { output.writeFieldBegin('codec', thrift.Thrift.Type.I32, 4); output.writeI32(this.codec); output.writeFieldEnd(); } if (this.num_values != null) { output.writeFieldBegin('num_values', thrift.Thrift.Type.I64, 5); output.writeI64(this.num_values); output.writeFieldEnd(); } if (this.total_uncompressed_size != null) { output.writeFieldBegin('total_uncompressed_size', thrift.Thrift.Type.I64, 6); output.writeI64(this.total_uncompressed_size); output.writeFieldEnd(); } if (this.total_compressed_size != null) { output.writeFieldBegin('total_compressed_size', thrift.Thrift.Type.I64, 7); output.writeI64(this.total_compressed_size); output.writeFieldEnd(); } if (this.key_value_metadata != null) { output.writeFieldBegin('key_value_metadata', thrift.Thrift.Type.LIST, 8); output.writeListBegin(thrift.Thrift.Type.STRUCT, this.key_value_metadata.length); this.key_value_metadata.forEach((value_3: KeyValue.KeyValue): void => { value_3.write(output); }); output.writeListEnd(); output.writeFieldEnd(); } if (this.data_page_offset != null) { output.writeFieldBegin('data_page_offset', thrift.Thrift.Type.I64, 9); output.writeI64(this.data_page_offset); output.writeFieldEnd(); } if (this.index_page_offset != null) { output.writeFieldBegin('index_page_offset', thrift.Thrift.Type.I64, 10); output.writeI64(this.index_page_offset); output.writeFieldEnd(); } if (this.dictionary_page_offset != null) { output.writeFieldBegin('dictionary_page_offset', thrift.Thrift.Type.I64, 11); output.writeI64(this.dictionary_page_offset); output.writeFieldEnd(); } if (this.statistics != null) { output.writeFieldBegin('statistics', thrift.Thrift.Type.STRUCT, 12); this.statistics.write(output); output.writeFieldEnd(); } if (this.encoding_stats != null) { output.writeFieldBegin('encoding_stats', thrift.Thrift.Type.LIST, 13); output.writeListBegin(thrift.Thrift.Type.STRUCT, this.encoding_stats.length); this.encoding_stats.forEach((value_4: PageEncodingStats.PageEncodingStats): void => { value_4.write(output); }); output.writeListEnd(); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; } public static read(input: thrift.TProtocol): ColumnMetaData { input.readStructBegin(); let _args: any = {}; while (true) { const ret: thrift.TField = input.readFieldBegin(); const fieldType: thrift.Thrift.Type = ret.ftype; const fieldId: number = ret.fid; if (fieldType === thrift.Thrift.Type.STOP) { break; } switch (fieldId) { case 1: if (fieldType === thrift.Thrift.Type.I32) { const value_5: Type.Type = input.readI32(); _args.type = value_5; } else { input.skip(fieldType); } break; case 2: if (fieldType === thrift.Thrift.Type.LIST) { const value_6: Array<Encoding.Encoding> = new Array<Encoding.Encoding>(); const metadata_1: thrift.TList = input.readListBegin(); const size_1: number = metadata_1.size; for (let i_1: number = 0; i_1 < size_1; i_1++) { const value_7: Encoding.Encoding = input.readI32(); value_6.push(value_7); } input.readListEnd(); _args.encodings = value_6; } else { input.skip(fieldType); } break; case 3: if (fieldType === thrift.Thrift.Type.LIST) { const value_8: Array<string> = new Array<string>(); const metadata_2: thrift.TList = input.readListBegin(); const size_2: number = metadata_2.size; for (let i_2: number = 0; i_2 < size_2; i_2++) { const value_9: string = input.readString(); value_8.push(value_9); } input.readListEnd(); _args.path_in_schema = value_8; } else { input.skip(fieldType); } break; case 4: if (fieldType === thrift.Thrift.Type.I32) { const value_10: CompressionCodec.CompressionCodec = input.readI32(); _args.codec = value_10; } else { input.skip(fieldType); } break; case 5: if (fieldType === thrift.Thrift.Type.I64) { const value_11: Int64 = input.readI64(); _args.num_values = value_11; } else { input.skip(fieldType); } break; case 6: if (fieldType === thrift.Thrift.Type.I64) { const value_12: Int64 = input.readI64(); _args.total_uncompressed_size = value_12; } else { input.skip(fieldType); } break; case 7: if (fieldType === thrift.Thrift.Type.I64) { const value_13: Int64 = input.readI64(); _args.total_compressed_size = value_13; } else { input.skip(fieldType); } break; case 8: if (fieldType === thrift.Thrift.Type.LIST) { const value_14: Array<KeyValue.KeyValue> = new Array<KeyValue.KeyValue>(); const metadata_3: thrift.TList = input.readListBegin(); const size_3: number = metadata_3.size; for (let i_3: number = 0; i_3 < size_3; i_3++) { const value_15: KeyValue.KeyValue = KeyValue.KeyValue.read(input); value_14.push(value_15); } input.readListEnd(); _args.key_value_metadata = value_14; } else { input.skip(fieldType); } break; case 9: if (fieldType === thrift.Thrift.Type.I64) { const value_16: Int64 = input.readI64(); _args.data_page_offset = value_16; } else { input.skip(fieldType); } break; case 10: if (fieldType === thrift.Thrift.Type.I64) { const value_17: Int64 = input.readI64(); _args.index_page_offset = value_17; } else { input.skip(fieldType); } break; case 11: if (fieldType === thrift.Thrift.Type.I64) { const value_18: Int64 = input.readI64(); _args.dictionary_page_offset = value_18; } else { input.skip(fieldType); } break; case 12: if (fieldType === thrift.Thrift.Type.STRUCT) { const value_19: Statistics.Statistics = Statistics.Statistics.read(input); _args.statistics = value_19; } else { input.skip(fieldType); } break; case 13: if (fieldType === thrift.Thrift.Type.LIST) { const value_20: Array<PageEncodingStats.PageEncodingStats> = new Array<PageEncodingStats.PageEncodingStats>(); const metadata_4: thrift.TList = input.readListBegin(); const size_4: number = metadata_4.size; for (let i_4: number = 0; i_4 < size_4; i_4++) { const value_21: PageEncodingStats.PageEncodingStats = PageEncodingStats.PageEncodingStats.read(input); value_20.push(value_21); } input.readListEnd(); _args.encoding_stats = value_20; } else { input.skip(fieldType); } break; default: { input.skip(fieldType); } } input.readFieldEnd(); } input.readStructEnd(); if ( _args.type !== undefined && _args.encodings !== undefined && _args.path_in_schema !== undefined && _args.codec !== undefined && _args.num_values !== undefined && _args.total_uncompressed_size !== undefined && _args.total_compressed_size !== undefined && _args.data_page_offset !== undefined ) { return new ColumnMetaData(_args); } else { throw new thrift.Thrift.TProtocolException( thrift.Thrift.TProtocolExceptionType.UNKNOWN, 'Unable to read ColumnMetaData from input' ); } } }
the_stack
import {Class, AnyTiming, Timing} from "@swim/util"; import {Affinity, MemberFastenerClass, Property} from "@swim/component"; import type {Color} from "@swim/style"; import {Look, Mood} from "@swim/theme"; import {ViewRef} from "@swim/view"; import type {GraphicsView} from "@swim/graphics"; import {Controller, TraitViewRef} from "@swim/controller"; import {DialView} from "./DialView"; import {DialLabel, DialLegend, DialTrait} from "./DialTrait"; import type {DialControllerObserver} from "./DialControllerObserver"; /** @public */ export class DialController extends Controller { override readonly observerType?: Class<DialControllerObserver>; protected updateLabel(value: number, limit: number, dialTrait: DialTrait): void { if (dialTrait.label.hasAffinity(Affinity.Intrinsic)) { const label = dialTrait.formatLabel(value, limit); if (label !== void 0) { dialTrait.label.setValue(label, Affinity.Intrinsic); } } } protected updateLegend(value: number, limit: number, dialTrait: DialTrait): void { if (dialTrait.legend.hasAffinity(Affinity.Intrinsic)) { const legend = dialTrait.formatLegend(value, limit); if (legend !== void 0) { dialTrait.legend.setValue(legend, Affinity.Intrinsic); } } } protected setValue(value: number, timing?: AnyTiming | boolean): void { const dialView = this.dial.view; if (dialView !== null && dialView.value.hasAffinity(Affinity.Intrinsic)) { if (timing === void 0 || timing === true) { timing = this.dialTiming.value; if (timing === true) { timing = dialView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } dialView.value.setState(value, timing, Affinity.Intrinsic); } } protected setLimit(limit: number, timing?: AnyTiming | boolean): void { const dialView = this.dial.view; if (dialView !== null && dialView.limit.hasAffinity(Affinity.Intrinsic)) { if (timing === void 0 || timing === true) { timing = this.dialTiming.value; if (timing === true) { timing = dialView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } dialView.limit.setState(limit, timing, Affinity.Intrinsic); } } protected setDialColor(dialColor: Look<Color> | Color | null, timing?: AnyTiming | boolean): void { const dialView = this.dial.view; if (dialView !== null) { if (timing === void 0 || timing === true) { timing = this.dialTiming.value; if (timing === true) { timing = dialView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } if (dialColor instanceof Look) { dialView.dialColor.setLook(dialColor, timing, Affinity.Intrinsic); } else { dialView.dialColor.setState(dialColor, timing, Affinity.Intrinsic); } } } protected setMeterColor(meterColor: Look<Color> | Color | null, timing?: AnyTiming | boolean): void { const dialView = this.dial.view; if (dialView !== null) { if (timing === void 0 || timing === true) { timing = this.dialTiming.value; if (timing === true) { timing = dialView.getLook(Look.timing, Mood.ambient); } } else { timing = Timing.fromAny(timing); } if (meterColor instanceof Look) { dialView.meterColor.setLook(meterColor, timing, Affinity.Intrinsic); } else { dialView.meterColor.setState(meterColor, timing, Affinity.Intrinsic); } } } protected createLabelView(label: DialLabel): GraphicsView | string | null { if (typeof label === "function") { return label(this.dial.trait); } else { return label; } } protected setLabelView(label: DialLabel | null): void { const dialView = this.dial.view; if (dialView !== null) { const labelView = label !== null ? this.createLabelView(label) : null; dialView.label.setView(labelView); } } protected createLegendView(legend: DialLegend): GraphicsView | string | null { if (typeof legend === "function") { return legend(this.dial.trait); } else { return legend; } } protected setLegendView(legend: DialLegend | null): void { const dialView = this.dial.view; if (dialView !== null) { const legendView = legend !== null ? this.createLegendView(legend) : null; dialView.legend.setView(legendView); } } @Property({type: Timing, inherits: true}) readonly dialTiming!: Property<this, Timing | boolean | undefined, AnyTiming>; @TraitViewRef<DialController, DialTrait, DialView>({ traitType: DialTrait, observesTrait: true, willAttachTrait(dialTrait: DialTrait): void { this.owner.callObservers("controllerWillAttachDialTrait", dialTrait, this.owner); }, didAttachTrait(dialTrait: DialTrait): void { const dialView = this.view; if (dialView !== null) { this.owner.setValue(dialTrait.value.value); this.owner.setLimit(dialTrait.limit.value); const dialColor = dialTrait.dialColor.value; if (dialColor !== null) { this.owner.setDialColor(dialColor); } const meterColor = dialTrait.meterColor.value; if (meterColor !== null) { this.owner.setMeterColor(meterColor); } this.owner.setLabelView(dialTrait.label.value); this.owner.setLegendView(dialTrait.legend.value); } }, didDetachTrait(dialTrait: DialTrait): void { this.owner.callObservers("controllerDidDetachDialTrait", dialTrait, this.owner); }, traitDidSetDialValue(newValue: number, oldValue: number): void { this.owner.setValue(newValue); }, traitDidSetDialLimit(newLimit: number, oldLimit: number): void { this.owner.setLimit(newLimit); }, traitDidSetDialColor(newDialColor: Look<Color> | Color | null, oldDialColor: Look<Color> | Color | null): void { this.owner.setDialColor(newDialColor); }, traitDidSetMeterColor(newMeterColor: Look<Color> | Color | null, oldMeterColor: Look<Color> | Color | null): void { this.owner.setMeterColor(newMeterColor); }, traitDidSetDialLabel(newLabel: DialLabel | null, oldLabel: DialLabel | null): void { this.owner.setLabelView(newLabel); }, traitDidSetDialLegend(newLegend: DialLegend | null, oldLegend: DialLegend | null): void { this.owner.setLegendView(newLegend); }, viewType: DialView, observesView: true, willAttachView(dialView: DialView): void { this.owner.callObservers("controllerWillAttachDialView", dialView, this.owner); }, didAttachView(dialView: DialView): void { const dialTrait = this.trait; if (dialTrait !== null) { const dialColor = dialTrait.dialColor.value; if (dialColor !== null) { this.owner.setDialColor(dialColor); } const meterColor = dialTrait.meterColor.value; if (meterColor !== null) { this.owner.setMeterColor(meterColor); } } this.owner.label.setView(dialView.label.view); this.owner.legend.setView(dialView.legend.view); if (dialTrait !== null) { const value = dialView.value.value; const limit = dialView.limit.value; this.owner.updateLabel(value, limit, dialTrait); this.owner.updateLegend(value, limit, dialTrait); this.owner.setValue(dialTrait.value.value); this.owner.setLimit(dialTrait.limit.value); this.owner.setLabelView(dialTrait.label.value); this.owner.setLegendView(dialTrait.legend.value); } }, willDetachView(dialView: DialView): void { this.owner.label.setView(null); this.owner.legend.setView(null); }, didDetachView(dialView: DialView): void { this.owner.callObservers("controllerDidDetachDialView", dialView, this.owner); }, viewWillSetDialValue(newValue: number, oldValue: number, dialView: DialView): void { this.owner.callObservers("controllerWillSetDialValue", newValue, oldValue, this.owner); }, viewDidSetDialValue(newValue: number, oldValue: number, dialView: DialView): void { const dialTrait = this.trait; if (dialTrait !== null) { const limit = dialView.limit.value; this.owner.updateLabel(newValue, limit, dialTrait); this.owner.updateLegend(newValue, limit, dialTrait); } this.owner.callObservers("controllerDidSetDialValue", newValue, oldValue, this.owner); }, viewWillSetDialLimit(newLimit: number, oldLimit: number, dialView: DialView): void { this.owner.callObservers("controllerWillSetDialLimit", newLimit, oldLimit, this.owner); }, viewDidSetDialLimit(newLimit: number, oldLimit: number, dialView: DialView): void { const dialTrait = this.trait; if (dialTrait !== null) { const value = dialView.value.value; this.owner.updateLabel(value, newLimit, dialTrait); this.owner.updateLegend(value, newLimit, dialTrait); } this.owner.callObservers("controllerDidSetDialLimit", newLimit, oldLimit, this.owner); }, viewWillAttachDialLabel(labelView: GraphicsView): void { this.owner.label.setView(labelView); }, viewDidDetachDialLabel(labelView: GraphicsView): void { this.owner.label.setView(null); }, viewWillAttachDialLegend(legendView: GraphicsView): void { this.owner.legend.setView(legendView); }, viewDidDetachDialLegend(legendView: GraphicsView): void { this.owner.legend.setView(null); }, }) readonly dial!: TraitViewRef<this, DialTrait, DialView>; static readonly dial: MemberFastenerClass<DialController, "dial">; @ViewRef<DialController, GraphicsView>({ key: true, willAttachView(labelView: GraphicsView): void { this.owner.callObservers("controllerWillAttachDialLabelView", labelView, this.owner); }, didDetachView(labelView: GraphicsView): void { this.owner.callObservers("controllerDidDetachDialLabelView", labelView, this.owner); }, }) readonly label!: ViewRef<this, GraphicsView>; static readonly label: MemberFastenerClass<DialController, "label">; @ViewRef<DialController, GraphicsView>({ key: true, willAttachView(legendView: GraphicsView): void { this.owner.callObservers("controllerWillAttachDialLegendView", legendView, this.owner); }, didDetachView(legendView: GraphicsView): void { this.owner.callObservers("controllerDidDetachDialLegendView", legendView, this.owner); }, }) readonly legend!: ViewRef<this, GraphicsView>; static readonly legend: MemberFastenerClass<DialController, "legend">; }
the_stack
import { Attribute, Block, Configuration as CSSBlocksConfiguration, Style, isFalseCondition, isTrueCondition, } from "@css-blocks/core"; import { EmberAnalysis, HandlebarsTemplate, TEMPLATE_TYPE } from "@css-blocks/ember-utils"; import type { AST, ASTPlugin, NodeVisitor, Syntax, } from "@glimmer/syntax"; import { assertNever } from "@opticss/util"; import * as debugGenerator from "debug"; import * as path from "path"; import { ElementAnalyzer, StringExpression as StringAST, TemplateElement, isStyleOfHelper } from "./ElementAnalyzer"; import { getEmberBuiltInStates, isEmberBuiltIn, isEmberBuiltInNode } from "./EmberBuiltins"; import { cssBlockError, isConcatStatement, isMustacheStatement, isPathExpression, isStringLiteral, isSubExpression, isTextNode, pathString } from "./utils"; export const CONCAT_HELPER_NAME = "-css-blocks-concat"; const enum StyleCondition { STATIC = 1, BOOLEAN = 2, TERNARY = 3, SWITCH = 4, } const enum FalsySwitchBehavior { error = 0, unset = 1, default = 2, } const NOOP_VISITOR = {}; const DEBUG = debugGenerator("css-blocks:glimmer:analyzing-rewriter"); export interface ASTPluginWithDeps extends ASTPlugin { /** * If this method exists, it is called with the relative path to the current * file just before processing starts. Use this method to reset the * dependency tracking state associated with the file. */ resetDependencies?(relativePath: string): void; /** * This method is called just as the template finishes being processed. * * @param relativePath A relative path to the file that may have dependencies. * @return paths to files that are a dependency for the given * file. Any relative paths returned by this method are taken to be relative * to the file that was processed. */ dependencies?(relativePath: string): string[]; } type ElementSourceAnalysis = ReturnType<TemplateElement["getSourceAnalysis"]>; export class TemplateAnalyzingRewriter implements ASTPluginWithDeps { visitor: NodeVisitor; visitors: NodeVisitor; elementCount: number; template: HandlebarsTemplate; block: Block | null | undefined; syntax: Syntax; elementAnalyzer: ElementAnalyzer<TEMPLATE_TYPE>; cssBlocksOpts: CSSBlocksConfiguration; helperInvocation: HelperInvocationGenerator; constructor(template: HandlebarsTemplate, block: Block | undefined | null, analysis: EmberAnalysis, options: CSSBlocksConfiguration, syntax: Syntax) { this.elementCount = 0; this.template = template; this.block = block; this.syntax = syntax; this.elementAnalyzer = new ElementAnalyzer(analysis, options); this.cssBlocksOpts = options; this.helperInvocation = new HelperInvocationGenerator(syntax.builders); if (this.block) { this.visitor = { ElementNode: this.ElementNode.bind(this), SubExpression: this.HelperStatement.bind(this), MustacheStatement: this.HelperStatement.bind(this), BlockStatement: this.HelperStatement.bind(this), }; } else { this.visitor = NOOP_VISITOR; } this.visitors = this.visitor; if (block) { block.eachBlockExport(analysis.addBlock.bind(analysis)); } } debug(message: string, ...args: unknown[]): void { DEBUG(`${this.template}: ${message}`, ...args); } get name(): string { return this.block ? "css-blocks-glimmer-rewriter" : "css-blocks-noop"; } /** * @param relativePath the relative path to the template starting at the root * of the input tree. * @returns Files this template file depends on. */ dependencies(relativePath: string): Array<string> { this.debug("Getting dependencies for", relativePath); if (!this.block) return []; let deps: Set<string> = new Set(); let importer = this.cssBlocksOpts.importer; for (let block of [this.block, ...this.block.transitiveBlockDependencies()]) { // TODO: Figure out why the importer is returning null here. let blockFile = importer.filesystemPath(block.identifier, this.cssBlocksOpts); this.debug("block file path is", blockFile); if (blockFile) { if (!path.isAbsolute(blockFile)) { // this isn't actually relative to the rootDir but it doesn't matter // because the shared root directory will be removed by the relative // path calculation. let templatePath = path.dirname(path.resolve(this.cssBlocksOpts.rootDir, relativePath)); let blockPath = path.resolve(this.cssBlocksOpts.rootDir, blockFile); blockFile = path.relative(templatePath, blockPath); } deps.add(blockFile); } // These dependencies happen when additional files get involved via preprocessors. for (let additionalDep of block.dependencies) { deps.add(additionalDep); } } let depArray = new Array(...deps); return depArray; } HelperStatement(node: AST.MustacheStatement | AST.BlockStatement | AST.SubExpression) { if (isEmberBuiltInNode(node)) { this.BuiltInStatement(node); } else if (isStyleOfHelper(node)) { this.StyleOfHelper(node); } } BuiltInStatement(node: AST.MustacheStatement | AST.BlockStatement) { this.elementCount++; let name = pathString(node); if (!isEmberBuiltIn(name)) return; const attrToStateMap = getEmberBuiltInStates(name); let atRootElement = (this.elementCount === 1); const attrMap = this.elementAnalyzer.analyzeForRewrite(node, atRootElement); // Remove all the source attributes for styles. node.hash.pairs = node.hash.pairs.filter(a => this.elementAnalyzer.isAttributeAnalyzed(a.key)[0] === null).filter(a => !attrToStateMap[a.key]); for (let attr of Object.keys(attrMap)) { let element = attrMap[attr]; if (element) { this.debug(element.forOptimizer(this.cssBlocksOpts)[0].toString()); let attrValue = this.buildClassValue(true, element); let hash = this.syntax.builders.pair(attr, attrValue!); node.hash.pairs.push(hash); } } } buildClassValue(subExpression: false, analysis: TemplateElement, node?: AST.MustacheStatement): AST.MustacheStatement | AST.ConcatStatement | null; buildClassValue(subExpression: true, analysis: TemplateElement, node?: AST.SubExpression): AST.SubExpression | null; buildClassValue(subExpression: boolean, analysis: TemplateElement, node?: AST.SubExpression | AST.MustacheStatement): AST.SubExpression | AST.MustacheStatement | AST.ConcatStatement | null { const { sexpr, path, mustache } = this.syntax.builders; if (subExpression) { if (node && !isSubExpression(node)) { throw new Error(`Illegal node ${node.type}`); } else if (!node) { node = sexpr(path(HelperInvocationGenerator.CLASSNAMES_HELPER)); } return this.helperInvocation.build(analysis, node); } else { if (node && isSubExpression(node)) { throw new Error(`Illegal node ${node.type}`); } else if (!node) { node = mustache(path(HelperInvocationGenerator.CLASSNAMES_HELPER)); } return this.helperInvocation.build(analysis, node); } } StyleOfHelper(node: AST.MustacheStatement | AST.SubExpression): void { this.elementCount++; let atRootElement = (this.elementCount === 1); let attrMap = this.elementAnalyzer.analyzeForRewrite(node, atRootElement, true); let attrNames = Object.keys(attrMap); if (attrNames.length !== 1 || attrNames[0] !== "class") { const names = attrNames.filter(name => name !== "class"); throw cssBlockError(`Unexpected attribute(s) [${names.join(", ")}] in rewrite for style-of helper.`, node, this.template.relativePath); } if (isMustacheStatement(node)) { this.buildClassValue(false, attrMap["class"], node); } else { this.buildClassValue(true, attrMap["class"], node); } } ElementNode(node: AST.ElementNode): void { this.elementCount++; let atRootElement = (this.elementCount === 1); let attrMap = this.elementAnalyzer.analyzeForRewrite(node, atRootElement); // Remove all the source attributes for styles. node.attributes = node.attributes.filter(a => this.elementAnalyzer.isAttributeAnalyzed(a.name)[0] === null); for (let attrName of Object.keys(attrMap)) { let analysis: TemplateElement = attrMap[attrName]; let attrValue = this.buildClassValue(false, analysis); if (!attrValue) continue; if (isTextNode(attrValue) && attrValue.chars === "") continue; // Add the new attribute. // This assumes the class attribute was forbidden. If we ever change // that assumption, we must merge with that attribute instead. let attr = this.syntax.builders.attr(attrName, attrValue); node.attributes.push(attr); } } } class HelperInvocationGenerator { static CLASSNAMES_HELPER = "-css-blocks"; static HELPER_VERSION = 0; builders: Syntax["builders"]; constructor(builders: Syntax["builders"]) { this.builders = builders; } build(analysis: TemplateElement, node: AST.MustacheStatement): AST.MustacheStatement | null; build(analysis: TemplateElement, node: AST.SubExpression): AST.SubExpression | null; build(analysis: TemplateElement, node: AST.SubExpression | AST.MustacheStatement): AST.SubExpression | AST.MustacheStatement | null { const { path, number: num, hash } = this.builders; let sourceAnalysis = analysis.getSourceAnalysis(); if (sourceAnalysis.size() === 0) { return null; } node.path = path(HelperInvocationGenerator.CLASSNAMES_HELPER); node.params = []; node.hash = hash(); node.params.push(num(HelperInvocationGenerator.HELPER_VERSION)); let stylesUsed = new Array<Style>(); let blocksUsed = new Array<Block>(); let staticParams = this.buildStaticParams(sourceAnalysis, stylesUsed); let ternaryParams = this.buildTernaryParams(sourceAnalysis, stylesUsed); let booleanParams = this.buildBooleanParams(sourceAnalysis, stylesUsed); let switchParams = this.buildSwitchParams(sourceAnalysis, blocksUsed); let styleParams = this.buildStyleParams(sourceAnalysis, blocksUsed, stylesUsed); let blockParams = this.buildBlockParams(blocksUsed); node.params.push(...blockParams); node.params.push(...styleParams); node.params.push(...staticParams ); node.params.push(...ternaryParams); node.params.push(...booleanParams); node.params.push(...switchParams); return node; } buildBlockParams(blocksUsed: Array<Block>): Array<AST.Expression> { const { number: num, string: str, null: nullNode } = this.builders; let blockParams = new Array<AST.Expression>(); blockParams.push(num(blocksUsed.length)); for (let block of blocksUsed) { blockParams.push(str(block.guid)); blockParams.push(nullNode()); // this could be a block when we implement block passing } return blockParams; } buildStyleParams(sourceAnalysis: ElementSourceAnalysis, blocks: Array<Block>, stylesUsed: Array<Style>): Array<AST.Expression> { const { number: num, string: str } = this.builders; let styleParams = new Array<AST.Expression>(); styleParams.push(num(stylesUsed.length)); for (let style of stylesUsed) { styleParams.push(num(blockIndex(blocks, style))); styleParams.push(str(style.asSource())); } styleParams.push(num(sourceAnalysis.size())); return styleParams; } buildStaticParams(sourceAnalysis: ElementSourceAnalysis, stylesUsed: Array<Style>): Array<AST.Expression> { const { number: num } = this.builders; let params = new Array<AST.Expression>(); for (let style of sourceAnalysis.staticStyles) { params.push(num(StyleCondition.STATIC)); params.push(num(styleIndex(stylesUsed, style))); } return params; } buildTernaryParams(sourceAnalysis: ElementSourceAnalysis, stylesUsed: Array<Style>): Array<AST.Expression> { const { number: num } = this.builders; let params = new Array<AST.Expression>(); for (let ternaryClass of sourceAnalysis.ternaryStyles) { params.push(num(StyleCondition.TERNARY)); if (isMustacheStatement(ternaryClass.condition!)) { params.push(this.mustacheToExpression(this.builders, ternaryClass.condition)); } else { params.push(ternaryClass.condition!); } if (isTrueCondition(ternaryClass)) { params.push(num(ternaryClass.whenTrue.length)); for (let cls of ternaryClass.whenTrue) { params.push(num(styleIndex(stylesUsed, cls))); } } else { // there are no classes applied if true params.push(num(0)); } if (isFalseCondition(ternaryClass)) { params.push(num(ternaryClass.whenFalse.length)); for (let cls of ternaryClass.whenFalse) { params.push(num(styleIndex(stylesUsed, cls))); } } else { // there are no classes applied if false params.push(num(0)); } } return params; } buildBooleanParams(sourceAnalysis: ElementSourceAnalysis, stylesUsed: Array<Style>): Array<AST.Expression> { const { number: num } = this.builders; let params = new Array<AST.Expression>(); for (let dynamicAttr of sourceAnalysis.booleanStyles) { params.push(num(StyleCondition.BOOLEAN)); if (isMustacheStatement(dynamicAttr.condition)) { params.push(this.mustacheToExpression(this.builders, dynamicAttr.condition)); } else { params.push(dynamicAttr.condition); } params.push(num(dynamicAttr.value.size)); for (let attr of dynamicAttr.value) { params.push(num(styleIndex(stylesUsed, attr))); } } return params; } buildSwitchParams(sourceAnalysis: ElementSourceAnalysis, blocksUsed: Array<Block>): Array<AST.Expression> { const { number: num, string: str } = this.builders; let params = new Array<AST.Expression>(); for (let switchStyle of sourceAnalysis.switchStyles) { let values = Object.keys(switchStyle.group); params.push(num(StyleCondition.SWITCH)); if (switchStyle.disallowFalsy) { params.push(num(FalsySwitchBehavior.error)); } else { params.push(num(FalsySwitchBehavior.unset)); } // We have to find the attribute that belongs to the most specific sub-block. let attr: Attribute | undefined; for (let value of values) { let attrValue = switchStyle.group[value]; if (!attr) { attr = attrValue.attribute; } else { if (attr.block.isAncestorOf(attrValue.block)) { attr = attrValue.attribute; } } } params.push(num(blockIndex(blocksUsed, attr!))); params.push(str(attr!.asSource())); params.push(this.mustacheToStringExpression(this.builders, switchStyle.stringExpression!)); } return params; } mustacheToExpression(builders: Syntax["builders"], expr: AST.MustacheStatement): AST.Expression { if (isPathExpression(expr.path)) { if (expr.params.length === 0 && expr.hash.pairs.length === 0) { return expr.path; } else { return builders.sexpr(expr.path, expr.params, expr.hash); } } else if (isStringLiteral(expr.path)) { return expr.path; } else { return expr.path; } } mustacheToStringExpression(builders: Syntax["builders"], stringExpression: Exclude<StringAST, null>): AST.Expression { if (isConcatStatement(stringExpression)) { return builders.sexpr( builders.path(CONCAT_HELPER_NAME), stringExpression.parts.reduce( (arr, val) => { if (val.type === "TextNode") { arr.push(builders.string(val.chars)); } else { arr.push(val.path); } return arr; }, new Array<AST.Expression>())); } else if (isSubExpression(stringExpression)) { return stringExpression; } else if (isPathExpression(stringExpression)) { return builders.sexpr(stringExpression); } else if (isMustacheStatement(stringExpression)) { return this.mustacheToExpression(builders, stringExpression); } else { return assertNever(stringExpression); } } } function styleIndex(stylesUsed: Array<Style>, style: Style): number { let index = stylesUsed.indexOf(style); if (index >= 0) { return index; } stylesUsed.push(style); return stylesUsed.length - 1; } function blockIndex(blocks: Array<Block>, style: Style | Attribute) { for (let i = 0; i < blocks.length; i++) { if (style.block === blocks[i] || style.block.isAncestorOf(blocks[i])) { return i; } else if (blocks[i].isAncestorOf(style.block)) { blocks[i] = style.block; return i; } } blocks.push(style.block); return blocks.length - 1; }
the_stack
import { AST_NODE_TYPES, AST_TOKEN_TYPES, STORAGE_CLASS, } from '../ast/glsl-ast-node-types'; import { ArrayExpression, AssignmentExpression, BaseNode, BinaryExpression, BlockStatement, CallExpression, ConditionalExpression, DataType, DoWhileStatement, Expression, ExpressionStatement, ForStatement, FunctionDeclaration, FunctionExpression, Identifier, IfStatement, MemberExpression, NumThreadStatement, Program, ReturnStatement, Scalar, Scope, Statement, UnaryExpression, UpdateExpression, VariableDeclaration, VariableDeclarator, WhileStatement, } from '../ast/glsl-tree'; import { DefineValuePlaceholder, GLSLContext } from '../Compiler'; import { dataTypeMap as transformDataTypeMap } from '../Transformer'; import { builtinFunctions, componentWiseFunctions, importFunctions, typeCastFunctions, } from '../utils/builtin-functions'; import { compareDataTypePriority, getByteCount, getComponentDataTypeFromVector, getComponentSize, isArray, isLeft, isMatrix, isScalar, isVector, } from '../utils/data-type'; import { getIdentifierFromScope, traverseUpwards } from '../utils/node'; import { ICodeGenerator, Target } from './ICodeGenerator'; const dataTypeMap: Record<DataType, string> = { [AST_TOKEN_TYPES.Void]: 'void', [AST_TOKEN_TYPES.Boolean]: 'bool', [AST_TOKEN_TYPES.Int32]: 'i32', [AST_TOKEN_TYPES.Uint32]: 'u32', [AST_TOKEN_TYPES.Float]: 'f32', [AST_TOKEN_TYPES.Vector2Float]: 'vec2<f32>', [AST_TOKEN_TYPES.Vector3Float]: 'vec3<f32>', [AST_TOKEN_TYPES.Vector4Float]: 'vec4<f32>', [AST_TOKEN_TYPES.Vector2Int]: 'vec2<i32>', [AST_TOKEN_TYPES.Vector3Int]: 'vec3<i32>', [AST_TOKEN_TYPES.Vector4Int]: 'vec4<i32>', [AST_TOKEN_TYPES.Vector2Uint]: 'vec2<u32>', [AST_TOKEN_TYPES.Vector3Uint]: 'vec3<u32>', [AST_TOKEN_TYPES.Vector4Uint]: 'vec4<u32>', [AST_TOKEN_TYPES.Vector2Boolean]: 'vec2<bool>', [AST_TOKEN_TYPES.Vector3Boolean]: 'vec3<bool>', [AST_TOKEN_TYPES.Vector4Boolean]: 'vec4<bool>', [AST_TOKEN_TYPES.Matrix3x3Float]: 'mat3x3<f32>', [AST_TOKEN_TYPES.Matrix4x4Float]: 'mat4x4<f32>', [AST_TOKEN_TYPES.FloatArray]: 'array<f32>', [AST_TOKEN_TYPES.Vector4FloatArray]: 'array<vec4<f32>>', }; export class CodeGeneratorWGSL implements ICodeGenerator { public static GWEBGPU_UNIFORM_PARAMS = 'gWebGPUUniformParams'; public static GWEBGPU_BUFFER = 'gWebGPUBuffer'; private context: GLSLContext; private bufferBindingIndex = -1; public clear() { this.bufferBindingIndex = -1; } public generate(program: Program, context?: GLSLContext): string { if (context) { this.context = context; } // @see https://gpuweb.github.io/gpuweb/wgsl.html#builtin-variables const body = program.body .map((stmt) => this.generateStatement(stmt)) .join('\n'); return `import "GLSL.std.450" as std; ${importFunctions[Target.WGSL]} # var gWebGPUDebug : bool = false; # var gWebGPUDebugOutput : vec4<f32> = vec4<f32>(0.0); [[builtin global_invocation_id]] var<in> globalInvocationID : vec3<u32>; # [[builtin work_group_size]] var<in> workGroupSize : vec3<u32>; # [[builtin work_group_id]] var<in> workGroupID : vec3<u32>; [[builtin local_invocation_id]] var<in> localInvocationID : vec3<u32>; # [[builtin num_work_groups]] var<in> numWorkGroups : vec3<u32>; [[builtin local_invocation_idx]] var<in> localInvocationIndex : u32; ${this.generateUniforms()} ${this.generateBuffers()} ${this.generateGlobalVariableDeclarations()} ${body} entry_point compute as "main" = main; `; } public generateStatement(stmt: Statement): string { if (stmt.type === AST_NODE_TYPES.VariableDeclaration) { return this.generateVariableDeclaration(stmt); } else if (stmt.type === AST_NODE_TYPES.FunctionDeclaration) { return this.generateFunctionExpression(stmt); } else if (stmt.type === AST_NODE_TYPES.BlockStatement) { return this.generateBlockStatement(stmt); } else if (stmt.type === AST_NODE_TYPES.NumThreadStatement) { return this.generateNumThreadStatement(stmt); } else { // tslint:disable-next-line:no-console console.warn(`[WGSL compiler]: unknown statement: ${stmt.type}`); } return ''; } public generateNumThreadStatement(stmt: NumThreadStatement): string { // 需要作为 main 函数属性声明 return ''; } public generateVariableDeclaration(stmt: VariableDeclaration): string { return stmt.declarations .map((declarator) => { if (declarator.storageClass === STORAGE_CLASS.UniformConstant) { // @see https://gpuweb.github.io/gpuweb/wgsl.html#module-constants // eg. const golden : f32 = 1.61803398875; // const define = this.context?.defines.find( // (d) => d.name === declarator.id.name, // ); // const placeHolder = `${DefineValuePlaceholder}${define?.name}`; // return `const ${declarator.id.name} : ${this.generateDataType( // declarator.id.dataType, // )} = ${ // define?.runtime // ? placeHolder // : this.generateExpression(declarator.init) // };`; // TODO: v-0022 Global variables must have a storage class // https://gpuweb.github.io/gpuweb/wgsl.html#validation } else if ( declarator.storageClass === STORAGE_CLASS.Uniform || declarator.storageClass === STORAGE_CLASS.StorageBuffer ) { // const name = declarator.id.name; // const componentDataType = getComponentDataTypeFromVector( // declarator.id.dataType, // ); // const componentDataTypeStr = this.generateDataType(componentDataType); // const dataType = this.generateDataType(declarator.id.dataType); // 不在这里生成 } else if (declarator.storageClass === STORAGE_CLASS.Private) { if (declarator.init) { // var a : f32 = 1.0; // var b : vec3<f32> = vec3<f32>(1.0, 1.0, 1.0); return `var ${declarator.id.name} : ${this.generateDataType( declarator.id.dataType, )} = ${this.generateExpression( declarator.init, declarator.id.dataType, )};`; } else { // var a : f32; // Root Scope 中不允许声明变量但不赋值 if ( stmt.parent && (stmt.parent as Program).type === AST_NODE_TYPES.Program ) { return ''; } return `var ${declarator.id.name} : ${this.generateDataType( declarator.id.dataType, )};`; } } return ''; }) .join('\n'); } public generateBlockStatement(stmt: BlockStatement): string { return stmt.body .map((s) => { if (s.type === AST_NODE_TYPES.VariableDeclaration) { return this.generateVariableDeclaration(s); } else if (s.type === AST_NODE_TYPES.ExpressionStatement) { return this.generateExpression(s.expression) + ';'; } else if (s.type === AST_NODE_TYPES.ReturnStatement) { return this.generateReturnStatement(s); } else if (s.type === AST_NODE_TYPES.IfStatement) { return this.generateIfStatement(s); } else if (s.type === AST_NODE_TYPES.ForStatement) { return this.generateForStatement(s); } else if (s.type === AST_NODE_TYPES.BreakStatement) { return 'break;'; } else if (s.type === AST_NODE_TYPES.ContinueStatement) { return 'continue;'; } else if (s.type === AST_NODE_TYPES.WhileStatement) { return this.generateWhileStatement(s); } else if (s.type === AST_NODE_TYPES.DoWhileStatement) { return this.generateDoWhileStatement(s); } else { // tslint:disable-next-line:no-console console.warn(`[WGSL compiler]: unknown statement: ${stmt}`); } return ''; }) .join('\n'); } public generateReturnStatement(stmt: ReturnStatement): string { // 必须匹配函数返回值类型,需要向上查找最近的的 FunctionDeclaration const returnType = traverseUpwards<DataType>(stmt, (currentNode) => { if ( (currentNode as FunctionDeclaration).type === AST_NODE_TYPES.FunctionDeclaration && (currentNode as FunctionDeclaration).returnType ) { return (currentNode as FunctionDeclaration).returnType; } }); return `return ${(stmt.argument && this.generateExpression(stmt.argument, returnType)) || ''};`; } public generateWhileStatement(stmt: WhileStatement): string { // https://gpuweb.github.io/gpuweb/wgsl.html#loop-statement return `loop { if (${this.generateExpression(stmt.test)}) { break; } ${this.generateStatement(stmt.body)} }`; } public generateDoWhileStatement(stmt: DoWhileStatement): string { return `loop { ${this.generateStatement(stmt.body)} if (${this.generateExpression(stmt.test)}) { break; } }`; } public generateForStatement(node: ForStatement): string { let init = ''; if (node.init?.type === AST_NODE_TYPES.VariableDeclaration) { // 修改 init 类型例如 int i = 0; node.init.declarations.forEach((d) => { d.id.dataType = AST_TOKEN_TYPES.Int32; }); init = this.generateVariableDeclaration(node.init); } else if (node.init?.type === AST_NODE_TYPES.AssignmentExpression) { init = this.generateExpression(node.init); } return `for (${init} ${node.test && this.generateExpression(node.test)}; ${node.update && this.generateExpression(node.update)}) {${this.generateBlockStatement( node.body as BlockStatement, )}}`; } public generateIfStatement(node: IfStatement): string { let consequent = ''; if (node.consequent.type === AST_NODE_TYPES.ExpressionStatement) { consequent = this.generateExpression(node.consequent.expression); } else if (node.consequent.type === AST_NODE_TYPES.BlockStatement) { consequent = this.generateBlockStatement(node.consequent); } else if (node.consequent.type === AST_NODE_TYPES.ReturnStatement) { consequent = this.generateReturnStatement(node.consequent); } else if (node.consequent.type === AST_NODE_TYPES.BreakStatement) { consequent = 'break;'; } let alternate = ''; if (node.alternate) { if (node.alternate.type === AST_NODE_TYPES.ExpressionStatement) { alternate = this.generateExpression(node.alternate.expression); } else if (node.alternate.type === AST_NODE_TYPES.BlockStatement) { alternate = this.generateBlockStatement(node.alternate); } else if (node.alternate.type === AST_NODE_TYPES.ReturnStatement) { alternate = this.generateReturnStatement(node.alternate); } else if (node.alternate.type === AST_NODE_TYPES.BreakStatement) { alternate = 'break;'; } } return `if (${this.generateExpression(node.test)}) {${consequent}}${ alternate ? `else {${alternate}}` : '' }`; } public generateFunctionExpression( stmt: FunctionDeclaration | FunctionExpression, ): string { // fn compute_main() -> void { if (stmt.body) { const attributes = ''; let append = ''; if (this.context && stmt.id?.name === 'main') { const [x, y, z] = this.context.threadGroupSize; // @see https://github.com/gpuweb/gpuweb/pull/1046/files // attributes = `[[ workgroup_size(${x},${y},${z})]]\n`; } // every function must has a return statement const lastStatment = stmt.body.body[stmt.body.body.length - 1]; if (lastStatment.type !== AST_NODE_TYPES.ReturnStatement) { append = '\nreturn;'; } return `${attributes}fn ${stmt.id?.name}(${(stmt.params || []) .map( (p) => p.type === AST_NODE_TYPES.Identifier && `${p.name} : ${this.generateDataType(p.dataType)}`, ) .join(', ')}) -> ${this.generateDataType( stmt.returnType || AST_TOKEN_TYPES.Void, )} {${this.generateBlockStatement(stmt.body)}${append}}`; } return ''; } public generateExpression( expression: Expression | null, dataType?: DataType, ): string { // @ts-ignore if (isScalar(expression?.type)) { return this.generateScalar( // @ts-ignore dataType || expression?.type, // @ts-ignore expression.value, ); // @ts-ignore } else if (isVector(expression?.type)) { // @ts-ignore return this.generateVector( // @ts-ignore dataType || expression?.type, // @ts-ignore expression.value, ); // @ts-ignore } else if (isMatrix(expression?.type)) { return this.generateMatrix( // @ts-ignore dataType || expression?.type, // @ts-ignore expression.value, ); } else if (expression?.type === AST_NODE_TYPES.ArrayExpression) { return this.generateArrayExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.Identifier) { const id = getIdentifierFromScope(expression, expression.name); const storageClass = (id?.parent as VariableDeclarator)?.storageClass; // 需要改变引用方式 if (id && storageClass) { if (storageClass === STORAGE_CLASS.StorageBuffer) { const bufferIndex = this.context.uniforms .filter((u) => u.storageClass === STORAGE_CLASS.StorageBuffer) .findIndex((u) => u.name === id.name); if (bufferIndex > -1) { return `${CodeGeneratorWGSL.GWEBGPU_BUFFER}${bufferIndex}.${expression.name}`; } } else if (storageClass === STORAGE_CLASS.Uniform) { const uniform = this.context.uniforms .filter((u) => u.storageClass === STORAGE_CLASS.Uniform) .find((u) => u.name === id.name); if (uniform) { return `${CodeGeneratorWGSL.GWEBGPU_UNIFORM_PARAMS}.${expression.name}`; } } } // 如果引用内置函数 if (componentWiseFunctions.indexOf(expression.name) > -1) { return `std::${expression.name}`; } // 如果引用常量 const define = this.context?.defines.find( (d) => d.name === expression.name, ); if (define) { const placeHolder = `${DefineValuePlaceholder}${define?.name}`; return define.runtime ? placeHolder : `${define.value}`; } // 如果使用内置类型转换函数 eg. i32(f32) // @see https://gpuweb.github.io/gpuweb/wgsl.html#conversion-expr if ( typeCastFunctions.indexOf(expression.name) > -1 && (expression?.parent as CallExpression).type === AST_NODE_TYPES.CallExpression ) { return this.generateDataType(transformDataTypeMap[expression.name]); } return this.castingDataType( dataType, expression.dataType, expression.name, ); } else if (expression?.type === AST_NODE_TYPES.BinaryExpression) { return this.generateBinaryExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.CallExpression) { return this.generateCallExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.AssignmentExpression) { return this.generateAssignmentExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.UpdateExpression) { return this.generateUpdateExpression(expression); } else if (expression?.type === AST_NODE_TYPES.MemberExpression) { return this.generateMemberExpression(expression); } else if (expression?.type === AST_NODE_TYPES.ConditionalExpression) { return this.generateConditionalExpression(expression); } else if (expression?.type === AST_NODE_TYPES.UnaryExpression) { return this.generateUnaryExpression(expression, dataType); } else { // tslint:disable-next-line:no-console console.warn( `[WGSL compiler]: unknown expression: ${expression}`, dataType, ); } return ''; } public generateUnaryExpression( expression: UnaryExpression, dataType?: DataType, ): string { return `${expression.operator}${this.generateExpression( expression.argument, dataType, )}`; } public generateConditionalExpression( expression: ConditionalExpression, ): string { // use select() instead of ternary operator // @see https://github.com/gpuweb/gpuweb/issues/826 // @see https://gpuweb.github.io/gpuweb/wgsl.html#logical-builtin-functions return `select(${this.generateExpression( expression.consequent, )}, ${this.generateExpression( expression.alternate, )}, ${this.generateExpression(expression.test)})`; } public generateMemberExpression(expression: MemberExpression): string { const objectStr = this.generateExpression(expression.object); if (expression.property.type === AST_NODE_TYPES.Identifier) { if (!expression.computed) { // swizzling & struct uniform eg. params.u_k / vec.rgba return `${objectStr}.${(expression.property as Identifier).name}`; } else { return `${objectStr}[${(expression.property as Identifier).name}]`; } } else if ( (expression.property.type === AST_TOKEN_TYPES.Float || expression.property.type === AST_TOKEN_TYPES.Int32 || expression.property.type === AST_TOKEN_TYPES.Uint32) && isFinite(Number(expression.property.value)) ) { const index = Number(expression.property.value); if ( expression.object.type === AST_NODE_TYPES.Identifier && isArray(expression.object.dataType) ) { // shared[0] 此时不能写成 shared.x return `${objectStr}[${index}]`; } else { let swizzlingComponent = 'x'; switch (index) { case 0: swizzlingComponent = 'x'; break; case 1: swizzlingComponent = 'y'; break; case 2: swizzlingComponent = 'z'; break; case 3: swizzlingComponent = 'w'; break; } // vec[0] // 考虑 getData()[0] 的情况,转译成 getData().x return `${objectStr}.${swizzlingComponent}`; } } else { // data[a + b] return `${objectStr}[${this.generateExpression(expression.property)}]`; } } public generateUpdateExpression(expression: UpdateExpression): string { const { name } = expression.argument as Identifier; // don't support i++ or ++i // @see https://gpuweb.github.io/gpuweb/wgsl.html#for-statement if (expression.operator === '++') { return `${name} = ${name} + 1`; } else if (expression.operator === '--') { return `${name} = ${name} - 1`; } return expression.prefix ? `${expression.operator}${name}` : `${name}${expression.operator}`; } public generateAssignmentExpression( expression: AssignmentExpression, dataType?: DataType, ): string { const left = this.generateExpression(expression.left, dataType); const right = this.generateExpression(expression.right, dataType); // wgsl don't support these operators: += *= -=... if (expression.operator.length > 1 && expression.operator.endsWith('=')) { const realOperator = expression.operator.substr( 0, expression.operator.length - 1, ); return `${left} = ${left} ${realOperator} ${right}`; } return `${left} ${expression.operator} ${right}`; } public generateArrayExpression( expression: ArrayExpression, dataType?: DataType, ): string { const dt = expression.dataType || dataType || AST_TOKEN_TYPES.Vector4Float; // vec3<f32>(1.0, 2.0, 3.0) return `${this.generateDataType(dt)}(${expression.elements .map((e) => this.generateExpression(e, getComponentDataTypeFromVector(dt)), ) .join(', ')})`; } public generateBinaryExpression( expression: BinaryExpression, dataType?: DataType, ): string { const needBracket = // @ts-ignore expression.parent?.type === AST_NODE_TYPES.BinaryExpression; return `${needBracket ? '(' : ''}${this.generateExpression( expression.left, dataType, )} ${expression.operator} ${this.generateExpression( expression.right, dataType, )}${needBracket ? ')' : ''}`; } // TODO: 替换 Math.sin() -> sin() public generateCallExpression( expression: CallExpression, dataType?: DataType, ): string { const isComponentWise = expression.callee.type === AST_NODE_TYPES.Identifier && componentWiseFunctions.indexOf(expression.callee.name) > -1; let params: Identifier[] = []; if (expression.callee.type === AST_NODE_TYPES.Identifier) { // 获取函数声明时的参数类型 const functionId = getIdentifierFromScope( expression, expression.callee.name, true, ); if ( functionId && (functionId.parent as FunctionDeclaration).type === AST_NODE_TYPES.FunctionDeclaration ) { params = (functionId.parent as FunctionDeclaration).params; } } return `${this.generateExpression(expression.callee)}(${expression.arguments .map((e, i) => { // if (e.type === AST_NODE_TYPES.CallExpression) { // // int(floor(v.x + 0.5)) // // 考虑函数嵌套的情况,需要丢弃掉外层推断的类型 // return this.generateExpression(e); // } return this.generateExpression( e, isComponentWise ? dataType : params[i] && params[i].dataType, ); }) .join(', ')})`; } public generateDataType(dt: DataType): string { return dataTypeMap[dt]; } public generateScalar(dt: DataType, scalar: number | boolean): string { if (dt === AST_TOKEN_TYPES.Boolean) { return `${!!scalar}`; } else if (dt === AST_TOKEN_TYPES.Float) { return this.wrapFloat(`${Number(scalar)}`); } else if (dt === AST_TOKEN_TYPES.Int32 || dt === AST_TOKEN_TYPES.Uint32) { return parseInt(`${Number(scalar)}`, 10).toString(); } return `${scalar}`; } public generateVector(dt: DataType, vector: number | boolean): string { const componentDataType = getComponentDataTypeFromVector(dt); return this.castingDataType( dt, componentDataType, this.generateScalar(componentDataType, vector), ); } public generateMatrix(dt: DataType, vector: number | boolean): string { const componentDataType = getComponentDataTypeFromVector(dt); return this.castingDataType( dt, componentDataType, this.generateScalar(componentDataType, vector), ); } private wrapFloat(float: string): string { return float.indexOf('.') === -1 ? `${float}.0` : float; } private castingDataType( dt1: DataType | undefined, dt2: DataType, content: string, ): string { // 需要强制类型转换 if (dt1 && dt1 !== dt2) { const castDataType = compareDataTypePriority(dt1, dt2); if (castDataType !== dt2) { return `${this.generateDataType(castDataType)}(${content})`; } } return content; } private generateSwizzling(dt: DataType): string { const size = getComponentSize(dt); if (size === 3) { return '.rgb'; } else if (size === 2) { return '.rg'; } else if (size === 4) { return '.rgba'; } else { return '.r'; } } private generateGlobalVariableDeclarations() { if (!this.context) { return ''; } return `${this.context.globalDeclarations .map( (gd) => `${(gd.shared && 'shared') || ''} ${this.generateDataType( getComponentDataTypeFromVector(gd.type), ).replace('[]', '')} ${gd.name}[${gd.value}];`, ) .join('\n')} `; } private generateUniforms(): string { if (!this.context) { return ''; } let offset = 0; const uniformDeclarations = this.context.uniforms .map((uniform) => { if ( uniform.storageClass === STORAGE_CLASS.Uniform // WebGPU Compute Shader 使用 buffer 而非 uniform ) { const byteCount = getByteCount(uniform.type); const ret = `[[offset ${offset}]] ${ uniform.name } : ${this.generateDataType(uniform.type)};`; offset += byteCount; return ret; } return ''; }) .join('\n ') // 缩进 .trim(); return ( uniformDeclarations && `type GWebGPUParams = [[block]] struct { ${uniformDeclarations} }; [[binding ${++this.bufferBindingIndex}, set 0]] var<uniform> ${ CodeGeneratorWGSL.GWEBGPU_UNIFORM_PARAMS } : GWebGPUParams;` ); } private generateBuffers() { if (!this.context) { return ''; } let bufferIndex = -1; return this.context.uniforms .map((u) => { if (u.storageClass === STORAGE_CLASS.StorageBuffer) { bufferIndex++; ++this.bufferBindingIndex; const componentDataType = getComponentDataTypeFromVector(u.type); return `type GWebGPUBuffer${bufferIndex} = [[block]] struct { [[offset 0]] ${u.name} : [[stride ${getByteCount( componentDataType, )}]] array<${this.generateDataType(componentDataType)}>; }; [[binding ${this.bufferBindingIndex}, set 0]] var<storage_buffer> ${ CodeGeneratorWGSL.GWEBGPU_BUFFER }${bufferIndex} : GWebGPUBuffer${bufferIndex};`; // } else if (u.type === 'image2D') { // return `layout(set = 0, binding = ${++this // .bufferBindingIndex}) uniform texture2D ${u.name}; // layout(set = 0, binding = ${++this.bufferBindingIndex}) uniform sampler ${ // u.name // }Sampler; // `; } return ''; }) .filter((line) => line) .join('\n') .trim(); } }
the_stack
import "setting-tab.less"; import assertNever from "assert-never"; import { cloneDeep } from "lodash-es"; import { App, debounce, Modal, Notice, PluginSettingTab, Setting, TextComponent, } from "obsidian"; import t from "./lang/helper"; import { filterKeyWithType, strToFragment } from "./misc"; import MNComp from "./mn-main"; import { DEFAULT_SETTINGS } from "./settings"; import { NoteViewKeys } from "./template/note-template"; import { SelViewKeys } from "./template/sel-template"; import { TocViewKeys } from "./template/toc-template"; import { Templates, TplCfgRec, TplCfgRecs, TplCfgTypes, } from "./typings/tpl-cfg"; export class MNCompSettingTab extends PluginSettingTab { constructor(public plugin: MNComp) { super(plugin.app, plugin); } display(): void { const { containerEl } = this; containerEl.empty(); this.containerEl.toggleClass("mn-settings", true); this.general(); this.templates(); } general() { this.containerEl.createEl("h2", { text: t("settings.general.heading"), }); this.dateFormat(); this.autoPaste(); this.aliasBelowH1(); } aliasBelowH1() { new Setting(this.containerEl) .setName(t("settings.general.alias_below_h1_name")) .setDesc(t("settings.general.alias_below_h1_desc")) .addToggle((toggle) => toggle .setValue(this.plugin.settings.aliasBelowH1) .onChange(async (val) => { this.plugin.settings.aliasBelowH1 = val; await this.plugin.saveSettings(); }), ); } dateFormat() { new Setting(this.containerEl) .setName(t("settings.general.date_format_name")) .setDesc( createFragment((el) => { el.appendText(t("settings.general.date_format_desc")); el.createEl("br"); el.createEl("a", { text: t("settings.general.check_details"), href: "https://momentjs.com/docs/#/displaying/format/", }); }), ) .addText((text) => { const onChange = async (value: string) => { this.plugin.settings.defaultDateFormat = value; await this.plugin.saveSettings(); }; text .setValue(this.plugin.settings.defaultDateFormat) .onChange(debounce(onChange, 500, true)); }); } autoPaste() { new Setting(this.containerEl) .setName(t("settings.general.autopaste_only_note")) .addToggle((toggle) => toggle .setValue(this.plugin.settings.autopasteOnlyNote) .onChange(async (val) => { this.plugin.settings.autopasteOnlyNote = val; await this.plugin.saveSettings(); }), ); } templates() { const { containerEl } = this; const tplHeading = containerEl.createEl("h2", { text: t("settings.tpl_cfg.heading"), }); const types = ["sel", "note", "toc"] as const, anchors = types.map((t) => { // display each section for different template types const [id, heading] = this.tplCfg(t); return createEl("li", {}, (el) => el.appendChild(createEl("a", { href: "#" + id, text: heading })), ); }); // insert links to each section tplHeading.insertAdjacentElement( "afterend", createEl("ul", { cls: "horizontal-list" }, (el) => anchors.forEach((a) => el.appendChild(a)), ), ); } tplCfg(type: TplCfgTypes): [id: string, heading: string] { const { containerEl } = this, { cfgs: nameTplMap } = this.plugin.settings.templates[type], defaultVal = DEFAULT_SETTINGS.templates[type].cfgs.get("default"), elNameMap = new WeakMap<HTMLElement, string>(); const sectionEl = containerEl.createDiv({ cls: "section", attr: { id: "mn-tpls-" + type }, }); const heading = t(`settings.tpl_cfg.headings.${type}`); // Heading new Setting(sectionEl) .addButton((b) => // add new button b .setIcon("plus-with-circle") .setTooltip(t("settings.tpl_cfg.tooltips.add_new")) .onClick(async () => { const name = Date.now().toString(), cfg = cloneDeep(defaultVal) as any; nameTplMap.set(name, cfg); render(cfg, name).scrollIntoView(); await this.plugin.saveSettings(); }), ) .then((s) => s.nameEl.createEl("h3", { text: heading })); // Template Configs const render = (cfg: TplCfgRecs, name: string): HTMLElement => { let entryEl = sectionEl.createEl( "details", { cls: ["tpl-entry"] }, (el) => elNameMap.set(el, name), ); const buttonRemove = (setting: Setting) => { const handleClick = () => { if (!nameTplMap.delete(elNameMap.get(entryEl) ?? "")) { console.error( "failed to remove %s from %o", elNameMap.get(entryEl), nameTplMap, ); } sectionEl.removeChild(entryEl); }; setting.addButton((b) => // remove button b .setClass("mod-warning") .setIcon("trash") .setTooltip(t("settings.tpl_cfg.tooltips.remove")) .onClick(handleClick), ); }, buttonPreview = (setting: Setting) => { const handleClick = async () => { const preview = await this.plugin.mnHandler.previewWith(type, name); if (preview) new PreviewTpl(this.app, preview).open(); else if (typeof preview === "string") { new Notice("Empty string rendered"); } }; setting.addButton((b) => // remove button b .setIcon("popup-open") .setTooltip(t("settings.tpl_cfg.tooltips.preview")) .onClick(handleClick), ); }, isDefault = name === "default"; // Name El new Setting(entryEl.createEl("summary", { cls: "tpl-name" })).then( (s) => { const tooltip = t("settings.tpl_cfg.tooltips.tpl_name"); if (isDefault) { s.setName(name); s.setTooltip(tooltip); } else { s.settingEl.addClass("canwarp"); s.infoEl.createEl( "input", { type: "text", attr: { spellcheck: false, "aria-label": tooltip }, }, (el) => { const onChange = async (ev: Event) => { const value = (ev.target as HTMLInputElement).value; nameTplMap.delete(name); elNameMap.set(entryEl, value); nameTplMap.set(value, cfg as any); await this.plugin.saveSettings(); }; el.value = name; el.addEventListener("change", debounce(onChange, 500, true)); }, ); buttonRemove(s); } buttonPreview(s); }, ); let toggleKeys = [] as filterKeyWithType<typeof cfg, boolean>[]; for (const [cfgK, cfgVal] of Object.entries(cfg)) { const cfgKey = cfgK as keyof typeof cfg; if (cfgKey === "templates") { switch (type) { case "sel": setTemplates(cfgVal, entryEl, this, setSel); break; case "note": setTemplates(cfgVal, entryEl, this, setNote); break; case "toc": setTemplates(cfgVal, entryEl, this, setToc); break; default: assertNever(type); } } else if ((cfgKey as keyof TplCfgRec<"toc">) === "indentChar") { const cfgToc = cfg as TplCfgRec<"toc">, keyToc = cfgKey as "indentChar"; let input: null | TextComponent = null; new Setting(entryEl) .setName(t("settings.tpl_cfg.indent_char_name")) .setDesc(t("settings.tpl_cfg.indent_char_desc")) .addText((text) => { const onChange = async (value: string) => { cfgToc[keyToc] = value; await this.plugin.saveSettings(); }; input = text .setValue(cfgVal) .onChange(debounce(onChange, 500, true)) .setDisabled(cfgVal === true); text.inputEl.hidden = cfgVal === true; text.inputEl.size = 4; text.inputEl.addClass("indent-char"); }) .addToggle((toggle) => toggle.setValue(cfgVal === true).onChange(async (val) => { cfgToc[keyToc] = val ? true : ""; if (input) { input.setDisabled(val); input.inputEl.hidden = val; } await this.plugin.saveSettings(); }), ); } else if (typeof cfgVal === "boolean") { toggleKeys.push(cfgK); } else { console.error( "Unable to render template extra param %s: %o", cfgK, cfgVal, ); } } toggleKeys.length > 0 && toggleKeys.sort().forEach((key) => { new Setting(entryEl) .setName(t(`settings.tpl_cfg.toggles_name.${key}`)) .setDesc(strToFragment(t(`settings.tpl_cfg.toggles_desc.${key}`))) .addToggle((toggle) => toggle.setValue(cfg[key]).onChange(async (value) => { cfg[key] = value; await this.plugin.saveSettings(); }), ); }); return entryEl; }; nameTplMap.forEach(render as any); return [sectionEl.id, heading]; } } class PreviewTpl extends Modal { constructor(app: App, public md: string) { super(app); } onOpen() { this.contentEl.setText(this.md); } onClose() { this.contentEl.empty(); } } type setNameDescFunc<T extends TplCfgTypes> = ( key: keyof Templates<T>, ) => [name: string, desc: string]; const setTemplates = <T extends TplCfgTypes>( templates: Templates<T>, target: HTMLElement, st: MNCompSettingTab, setNameDesc: setNameDescFunc<T>, ) => { for (const k of Object.keys(templates)) { const key = k as keyof typeof templates; let setting = new Setting(target).addTextArea((text) => { const onChange = async (value: string) => { templates[key] = value; await st.plugin.saveSettings(); }; text.setValue(templates[key]).onChange(debounce(onChange, 500, true)); text.inputEl.cols = 30; text.inputEl.rows = 5; }); const [name, desc] = setNameDesc(key); setting.setName(name).setDesc(strToFragment(desc)); } }; const setNote: setNameDescFunc<"note"> = (key) => { const getPlaceholders = (t: typeof key) => NoteViewKeys[t].map((v) => `{{${v}}}`).join(", "); switch (key) { case "body": return [ t("settings.tpl_cfg.templates_name.note_body"), t("settings.tpl_cfg.templates_desc.note_body", { cmt_ph: "{{> Comments}}", phs: getPlaceholders(key), }), ]; case "comment": return [ t("settings.tpl_cfg.templates_name.note_comment"), t("settings.tpl_cfg.templates_desc.note_comment", { phs: "{{.}}, " + getPlaceholders(key), }), ]; case "cmt_linked": return [ t("settings.tpl_cfg.templates_name.note_cmt_linked"), t("settings.tpl_cfg.templates_desc.note_cmt_linked", { phs: getPlaceholders(key), }), ]; default: assertNever(key); } }; const setSel: setNameDescFunc<"sel"> = (key) => { switch (key) { case "sel": return [ t("settings.tpl_cfg.templates_name.sel"), t("settings.tpl_cfg.templates_desc.sel", { phs: SelViewKeys.map((v) => `{{${v}}}`).join(", "), }), ]; default: assertNever(key); } }; const setToc: setNameDescFunc<"toc"> = (key) => { switch (key) { case "item": return [ t("settings.tpl_cfg.templates_name.toc_item"), t("settings.tpl_cfg.templates_desc.toc_item", { phs: TocViewKeys.map((v) => `{{${v}}}`).join(", "), }), ]; default: assertNever(key); } };
the_stack
import * as React from 'react'; import { fireEvent, wait } from '@testing-library/react'; import renderWithProvider from '@synerise/ds-utils/dist/testing/renderWithProvider/renderWithProvider'; import { ViewMeta } from '../ColumnManager.types'; import ColumnManager from '../ColumnManager'; import { Column } from '../ColumnManagerItem/ColumManagerItem.types'; interface View { meta: ViewMeta; columns: Column[]; } const ITEM_FILTER_TEXTS = { activateItemTitle: 'By activating this filter, you will cancel your unsaved filter settings', activate: 'Activate', cancel: 'Cancel', deleteConfirmationTitle: 'Delete filter', deleteConfirmationDescription: 'Deleting this filter will permanently remove it from templates library. All tables using this filter will be reset.', deleteLabel: 'Delete', deleteConfirmationYes: 'Yes', deleteConfirmationNo: 'No', noResults: 'No results', searchPlaceholder: 'Search', searchClearTooltip: 'Clear', title: 'Item filter', }; const TEXTS = { title: 'Manage columns', searchPlaceholder: 'Search', searchResults: 'Results', noResults: 'No results', visible: 'Visible', hidden: 'Hidden', saveView: 'Save view', cancel: 'Cancel', apply: 'Apply', fixedLeft: 'Fixed left', fixedRight: 'Fixed right', clear: 'Clear', viewName: 'View name', viewDescription: 'Description', viewNamePlaceholder: 'Name', viewDescriptionPlaceholder: 'Description', mustNotBeEmpty: 'Must not be empty', searchClearTooltip: 'Clear', }; const COLUMNS = [ { id: '0', name: 'User name', visible: true, type: 'text', fixed: 'left', chosen: false, selected: false, }, { id: '1', name: 'City', visible: true, type: 'text', fixed: undefined, chosen: false, selected: false, }, { id: '2', name: 'Language', visible: false, type: 'text', fixed: undefined, chosen: false, selected: false, }, { id: '3', name: 'Clients numbers', visible: false, type: 'number', fixed: undefined, chosen: false, selected: false, }, ]; const FILTERS = [ { id: '0000', name: 'Filter #1', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do elit', created: '01-05-2020 12:02', canUpdate: true, canDelete: true, canDuplicate: true, categories: ['My filters', 'All filters'], user: { firstname: 'Jan', lastname: 'Nowak', }, columns: COLUMNS, }, { id: '0001', name: 'Filter #2', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do elit', created: '01-12-2019 12:02', canUpdate: false, canDelete: false, canDuplicate: true, categories: ['All filters'], user: { firstname: 'Kamil', lastname: 'Kowalski', }, columns: COLUMNS, }, ]; const CATEGORIES = [ { label: 'All filters', hasMore: false, items: [ { id: '0000', name: 'Filter #1', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do elit', created: '01-05-2020 12:02', canUpdate: true, canDelete: true, canDuplicate: true, user: { firstname: 'Jan', lastname: 'Nowak', }, columns: COLUMNS, }, { id: '0001', name: 'Filter #2', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do elit', created: '01-12-2019 12:02', canUpdate: false, canDelete: false, canDuplicate: true, user: { firstname: 'Kamil', lastname: 'Kowalski', }, columns: COLUMNS, }, ], }, { label: 'My filters', hasMore: false, items: [ { id: '0002', name: 'Filter #3', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do elit', created: '01-05-2020 12:02', canUpdate: true, canDelete: true, canDuplicate: true, user: { firstname: 'Jan', lastname: 'Nowak', }, columns: COLUMNS, }, { id: '0003', name: 'Filter #4', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do elit', created: '01-12-2019 12:02', canUpdate: false, canDelete: false, canDuplicate: true, user: { firstname: 'Kamil', lastname: 'Kowalski', }, columns: COLUMNS, }, ], }, ]; const COLUMN_MANAGER = ( visible: boolean = true, hide: () => void = () => {}, onSave: (currentView: View) => void = () => {}, onApply = () => {}, selectedFilter = '' ) => ( <ColumnManager hide={hide} visible={visible} columns={COLUMNS} onSave={onSave} onApply={onApply} texts={TEXTS} itemFilterConfig={{ removeItem: (params: { id: string }) => {}, editItem: (params: { id: string; name: string }) => {}, selectItem: (params: { id: string }) => {}, duplicateItem: (params: { id: string }) => {}, selectedItemId: selectedFilter, categories: CATEGORIES, items: FILTERS, texts: ITEM_FILTER_TEXTS, }} /> ); describe('ColumnManager', () => { it('should render', () => { // ARRANGE const { getByText } = renderWithProvider( COLUMN_MANAGER( true, () => {}, () => {}, () => {}, '' ) ); //ASSERT expect(getByText('Manage columns')).toBeTruthy(); expect(getByText('Visible')).toBeTruthy(); expect(getByText('Hidden')).toBeTruthy(); expect(getByText('Save view')).toBeTruthy(); expect(getByText('Cancel')).toBeTruthy(); expect(getByText('Apply')).toBeTruthy(); }); it('should close himself when close or cancel button has been clicked', () => { // ARRANGE const hide = jest.fn(); const { getByTestId } = renderWithProvider( COLUMN_MANAGER( true, hide, () => {}, () => {}, '' ) ); // ACT fireEvent.click(getByTestId('ds-column-manager-close')); fireEvent.click(getByTestId('ds-column-manager-cancel')); // ASSERT expect(hide).toBeCalledTimes(2); }); it('should call onApply function with current columns configuration', () => { // ARRANGE const hide = jest.fn(); const apply = jest.fn(); const { getByTestId } = renderWithProvider(COLUMN_MANAGER(true, hide, () => {}, apply, '')); // ACT fireEvent.click(getByTestId('ds-column-manager-apply')); // ASSERT expect(apply).toBeCalledWith(COLUMNS, undefined); }); it('should save new filter', async () => { // ARRANGE const hide = jest.fn(); const apply = jest.fn(); const save = jest.fn(); const { getByTestId, getByPlaceholderText, getByText } = renderWithProvider( COLUMN_MANAGER(true, hide, save, apply, '') ); // ACT fireEvent.click(getByText('Save view')); await wait(); // ARRANGE const nameInput = getByPlaceholderText('Name'); const modalApply = getByTestId('ds-modal-apply'); // ACT fireEvent.change(nameInput, { target: { value: 'Test name' } }); fireEvent.click(modalApply); // ASSERT expect(save).toBeCalledWith({ meta: { name: 'Test name', description: '' }, columns: COLUMNS }); }); it('should show validation error on new filter modal', async () => { // ARRANGE const hide = jest.fn(); const apply = jest.fn(); const save = jest.fn(); const { getByTestId, getByText } = renderWithProvider(COLUMN_MANAGER(true, hide, save, apply, '')); // ACT fireEvent.click(getByText('Save view')); await wait(); // ARRANGE const modalApply = getByTestId('ds-modal-apply'); // ACT fireEvent.click(modalApply); await wait(); // ARRNGE const errorMessage = getByText('Must not be empty'); // ASSERT expect(errorMessage).toBeTruthy(); }); it('should show 2 visible and 2 hidden columns', async () => { // ARRANGE const hide = jest.fn(); const apply = jest.fn(); const save = jest.fn(); const { queryAllByTestId } = renderWithProvider(COLUMN_MANAGER(true, hide, save, apply, '')); const hiddenColumns = queryAllByTestId('ds-column-manager-hidden-item'); const visibleColumns = queryAllByTestId('ds-column-manager-visible-item'); // ASSERT expect(hiddenColumns.length).toBe(2); expect(visibleColumns.length).toBe(2); }); it('should show move first column to hidden list', async () => { // ARRANGE const hide = jest.fn(); const apply = jest.fn(); const save = jest.fn(); const { queryAllByTestId } = renderWithProvider(COLUMN_MANAGER(true, hide, save, apply, '')); let visibleColumns = queryAllByTestId('ds-column-manager-visible-item'); // ACT const firstItem = visibleColumns[0]; const firstSwitch = firstItem.querySelector('.ant-switch'); firstSwitch && fireEvent.click(firstSwitch); await wait(); const hiddenColumns = queryAllByTestId('ds-column-manager-hidden-item'); visibleColumns = queryAllByTestId('ds-column-manager-visible-item'); // ASSERT expect(hiddenColumns.length).toBe(3); expect(visibleColumns.length).toBe(1); }); it('should show columns which contains `city` in name', async () => { // ARRANGE const hide = jest.fn(); const apply = jest.fn(); const save = jest.fn(); const { queryAllByTestId, getByPlaceholderText } = renderWithProvider(COLUMN_MANAGER(true, hide, save, apply, '')); // ACT fireEvent.change(getByPlaceholderText('Search'), { target: { value: 'City' } }); await wait(); const filteredColumns = queryAllByTestId('ds-column-manager-filtered-item'); // ASSERT expect(filteredColumns.length).toBe(1); }); it('should show ItemFilter component', async () => { // ARRANGE const hide = jest.fn(); const apply = jest.fn(); const save = jest.fn(); const { getByTestId, getByText } = renderWithProvider(COLUMN_MANAGER(true, hide, save, apply, '')); // ACT fireEvent.click(getByTestId('ds-column-manager-show-filters')); await wait(); // ASSERT expect(getByText('Item filter')).toBeTruthy(); }); });
the_stack
// Import required packages import fs = require("fs"); import path = require("path"); import ts = require("typescript"); import Kernel = require("jp-kernel"); import diff = require("diff"); import {sys} from "typescript"; const $TScode = fs.readFileSync(path.join(__dirname, "startup.ts")).toString("utf-8"); /** * A logger class for error/debug messages */ class Logger { private static usage = ` Usage: node kernel.js [options] connection_file Options: --debug Enables debugging ITypescript kernel --off-es-module-interop Turn off warning for "esModuleInterop" option. --hide-undefined Hide 'undefined' results --hide-execution-result Hide the result of execution --protocol=major[.minor[.patch]]] The version of Jupyter protocol. --working-dir=path Working directory for this kernel --startup-script=path Location of a script which ITypescript will execute at startup. `; /** * Logging function (Do nothing by default). */ static log: (...msgs: any[]) => void = () => { }; /** * Set logger function as verbose level. */ static onVerbose() { Logger.log = (...msgs: any[]) => { process.stderr.write("KERNEL: "); console.error(msgs.join(" ")); }; } /** * Set logger function as debug level. */ static onProcessDebug() { try { const debugging = require("debug")("KERNEL:"); Logger.log = (...msgs: any[]) => { debugging(msgs.join(" ")); }; } catch (err) { Logger.onVerbose(); } } /** * Throw fatal error and exit. * @param msgs messages to be displayed */ static throwAndExit(...msgs: any[]) { console.error(msgs.join(" ")); Logger.printUsage(); process.exit(1); } /** * Print the usage string. */ static printUsage() { console.error(Logger.usage); } } /** * A data interface which represents [Config](https://n-riesco.github.io/jp-kernel/global.html#Config) class in jp-kernel */ interface KernelConfig { // Frontend connection file connection?: Object; // Session current working directory cwd: string; // Enable debug mode debug: boolean; // Do not show execution result hideExecutionResult: boolean; // Do not show undefined results hideUndefined: boolean; // Content of kernel_info_reply message kernelInfoReply: Object; // Message protocol version protocolVersion: string; // Callback invoked at session startup. // This callback can be used to setup a session; e.g. to register a require extensions. startupCallback: () => void; // Path to a script to be run at startup. // Path to a folder also accepted, in which case all the scripts in the folder will be run. startupScript?: string; // If defined, this function transpiles the request code into Javascript that can be run by the Node.js session. transpile?: (code: string) => string; } /** * Configuration builder class for ITypescript kernel */ class Configuration { // Indicate whether this kernel is under debug private _onDebug = false; // Indicate whether ESModuleInterop option should be turned off private _offESInterop = false; // Path of working directory private _workingDir: string = process.cwd(); // Indicate whether I should hide undefined result private hideUndefined = false; // Indicate whether I should hide execution result private hideExecutionResult = false; // The version of protocol private protocolVer = "5.1"; // Basic startup script (Enable $TS usage) private onStartup = function () { this.session.execute($TScode, {}); }; // Is kernel connected? private isConnSet = false; // The object handles Jupyter connection private conn: Object = {}; // The response which will be sent to Jupyter private response: Object; // The startup script private _startupScript: string; static parseOptions(lines: string[]) { const result: {kernel: any; compiler: ts.CompilerOptions} = { kernel: {}, compiler: {}, }; for (const line of lines) { let [keyword, ...args] = line.slice(1).split(" "); const val = args.join(" "); keyword = keyword.trim(); switch (keyword.toLowerCase()) { case "async": case "asynchronous": result.kernel["asynchronous"] = true; break; case "module": case "jsx": case "target": case "moduleResolution": break; default: result.compiler[keyword] = val; break; } } return result; } /** * Build-up jp-kernel Config object. */ get config(): KernelConfig { // Generate file for transpile let options: ts.CompilerOptions = { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES5, moduleResolution: ts.ModuleResolutionKind.NodeJs, esModuleInterop: !this._offESInterop }; const configFile = ts.findConfigFile(this._workingDir, ts.sys.fileExists); let tsConfigWarnings: string[] = []; if (!configFile) { tsConfigWarnings.push("<b>Configuration is not found!</b> Default configuration will be used: <pre>" + JSON.stringify(options) + "</pre>"); } else { const parseConfigHost: ts.ParseConfigFileHost = { getCurrentDirectory: () => this._workingDir, readDirectory: ts.sys.readDirectory, readFile: ts.sys.readFile, useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, fileExists: ts.sys.fileExists, onUnRecoverableConfigFileDiagnostic: (diagnostic) => { tsConfigWarnings.push("<b>Error parsing configuration file!</b><pre>" + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + "</pre>"); } }; const parsedConfig = ts.getParsedCommandLineOfConfigFile(configFile, {}, parseConfigHost); if (parsedConfig) { options = parsedConfig.options; } } let snapshot: string[] = []; let workFileVersion = 0; let prevLines = 0; let prevJSCode = ""; const copiedOpts = Object.assign({}, options); console.log(options); const FILENAME = "cell.ts"; const langServHost: ts.LanguageServiceHost = { getScriptFileNames: () => [FILENAME], getScriptVersion: fileName => workFileVersion.toString(), getScriptSnapshot: fileName => { if (fileName === FILENAME) { return ts.ScriptSnapshot.fromString(snapshot.join("\n")); } else if (!fs.existsSync(fileName)) { return undefined; } return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString()); }, getCurrentDirectory: () => this._workingDir, getCompilationSettings: () => copiedOpts, getDefaultLibFileName: options => ts.getDefaultLibFilePath(options), fileExists: (filename: string) => { return filename === FILENAME ? true : ts.sys.fileExists(filename); }, readFile: (filename: string, encoding?: string) => { return filename === FILENAME ? snapshot.join("\n") : ts.sys.readFile(filename, encoding); }, readDirectory: (path: string) => { return ts.sys.readDirectory(path); } }; const services = ts.createLanguageService(langServHost, ts.createDocumentRegistry()); const execTranspile = (fileName: string) => { const output = services.getEmitOutput(fileName); const allDiagnostics = services .getCompilerOptionsDiagnostics() .concat(services.getSyntacticDiagnostics(fileName)) .concat(services.getSemanticDiagnostics(fileName)); if (output.emitSkipped || allDiagnostics.length > 0) { throw Error(allDiagnostics.map(diagnostic => { const code = `TS${diagnostic.code}`; const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); if (diagnostic.file) { let {line, character} = diagnostic.file.getLineAndCharacterOfPosition( diagnostic.start! ); if (diagnostic.file.fileName === FILENAME) { const theErrorLine = snapshot[line]; const errorPos = "_".repeat(character) + "^"; line -= prevLines - 1; if (line < 0) { return `Conflict with a committed line: \n${theErrorLine}\n${errorPos}\n${code}: ${message}`; } else { return `Line ${line}, Character ${character + 1}\n${theErrorLine}\n${errorPos}\n${code}: ${message}`; } } else { return `${diagnostic.file.fileName} Line ${line}, Character ${character + 1}.\n${code}: ${message}`; } } else { return `${code}: ${message}`; } }).join("\n\n")); } return output.outputFiles[0].text; }; const transpiler = (rawCode: string) => { let code = rawCode.split("\n"); let overrideOptions: any = null; if (code[0].startsWith("%")) { overrideOptions = Configuration.parseOptions(code.filter(x => x.startsWith("%"))); code = code.filter(x => !x.startsWith("%")); } if (overrideOptions) { if (overrideOptions.kernel["asynchronous"]) { code = ["$$.async();"].concat(code); } for (const key of Object.getOwnPropertyNames(overrideOptions.compiler)) { const isPermanent = key.endsWith("!"); const keyname = key.replace(/!$/, ""); const parsed = JSON.parse(overrideOptions.compiler[key]); copiedOpts[keyname] = parsed; if (isPermanent) { // Rewrite default options options[keyname] = parsed; } } } workFileVersion += 1; snapshot.push(...code); if (!this._offESInterop && code.some(x => x.trim().startsWith("import ")) && !copiedOpts["esModuleInterop"]) { tsConfigWarnings.push("<b>The option 'esModuleInterop' is not true!</b> " + "Import statement may not work as expected. Consider adding 'esModuleInterop' option to your " + "tsconfig.json or add '%esModuleInterop! true' at the top of the cell."); } try { const generated = execTranspile(FILENAME); const codeChange = diff.diffLines(prevJSCode, generated, {newlineIsToken: true}); let codeslice = codeChange.filter(s => s.added).map(s => s.value).join("\n"); prevLines = snapshot.length; prevJSCode = generated; if (tsConfigWarnings && workFileVersion > 1) { // Prepend warnings before code const warnings = tsConfigWarnings.map(str => "$$.html(\"<div style='background:#ffecb3;padding:1em;border-left:2px solid #ff6d00'>" + str.replace(/"/g, "\\\"") + "</div>\");\n").join("\n"); codeslice = warnings + codeslice; tsConfigWarnings = []; } if (overrideOptions) { // Restore overrided compiler options for (const key of Object.getOwnPropertyNames(overrideOptions.compiler)) { const keyname = key.replace(/!$/, ""); copiedOpts[keyname] = options[keyname]; } } return codeslice; } catch (e) { snapshot = snapshot.slice(0, prevLines); throw e; } }; // Object for return (set by default) const baseObj: KernelConfig = { cwd: this._workingDir, hideUndefined: this.hideUndefined, hideExecutionResult: this.hideExecutionResult, protocolVersion: this.protocolVer, startupCallback: this.onStartup, debug: this._onDebug, kernelInfoReply: this.response, startupScript: this._startupScript, transpile: transpiler }; // If the connection is missing, throw error. if (this.isConnSet) { baseObj.connection = this.conn; } else { Logger.throwAndExit("Error: missing {connectionFile}"); } return baseObj; } /** * Connect jp-kernel * @param filepath Path of connection file. */ set connectionWith(filepath: string) { // If connection is already set, throw and exit. if (this.isConnSet) { Logger.throwAndExit("Error: {connectionFile} cannot be set more than once"); } this.isConnSet = true; this.conn = JSON.parse(fs.readFileSync(filepath).toString()); } // Turn on debug feature onDebug() { this._onDebug = true; } // Turn on typechecking feature offESInterop() { this._offESInterop = true; } // Turn on hiding undefined results hideUndef() { this.hideUndefined = true; } // Turn on hiding execution results hideExec() { this.hideExecutionResult = true; } /** * Set working directory as given path * @param path Path for working directory */ set workingDir(path: string) { this._workingDir = path; } /** * Set protocol version of Jupyter * @param ver Version to be set. */ set protocolVersion(ver: string) { this.protocolVer = ver; const majorVersion: number = parseInt(ver.split(".")[0]); if (majorVersion <= 4) { const tsVer = ts.version.split(".") .map(function (v) { return parseInt(v, 10); }); const protocolVersion = ver.split(".") .map(function (v) { return parseInt(v, 10); }); this.response = { "language": "typescript", "language_version": tsVer, "protocol_version": protocolVersion, }; } else { const itsVersion = JSON.parse( fs.readFileSync(path.join(__dirname, "..", "package.json")).toString() ).version; this.response = { "protocol_version": ver, "implementation": "typescript", "implementation_version": itsVersion, "language_info": { "name": "typescript", "version": ts.version, "mimetype": "application/x-typescript", "file_extension": ".ts" }, "banner": ( "ITypescript v" + itsVersion + "\n" + "https://github.com/winnekes/itypescript\n" ), "help_links": [{ "text": "TypeScript Doc", "url": "http://typescriptlang.org/docs/", }], }; } } /** * Set startup script * @param script Script code to be launched. */ set startupScript(script: string) { this._startupScript = script; } } /** * Argument parser class */ class Parser { /** * Parse arguments of this process */ static parse() { // Generate a configuration builder const configBuilder = new Configuration(); // Load arguments const argv = process.argv.slice(2); // For each arguments, check and update configuration. for (const arg of argv) { const [name, ...values] = arg.slice(2).split("="); switch (name) { case "debug": configBuilder.onDebug(); Logger.onVerbose(); break; case "hide-undefined": configBuilder.hideUndef(); break; case "hide-execution-result": configBuilder.hideExec(); break; case "protocol": configBuilder.protocolVersion = values.join("="); break; case "working-dir": configBuilder.workingDir = values.join("="); break; case "startup-script": configBuilder.startupScript = values.join("="); break; default: configBuilder.connectionWith = arg; break; } } return configBuilder.config; } } /** * Below: Launch codes for Kernel ***/ // Check whether DEBUG is set in the environment if (process.env["DEBUG"]) { Logger.onProcessDebug(); } // Parse configuration const config = Parser.parse(); // Start kernel with parsed configuration const kernel = new Kernel(config); // Interpret a SIGINT signal as a request to interrupt the kernel process.on("SIGINT", function () { Logger.log("Interrupting kernel"); kernel.destroy(); // Destroy the connection });
the_stack
import * as moment from 'moment-timezone'; import { ArgumentOutOfRangeException, ArgumentException } from "../js/Exceptions/ArgumentException"; export class TimeSpan { private get duration(): moment.Duration { return this.getMomentDuration(); } private getMomentDuration: () => moment.Duration; private setMomentDuration: (value) => void; constructor(ms: number); constructor(duration: moment.DurationInputArg1 | moment.DurationInputObject); constructor(hours: number, minutes: number, seconds); constructor(days: number, hours: number, minutes: number, seconds); constructor(days: number, hours: number, minutes: number, seconds: number, milliseconds); constructor(daysOrHoursOrMsOrDuration: number | moment.Duration, hoursOrMinutes?: number, minutesOrSeconds?: number, seconds?: number, milliseconds?: number) { let duration: moment.Duration = null; let argsLength = arguments.length; if (argsLength === 1) { duration = moment.duration(daysOrHoursOrMsOrDuration); } else { let momentInput: moment.DurationInputObject = {}; if (argsLength === 3) { momentInput.hours = <number>daysOrHoursOrMsOrDuration; momentInput.minutes = hoursOrMinutes; momentInput.seconds = minutesOrSeconds; } if (argsLength >= 4) { momentInput.days = <number>daysOrHoursOrMsOrDuration; momentInput.hours = hoursOrMinutes; momentInput.minutes = minutesOrSeconds; momentInput.seconds = seconds; } if (argsLength === 5) { momentInput.millisecond = milliseconds; } duration = moment.duration(momentInput); } this.getMomentDuration = () => duration; this.setMomentDuration = (value) => duration = value; } humanize(withSuffix?: boolean): string { return this.duration.humanize(withSuffix); } as(units: moment.unitOfTime.Base): number { return this.duration.as(units); } get Milliseconds(): number { return this.duration.milliseconds(); } get TotalMilliseconds(): number { return this.duration.asMilliseconds(); } get Seconds(): number { return this.duration.seconds(); } get TotalSeconds(): number { return this.duration.asSeconds(); } get Minutes(): number { return this.duration.minutes(); } get TotalMinutes(): number { return this.duration.asMinutes(); } get Hours(): number { return this.duration.hours(); } get TotalHours(): number { return this.duration.asHours(); } get Days(): number { return this.duration.days(); } get TotalDays(): number { return this.duration.asDays(); } get Months(): number { return this.duration.months(); } get TotalMonths(): number { return this.duration.asMonths(); } get Years(): number { return this.duration.years(); } get TotalYears(): number { return this.duration.asYears(); } get Weeks(): number { return this.duration.weeks() } get Totalweeks(): number { return this.duration.asWeeks() } Add(num: number, unit: moment.unitOfTime.Base): TimeSpan; Add(ms: number): TimeSpan; Add(ts: TimeSpan): TimeSpan; Add(a: number | TimeSpan, p?: moment.unitOfTime.Base): TimeSpan { if (arguments.length === 1) { return new TimeSpan(typeof a === 'number' ? this.duration.add(a) : a.TotalMilliseconds); } else { return new TimeSpan(this.duration.add(a as number, p)); } } Subtract(n: number, p: moment.unitOfTime.Base): TimeSpan; Subtract(n: number): TimeSpan; Subtract(d: TimeSpan): TimeSpan; Subtract(a: any, p?: moment.unitOfTime.Base): TimeSpan { if (arguments.length === 1) { return new TimeSpan(this.duration.subtract(a)); } else { return new TimeSpan(this.duration.subtract(a, p)); } } ToISOString(): string { return this.duration.toISOString(); } ToJSON(): string { return this.duration.toJSON(); } /** @internal */ public static MillisPerSecond: number = 1000; //const /** @internal */ public static MillisPerMinute: number = TimeSpan.MillisPerSecond * 60; // 60,000 //const /** @internal */ public static MillisPerHour: number = TimeSpan.MillisPerMinute * 60; // 3,600,000 //const /** @internal */ public static MillisPerDay: number = TimeSpan.MillisPerHour * 24; // 86,400,000 //const private static MaxSeconds: number = Number.MAX_VALUE / TimeSpan.MillisPerSecond;// TimeSpan.TicksPerSecond; //const private static MinSeconds: number = Number.MIN_VALUE / TimeSpan.MillisPerSecond;// TimeSpan.TicksPerSecond; //const private static MaxMilliSeconds: number = Number.MAX_VALUE;/// TimeSpan.TicksPerMillisecond; //const private static MinMilliSeconds: number = Number.MIN_VALUE;/// TimeSpan.TicksPerMillisecond; //const //private static TicksPerTenthSecond:number = TimeSpan.TicksPerMillisecond * 100; //const public static readonly Zero: TimeSpan = new TimeSpan(0);//readonly public static readonly MaxValueTimeSpan = new TimeSpan(Number.MAX_VALUE);//readonly public static readonly MinValueTimeSpan = new TimeSpan(Number.MIN_VALUE);//readonly public static FromDays(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerDay); } public static FromHours(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerHour); } public static FromMilliseconds(value: number): TimeSpan { return new TimeSpan(value); } public static FromMinutes(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerMinute); } public static FromSeconds(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerSecond); } valueOf() { return this.duration.asMilliseconds(); } toString() { return this.duration.toISOString(); } } module TimeSpan2 { /** TimeSpan basics from c# using momentjs */ class TimeSpan { // non ticks use in js - public static TicksPerMillisecond:number = 10000; //const // non ticks use in js - private static MillisecondsPerTick:number = 1.0 / TimeSpan.TicksPerMillisecond; //const // non ticks use in js - public static TicksPerSecond:number = TimeSpan.TicksPerMillisecond * 1000; // 10,000,000 //const // non ticks use in js - private static SecondsPerTick:number = 1.0 / TimeSpan.TicksPerSecond; // 0.0001 //const // non ticks use in js - public static TicksPerMinute:number = TimeSpan.TicksPerSecond * 60; // 600,000,000 //const // non ticks use in js - private static MinutesPerTick:number = 1.0 / TimeSpan.TicksPerMinute; // 1.6666666666667e-9 //const // non ticks use in js - public static TicksPerHour:number = TimeSpan.TicksPerMinute * 60; // 36,000,000,000 //const // non ticks use in js - private static HoursPerTick:number = 1.0 / TimeSpan.TicksPerHour; // 2.77777777777777778e-11 //const // non ticks use in js - public static TicksPerDay:number = TimeSpan.TicksPerHour * 24; // 864,000,000,000 //const // non ticks use in js - private static DaysPerTick:number = 1.0 / TimeSpan.TicksPerDay; // 1.1574074074074074074e-12 //const private static MillisPerSecond: number = 1000; //const private static MillisPerMinute: number = TimeSpan.MillisPerSecond * 60; // 60,000 //const private static MillisPerHour: number = TimeSpan.MillisPerMinute * 60; // 3,600,000 //const private static MillisPerDay: number = TimeSpan.MillisPerHour * 24; // 86,400,000 //const private static MaxSeconds: number = Number.MAX_VALUE / TimeSpan.MillisPerSecond;// TimeSpan.TicksPerSecond; //const private static MinSeconds: number = Number.MIN_VALUE / TimeSpan.MillisPerSecond;// TimeSpan.TicksPerSecond; //const private static MaxMilliSeconds: number = Number.MAX_VALUE;/// TimeSpan.TicksPerMillisecond; //const private static MinMilliSeconds: number = Number.MIN_VALUE;/// TimeSpan.TicksPerMillisecond; //const //private static TicksPerTenthSecond:number = TimeSpan.TicksPerMillisecond * 100; //const public static Zero: TimeSpan = new TimeSpan(0);//readonly public static MaxValueTimeSpan = new TimeSpan(Number.MAX_VALUE);//readonly public static MinValueTimeSpan = new TimeSpan(Number.MIN_VALUE);//readonly private _millis: number = 0; public constructor(milliseconds: number); public constructor(hours: number, minutes: number, seconds: number); public constructor(days: number, hours: number, minutes: number, seconds: number); public constructor(days: number, hours: number, minutes: number, seconds: number, milliseconds: number); public constructor(millisOrHrsOrDays: number, minsOrHrs?: number, secsOrMins?: number, seconds?: number, milliseconds?: number) { let argsLength: number = arguments.length; let millis = 0; if (typeof milliseconds !== 'undefined') millis = milliseconds; switch (argsLength) { case 1: this._millis = millisOrHrsOrDays; break; case 3: this._millis = TimeSpan.TimeToTicks(millisOrHrsOrDays, minsOrHrs, secsOrMins); break; case 4: case 5: let totalSeconds = millisOrHrsOrDays * 24 * 3600 + minsOrHrs * 3600 + secsOrMins * 60 + seconds; if (totalSeconds > TimeSpan.MaxSeconds || totalSeconds < TimeSpan.MinSeconds) throw new ArgumentOutOfRangeException("DateTime.ts - TimeSpan.ctor - Overflow_TimeSpanTooLong"); this._millis = totalSeconds * TimeSpan.MillisPerSecond + millis; break default: throw new Error("DateTime.ts - TimeSpan.ctor - invalid number of arguments"); } } private static TimeToTicks(hour: number, minute: number, second: number): number { // totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31, // which is less than 2^44, meaning we won't overflow totalSeconds. let totalSeconds = hour * 3600 + minute * 60 + second; if (totalSeconds > this.MaxSeconds || totalSeconds < this.MinSeconds) throw new ArgumentOutOfRangeException("DateTime.ts - TimeSpan.TimeToTicks - Overflow_TimeSpanTooLong"); return totalSeconds * this.MillisPerSecond; } public get Days(): number { return Math.floor(this._millis / TimeSpan.MillisPerDay); } public get Hours(): number { return Math.floor(this._millis / TimeSpan.MillisPerHour); } public get Milliseconds(): number { return Math.floor(this._millis); } public get Minutes(): number { return Math.floor(this._millis / TimeSpan.MillisPerMinute); } public get Seconds(): number { return Math.floor(this._millis / TimeSpan.MillisPerSecond); } //public get Ticks(): number { return Math.floor( this._millis / TimeSpan.); } public get TotalDays(): number { return this._millis / TimeSpan.MillisPerDay; } public get TotalHours(): number { return this._millis / TimeSpan.MillisPerHour; } public get TotalMilliseconds(): number { return this._millis; } public get TotalMinutes(): number { return this._millis / TimeSpan.MillisPerMinute; } public get TotalSeconds(): number { return this._millis / TimeSpan.MillisPerSecond; } // Compares two TimeSpan values, returning an integer that indicates their // relationship. // public static Compare(t1: TimeSpan, t2: TimeSpan): number { if (t1._millis > t2._millis) return 1; if (t1._millis < t2._millis) return -1; return 0; } public static Equals(t1: TimeSpan, t2: TimeSpan): boolean { return t1._millis === t2._millis; } public static FromDays(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerDay); } public static FromHours(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerHour); } public static FromMilliseconds(value: number): TimeSpan { return new TimeSpan(value); } public static FromMinutes(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerMinute); } public static FromSeconds(value: number): TimeSpan { return new TimeSpan(value * TimeSpan.MillisPerSecond); } //public static FromTicks(value: number): TimeSpan{ return new TimeSpan(value * TimeSpan.MillisPerDay); } public static Parse(s: string): TimeSpan { return null; } //public static Parse(input: string, formatProvider: IFormatProvider): TimeSpan; //public static ParseExact(string input, string[] formats, IFormatProvider formatProvider): TimeSpan; //public static ParseExact(string input, string format, IFormatProvider formatProvider): TimeSpan; //public static ParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles): TimeSpan; //public static ParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles): TimeSpan; //public static TryParse(string s, out TimeSpan result): boolean; //public static TryParse(string input, IFormatProvider formatProvider, out TimeSpan result): boolean; //public static TryParseExact(string input, string[] formats, IFormatProvider formatProvider, out TimeSpan result): boolean; //public static TryParseExact(string input, string format, IFormatProvider formatProvider, out TimeSpan result): boolean; //public static TryParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result): boolean; //public static TryParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result): boolean { } public Add(ts: TimeSpan): TimeSpan { let result = this._millis + ts._millis; // Overflow if signs of operands was identical and result's sign was opposite. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((this._millis >>> 63 === ts._millis >> 63) && (this.Milliseconds >>> 63 !== result >> 63)) throw new Error("Overflow_TimeSpanTooLong");//OverflowException return new TimeSpan(result); } public CompareTo(value: TimeSpan): number; public CompareTo(value: any): number; public CompareTo(value: any): number { if (!(value instanceof TimeSpan)) throw new Error("Arg_MustBeTimeSpan");//ArgumentException let m: number = (<TimeSpan>value)._millis; if (this._millis > m) return 1; if (this._millis < m) return -1; return 0; } // public Duration(): TimeSpan; // public Equals(objTimeSpan): boolean; // public override bool Equals(object value); // public override int GetHashCode(); // public Negate(): TimeSpan; // public Subtract(ts: TimeSpan): TimeSpan; // public ToString(): string; // public ToString(format: string): string; // public ToString(format: string, formatProvider: IFormatProvider): string; // public static TimeSpan operator + (TimeSpan t); // public static TimeSpan operator + (TimeSpan t1, TimeSpan t2); // public static TimeSpan operator - (TimeSpan t); // public static TimeSpan operator - (TimeSpan t1, TimeSpan t2); // public static bool operator == (TimeSpan t1, TimeSpan t2); // public static bool operator != (TimeSpan t1, TimeSpan t2); // public static bool operator <(TimeSpan t1, TimeSpan t2); // public static bool operator >(TimeSpan t1, TimeSpan t2); // public static bool operator <= (TimeSpan t1, TimeSpan t2); // public static bool operator >= (TimeSpan t1, TimeSpan t2); } }
the_stack
declare namespace Layui { /** * 第一个按钮回调即yes回调 * @param [index] 当前层索引参数 * @param [layero] 当前层的jqDOM */ type LayerCallbackYes = (index: number, layero: JQuery) => boolean | void; /** * 层关闭的回调,如果不想关闭,return false即可 * @param [index] 当前层索引参数 * @param [layero] 当前层的DOM对象 */ type LayerCallbackCancel = (index: number, layero: JQuery) => boolean | void; type LayerCallbackEnd = () => void; type LayerCallbackFull = (layero: JQuery) => void; type LayerCallbackMin = (layero: JQuery, index: number) => void; type LayerCallbackRestore = (layero: JQuery) => void; /** * 输入层 * @param [value] 输入的值 * @param [index] 当前层实例的索引 * @param [layero] 当前层的jqDOM */ type LayerCallbackPrompt = (value: string, index: number, layero: JQuery) => void; type ExportsCallback = (this: Layui, fn: (app: string, exports: object) => void) => void; /** * 全局属性 */ interface GlobalConfigOptions { /** * layui.js 所在目录(如果是 script 单独引入 layui.js,无需设定该参数)一般可无视 */ dir?: string; /** * 一般用于更新模块缓存,默认不开启。设为 true 即让浏览器不缓存。也可以设为一个固定的值,如:201610 */ version?: boolean; /** * 用于开启调试模式,默认 false,如果设为 true,则JS模块的节点会保留在页面 */ debug?: boolean; /** * 设定扩展的 layui 模块的所在目录,一般用于外部模块扩展 */ base?: string; } /** * 地址中的参数和路径信息 */ interface UrlHash { hash: string; href?: string; path: string[]; search: { [index: string]: string }; } interface CarouselOption { /** * 指向容器选择器,如:elem: '#id'。也可以是DOM对象 */ elem?: string | HTMLElement | JQuery; /** * 设定轮播容器宽度,支持像素和百分比 默认:'600px' * @default '600px' */ width?: string; /** * 设定轮播容器高度,支持像素和百分比 * @default '280px' */ height?: string; /** * 是否全屏轮播 * @default false */ full?: boolean; /** * 轮播切换动画方式 * @default 'default' * @example * anim: 'default' //(左右切换) * anim: 'updown' //(上下切换) * anim: 'fade' //(渐隐渐显切换) */ anim?: 'default' | 'updown' | 'fade'; /** * 是否自动切换 * @default true */ autoplay?: boolean; /** * 自动切换的时间间隔,单位:ms(毫秒),不能低于800 * @default 3000 */ interval?: number; /** * 初始开始的条目索引 * @default 0 */ index?: number; /** * 切换箭头默认显示状态 * @default 'hover' * @example * arrow: hover // (悬停显示) * arrow: always // (始终显示) * arrow: none //(始终不显示) */ arrow?: 'hover' | 'always' | 'none'; /** * 指示器位置 * @default 'inside' * @example * indicator: inside // (容器内部) * indicator: outside // (容器外部) * indicator: none //(不显示) */ indicator?: 'insider' | 'outsider' | 'none'; /** * 指示器的触发事件 * @default 'click' */ trigger?: string; } interface CarouselItem { /** * 当前条目的索引 */ index: number; /** * 上一个条目的索引 */ prevIndex: number; /** * 当前条目的元素对象 */ item: JQuery; } interface CarouselClass { /** * 配置属性 */ config: CarouselOption; /** * 初始焦点 */ elemItem: JQuery; /** * 轮播渲染 */ render(): void; /** * 重置轮播 */ reload(options: { [index: string]: string }): void; /** * 获取上一个等待条目的索引 */ prevIndex(): number; /** * 获取下一个等待条目的索引 */ nextIndex(): number; /** * 手动递增索引值 */ addIndex(num: number): void; /** * 手动递减索引值 */ subIndex(num: number): void; /** * 自动轮播 */ autoplay(): void; /** * 箭头 */ arrow(): void; /** * 指示器 */ indicator(): void; /** * 滑动切换 type :sub减,其他增 */ slide(type: string, num: number): void; /** * 事件处理 */ events(): void; } // https://www.layui.com/doc/modules/carousel.html // carousel 是 layui 2.0 版本中新增的全新模块,主要适用于跑马灯/轮播等交互场景。 // 它并非单纯地为焦点图而生,准确地说,它可以满足任何类型内容的轮播式切换操作, // 更可以胜任 FullPage (全屏上下轮播)的需求,简洁而不失强劲,灵活而优雅。 /** * 轮播组件 */ interface Carousel { config: { [index: string]: any }; /** * 核心入口 */ render(options: CarouselOption): object; /** * 绑定切换事件 * @param [event] 事件 * @param [callback] 回调 */ on(event: string, callback: (this: CarouselClass, obj: CarouselItem) => any): any; /** * 重置轮播 * @param [options] 基础参数 */ reload(options?: CarouselOption): void; /** * 设置轮播组件的全局参数 * @param [options] 基础参数 */ set(options?: CarouselOption): Carousel; } /** * code高亮参数 */ interface CodeOption { /** * 指定元素的选择器 默认值为.layui-code */ elem?: string; /** * 设定标题 默认值为code */ title?: string; /** * 设置最大高度,请注意必须加px,默认无:则会自适应高度,且不会出现滚动条 */ height?: string; /** * 是否转义html标签,默认false */ encode?: boolean; /** * 风格选择(目前内置了两种:默认和notepad) */ skin?: string; /** * 是否剔除右上关于 */ about?: boolean; } interface ColorPickerOption { /** * 指向容器选择器 */ elem?: string | HTMLElement | JQuery; /** * 默认颜色,不管你是使用 hex、rgb 还是 rgba 的格式输入,最终会以指定的格式显示。 */ color?: string; /** * 颜色显示/输入格式,可选值: hex、rgb <br/>&nbsp; * 若在 rgb 格式下开启了透明度,格式会自动变成 rgba。在没有输入颜色的前提下,组件会默认为 #000 也就是黑色。 */ format?: 'hex' | 'rgb' | 'rgba'; /** * 是否开启透明度,若不开启,则不会显示透明框。<br/>&nbsp; * 开启了透明度选项时,当你的默认颜色为 hex 或 rgb 格式,组件会默认加上值为 1 的透明度。<br/>&nbsp; * 相同的,当你没有开启透明度,却以 rgba 格式设置默认颜色时,组件会默认没有透明度。<br/>&nbsp; * 注意:该参数必须配合 rgba 颜色值使用 */ alpha?: boolean; /** * 预定义颜色是否开启 */ predefine?: boolean; /** * 预定义颜色,此参数需配合 predefine: true 使用。 */ colors?: string[]; /** * 下拉框大小,可以选择:lg、sm、xs。 */ size?: 'lg' | 'sm' | 'xs'; /** * 颜色被改变的回调 */ change?(this: ColorPickerOption, color: string): void; /** * 颜色选择后的回调 */ done?(this: ColorPickerOption, color: string): void; } // https://www.layui.com/doc/modules/colorpicker.html /** * 颜色选择器 */ interface ColorPicker { config: { [index: string]: any }; index: number; render(option: ColorPickerOption): ColorPicker; set(option: ColorPickerOption): ColorPicker; /** * 绑定切换事件 * @param [event] 事件名 * @param [callback] 回调函数 */ on(event: string, callback: (this: Layui, params: any) => any): any; } interface DropDownOptionData { /** * 菜单标题 */ title?: string; /** * 菜单 ID。用户菜单项唯一索引 */ id?: string | number; /** * 菜单项的超链接地址。若填写,点击菜单将直接发生跳转。 */ href?: string; /** * 菜单项超链接的打开方式,需 href 填写才生效。 <br/>&nbsp; * 一般可设为 _blank 或 _self 等 默认:_self */ target?: string; /** * 菜单项的类型,normal(默认) ,group(垂直菜单组) <br/>&nbsp; * parent(横向父子菜单) ,-(分割线) 默认:normal 或 不填 */ type?: string; /** * 子级菜单数据项。参数同父级,可无限嵌套。 默认:[] */ child?: any[]; /** * 自定义当前菜单项模板,优先级高于全局设定的 templet。详见下文。 */ templet?: string; [index: string]: any; } interface DropDownOption { /** * 绑定触发组件的元素。必填项 */ elem: string | HTMLElement | JQuery; /** * 菜单列数据项,其参数详见下文。必填项 也可用content支持模板 */ data?: DropDownOptionData[]; /** * 给当前实例设置个唯一标识 */ id?: string; /** * 触发组件的事件类型。支持所有事件,如:click/hover/mousedown/contextmenu 等 默认:click */ trigger?: string; /** * 是否初始即显示组件面板 默认:false */ show?: boolean; /** * 下拉面板相对绑定元素的水平对齐方式(支持: left/center/right) v2.6.8 新增 默认:left */ align?: 'left' | 'center' | 'right'; /** * 是否允许菜单组展开收缩 默认:true */ isAllowSpread?: boolean; /** * 是否初始展开子菜单 默认:true */ isSpreadItem?: boolean; /** * 延迟关闭的毫秒数。当 trigger 为 hover 时才生效 默认:300 */ delay?: number; /** * 自定义组件的样式类名 */ className?: string; /** * 设置组件的 style 属性,从而定义新的样式 */ style?: string; /** * 全局定义菜单的列表模板,添加任意 html 字符,模版将被 laytpl 组件所转义,<br/>&nbsp; * 因此可通过 {{ d.title }} 的方式得到当前菜单配置的数据。<br/>&nbsp; * 详见 https:// www.layui.com/doc/modules/dropdown.html#templet */ templet?: string; /** * 自定义组件内容,从而替代默认的菜单结构 */ content?: string; /** * 组件成功弹出后的回调,并返回两个参数 * @param [elemPanel] 弹出的面板 * @param [elem] 点击的面板 */ ready?(elemPanel: JQuery, elem: JQuery): void; /** * 菜单项被点击时的回调,并返回两个参数 */ click?(data: any, othis: JQuery): void; } /** * reload时是用,全部可选 */ type DropDownOptionForReload = Partial<DropDownOption>; /** * 全部必有项 用于查看 */ type DropDownOptionForRead = Required<DropDownOption>; interface DropDownModule { config: DropDownOptionForRead; reload(options?: DropDownOptionForReload | object): void; } interface DropDown { config: { [index: string]: any }; index: number; set(options: DropDownOption): DropDown; /** * 给dropdown绑定事件,当前只有click 即event类似:click(id|filter) * @param [event] 事件名 如: click(id|filter) 括号内是.layui-menu的id=""或者lay-filter="" * @param [callback] 回调中的参数是 <li lay-options="{id: 101}">中lay-options的值 字符串用'' */ on(event: string, callback: (this: HTMLElement, obj: any) => any): any; /** * 重载实例 * @param [id] id参数为render>options中的id,如果render时未指定id则从1开始。 * @param [options] 全部基础参数 */ reload(id: string, options: DropDownOptionForReload): DropDownModule; /** * 核心入口 */ render(options: DropDownOption): DropDownModule; } interface TabOption { /** * 选项卡的标题 不写则是unnaming */ title?: string; /** * '选项卡的内容' ,支持传入html */ content?: string; /** * 选项卡标题的lay-id属性值 */ id?: string; } interface TabElement { /** * 指定tab头元素项 */ headerElem: string | HTMLElement | JQuery; /** * 指定tab主体元素项 */ bodyElem: string | HTMLElement | JQuery; } // https://www.layui.com/doc/modules/element.html /** * 元素操作 */ interface Element { config: { [index: string]: any }; // set(options?: ): object; 很少用 /** * 用于元素的一些事件触发 * @param [filter] 比如:tab(filter),tabDelete(filter),nav(filter),collapse(filter) * @param [callback] 不同filter对应的data类型不同 */ on(filter: string, callback: (this: any, data: any) => any): any; /** * 用于新增一个Tab选项 * @param [filter] tab元素的 lay-filter="value" 过滤器的值(value) * @param [options] 设定可选值的对象, */ tabAdd(filter: string, options: TabOption): void; /** * 用于删除指定的Tab选项 * @param [filter] tab元素的 lay-filter="value" 过滤器的值(value) * @param [layid] 选项卡标题列表的 属性 lay-id 的值 */ tabDelete(filter: string, layid: string): void; /** * 用于外部切换到指定的Tab项上 * @param [filter] 比如:element.tabChange('demo', 'layid');中的'demo' * @param [layid] 比如:lay-id="yyy"中的'yyy' */ tabChange(filter: string, layid: string): void; /** * 用于绑定自定义 Tab 元素(即非 layui 自带的 tab 结构) * @param [option] 参数 */ tab(option: TabElement): void; /** * 用于动态改变进度条百分比: 例如:element.progress('demo', '30%'); * @param [filter] lay-filter * @param [percent] 比例 */ progress(filter: string, percent: string): void; /** * 更新渲染同render, 2.1.6 开始,可以用 element.render(type, filter); 方法替代 * @param [type] 可选有:'tab' | 'nav' | 'breadcrumb' | 'progress' | 'collapse' * @param [filter] lay-filter */ init(type?: 'tab' | 'nav' | 'breadcrumb' | 'progress' | 'collapse', filter?: string): void; /** * 更新渲染 ,当type不能识别时,layui会遍历渲染"tab""nav"|"breadcrumb"|"progress"|"collapse" 全部;<br/>&nbsp; * @param [type] 表单的type类型,如下: <br/>&nbsp; * 1、tab 重新对tab选项卡进行初始化渲染, <br/>&nbsp; * 2、nav 重新对导航进行渲染 <br/>&nbsp; * 3、breadcrumb 重新对面包屑进行渲染 <br/>&nbsp; * 4、progress 重新对进度条进行渲染 <br/>&nbsp; * 5、collapse 重新对折叠面板进行渲染 <br/>&nbsp; * @param [filter] 为元素的 lay-filter="" 的值,用于局部更新 */ render(type?: 'tab' | 'nav' | 'breadcrumb' | 'progress' | 'collapse', filter?: string): void; } interface FlowOption { /** * 指定列表容器的选择器 */ elem?: string | HTMLElement; /** * 滚动条所在元素选择器,默认document。如果你不是通过窗口滚动来触发流加载, <br/>&nbsp; * 而是页面中的某一个容器的滚动条,那么通过该参数指定即可。 */ scrollElem?: string | HTMLElement; /** * 是否自动加载。默认true。如果设为false,点会在列表底部生成一个“加载更多”的button,则只能点击它才会加载下一页数据。 */ isAuto?: boolean; /** * 用于显示末页内容,可传入任意HTML字符。默认为:没有更多了 */ end?: string; /** * 是否开启图片懒加载。默认false。 <br/>&nbsp; * 如果设为true,则只会对在可视区域的图片进行按需加载。但与此同时,在拼接列表字符的时候, <br/>&nbsp; * 你不能给列表中的img元素赋值src,必须要用lay-src取代 */ isLazyimg?: boolean; /** * 与底部的临界距离,默认50。即当滚动条与底部产生该距离时,触发加载。注意:只有在isAuto为true时有效。 */ mb?: number; /** * 到达临界点触发加载的回调。信息流最重要的一个存在。携带两个参数:page, next */ done?: (page: number, next: (html: string, hasMore: boolean) => void) => void; } // https://www.layui.com/doc/modules/flow.html /** * 流加载 */ interface Flow { /** * 流加载 * @param option 信息流参数 */ load(option: FlowOption): void; /** * 图片懒加载 * @param [option] 参数 */ lazyimg(option?: { /** * 指定开启懒加载的img元素选择器,如 elem: '.demo img' 或 elem: 'img.load' 默认:img */ elem?: string; /** * 滚动条所在元素选择器,默认document */ scrollElem?: string; }): void; } interface LayFormData { /** * 被执行事件的元素DOM对象,一般为button对象 ,可能是input select button等不能用HTMLElement */ elem: any; /** * 得到美化后的DOM对象=$(selector) */ othis: JQuery; /** * DOM对象值 */ value: string; /** * 被执行提交的form对象,一般在存在form标签时才会返回 */ form: HTMLFormElement; /** * 当前容器的全部表单字段,名值对形式:{name: value} */ field: any; } interface LayFormVerifyConfig { [index: string]: ((value: string, item: HTMLElement) => any) | [RegExp, string]; } // https://www.layui.com/doc/element/form.html // https://www.layui.com/doc/modules/form.html /** * 表单 - 页面元素 */ interface Form { config: { autocomplete: any; /** * form内置的验证 */ verify: { /** * 日期验证 date[0]是正则,date[1]是验证失败的提示("日期格式不正确") */ date: [RegExp, string]; /** * 邮箱验证 email[0]是正则,email[1]是验证失败的提示("邮箱格式不正确") */ email: [RegExp, string]; /** * 身份证号验证 identity[0]是正则,identity[1]是验证失败的提示( 请输入正确的身份证号") */ identity: [RegExp, string]; /** * 验证数字,如果参数不是数字则返回"只能填写数字",是数字则无返回值 <br/>&nbsp; * bug:当0,"0"会提示不是数字 * @param [arg] 参数 比如 1,"1",-1 */ number: (arg: any) => string | null; /** * 手机号验证 phone[0]是正则,phone[1]是验证失败的提示("请输入正确的手机号") */ phone: [RegExp, string]; /** * 空值验证 required[0]是正则,required[1]是为空的提示("必填项不能为空") */ required: [RegExp, string]; /** * url验证 url[0]是正则,url[1]是验证失败的提示("链接格式不正确") */ url: [RegExp, string]; [index: string]: [RegExp, string] | ((...arg: any) => any); }; }; /** * 取值,取出所有子元素是input,select,textarea且有name的表单值 * @param [filter] class=""lay-filter=""中的值 * @param [itemForm] 表单field子元素的父容器,没有则是第一个.layui-form作为父元素。实例:$(".layui-form"), */ getValue(filter: string, itemForm?: JQuery): { [index: string]: string }; /** * 表单field元素回调事件 (每个表单都有一个默认事件) * @param [event] 类似: select(x)|checkbox(x)|switch(x)|radio(x)|submit(x) x为field上的lay-filter="x" * @param [callback] 回调函数 */ on(event: string, callback: (data: LayFormData) => any): any; /** * 更新渲染,对动态插入的元素渲染 * @param [type] 可选:'select' | 'checkbox' | 'radio' | null * @param [filter] lay-filter */ render(type?: 'select' | 'checkbox' | 'radio' | null, filter?: string): Form; /** * 表单赋值 / 取值 * @param [filter] .layui-form 上的lay-filter=""值 * @param [obj] 要设置的值 */ val(filter: string, obj?: object): any; /** * 维护表单验证 * @param [config] 验证参数 */ verify(config: LayFormVerifyConfig): Form; } interface LAY extends Omit<any[], 'find'> { /** * 当前的选择器 */ selector: string | undefined; /** * 添加css类 * @param [className] 类名,必须项 比如 a 或 a b * @param [remove] 是否是移除className 默认false即添加 */ addClass(className: string, remove?: boolean): HTMLElement[]; /** * 追加内容 * @param [elem] html或者元素对象 */ append(elem?: string | HTMLElement): HTMLElement[]; /** * 设置元素属性 * @param [key] 是attribute的key * @param [value] 是attribute的value */ attr(key: string, value: any): HTMLElement[]; /** * 获取第一个元素属性 */ attr(): string; /** * 添加 css style * @param [key] 属性css * @param [value] 值 */ css(key: string, value: any): HTMLElement[]; /** * 获取 css style * @param [key] 属性css */ css(key: string): string; /** * 对元素遍历 * @param [fn] (index,elem) */ each(fn?: (this: HTMLElement, index: number, elem: HTMLElement) => any): HTMLElement[]; /** * 查找子元素 * @param [selector] 选择器 */ find(selector: string | HTMLElement): LAY; /** * 是否包含 css 类 * @param [className] 类名 */ hasClass(className: string): boolean; /** * 设置高度 * @param [value] 元素宽度 */ height(value: number | string): HTMLElement[]; /** * 获取第一个元素高度 */ height(): number; /** * 设置元素的innerHTML * @param [html] html */ html(html: string): HTMLElement[]; /** * 获取第一个元素的innerHTML */ html(): string; /** * 解除事件 * @param [eventName] 事件名 比如click * @param [fn] 回调 */ off(eventName: string, fn: (...args: any) => any): HTMLElement[]; /** * 事件绑定,注意:只支持内置事件,不支持自定义事件 * @param [eventName] 事件名 比如click,自定事件会绑定失败 * @param [fn] 回调 (tip:this:any) */ on(eventName: keyof HTMLElementEventMap, fn: (...args: any) => any): HTMLElement[]; /** * 移除元素 * @param [elem] 实际是removeChild(elem) */ remove(elem: HTMLElement): HTMLElement[]; /** * 移除 指定的attribute * @param [key] 是attribute的key */ removeAttr(key: string): HTMLElement[]; /** * 移除 className * @param [className] */ removeClass(className: string): HTMLElement[]; /** * 设置元素的value * @param [value] 值 */ val(value: any): HTMLElement[]; /** * 获取第一个元素的value */ val(): string; /** * 设置宽度 * @param [value] 元素宽度 */ width(value: number | string): HTMLElement[]; /** * 获取第一个元素宽度 */ width(): number; } interface Lay { /** * 查找 DOM 作为返回实例的操作对象 * @param [selector] 选择器 原始dom或者选择器串 */ (selector?: string | HTMLElement): LAY; v: string; /** * 把多个对象深层复制到dest,返回也为dest * @param [dest] * @param [src] */ extend(dest: any, ...src: any): any; /** * 如果是ie则是版本,非ie则false */ ie: boolean | string; layui: Layui; /** * 获取当前 JS 所在目录 */ getPath: string; /** * 阻止事件冒泡 */ stope(event?: Event): void; /** * 对象(Array、Object、DOM 对象等)遍历,可用于取代 for 语句 同layui.each * @param [obj] * @param [fn] */ each(obj: object, fn?: (k: string, v: any) => void): Lay; /** * 数字前置补零 * @param [num] 数字 * @param [length] 补0后的长度 */ digit(num?: any, length?: number): string; /** * 根据tagName生成HTMLElement子元素 * @param [elemName] ts中小写可智能提示 * @param [attr] 属性名 */ elem<K extends keyof HTMLElementTagNameMap>(elemName: K, attr?: object): HTMLElementTagNameMap[K]; /** * 根据tagName生成HTMLElement子元素 * @param elemName 非小写内置tagName * @param [attr] 属性名 */ elem(elemName: string, attr?: object): HTMLElement; /** * 当前页面body是否存在滚动条 */ hasScrollbar(): boolean; /** * unknown * @param [elem] HTMLElement * @param [elemView] * @param [obj] */ position(elem: HTMLElement, elemView: any, obj?: any): any; /** * 获取元素上的参数,同jquery.attr() * @param [elem] html元素 * @param [attr] 若空则为lay-options */ options(elem: string | HTMLElement | JQuery, attr?: string): any; /** * 元素是否属于顶级元素(顶级:document 或 body) * @param [elem] 只有document或body才返回true */ isTopElem(elem: any): boolean; } interface DateParam { year?: number; month?: number; date?: number; hours?: number; minutes?: number; seconds?: number; } interface DateOption { /** * 绑定的元素 ,选择的值会填充该元素 */ elem?: string | HTMLElement | JQuery; /** * 控件选择类型 */ type?: 'year' | 'month' | 'date' | 'time' | 'datetime'; /** * 开启左右面板范围选择 */ range?: string | boolean | any[]; /** * 自定义格式 默认值:yyyy-MM-dd 实例: 'yyyy年MM月dd日' <br/>&nbsp; * yyyy 年份,至少四位数。如果不足四位,则前面补零 <br/>&nbsp; * y 年份,不限制位数,即不管年份多少位,前面均不补零 <br/>&nbsp; * MM 月份,至少两位数。如果不足两位,则前面补零。 <br/>&nbsp; * M 月份,允许一位数。 <br/>&nbsp; * dd 日期,至少两位数。如果不足两位,则前面补零。 <br/>&nbsp; * d 日期,允许一位数。 <br/>&nbsp; * HH 小时,至少两位数。如果不足两位,则前面补零。 <br/>&nbsp; * H 小时,允许一位数。 <br/>&nbsp; * mm 分钟,至少两位数。如果不足两位,则前面补零。 <br/>&nbsp; * m 分钟,允许一位数。 <br/>&nbsp; * ss 秒数,至少两位数。如果不足两位,则前面补零。 <br/>&nbsp; * s 秒数,允许一位数。 <br/>&nbsp; */ format?: string; /** * 初始值 ""|new Date()|20180115 */ value?: string | Date | number; /** * 初始值填充 默认值:true <br/>&nbsp; */ /** * 用于控制是否自动向元素填充初始值(需配合 value 参数使用) */ isInitValue?: boolean; /** * 是否开启选择值预览 <br/>&nbsp; * 用于控制是否显示当前结果的预览(type 为 datetime 时不开启) */ isPreview?: boolean; /** * 最小范围内的日期时间值 <br/>&nbsp; * 1.如果值为字符类型,则:年月日必须用 -(中划线)分割、时分秒必须用 :(半角冒号)号分割。这里并非遵循 format 设定的格式 <br/>&nbsp; * 2.如果值为整数类型,且数字<86400000,则数字代表天数,如:min: -7,即代表最小日期在7天前,正数代表若干天后 <br/>&nbsp; * 3.如果值为整数类型,且数字 ≥ 86400000,则数字代表时间戳,如:max: 4073558400000,即代表最大日期在:公元3000年1月1日 */ min?: string | number; /** * 最大范围内的日期时间值 <br/>&nbsp; * 1.如果值为字符类型,则:年月日必须用 -(中划线)分割、时分秒必须用 :(半角冒号)号分割。这里并非遵循 format 设定的格式 <br/>&nbsp; * 2.如果值为整数类型,且数字<86400000,则数字代表天数,如:min: -7,即代表最小日期在7天前,正数代表若干天后 <br/>&nbsp; * 3.如果值为整数类型,且数字 ≥ 86400000,则数字代表时间戳,如:max: 4073558400000,即代表最大日期在:公元3000年1月1日 */ max?: string | number; /** * 自定义弹出控件的事件 默认值:focus,如果绑定的元素非输入框,则默认事件为:click */ trigger?: string; /** * 默认显示 默认值:false */ show?: boolean; /** * 阻止关闭事件冒泡 */ closeStop?: string; /** * 定位方式 */ position?: 'abolute' | 'fixed' | 'static'; /** * 层叠顺序 ,如果 position 参数设为 static 时,该参数无效。 */ zIndex?: number; /** * 是否显示底部栏 */ showBottom?: boolean; /** * 工具按钮 默认值:['clear', 'now', 'confirm'] */ btns?: Array<'clear' | 'now' | 'confirm'>; /** * 语言 内置了两种语言版本:cn(中文版)、en(国际版,即英文版) ,默认值:cn */ lang?: 'cn' | 'en'; /** * 主题 ,默认值:default */ theme?: string | 'default' | 'molv' | 'grid'; /** * 是否显示公历节日 默认值:false */ calendar?: boolean; /** * 标注重要日子 实例:{'0-0-31':'月末'} 比如2月bug */ mark?: { [key: string]: string }; eventElem?: string | HTMLElement | JQuery; /** * 控件初始打开的回调 * @param [date] 基础参数 */ ready?(dateParam: DateParam): void; /** * 日期时间被切换后的回调 this to test and elem * @param [value] 得到日期生成的值,如:2017-08-18 范围:"2021-07-06 - 2021-08-09" * @param [date] 得到日期时间对象:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0} * @param [endDate] 开启范围选择(range: true)才会返回。对象成员同上date */ change?(this: Required<DateOption>, value: string, date: DateParam, endDate: DateParam): void; /** * 控件选择完毕后的回调 * @param [value] 得到日期生成的值,如:2017-08-18 范围:"2021-07-06 - 2021-08-09" * @param [date] 得到日期时间对象:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0} * @param [endDate] 开启范围选择(range: true)才会返回。对象成员同上date */ done?(value: string, date: DateParam, endDate: DateParam): void; } /** * 日期和时间组件 */ interface Laydate { /** * 核心方法 * @param [options] 基础参数 */ render(options: DateOption): { config: DateOption; hint: (content: string) => void }; /** * 设置全局参数 * @param [options] */ set(options?: DateOption): Laydate; /** * 配置基础路径 <br/>&nbsp; * 如果你不是采用 layui 或者普通 script 标签方式加载的 laydate.js, <br/>&nbsp; * 而是采用 requirejs 等其它方式引用 laydate, <br/>&nbsp; * 那么你需要设置基础路径,以便 laydate.css 完成加载。 */ path: string; /** * 获取指定年月的最后一天 * @param [month] month默认为当前月 * @param [year] year默认为当前年 */ getEndDate(month?: number, year?: number): number; } /** * 编辑器基本设置 */ interface EditOption { /** * 重新定制编辑器工具栏,如: tool: ['link', 'unlink', 'face'] 当前可选有: <br/>&nbsp; * 'strong' //加粗 <br/>&nbsp; * ,'italic' //斜体 <br/>&nbsp; * ,'underline' //下划线 <br/>&nbsp; * ,'del' //删除线 <br/>&nbsp; * * ,'|' //分割线 <br/>&nbsp; * * ,'left' //左对齐 <br/>&nbsp; * ,'center' //居中对齐 <br/>&nbsp; * ,'right' //右对齐 <br/>&nbsp; * ,'link' //超链接 <br/>&nbsp; * ,'unlink' //清除链接 <br/>&nbsp; * ,'face' //表情 <br/>&nbsp; * ,'image' //插入图片 <br/>&nbsp; * ,'help' //帮助 <br/>&nbsp; */ tool?: string[]; /** * 不显示编辑器工具栏,一般用于隐藏默认配置的工具bar */ hideTool?: string[]; /** * 设定编辑器的初始高度 */ height?: number | string; /** * 设定图片上传接口,如:uploadImage: {url: '/upload/', type: 'post'},需要服务端返回: <br/>&nbsp; * { <br/>&nbsp; * "code": 0 // 0表示成功,其它失败 <br/>&nbsp; * ,"msg": "" // 提示信息 一般上传失败后返回 <br/>&nbsp; * ,"data": { <br/>&nbsp; * "src": "图片路径" <br/>&nbsp; * ,"title": "图片名称" //可选 <br/>&nbsp; * } <br/>&nbsp; * } <br/>&nbsp; */ uploadImage?: { url: string; type: string }; } // https://www.layui.com/doc/modules/layedit.html /** * 富文本编辑器 */ interface Layedit { /** * 用于建立编辑器的核心方法 * @param [id] 实例元素(一般为textarea)的id值 * @param [options] 编辑器的可配置项 */ build(id: string, options?: EditOption): any; /** * 设置编辑器的全局属性 * @param [options] */ set(options: EditOption): Layedit; /** * 获得编辑器的内容 * @param [index] 即执行layedit.build返回的值 */ getContent(index: number): string; /** * 获得编辑器的纯文本内容 * @param [index] 即执行layedit.build返回的值 */ getText(index: number): string; /** * 用于同步编辑器内容到textarea(一般用于异步提交) * @param [index] 即执行layedit.build返回的值 */ sync(index: number): void; /** * 获取编辑器选中的文本 * @param [index] 即执行layedit.build返回的值 */ getSelection(index: number): string; } // https://www.layui.com/doc/modules/layer.html#base /** * 弹层组件 */ interface LayerOptions { /** * 基本层类型 ,layer提供了5种层类型。可传入的值有: <br/>&nbsp; * 0(默认信息框),1(页面层), <br/>&nbsp; * 2(iframe层),3(加载层),4(tips层)。 <br/>&nbsp; * 若你采用layer.open({type: 1})方式调用,则type为必填项(信息框除外) */ type?: 0 | 1 | 2 | 3 | 4; /** * 标题,不想显示标题栏可以title: false * @example * title :'我是标题' * title: ['文本', 'font-size:18px;'] // 给文本指定style样式 */ title?: string | boolean | string[]; /** * 内容 * @default '' */ content?: string | HTMLElement | JQuery | string[]; /** * 样式类名,允许你传入layer内置的样式class名,还可以传入您自定义的class名 * @default '' * @example * skin: 'demo-class' */ skin?: string; /** * 宽高 * @default 'auto' * @example * area: '500px' // 高会自适应 * area: ['500px', '300px'] // 指定宽高 */ area?: string | string[]; // https://www.layui.com/doc/modules/layer.html#offset /** * 坐标 * @default 'auto' // 即垂直水平居中 * @example * offset: '100px' // 只定义top坐标,水平保持居中 * offset: ['100px', '50px'] // 同时定义top、left坐标 * offset: 't' // 快捷设置顶部坐标 * offset: 'r' // 快捷设置右边缘坐标 * offset: 'b' // 快捷设置底部坐标 * offset: 'l' // 快捷设置左边缘坐标 * offset: 'lt' // 快捷设置左上角 * offset: 'lb' // 快捷设置左下角 * offset: 'rt' // 快捷设置右上角 * offset: 'rb' // 快捷设置右下角 */ offset?: number | string | string[]; /** * 图标 <br/>&nbsp; * 当type为0(即信息框)可以传入0-6启用图标 <br/>&nbsp; * 当type为3(即加载层)可以传入0-2启用图标 * @default -1 // 不显示图标 * @example * type:0,icon: 0 //0(!),1(√),2(x),3(?),4(锁),5(cry),6(smile), 其他数字同0 * type:3,icon:0 //0(3个点),1(慢圈),2(慢快圈) ,其他数字同0 */ icon?: number; // https://www.layui.com/doc/modules/layer.html#btn /** * 按钮 <br/>&nbsp; * 信息框模式时(type:0),btn默认是一个确认按钮,其它层类型则默认不显示,加载层和tips层则无效 <br/>&nbsp; * 可以定义更多按钮,比如:btn: ['按钮1', '按钮2', '按钮3', …],按钮1的回调是yes, <br/>&nbsp; * 而从按钮2开始,则回调为btn2: function(){},以此类推。 * @default '确认' * @example * type:0,btn: '我知道了' * type:0,btn: ['yes','btn2'] // 第一个对应yes回调,后边对应btn2,btn3回调 */ btn?: string | string[]; /** * 按钮排列 默认:r <br/>&nbsp; * @default 'r' * @example * btnAlign: 'l' // 按钮左对齐 * btnAlign: 'c' // 按钮居中对齐 * btnAlign: 'r' // 按钮右对齐。默认值,不用设置 */ btnAlign?: string; /** * 右上角的关闭按钮 默认:1 <br/>&nbsp; * layer提供了两种风格的关闭按钮,可通过配置1和2来展示,如果不显示,则closeBtn: 0 * @default 1 * @example * closeBtn: 0 // 隐藏右上角的关闭按钮 * closeBtn: 1 // x * closeBtn: 2 // O+x */ closeBtn?: string | boolean | number; /** * 遮罩 * @default 0.3 // 0.3透明度的黑色背景('#000') * @example * shade: 0 // 不显示遮罩 * shade: [0.8, '#393D49'] // 指定透明度和遮罩颜色 */ shade?: string | boolean | number | [number, string]; /** * 是否点击遮罩关闭 * @default false */ shadeClose?: boolean; /** * 自动关闭所需毫秒 * @default 0 * @example * time: 5000 // 即代表5秒后自动关闭 */ time?: number; /** * 用于控制弹层唯一标识 <br/>&nbsp; * 设置该值后,不管是什么类型的层,都只允许同时弹出一个。一般用于页面层和iframe层模式 * @default '' */ id?: string; // https://www.layui.com/doc/modules/layer.html#anim /** * 弹出动画 <br/>&nbsp; * 目前anim可支持的动画类型有0-6 如果不想显示动画,设置 anim: -1 即可 * @default 0 * @example * anim: -1 // 不显示动画 * anim: 0 // 平滑放大。默认 * anim: 1 // 从上掉落 * anim: 2 // 从最底部往上滑入 * anim: 3 // 从左滑入 * anim: 4 // 从左翻滚 * anim: 5 // 渐显 * anim: 6 // 抖动 */ anim?: number; /** * 关闭动画 * @default true */ isOutAnim?: boolean; /** * 最大最小化 <br/>&nbsp; * 该参数值对type:1和type:2有效,需要显示配置maxmin: true即可 * @default false // 默认不显示最大小化按钮 * @example * type:1,maxmin:true * type:2,maxmin:true */ maxmin?: boolean; /** * 固定 ,即鼠标滚动时,层是否固定在可视区域 * @default true // 默认固定在可视区域显示 * @example * fixed: false // 不固定 */ fixed?: boolean; /** * 是否允许拉伸 ,该参数对loading(type:3)、tips(type:4)层无效 * @default true // 允许拉伸,在弹层右下角拖动来拉伸尺寸 */ resize?: boolean; /** * 监听窗口拉伸动作 * @default null */ resizing?(layero: JQuery): any; /** * 是否允许浏览器出现滚动条 * @default true */ scrollbar?: boolean; /** * 最大宽度 ,只有当area: 'auto'时,maxWidth的设定才有效。 * @default 360 * @example * area: 'auto',maxWidth: 800 */ maxWidth?: number; /** * 层叠顺序 * @default 19891014 */ zIndex?: number; /** * 触发拖动的元素 * @default '.layui-layer-title' */ move?: string | boolean | HTMLElement; /** * 固定1,不能修改 */ readonly moveType?: boolean; /** * 是否允许拖拽到窗口外 * @default false * */ moveOut?: boolean; /** * 拖动完毕后的回调方法 * @default null */ moveEnd?: null | ((layero: JQuery) => any); /** * tips方向和颜色 * @default 2 // 箭头在右边,黑色 * @example * tips: 1 //箭头在上 * tips: 2 //箭头在右 * tips: 3 //箭头在下 * tips: 4 //箭头在左 * layui.layer.tips('提示内容','#abc',{tips:1}) * layui.layer.tips('提示内容','#abc',{tips:[1, 'red']}) // 指定颜色 * layui.layer.tips('提示内容','#abc',{tips:[1, '#f00']}) * layui.layer.tips('提示内容','#abc',{tips:[1, 'rgb(255,0,0)']}) */ tips?: number | [number, string]; /** * 是否允许多个tips ,true则允许多个意味着不会销毁之前的tips层 * @default false // 同一时刻只有一个提示框 */ tipsMore?: boolean; /** * 层弹出后的成功回调方法 */ success?(layero: JQuery, index: number): void; /** * 确定按钮回调方法 */ yes?: LayerCallbackYes; /** * 可以定义更多按钮,比如:btn: ['按钮1', '按钮2', '按钮3', …],按钮1的回调是yes, <br/>&nbsp; * 而从按钮2开始,则回调为btn2: function(){},以此类推。 */ btn2?: LayerCallbackYes; btn3?: LayerCallbackYes; btn4?: LayerCallbackYes; btn5?: LayerCallbackYes; btn6?: LayerCallbackYes; btn7?: LayerCallbackYes; btn8?: LayerCallbackYes; btn9?: LayerCallbackYes; /** * 右上角关闭按钮触发的回调 */ cancel?: LayerCallbackCancel; /** * 层销毁后触发的回调 */ end?: LayerCallbackEnd; /** * 最大化后触发的回调 */ full?: LayerCallbackFull; /** * 最小化后触发的回调 */ min?: LayerCallbackMin; /** * 还原后触发的回调 */ restore?: LayerCallbackRestore; /** * 最小化后是否默认堆叠在左下角 默认:true */ minStack?: boolean; } /** * 配置layer层的基础参数 * @example ```javascript * layui.layer.config({ * anim: 1, // 默认动画风格 * skin: 'layui-layer-molv', // 默认皮肤 * extend: 'myskin/style.css', // 样式位置 * //... * }); */ interface LayerConfigOptions extends LayerOptions { /** * layer.js所在的目录,可以是绝对目录,也可以是相对目录 * @example * path: '/res/layer/' */ path?: string; /** * 要加载的拓展css皮肤 <br/>&nbsp; * 如果是独立版的layer,则将 myskin 存放在 ./skin 目录下 <br/>&nbsp; * 如果是layui中使用layer,则将 myskin 存放在 ./css/modules/layer 目录下 * @example * extend: 'myskin/style.css' */ extend?: string[] | string; } /** * 输入框的参数对象 * @example ```javascript * layui.layer.prompt({ * formType: 2, // 输入框类型,支持0(文本)默认1(密码)2(多行文本) * value: '初始值', // 初始时的值,默认空字符 * maxlength: 140, // 可输入文本的最大长度,默认500 * title: '请输入值', * area: ['800px', '350px'], // 自定义文本域宽高 * },(value, index, elem) => { * layui.layer.alert(value); // 得到value * layui.layer.close(index); * }, * ); * ``` */ interface LayerPromptOptions extends LayerOptions { /** * 输入框类型,支持0(文本)默认1(密码)2(多行文本) * @example * formType: 0 // 文本 * formType: 1 // 密码 * formType: 2 // 多行文本 */ formType?: number; /** * 初始时的值 * @default '' */ value?: string; /** * 可输入文本的最大长度 * @default 500 */ maxlength?: number; /** * 自定义文本域宽高 * @example * ['800px', '350px'] */ area?: string[]; } interface LayerTabOptions extends LayerOptions { tab: Array<{ title: string; content: string }>; } interface LayerPhotosOptions extends LayerOptions { /** * json或者选择器 用于构造img */ photos?: LayerPhotosData | string | JQuery; /** * 切换图片时触发 * @param [pic] 当前图片的一些信息 * @param [layero] 当前元素 */ tab?(pic: LayerPhotosDataItem, layero: JQuery): void; } interface LayerPhotosData { /** * 相册标题 */ title?: string; /** * 相册id * @example * id: 123 */ id?: number; /** * 初始显示的图片序号 * @default 0 */ start?: number; /** * 相册包含的图片,数组格式 * @example ```javascript * "data": [{ * "alt": "图片名", * "pid": 666, //图片id * "src": "", //原图地址 * "thumb": "" //缩略图地址 * }] * ``` */ data?: LayerPhotosDataItem[]; } interface LayerPhotosDataItem { /** * 图片名 */ alt?: string; /** * 图片id */ pid?: number; /** * 原图地址 */ src?: string; /** * 缩略图地址 */ thumb?: string; } /** * 弹层组件 */ interface Layer { ie: boolean; index: number; path: string; v: string; zIndex: number; // https://www.layui.com/doc/modules/layer.html#layer.config /** * 初始化全局配置 * @param [options] 基础参数 * @param [fn] 无用 */ config(options: LayerConfigOptions, fn?: any): void; /** * 执行初始化,就绪后执行回调参数 <br/>&nbsp; * ready(path: string, callback: () => void): void; //兼容旧版? <br/>&nbsp; * 初始化就绪 (CSS完成的回调),当你在页面一打开就要执行弹层时可放入回调中 * @param [callback] 就绪后回调 */ ready(callback: () => void): void; /** * 原始核心方法 * @param [options] 基础参数 */ open(options?: LayerOptions): number; /** * 普通信息框 * @param [content] 内容 * @param [options] 基础参数 * @param [yes] 点击确定后的回调 */ alert(content?: any, options?: LayerOptions, yes?: LayerCallbackYes): number; // 源码中会第三个参数代替第二个。单独定义一个方法。 /** * 普通信息框 * @param [content] 内容 * @param [yes] 点击确定后的回调 */ alert(content: any, yes: LayerCallbackYes): number; /** * 询问框 * @param [content] 提示内容 * @param [options] 参数 * @param [yes] 确认回调 * @param [cancel] 右上角关闭按钮触发的回调 * @example ```javascript * layer.confirm('is not?', { * icon: 3, * title: '提示', * cancel: (index, layero) => { * console.log("点击了右上角关闭"); * //return false //点击右上角叉号不能关闭 * } * }, (index, layero) => { * console.log("点击了下边的第一个按钮'确定'"); * layer.close(index);//需要手动关闭 * }, (index, layero) => { * console.log("点击了下边的第二个按钮'取消'"); * //return false // 点击取消不能关闭 * }); * ``` */ confirm(content?: any, options?: LayerOptions, yes?: LayerCallbackYes, cancel?: LayerCallbackCancel): number; /** * 询问框 * @param [content] 提示内容 * @param [yes] 确认回调 * @param [cancel] 右上角关闭按钮触发的回调 * @example ```javascript * layer.confirm('is not?', (index,layero) => { * // do something * layer.close(index); * },(index,layero)=>{ * return false // 返回false则取消关闭 * }); * ``` */ confirm(content: any, yes: LayerCallbackYes, cancel?: LayerCallbackCancel): number; // https://www.layui.com/doc/modules/layer.html#layer.msg /** * 提示框 * @param [content] 提示内容 * @param [options] 参数 * @param [end] 自动关闭后的回调 */ msg(content?: string, options?: LayerOptions, end?: LayerCallbackEnd): number; // https://www.layui.com/doc/modules/layer.html#layer.load /** * 提示框 * @param [content] 提示内容 * @param [end] 自动关闭后的回调 */ msg(content: string, end?: LayerCallbackEnd): number; /** * 加载层 * @param [icon] 可用:0,1,2 * @param [options] 参数 */ load(icon?: number, options?: LayerOptions): number; /** * 加载层 * @param [options] 参数 */ load(options: LayerOptions): number; // https://www.layui.com/doc/modules/layer.html#layer.tips /** * tips层 * @param [content] 显示的内容 * @param [follow] 在那里显示 * @param [options] 参数 */ tips(content?: string, follow?: string | HTMLElement | JQuery, options?: LayerOptions): number; /** * 关闭指定层 * @param [index] 层索引 * @param [callback] 关闭后的回调 */ close(index: number, callback?: () => any): void; /** * 关闭所有层 * @param [type] 只想关闭某个类型的层,不传则关闭全部 */ /** * 闭所有层 * @param [type] 只想关闭某个类型(dialog,page,iframe,loading,tips)的层,不传则关闭全部 * @param [callback] 关闭所有层后执行回调 */ closeAll(type?: 'dialog' | 'page' | 'iframe' | 'loading' | 'tips', callback?: () => any): void; /** * * @param [callback] 关闭所有层后执行回调 */ closeAll(callback: () => any): void; /** * 重新定义层的样式 * @param [index] 层索引 * @param [options] 参数 * @param [limit] 影响宽度和高度 */ style(index: number, options: { [key: string]: string | number }, limit?: boolean): void; /** * 改变层的标题 * @param [title] 新标题 * @param [index] 层索引 */ title(title: string, index: number): void; /** * 获取iframe页的DOM * @param [selector] * @param [index] */ getChildFrame(selector: string | HTMLElement | JQuery, index: number): JQuery; /** * 获取特定iframe层的索引 * @param [windowName] 即window.name */ getFrameIndex(windowName: string): number; /** * 指定iframe层自适应 * @param [index] 层索引 */ iframeAuto(index: number): void; /** * 重置特定iframe url <br/>&nbsp; * 如:layer.iframeSrc(index, 'http://sentsin.com') * @param [index] 层索引 * @param [url] */ iframeSrc(index: number, url: string): void; /** * 置顶当前窗口 * @param [layero] */ setTop(layero: JQuery): void; /** * 手工执行最大化 * @param [index] 层索引 */ full(index: number): void; /** * 手工执行最小化 * @param [index] 层索引 */ min(index: number): void; /** * 手工执行还原 * @param [index] 层索引 */ restore(index: number): void; /** * 输入层 * @param [options] 参数 * @param [yes] 点击确定的回调,用该参数而不是用options的yes */ prompt(options?: LayerPromptOptions, yes?: LayerCallbackPrompt): number; /** * 输入层 * @param [yes] 点击确定的回调 */ prompt(yes: LayerCallbackPrompt): number; /** * tab层 * @param [options] 参数,一般配置area和tab */ tab(options?: LayerTabOptions): number; /** * 相册层 * @param [options] 参数 */ photos(options?: LayerPhotosOptions): number; } interface PageOptions { /** * 指向存放分页的容器,值可以是容器ID、DOM对象。如: <br/>&nbsp; * 1. elem: 'id' 注意:这里不能加 # 号 <br/>&nbsp; * 2. elem: document.getElementById('id') */ elem?: string | HTMLElement; /** * 数据总数。一般通过服务端得到 */ count?: number; /** * 每页显示的条数。laypage将会借助 count 和 limit 计算出分页数。 默认:10 */ limit?: number; /** * 每页条数的选择项。如果 layout 参数开启了 limit, 默认:[10, 20, 30, 40, 50] <br/>&nbsp; * 则会出现每页条数的select选择框 */ limits?: number[]; /** * 起始页。一般用于刷新类型的跳页以及HASH跳页 */ curr?: number | string; /** * 连续出现的页码个数 默认:5 */ groups?: number; /** * false:则不显示”上一页”的内容,其他值则是自定义”上一页”的内容 默认:上一页 */ prev?: string; /** * false:则不显示”下一页”的内容,其他值则是自定义”下一页”的内容 默认:下一页 */ next?: string; /** * false:则不显示”首页”的内容,其他值则是自定义”首页”的内容 默认:首页 */ first?: string | boolean; /** * false:则不显示”尾页”的内容,其他值则是自定义”尾页”的内容 默认:尾页 */ last?: string | boolean; /** * 自定义排版。可选值有: <br/>&nbsp; * count(总条目输区域)、prev(上一页区域)、 <br/>&nbsp; * page(分页区域)、next(下一页区域)、limit(条目选项区域)、 <br/>&nbsp; * refresh(页面刷新区域。注意:layui 2.3.0 新增) 、skip(快捷跳页区域) */ layout?: Array<'count' | 'prev' | 'page' | 'next' | 'limit' | 'refresh' | 'skip'>; /** * 自定义主题。支持传入:颜色值,或任意普通字符。 <br/>&nbsp; * 如: <br/>&nbsp; * 1. theme: '#c00' <br/>&nbsp; * 2. theme: 'xxx' //将会生成 class="layui-laypage-xxx" 的CSS类,以便自定义主题 */ theme?: string; /** * 开启location.hash,并自定义 hash 值。如果开启,在触发分页时, <br/>&nbsp; * 会自动对url追加:#!hash值={curr} 利用这个,可以在页面载入时就定位到指定页 * */ hash?: string | boolean; /** * 切换分页的回调 * @param [obj] 当前分页的所有选项值 * @param [first] 是否首次,一般用于初始加载的条件,true则会调用渲染 */ jump?(obj: PageOptionsForCallback, first: boolean): void; } /** * 先排除 */ interface PageOptionsForCallback extends Omit<Required<PageOptions>, 'count' | 'curr' | 'limit' | 'groups'> { /** * 数据总数。一般通过服务端得到 */ count: number; /** * 起始页。一般用于刷新类型的跳页以及HASH跳页 */ curr: number; /** * 每页条数的选择项。如果 layout 参数开启了 limit, 默认:[10, 20, 30, 40, 50] <br/>&nbsp; * 则会出现每页条数的select选择框 */ limit: number; /** * 自动计算出的总分页数 */ pages: number; /** * 连续出现的页码个数 默认:5 */ groups: number; } // https://www.layui.com/doc/modules/laypage.html /** * 分页模块 */ interface Laypage { index: number; on<K extends keyof HTMLElementEventMap>( elem: HTMLElement | null, event: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => void, ): void; on(elem: HTMLElement | null, event: string, listener: (this: HTMLElement, ...args: any) => any): void; render(options?: PageOptions): any; } // https://www.layui.com/doc/modules/laytpl.html /** * 模板引擎 */ interface Laytpl { (tpl: string): TplObject; /** * 重新定义分隔符 <br/>&nbsp; * 如果模版默认的 {{ }} 分隔符与你的其它模板(一般是服务端模板)存在冲突,你也可以重新定义分隔符: * @param [option] 例如:{open: '<%',close: '%>'} */ config(option?: { open?: string; close?: string }): void; } interface TplObject { tpl: string; /** * 执行解析,不常用,推荐render * @param [tpl] 模板串 * @param [data] 数据 */ parse(tpl: string, data: object): string; /** * 执行解析 * @param [data] 数据 * @param [callback] 解析后的回调,即可通过回调中参数也可通过render返回值获取解析后结果串 */ render(data: object, callback?: (str: string) => any): string; } interface RateOption { /** * 指向容器选择器 */ elem?: string | HTMLElement | JQuery; /** * 评分组件中具体星星的个数。<br/>&nbsp; * 个数当然是整数啦,残缺的星星很可怜的,所以设置了小数点的组件我们会默认向下取整 */ length?: number; /** * 评分的初始值 默认:0 */ value?: number; /** * 主题颜色。<br/>&nbsp; */ /** * 默认的组件颜色是#FFB800,你可以根据自身喜好来更改组件的颜色,以适用不同场景 */ theme?: string; /** * 设定组件是否可以选择半星 默认:false */ half?: boolean; /** * 是否显示评分对应的内容 默认:false */ text?: boolean; /** * 是否只读,即只用于展示而不可点 默认:false */ readonly?: boolean; /** * 自定义文本的回调 * @param [value] */ setText?(value: number): void; choose?(value: number): void; } // https://www.layui.com/doc/modules/rate.html /** * 评分组件 */ interface Rate { config: { [index: string]: any }; index: number; /** * * @param [event] * @param [callback] */ on(event: string, callback: (obj: any) => any): any; /** * 核心方法 * @param [option] 基础参数 */ render(option: RateOption): Rate; /** * 设置全局参数 * @param [options] 基础参数 */ set(options?: RateOption): Rate; } interface SliderOption { /** * 指向容器选择器 */ elem?: string | HTMLElement | JQuery; /** * 滑块类型,可选值有:default(水平滑块)、vertical(垂直滑块) 默认:default */ type?: 'default' | 'vertical'; /** * 滑动条最小值,正整数,默认: 0 */ min?: number; /** * 滑动条最大值 默认:100 */ max?: number; /** * 是否开启滑块的范围拖拽,若设为 true,则滑块将出现两个可拖拽的环 默认:false */ range?: boolean; /** * 滑块初始值,默认为数字,若开启了滑块为范围拖拽(即 range: true),则需赋值数组, <br/>&nbsp; * 表示开始和结尾的区间,如:value: [30, 60] */ value?: number | number[]; /** * 拖动的步长 默认:1 */ step?: number; /** * 是否显示间断点 默认:false */ showstep?: boolean; /** * 是否显示文字提示 默认:true */ tips?: boolean; /** * 是否显示输入框(注意:若 range 参数为 true 则强制无效) <br/>&nbsp; */ /** * 点击输入框的上下按钮,以及输入任意数字后回车或失去焦点,均可动态改变滑块 默认:false */ input?: boolean; /** * 滑动条高度,需配合 type:"vertical" 参数使用 默认:200 */ height?: number; /** * 是否将滑块禁用拖拽 默认:false */ disabled?: boolean; /** * 主题颜色,以便用在不同的主题风格下 默认:#009688 */ theme?: string; /** * 自定义提示文本 * @param [value] 滑块为范围模式是数组,否则是数字 */ setTips?(value: number | number[]): string; /** * 数值改变的回调 <br/>&nbsp; * @param [value] 滑块为范围模式是数组,否则是数字 */ change?(value: number | number[]): void; } // https://www.layui.com/doc/modules/slider.html /** * 滑块 */ interface Slider { config: { [index: string]: any }; index: number; /** * 设置滑块的全局参数 * @param [options] 基础参数 */ set(options?: SliderOption): Slider; // bug to fix on(event: string, callback: (obj: any) => any): any; /** * 核心方法 * @param [option] 参数 */ render(option: SliderOption): { config: SliderOption; /** * 改变指定滑块实例的数值 * @param [value] * @param [index] 若滑块开启了范围(range: true) 则index需要0和1 */ setValue(value: any, index?: number): void; }; // setValue(value1: number, value2?: number): void; } interface TableColumnOption { checkbox?: boolean; /** * 设定字段名。非常重要,且是表格数据列的唯一标识,若没有则用索引 */ field?: string; /** * 设定标题名称 */ title?: string; /** * 设定列宽,若不填写,则自动分配;若填写,则支持值为:数字、百分比。 <br/>&nbsp; * 请结合实际情况,对不同列做不同设定。 */ width?: string | number; /** * 局部定义当前常规单元格的最小宽度(默认:60), <br/>&nbsp; * 一般用于列宽自动分配的情况。其优先级高于基础参数中的 cellMinWidth */ minWidth?: number; /** * 设定列类型,可选有: 默认:normal */ type?: 'normal' | 'checkbox' | 'radio' | 'space' | 'numbers'; /** * 是否全选状态(默认:false)。必须复选框列开启后才有效, * 如果设置 true,则表示复选框默认全部选中。 */ LAY_CHECKED?: boolean; /** * 固定列。可选值有:left(固定在左)、right(固定在右)。一旦设定,对应的列将会被固定在左或右,不随滚动条而滚动。 <br/>&nbsp; * 注意:如果是固定在左,该列必须放在表头最前面;如果是固定在右,该列必须放在表头最后面。 <br/>&nbsp; * 非"right"就是left */ fixed?: 'left' | 'right'; /** * 是否初始隐藏列,默认:false */ hide?: boolean; /** * 是否开启该列的自动合计功能,默认:false。 <br>&nbsp; * 1、parseData中包含totalRow可以映射自定字段 <br>&nbsp; * 2、从 layui 2.6.3 开始,如果 totalRow 为一个 string 类型,则可解析为合计行的动态模板 <br>&nbsp; * 实例:totalRow: '{{ d.TOTAL_NUMS }} 单位' 或 '{{ parseInt(d.TOTAL_NUMS) }}' */ totalRow?: boolean | { score: number | string; experience: string } | string; /** * 用于显示自定义的合计文本 */ totalRowText?: string; /** * 是否允许排序(默认:false)。 <br>&nbsp; * 如果设置 true,则在对应的表头显示排序icon,从而对列开启排序功能 */ sort?: boolean; /** * 是否禁用拖拽列宽(默认:false)。默认情况下会根据列类型(type)来决定是否禁用,如复选框列,会自动禁用。 <br/>&nbsp; * 而其它普通列,默认允许拖拽列宽,当然你也可以设置 true 来禁用该功能。 */ unresize?: boolean; /** * 单元格编辑类型(默认不开启)目前只支持:text(输入框) */ edit?: 'text' | string; /** * 自定义单元格点击事件名,以便在 tool 事件中完成对该单元格的业务处理, <br/>&nbsp; * 比如:table.on('tool(tableFilter)', function(obj){obj.event=''}) */ event?: string; /** * 自定义单元格样式。即传入 CSS 样式,实例:"background-color: #5FB878; color: #fff"; */ style?: string; /** * 单元格排列方式。可选值有:left(默认)、center(居中)、right(居右) */ align?: 'left' | 'center' | 'right'; /** * 单元格所占列数(默认:1)。一般用于多级表头 */ colspan?: number; /** * 单元格所占行数(默认:1)。一般用于多级表头 */ rowspan?: number; /** * 自定义列模板,模板遵循 laytpl 语法 <br/>&nbsp; * 回调参数d从v2.6.8新增 LAY_COL 字段,可得到当前列的表头配置信息 * laytpl:https://www.layui.com/doc/modules/laytpl.html */ templet?: string | ((d: TableColumnOptionForTemplet) => string); /** * 绑定工具条模板。可在每行对应的列中出现一些自定义的操作性按钮 <br/>&nbsp; * dom选择器,例如#toolbar */ toolbar?: string; } /** * table 的templet回调参数格式 <br/>&nbsp; * tips:templet回调中可以使用 d.xx xx为任意参数 */ interface TableColumnOptionForTemplet { LAY_COL: TableColumnOptionForTempletCol; LAY_INDEX: number; LAY_TABLE_INDEX: number; /** * 该属性不存在,只是提示你:你可以用d.xxx 使用当前行中的任意数据属性。 */ '你可以用 d.xx 来使用当前行的其他属性': never; [index: string]: any; } /** * table的templet回调中 d.LAY_COL的格式定义 */ interface TableColumnOptionForTempletCol extends Required<TableColumnOption> { HAS_PARENT: boolean; PARENT_COL_INDEX: number; key: string; parentKey: string; } /** * 用于修改request参数名 */ interface TableRequestRename { /** * 页码的参数名称,默认:page */ pageName?: string; /** * 每页数据量的参数名,默认:limit */ limitName?: string; } /** * 用于修改Response参数名 */ interface TableResponseRename { /** * 规定数据状态的字段名称,默认:code */ statusName?: string; /** * 规定成功的状态码,默认:0 */ statusCode?: number; /** * 规定状态信息的字段名称,默认:msg */ msgName?: string; /** * 规定数据总数的字段名称,默认:count */ countName?: string; /** * 规定数据列表的字段名称,默认:data */ dataName?: string; } /* 服务端返回数据不固定 interface TableOriginResponse { status: number; message: string; total: number; data: any; [propName: string]: any; } */ /** * 响应 */ interface TableResponse { code?: number; msg?: string; count?: number; data?: any; [propName: string]: any; } interface TableRendered { config: TableOption; reload(options: TableOption, deep?: boolean): void; setColsWidth(): void; resize(): void; } // https://www.layui.com/doc/modules/table.html#options /** * 基础参数 */ interface TableOption { /** * 指定原始 table 容器的选择器或 DOM,方法渲染方式必填 */ elem?: string | HTMLElement | JQuery; /** * 设置表头。值是一个二维数组。方法渲染方式必填 ,1维是表头集合,二维是列集合 <br/>&nbsp; * https://www.layui.com/doc/modules/table.html#cols */ cols?: TableColumnOption[][]; /** * 接口地址 <br/>&nbsp; * 默认会自动传递两个参数:?page=1&limit=30(该参数可通过 request 自定义) <br/>&nbsp; * page 代表当前页码、limit 代表每页数据量 */ url?: string | null; /** * 开启表格头部工具栏区域,该参数支持四种类型值: <br>&nbsp; * toolbar: '#toolbarDemo' // 指向自定义工具栏模板选择器 <br>&nbsp; * toolbar: '<div>xxx</div>' // 直接传入工具栏模板字符 <br>&nbsp; * toolbar: true // 仅开启工具栏,不显示左侧模板 <br>&nbsp; * toolbar: 'default' // 让工具栏左侧显示默认的内置模板 */ toolbar?: string | HTMLElement | boolean; /** * 该参数可自由配置头部工具栏右侧的图标按钮 内置3个: <br>&nbsp; * filter: 显示筛选图标, <br>&nbsp; * exports: 显示导出图标, <br>&nbsp; * print: 显示打印图标 */ defaultToolbar?: Array< 'filter' | 'exports' | 'print' | string | { title?: string; layEvent?: string; icon?: string } >; /** * 设定容器宽度(超出容器会自动出现横向滚动条),默认宽度是跟随它的父元素铺满 */ width?: number | string; /** * 设定容器高度,如:'full-100' */ height?: number | string; /** * 全局定义所有常规单元格的最小宽度(默认:60) */ cellMinWidth?: number; /** * 数据渲染完的回调。你可以借此做一些其它的操作 * @param [res] 1、如果是异步请求数据方式,res即为你接口返回的信息。<br/>&nbsp; * 2、如果是直接赋值的方式,res即为:{data: [], count: 99} data为当前页数据、count为数据总长度 * @param [curr] 得到当前页码 * @param [count] 得到数据总量 */ done?(res: any, curr: number, count: number): void; /** * 数据请求失败的回调,返回两个参数:错误对象、内容 * @param [e] 错误对象 ,是jqXHR对象(对XHR扩展),不同jquery版本其格式不同 * @param [msg] 内容 比如 "error" */ error?(e: any, msg: any): void; /** * 直接赋值数据。既适用于只展示一页数据,也非常适用于对一段已知数据进行多页展示。 */ data?: any[]; /** * 是否开启 xss 字符过滤(默认 false) */ escape?: boolean; /** * 是否开启合计行区域 */ totalRow?: boolean; /** * 开启分页(默认:false),PageOptions时排除jump和elem */ page?: boolean | PageOptions; /** * 每页显示的条数(默认 10)。值需对应 limits 参数的选项。 <br/>&nbsp; * 注意:优先级低于 page 参数中的 limit 参数 */ limit?: number; /** * 每页条数的选择项,默认:[10,20,30,40,50,60,70,80,90]。 <br/>&nbsp; * 注意:优先级低于 page 参数中的 limits 参数 */ limits?: number[]; /** * 是否显示加载条(默认 true)。若为 false,则在切换分页时,不会出现加载条。 <br/>&nbsp; * 该参数只适用于 url 参数开启的方式 */ loading?: boolean; /** * 定义 table 的大标题(在文件导出等地方会用到) */ title?: string; /** * 自定义文本,如空数据时的异常提示等。 */ text?: { none: string }; /** * 默认 true,即直接由 table 组件在前端自动处理排序。 <br/>&nbsp; * 若为 false,则需自主排序,即由服务端返回排序好的数据 */ autoSort?: boolean; /** * 初始排序状态。 <br/>&nbsp; * 用于在数据表格渲染完毕时,默认按某个字段排序。 */ initSort?: { field: string; type?: 'null' | 'desc' | 'asc' }; /** * 设定容器唯一 id。id 是对表格的数据操作方法上是必要的传递条件,它是表格容器的索引 */ id?: string; /** * 用于设定表格风格 */ skin?: 'line' | 'row' | 'nob'; /** * 若不开启隔行背景,不设置该参数即可 */ even?: boolean; /** * 用于设定表格尺寸,若使用默认尺寸不设置该属性即可 */ size?: 'sm' | 'lg'; /** * 异接口http请求类型,默认:get */ method?: string; /** * 接口的其它参数。如:where: {token: 'sasasas', id: 123} */ where?: object | null; /** * 发送到服务端的内容编码类型。 <br/>&nbsp; * 如果你要发送 json 内容,可以设置:contentType: 'application/json' */ contentType?: string; /** * 接口的请求头。如:headers: {token: 'sasasas'} */ headers?: object; /** * 数据格式解析的回调函数,用于将返回的任意数据格式解析成 table 组件规定的数据格式。 * @param [res] 服务端返回的数据 */ parseData?(res: any): TableResponse; /** * 用于对分页请求的参数:page、limit重新设定名称,如果无需自定义请求参数,可不加该参数 <br/>&nbsp; * 通过parseData也可映射不同名称 */ request?: TableRequestRename; /** * 可以借助 response 重新设定本地识别响应字段名,如果无需自定义数据响应名称,可不加该参数 <br/>&nbsp; * 当默认支持的名称和服务端不一致可以通过本方式或者parseData来对应 */ response?: TableResponseRename; } // ------------以下TableOn 开头interface,在调用地方使用---------- /** * 点击table中checkbox后回调参数的类型 */ interface TableOnCheckbox { checked: true; data: object; del(): void; tr: JQuery; type: string; update(fields: object): void; } /** * 点击table上边工具栏后回调参数的类型 */ interface TableOnToolbar { config: TableOption; event: string; } /** * 点击table中工具列后回调参数的类型 */ interface TableOnTool { data: object; del(): void; event: string; tr: JQuery; update(fields: object): void; } /** * 点击table中行后回调参数的类型 */ interface TableOnRow { data: object; del(): void; tr: JQuery; update(fields: object): void; } /** * 点击table中单元格编辑后回调参数的类型 */ interface TableOnEdit { data: object; del(): void; field: string; tr: JQuery; update(fields: object): void; value: string; } /** * 点击table中列标题排序后回调参数的类型 */ interface TableOnSort { field: string; type: string; } // https://www.layui.com/doc/element/table.html // https://www.layui.com/doc/modules/table.html /** * 表格 - 页面元素 */ interface Table { cache: object; /** * 获取表格选中行(。id 即为 id 参数对应的值 * @param [id] */ checkStatus(id: string): { data: []; isAll: boolean }; /** * 清除临时Key (即:LAY_CHECKED和LAY_TABLE_INDEX) * @param [data] */ clearCacheKey(data: object): object; config: { checkName: 'LAY_CHECKED'; // 是否选中状态的字段名 indexName: 'LAY_TABLE_INDEX'; // 初始下标索引名,用于恢复排序 }; /** * 遍历表头 * @param [id] table参数中的id,无id则数字 * @param [callback] 回调 * @param [cols] */ eachCols(id: string, callback?: (...arg: any) => any, cols?: TableColumnOption[][]): void; /** * 导出自定数据到文件 * @param [id] table的id用于找到title当做下载文件名 * @param [data] 手动指定数据 * @param [type] 默认csv */ // exportFile(id: string, data: any[], type?: string): void; // exportFile(colName: any[], data: any[], type?: string): void; /** * 导出table中数据到文件 * @param [id] table选项中的id,指定id后则下载的文件名为table中title <br/>&nbsp; * 若传入数组则是导出的文件的列标题colName * @param [data] 传入数据则导出的是该数据,不传则用id从table找数据 * @param [type] 默认csv */ exportFile(id: string | any[], data?: any[] | null, type?: string): void; /** * 获取表格当前页的所有行数据 * @param [id] table参数中的id,无id则数字 */ getData(id: string): any[]; index: number; /** * 初始化 * @param [filter] lay-filter设定的值 * @param [option] 各项基础参数 */ init(filter: string, option?: TableOption): object; /** * 绑定事件 * <br/>&nbsp;注意:obj类型是变化的不能在ts指定,参考如下替代方案, * <br/>&nbsp; import TableOnCheckbox = layui.TableOnCheckbox; * <br/>&nbsp; table.on('checkbox(test)', function(obj){ * <br/>&nbsp; let rows:TableOnCheckbox=obj; * <br/>&nbsp; //然后,你就可以使用明确的属性了,两种方式编译后js中均为 let rows=obj; 输出不包含类型 * <br/>&nbsp; }); * <br/>&nbsp; 类型对应: (就是 TableOn+事件类型,无需记忆) * <br/>&nbsp; checkbox -> TableOnCheckbox * <br/>&nbsp; toolbar -> TableOnToolbar * <br/>&nbsp; tool -> TableOnTool * <br/>&nbsp; row -> TableOnRow * <br/>&nbsp; edit- -> TableOnEdit * <br/>&nbsp; sort -> TableOnSort * @param [event] mod(filter) * @param [callback] obj参考上边注释 */ on(event: string, callback: (this: any, obj: any) => any): void; /** * 表格重载 * @param [id] table的id,唯一实例标识 * @param [option] 基础参数 * @param [deep] true则深度复制 */ reload(id: string, option?: TableOption, deep?: boolean): void; /** * 核心入口 * @param [option] 基础参数 */ render(option: TableOption): TableRendered; /** * 重置表格尺寸结构 * @param [id] 如果指定表格唯一 id,则只执行该 id 对应的表格实例 */ resize(id: string): void; /** * 设置table全局项 * @param [option] 基础参数 */ set(option?: TableOption): Table; } interface TransferOption { /** * 指向容器选择器 */ elem?: string | HTMLElement | JQuery; /** * 穿梭框上方标题 */ title?: any[]; /** * 数据源 */ data?: any[]; /** * 用于对数据源进行格式解析 * @param [data] */ parseData?(data: any): any; /** * 初始选中的数据(右侧列表) */ value?: any[]; /** * 设定实例唯一索引,用于基础方法传参使用。 */ id?: string; /** * 是否开启搜索 */ showSearch?: boolean; /** * 定义左右穿梭框宽度 */ width?: number; /** * 定义左右穿梭框高度 */ height?: number; /** * 自定义文本,如空数据时的异常提示等。 */ text?: { /** * 没有数据时的文案 '无数据' */ none?: string; /** * 搜索无匹配数据时的文案 '无匹配数据' */ searchNone?: string; }; /** * 左右数据穿梭时的回调 * @param [data] 数据 * @param [index] 索引 */ onchange?(data: any, index: number): void; } interface TransferRendered { config: { [index: string]: any }; /** * 获得右侧数据 */ getData(): any[]; /** * 重载实例 bug to fix * @param [id] 实例唯一索引 * @param [options] 各项基础参数 */ reload(id: string, options: TransferOption): void; /** * 设定全局默认参数 bug to fix * * @param [options] 各项基础参数 */ } // https://www.layui.com/doc/modules/transfer.html /** * 穿梭框组件 */ interface Transfer { config: { [index: string]: any }; index: number; /** * 获得右侧数据 * @param [id] 实例唯一索引 */ getData(id: string): any[]; /** * 核心方法 * bug to fix * @param [option] 各项基础参数 */ render(option: TransferOption): TransferRendered; /** * 绑定事件,内部modName默认为transfer,绑定参考layui.onevent,触发参考layui.event * @param [events] * @param [callback] */ on(events: string, callback: (this: Layui, obj: any) => any): any; /** * 重载实例 bug to fix * @param [id] 实例唯一索引 * @param [options] 各项基础参数 */ reload(id: string, options: TransferOption): void; /** * 设定全局默认参数 bug to fix * * @param [options] 各项基础参数 */ set(options: TransferOption): void; } // https://www.layui.com/doc/modules/tree.html#data interface TreeData { /** * 节点标题 */ title?: string; /** * 节点唯一索引值,用于对指定节点进行各类操作 */ id?: string | number; /** * 节点字段名 */ field?: string; /** * 子节点。支持设定选项同父节点 */ children?: any[]; /** * 点击节点弹出新窗口对应的 url。需开启 isJump 参数 */ href?: string; /** * 节点是否初始展开,默认 false */ spread?: boolean; /** * 节点是否初始为选中状态(如果开启复选框的话),默认 false */ checked?: boolean; /** * 节点是否为禁用状态。默认 false */ disabled?: boolean; } interface TreeCheckData { data: any; checked: boolean; elem: JQuery; } interface TreeClickData { data: any; elem: JQuery; state: 'open' | 'close' | 'normal'; } interface TreeOperateData { data: any; elem: JQuery; /** * 除了add和update就是删除del */ type: 'add' | 'update' | 'del' | string; } /** * tree.reload()返回值 */ type TreeReloaded = Pick<Tree, 'config' | 'reload' | 'getChecked' | 'setChecked'>; // https://www.layui.com/doc/modules/tree.html#options /** * 基础参数 */ interface TreeOption { /** * 指向容器选择器 */ elem?: string | HTMLElement | JQuery; /** * 数据源 */ data?: TreeData[]; /** * 设定实例唯一索引,用于基础方法传参使用。 */ id?: string; /** * 是否显示复选框 */ showCheckbox?: boolean; /** * 是否开启节点的操作图标。默认 false。 */ // 目前支持的操作图标有:add、update、del,如:edit: ['add', 'update', 'del'] edit?: boolean | string[]; /** * 是否开启手风琴模式,默认 false */ accordion?: boolean; /** * 是否仅允许节点左侧图标控制展开收缩。默认 false(即点击节点本身也可控制)。 */ // 若为 true,则只能通过节点左侧图标来展开收缩 onlyIconControl?: boolean; /** * 是否允许点击节点时弹出新窗口跳转。默认 false, */ // 若开启,需在节点数据中设定 link 参数(值为 url 格式) isJump?: boolean; /** * 是否开启连接线。默认 true,若设为 false,则节点左侧出现三角图标。 */ showLine?: boolean; /** * 自定义各类默认文本,目前支持以下设定: */ text?: { /** * 节点默认名称 '未命名' */ defaultNodeName?: string; /** * 数据为空时的提示文本 '无数据' */ none?: string; }; /** * 复选框被点击的回调 * @param [obj] */ oncheck?(obj: TreeCheckData): void; /** * 节点被点击的回调 * @param [obj] */ click?(obj: TreeClickData): void; /** * 操作节点的回调 * @param [obj] */ operate?(obj: TreeOperateData): void; /** * 节点过滤的回调 * @param [obj] */ onsearch?(obj: { elem: any[] }): void; /** * 未知 * @param [args] */ dragstart?(...args: any): any; /** * 未知 * @param [args] */ dragend?(...args: any): any; } // https://www.layui.com/doc/modules/tree.html /** * 树形组件 */ interface Tree { /** * 全局参数项 */ config: { [index: string]: any }; /** * 返回选中的节点数据数组 * @param [id] render参数中的id ,注意data中需要有id属性才返回 */ getChecked(id: string): TreeData[]; /** * tree实例总数 */ index: number; /** * 绑定事件,内部modName默认为tree,绑定参考layui.onevent,触发参考layui.event * @param [events] * @param [callback] */ on(events: string, callback: (this: Layui, obj: any) => any): any; /** * 实例重载,重载一个已经创建的组件实例,覆盖基础属性 * @param [id] render参数中的id,保证id存在否则出js错误 * @param [options] 基础参数 */ reload(id: string, options: TreeOption): TreeReloaded; /** * 核心方法 * @param [option] 基础参数 */ render(option: TreeOption): any; /** * 设置tree全局参数(预设基础参数值) * @param [option] */ set(option?: TreeOption): Tree; /** * 设置节点勾选 * @param [id] */ /** * 设置节点勾选 * @param [id] render参数中的id,指明是哪个tree实例 * @param [nodeId] 树节点数据中的id 参考render->data->id */ setChecked(id: string, nodeId: any): void; } interface UploadOption { /** * 指向容器选择器,如:elem: '#id'。也可以是DOM对象 */ elem?: string | HTMLElement | JQuery; /** * 触发上传的元素 */ readonly item?: HTMLElement; /** * 服务端上传接口,如:'/api/upload/' */ url?: string; /** * 请求上传接口的额外参数,支持属性为function动态值 */ data?: object; /** * 接口的请求头。如:headers: {token: 'sasasas'} */ headers?: object; /** * 指定允许上传时校验的文件类型, 默认:images (即file,video,audio之外都可) <br/>&nbsp; */ // 可选值有:images(图片)、file(所有文件)、video(视频)、audio(音频) accept?: 'images' | 'file' | 'video' | 'audio'; /** * 规定打开文件选择框筛选出的文件类型,值为用逗号隔开。默认:images 如: <br/>&nbsp; */ // acceptMime: 'image/*'(只显示图片文件) <br/>&nbsp; // acceptMime: 'image/jpg, image/png'(只显示 jpg 和 png 文件) acceptMime?: string; /** * 允许上传的文件后缀。一般结合 accept 参数类设定。默认:jpg|png|gif|bmp|jpeg <br/>&nbsp; */ // 假设 accept 为 file 类型时,那么你设置 exts: 'zip|rar|7z' 即代表只允许上传压缩格式的文件。 <br/>&nbsp; // 如果 accept 未设定,那么限制的就是图片的文件格式 exts?: string; /** * 是否选完文件后自动上传。 默认:true <br/>&nbsp; */ // 如果设定 false,那么需要设置 bindAction 参数来指向一个其它按钮提交上传 auto?: boolean; /** * 指向一个按钮触发上传,一般配合 auto: false 来使用。值为选择器或DOM对象,如:bindAction: '#btn' */ bindAction?: string | HTMLElement; /** * 设定文件域的字段名,默认:file */ field?: string; /** * 设置文件最大可允许上传的大小,单位 KB。不支持ie8/9 ,默认:0(即无限制) */ size?: number; /** * 是否允许多文件上传。设置 true即可开启。不支持ie8/9 默认:false */ multiple?: boolean; /** * 设置同时可上传的文件数量,一般配合 multiple 参数出现。 默认:0(即无限制) */ number?: number; /** * 更新文件域相关属性 */ name?: string; /** * 是否接受拖拽的文件上传,设置 false 可禁用。不支持ie8/9 默认true */ drag?: boolean; /** * 请求上传的 http 类型 */ method?: string; /** * 选择文件后的回调函数 * @param [obj] 回调参数(工具对象) */ choose?(this: UploadOptionThis, obj: UploadCallbackArg): void; /** * 文件提交上传前的回调,返回false则停止上传 实例:before:function(this,obj){} * @param [obj] 回调参数(工具对象) */ before?(this: UploadOptionThis, obj: UploadCallbackArg): any; /** * 上传后的回调 * @param [res] 服务端response json * @param [index] 当前文件索引 (选择文件时自动生成的:new Date().getTime()+'-'+i) * @param [upload] 上传函数 */ done?(this: UploadOptionThis, res: any, index: string, upload: (files?: Blob[]) => void): void; /** * 执行上传请求出现异常的回调(一般为网络异常、URL 404等)。 <br/>&nbsp; * 返回两个参数,分别为:index(当前文件的索引)、upload(重新上传的方法 * @param [index] 当前文件索引 (选择文件时自动生成的:new Date().getTime()+'-'+i) * @param [upload] 上传函数 */ error?(this: UploadOptionThis, index: string, upload: (files?: Blob[]) => void): void; /** * 当文件全部被提交后,才触发 * @param [obj] 回调参数 */ allDone?(this: UploadOptionThis, obj: UploadAllDoneArg): void; /** * 进度回调 * @param [percent] 数字进度 * @param [elem] render参数中的elem(即点击元素dom) * @param [event] 事件 * @param [index] 当前文件索引 (选择文件时自动生成的:new Date().getTime()+'-'+i) */ progress?( this: UploadOptionThis, percent: number, elem: HTMLElement, event: ProgressEvent, index: string, ): void; } type UploadOptionThis = Required<UploadOption>; interface UploadAllDoneArg { /** * 得到总文件数 */ total: number; /** * 请求成功的文件数 */ successful: number; /** * 请求失败的文件数 */ aborted: number; } interface UploadCallbackArg { /** * 预览 * @param [callback] index索引,file文件,result比如图片base64编码 */ preview(callback: (index: string, file: File, result: any) => void): void; /** * 上传单个文件 <br/>&nbsp; * 对上传失败的单个文件重新上传,一般在某个事件中使用 * @param [index] 索引 (选择文件时自动生成的:new Date().getTime()+'-'+i) * @param [file] 文件 */ upload(index: string, file: Blob): void; /** * 追加文件到队列, 比如 choose回调中将每次选择的文件追加到文件队列 */ pushFile(): { [index: string]: File }; /** * 重置文件和文件名 * @param [index] 被重置的文件索引 (选择文件时自动生成的:new Date().getTime()+'-'+i) * @param [file] 新的文件 * @param [filename] 新的名字 */ resetFile(index: string, file: Blob, filename: any): void; } interface UploadRendered { /** * 参数信息 */ config: { [index: string]: any }; /** * 重载该实例,支持重载全部基础参数 * @param [options] 基础参数 */ reload(options?: UploadOption): void; /** * 重新上传的方法,一般在某个事件中使用 * @param [files] 需要上传的文件数组 */ upload(files?: Blob[]): void; } // https://www.layui.com/doc/modules/upload.html /** * 图片/文件上传 */ interface Upload { /** * 全局参数项 */ config: { [index: string]: any }; /** * 绑定事件,内部modName默认为 upload,绑定参考layui.onevent,触发参考layui.event * @param events * @param callback */ on(events: string, callback: (this: Layui, obj: any) => any): any; /** * 核心方法 * @param [option] 基础参数 */ render(option: UploadOption): UploadRendered; /** * 设置upload全局参数(预设基础参数值) * @param [option] 参数 */ set(option?: UploadOption): Upload; } interface UtilBarOption { /** * 默认false。如果值为true,则显示第一个bar,带有一个默认图标。 <br/>&nbsp; */ // 如果值为图标字符,则显示第一个bar,并覆盖默认图标 bar1?: boolean | string; /** * 默认false。如果值为true,则显示第二个bar,带有一个默认图标。 <br/>&nbsp; */ // 如果值为图标字符,则显示第二个bar,并覆盖默认图标 bar2?: boolean | string; /** * 自定义区块背景色 */ bgcolor?: string; /** * 用于控制出现TOP按钮的滚动条高度临界值。默认:200 */ showHeight?: number; /** * 你可以通过重置bar的位置,比如 css: {right: 100, bottom: 100} */ css?: { [key: string]: string | number | boolean }; /** * 点击bar的回调,函数返回一个type参数,用于区分bar类型。 <br/>&nbsp; * 支持的类型有:bar1、bar2、top * @param [type] bar1、bar2、top */ click?(type: string | 'bar1' | 'bar2' | 'top'): void; } // https://www.layui.com/doc/modules/util.html /** * 工具集 */ interface Util { /** * 固定块 * @param [option] 参数 */ fixbar(option?: UtilBarOption): void; /** * 倒计时 * @param [endTime] 结束时间戳或Date对象,如:4073558400000,或:new Date(2099,1,1). * @param [serverTime] 当前服务器时间戳或Date对象 * @param [callback] 回调函数。如果倒计时尚在运行,则每一秒都会执行一次。并且返回三个参数: <br/>&nbsp; * date(包含天/时/分/秒的对象)、 <br/>&nbsp; * serverTime(当前服务器时间戳或Date对象), <br/>&nbsp; * timer(计时器返回的ID值,用于clearTimeout) */ countdown( endTime?: number | Date, serverTime?: number | Date, callback?: (date: number[], serverTime_: typeof serverTime, timer: number) => void, ): void; /** * 某个时间在当前时间的多久前 * @param [time] 当前时间之前的时间戳或日期对象 * @param [onlyDate] 在超过30天后,true只返回日期字符,false不返回时分秒 */ timeAgo(time?: number | Date, onlyDate?: boolean): string; /** * 转化时间戳或日期对象为日期格式字符 * @param [time] 日期对象,也可以是毫秒数 ,默认:当前 * @param [format] 默认:yyyy-MM-dd HH:mm:ss */ toDateString(time?: number | Date, format?: string): any; /** * 数字前置补零 * @param [num] 数字 * @param [length] 补0后的长度 */ digit(num?: any, length?: number): string; /** * 转义 xss 字符 * @param str */ escape(str?: any): string; /** * 批量处理事件 * @param [attr] 绑定需要监听事件的元素属性 * @param [obj] 事件回调链 */ event(attr: string, obj: { [index: string]: (othis: JQuery) => any }): any; } /** * 缓存的所有数据 */ interface CacheData { base: string; builtin: Modules; /* // 仅包含layui.use指定的模块或者导入全部模块 ,callback:{ carousel: Function ,code: Function ,colorpicker: Function ,dropdown: Function ,element:Function ,flow: Function ,form: Function ,jquery: Function ,lay: Function ,laydate: Function ,layedit: Function ,layer: Function ,laypage: Function ,laytpl: Function ,"layui.all": Function ,rate: Function ,slider: Function ,table: Function ,transfer:Function ,tree: Function ,upload: Function ,util: Function [index:string]:Function }*/ dir: string; /** * 记录模块自定义事件 */ event: { [index: string]: { [index: string]: Array<(...arg: any) => any> } }; host: string; /** * 记录模块物理路径 */ modules: { [index: string]: string }; /** * 记录模块加载状态 */ status: { carousel: boolean; code: boolean; colorpicker: boolean; dropdown: boolean; element: boolean; flow: boolean; form: boolean; jquery: boolean; lay: boolean; laydate: boolean; layedit: boolean; layer: boolean; laypage: boolean; laytpl: boolean; 'layui.all': boolean; rate: boolean; slider: boolean; table: boolean; transfer: boolean; tree: boolean; upload: boolean; util: boolean; [index: string]: boolean; }; /** * 符合规范的模块请求最长等待秒数 */ timeout: number; version: string; } /** * 内置模块名和外置名称映射 */ type Modules = { [T in keyof LayuiModuleMap]: string }; interface LayuiModuleMap { carousel: Carousel; colorpicker: ColorPicker; dropdown: DropDown; element: Element; flow: Flow; form: Form; jquery: JQueryStatic; lay: Lay; laydate: Laydate; layedit: Layedit; layer: Layer; laypage: Laypage; laytpl: Laytpl; 'layui.all': string; rate: Rate; slider: Slider; table: Table; transfer: Transfer; tree: Tree; upload: Upload; util: Util; } } declare const layui: Layui;
the_stack
var undefined; var key; var $: any; var classList; var emptyArray = []; var concat = emptyArray.concat; var filter = emptyArray.filter; var slice = emptyArray.slice; var document = window.document; var elementDisplay = {}; var classCache = {}; var cssNumber = { 'column-count': 1, columns: 1, 'font-weight': 1, 'line-height': 1, opacity: 1, 'z-index': 1, zoom: 1 }; var fragmentRE = /^\s*<(\w+|!)[^>]*>/; var singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; var tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig; var rootNodeRE = /^(?:body|html)$/i; var capitalRE = /([A-Z])/g; // special attributes that should be get/set via method calls var methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset']; var adjacencyOperators = ['after', 'prepend', 'before', 'append']; var table = document.createElement('table'); var tableRow = document.createElement('tr'); var containers = { tr: document.createElement('tbody'), tbody: table, thead: table, tfoot: table, td: tableRow, th: tableRow, '*': document.createElement('div') }; var simpleSelectorRE = /^[\w-]*$/; var class2type = {}; var toString = class2type.toString; var zepto = {}; var camelize; var uniq; var tempParent = document.createElement('div'); var propMap = { tabindex: 'tabIndex', readonly: 'readOnly', for: 'htmlFor', class: 'className', maxlength: 'maxLength', cellspacing: 'cellSpacing', cellpadding: 'cellPadding', rowspan: 'rowSpan', colspan: 'colSpan', usemap: 'useMap', frameborder: 'frameBorder', contenteditable: 'contentEditable' }; var isArray = Array.isArray || function(object) { return object instanceof Array } zepto.matches = function(element, selector) { if (!selector || !element || element.nodeType !== 1) return false var matchesSelector = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector if (matchesSelector) return matchesSelector.call(element, selector) // fall back to performing a selector: var match; var parent = element.parentNode; var temp = !parent if (temp) (parent = tempParent).appendChild(element) match = ~zepto.qsa(parent, selector).indexOf(element) temp && tempParent.removeChild(element) return match } function type(obj) { return obj == null ? String(obj) : class2type[toString.call(obj)] || 'object' } function isFunction(value) { return type(value) == 'function' } function isWindow(obj) { return obj != null && obj == obj.window } function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE } function isObject(obj) { return type(obj) == 'object' } function isPlainObject(obj) { return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype } function likeArray(obj) { var length = !!obj && 'length' in obj && obj.length; var type = $.type(obj) return type != 'function' && !isWindow(obj) && ( type == 'array' || length === 0 || (typeof length === 'number' && length > 0 && (length - 1) in obj) ) } function compact(array) { return filter.call(array, function(item) { return item != null }) } function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array } camelize = function(str) { return str.replace(/-+(.)?/g, function(match, chr) { return chr ? chr.toUpperCase() : '' }) } function dasherize(str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase() } uniq = function(array) { return filter.call(array, function(item, idx) { return array.indexOf(item) == idx }) } function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)')) } function maybeAddPx(name, value) { return (typeof value === 'number' && !cssNumber[dasherize(name)]) ? value + 'px' : value } function defaultDisplay(nodeName) { var element, display if (!elementDisplay[nodeName]) { element = document.createElement(nodeName) document.body.appendChild(element) display = getComputedStyle(element, '').getPropertyValue('display') element.parentNode.removeChild(element) display == 'none' && (display = 'block') elementDisplay[nodeName] = display } return elementDisplay[nodeName] } function children(element) { return 'children' in element ? slice.call(element.children) : $.map(element.childNodes, function(node) { if (node.nodeType == 1) return node }) } function Z(dom, selector) { var i; var len = dom ? dom.length : 0 for (i = 0; i < len; i++) this[i] = dom[i] this.length = len this.selector = selector || '' } // `$.zepto.fragment` takes a html string and an optional tag name // to generate DOM nodes from the given html string. // The generated DOM nodes are returned as an array. // This function can be overridden in plugins for example to make // it compatible with browsers that don't support the DOM fully. zepto.fragment = function(html, name, properties) { var dom, nodes, container // A special case optimization for a single tag if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) if (!dom) { if (html.replace) html = html.replace(tagExpanderRE, '<$1></$2>') if (name === undefined) name = fragmentRE.test(html) && RegExp.$1 if (!(name in containers)) name = '*' container = containers[name] container.innerHTML = '' + html dom = $.each(slice.call(container.childNodes), function() { container.removeChild(this) }) } if (isPlainObject(properties)) { nodes = $(dom) $.each(properties, function(key, value) { if (methodAttributes.indexOf(key) > -1) nodes[key](value) else nodes.attr(key, value) }) } return dom } // `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. This method can be overridden in plugins. zepto.Z = function(dom, selector) { return new Z(dom, selector) } // `$.zepto.isZ` should return `true` if the given object is a Zepto // collection. This method can be overridden in plugins. zepto.isZ = function(object) { return object instanceof zepto.Z } // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and // takes a CSS selector and an optional context (and handles various // special cases). // This method can be overridden in plugins. zepto.init = function(selector, context) { var dom // If nothing given, return an empty Zepto collection if (!selector) return zepto.Z() // Optimize for string selectors else if (typeof selector === 'string') { selector = selector.trim() // If it's a html fragment, create nodes from it // Note: In both Chrome 21 and Firefox 15, DOM error 12 // is thrown if the fragment doesn't begin with < if (selector[0] == '<' && fragmentRE.test(selector)) { dom = zepto.fragment(selector, RegExp.$1, context), selector = null } // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // If it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // If a function is given, call it when the DOM is ready else if (isFunction(selector)) return $(document).ready(selector) // If a Zepto collection is given, just return it else if (zepto.isZ(selector)) return selector else { // normalize array if an array of nodes is given if (isArray(selector)) dom = compact(selector) // Wrap DOM nodes. else if (isObject(selector)) { dom = [selector], selector = null } // If it's a html fragment, create nodes from it else if (fragmentRE.test(selector)) { dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null } // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // And last but no least, if it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // create a new Zepto collection from the nodes found return zepto.Z(dom, selector) } // `$` will be the base `Zepto` object. When calling this // function just call `$.zepto.init, which makes the implementation // details of selecting nodes and creating Zepto collections // patchable in plugins. $ = function(selector, context) { return zepto.init(selector, context) } function extend(target, source, deep) { for (key in source) { if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) { target[key] = {} } if (isArray(source[key]) && !isArray(target[key])) { target[key] = [] } extend(target[key], source[key], deep) } else if (source[key] !== undefined) target[key] = source[key] } } // Copy all but undefined properties from one or more // objects to the `target` object. $.extend = function(target) { var deep; var args = slice.call(arguments, 1) if (typeof target === 'boolean') { deep = target target = args.shift() } args.forEach(function(arg) { extend(target, arg, deep) }) return target } // `$.zepto.qsa` is Zepto's CSS selector implementation which // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`. // This method can be overridden in plugins. zepto.qsa = function(element, selector) { var found; var maybeID = selector[0] == '#'; var maybeClass = !maybeID && selector[0] == '.'; var nameOnly = maybeID || maybeClass ? selector.slice(1) : selector; // Ensure that a 1 char tag name still gets checked var isSimple = simpleSelectorRE.test(nameOnly) return (element.getElementById && isSimple && maybeID) // Safari DocumentFragment doesn't have getElementById ? ((found = element.getElementById(nameOnly)) ? [found] : []) : (element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] : slice.call( isSimple && !maybeID && element.getElementsByClassName // DocumentFragment doesn't have getElementsByClassName/TagName ? maybeClass ? element.getElementsByClassName(nameOnly) // If it's simple, it could be a class : element.getElementsByTagName(selector) // Or a tag : element.querySelectorAll(selector) // Or it's not simple, and we need to query all ) } function filtered(nodes, selector) { return selector == null ? $(nodes) : $(nodes).filter(selector) } $.contains = document.documentElement.contains ? function(parent, node) { return parent !== node && parent.contains(node) } : function(parent, node) { while (node && (node = node.parentNode)) { if (node === parent) return true } return false } function funcArg(context, arg, idx, payload) { return isFunction(arg) ? arg.call(context, idx, payload) : arg } function setAttribute(node, name, value) { value == null ? node.removeAttribute(name) : node.setAttribute(name, value) } // access className property while respecting SVGAnimatedString function className(node, value) { var klass = node.className || ''; var svg = klass && klass.baseVal !== undefined if (value === undefined) return svg ? klass.baseVal : klass svg ? (klass.baseVal = value) : (node.className = value) } // "true" => true // "false" => false // "null" => null // "42" => 42 // "42.5" => 42.5 // "08" => "08" // JSON => parse if valid // String => self function deserializeValue(value) { try { return value ? value == 'true' || (value == 'false' ? false : value == 'null' ? null : +value + '' == value ? +value : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value } catch (e) { return value } } $.type = type $.isFunction = isFunction $.isWindow = isWindow $.isArray = isArray $.isPlainObject = isPlainObject $.isEmptyObject = function(obj) { var name for (name in obj) return false return true } $.isNumeric = function(val) { var num = Number(val); var type = typeof val return val != null && type != 'boolean' && (type != 'string' || val.length) && !isNaN(num) && isFinite(num) || false } $.inArray = function(elem, array, i) { return emptyArray.indexOf.call(array, elem, i) } $.camelCase = camelize $.trim = function(str) { return str == null ? '' : String.prototype.trim.call(str) } // plugin compatibility $.uuid = 0 $.support = { } $.expr = { } $.noop = function() {} $.map = function(elements, callback) { var value; var values = []; var i; var key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) { value = callback(elements[i], i) if (value != null) values.push(value) } } else { for (key in elements) { value = callback(elements[key], key) if (value != null) values.push(value) } } return flatten(values) } $.each = function(elements, callback) { var i, key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) { if (callback.call(elements[i], i, elements[i]) === false) return elements } } else { for (key in elements) { if (callback.call(elements[key], key, elements[key]) === false) return elements } } return elements } $.grep = function(elements, callback) { return filter.call(elements, callback) } if (window.JSON) $.parseJSON = JSON.parse // Populate the class2type map $.each('Boolean Number String Function Array Date RegExp Object Error'.split(' '), function(i, name) { class2type['[object ' + name + ']'] = name.toLowerCase() }) // Define methods that will be available on all // Zepto collections $.fn = { constructor: zepto.Z, length: 0, // Because a collection acts like an array // copy over these useful array functions. forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, sort: emptyArray.sort, splice: emptyArray.splice, indexOf: emptyArray.indexOf, concat: function() { var i; var value; var args = [] for (i = 0; i < arguments.length; i++) { value = arguments[i] args[i] = zepto.isZ(value) ? value.toArray() : value } return concat.apply(zepto.isZ(this) ? this.toArray() : this, args) }, // `map` and `slice` in the jQuery API work differently // from their array counterparts map: function(fn) { return $($.map(this, function(el, i) { return fn.call(el, i, el) })) }, slice: function() { return $(slice.apply(this, arguments)) }, ready: function(callback) { // don't use "interactive" on IE <= 10 (it can fired premature) if (document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement.doScroll)) { setTimeout(function() { callback($) }, 0) } else { var handler = function() { document.removeEventListener('DOMContentLoaded', handler, false) window.removeEventListener('load', handler, false) callback($) } document.addEventListener('DOMContentLoaded', handler, false) window.addEventListener('load', handler, false) } return this }, get: function(idx) { return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length] }, toArray: function() { return this.get() }, size: function() { return this.length }, remove: function() { return this.each(function() { if (this.parentNode != null) { this.parentNode.removeChild(this) } }) }, each: function(callback) { emptyArray.every.call(this, function(el, idx) { return callback.call(el, idx, el) !== false }) return this }, filter: function(selector) { if (isFunction(selector)) return this.not(this.not(selector)) return $(filter.call(this, function(element) { return zepto.matches(element, selector) })) }, add: function(selector, context) { return $(uniq(this.concat($(selector, context)))) }, is: function(selector) { return typeof selector === 'string' ? this.length > 0 && zepto.matches(this[0], selector) : selector && this.selector == selector.selector }, not: function(selector) { var nodes = [] if (isFunction(selector) && selector.call !== undefined) { this.each(function(idx) { if (!selector.call(this, idx)) nodes.push(this) }) } else { var excludes = typeof selector === 'string' ? this.filter(selector) : (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector) this.forEach(function(el) { if (excludes.indexOf(el) < 0) nodes.push(el) }) } return $(nodes) }, has: function(selector) { return this.filter(function() { return isObject(selector) ? $.contains(this, selector) : $(this).find(selector).size() }) }, eq: function(idx) { return idx === -1 ? this.slice(idx) : this.slice(idx, +idx + 1) }, first: function() { var el = this[0] return el && !isObject(el) ? el : $(el) }, last: function() { var el = this[this.length - 1] return el && !isObject(el) ? el : $(el) }, find: function(selector) { var result; var $this = this if (!selector) result = $() else if (typeof selector === 'object') { result = $(selector).filter(function() { var node = this return emptyArray.some.call($this, function(parent) { return $.contains(parent, node) }) }) } else if (this.length == 1) result = $(zepto.qsa(this[0], selector)) else result = this.map(function() { return zepto.qsa(this, selector) }) return result }, closest: function(selector, context) { var nodes = []; var collection = typeof selector === 'object' && $(selector) this.each(function(_, node) { while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector))) { node = node !== context && !isDocument(node) && node.parentNode } if (node && nodes.indexOf(node) < 0) nodes.push(node) }) return $(nodes) }, parents: function(selector) { var ancestors = []; var nodes = this while (nodes.length > 0) { nodes = $.map(nodes, function(node) { if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) { ancestors.push(node) return node } }) } return filtered(ancestors, selector) }, parent: function(selector) { return filtered(uniq(this.pluck('parentNode')), selector) }, children: function(selector) { return filtered(this.map(function() { return children(this) }), selector) }, contents: function() { return this.map(function() { return this.contentDocument || slice.call(this.childNodes) }) }, siblings: function(selector) { return filtered(this.map(function(i, el) { return filter.call(children(el.parentNode), function(child) { return child !== el }) }), selector) }, empty: function() { return this.each(function() { this.innerHTML = '' }) }, // `pluck` is borrowed from Prototype.js pluck: function(property) { return $.map(this, function(el) { return el[property] }) }, show: function() { return this.each(function() { this.style.display == 'none' && (this.style.display = '') if (getComputedStyle(this, '').getPropertyValue('display') == 'none') { this.style.display = defaultDisplay(this.nodeName) } }) }, replaceWith: function(newContent) { return this.before(newContent).remove() }, wrap: function(structure) { var func = isFunction(structure) if (this[0] && !func) { var dom = $(structure).get(0); var clone = dom.parentNode || this.length > 1 } return this.each(function(index) { $(this).wrapAll( func ? structure.call(this, index) : clone ? dom.cloneNode(true) : dom ) }) }, wrapAll: function(structure) { if (this[0]) { $(this[0]).before(structure = $(structure)) var children // drill down to the inmost element while ((children = structure.children()).length) structure = children.first() $(structure).append(this) } return this }, wrapInner: function(structure) { var func = isFunction(structure) return this.each(function(index) { var self = $(this); var contents = self.contents(); var dom = func ? structure.call(this, index) : structure contents.length ? contents.wrapAll(dom) : self.append(dom) }) }, unwrap: function() { this.parent().each(function() { $(this).replaceWith($(this).children()) }) return this }, clone: function() { return this.map(function() { return this.cloneNode(true) }) }, hide: function() { return this.css('display', 'none') }, toggle: function(setting) { return this.each(function() { var el = $(this) ;(setting === undefined ? el.css('display') == 'none' : setting) ? el.show() : el.hide() }) }, prev: function(selector) { return $(this.pluck('previousElementSibling')).filter(selector || '*') }, next: function(selector) { return $(this.pluck('nextElementSibling')).filter(selector || '*') }, html: function(html) { return 0 in arguments ? this.each(function(idx) { var originHtml = this.innerHTML $(this).empty().append(funcArg(this, html, idx, originHtml)) }) : (0 in this ? this[0].innerHTML : null) }, text: function(text) { return 0 in arguments ? this.each(function(idx) { var newText = funcArg(this, text, idx, this.textContent) this.textContent = newText == null ? '' : '' + newText }) : (0 in this ? this.pluck('textContent').join('') : null) }, attr: function(name, value) { var result return (typeof name === 'string' && !(1 in arguments)) ? (0 in this && this[0].nodeType == 1 && (result = this[0].getAttribute(name)) != null ? result : undefined) : this.each(function(idx) { if (this.nodeType !== 1) return if (isObject(name)) for (key in name) setAttribute(this, key, name[key]) else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name))) }) }, removeAttr: function(name) { return this.each(function() { this.nodeType === 1 && name.split(' ').forEach(function(attribute) { setAttribute(this, attribute) }, this) }) }, prop: function(name, value) { name = propMap[name] || name return (typeof name === 'string' && !(1 in arguments)) ? (this[0] && this[0][name]) : this.each(function(idx) { if (isObject(name)) for (key in name) this[propMap[key] || key] = name[key] else this[name] = funcArg(this, value, idx, this[name]) }) }, removeProp: function(name) { name = propMap[name] || name return this.each(function() { delete this[name] }) }, data: function(name, value) { var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase() var data = (1 in arguments) ? this.attr(attrName, value) : this.attr(attrName) return data !== null ? deserializeValue(data) : undefined }, val: function(value) { if (0 in arguments) { if (value == null) value = '' return this.each(function(idx) { this.value = funcArg(this, value, idx, this.value) }) } else { return this[0] && (this[0].multiple ? $(this[0]).find('option').filter(function() { return this.selected }).pluck('value') : this[0].value) } }, offset: function(coordinates) { if (coordinates) { return this.each(function(index) { var $this = $(this); var coords = funcArg(this, coordinates, index, $this.offset()); var parentOffset = $this.offsetParent().offset(); var props = { top: coords.top - parentOffset.top, left: coords.left - parentOffset.left } if ($this.css('position') == 'static') props.position = 'relative' $this.css(props) }) } if (!this.length) return null if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0])) { return { top: 0, left: 0 } } var obj = this[0].getBoundingClientRect() return { left: obj.left + window.pageXOffset, top: obj.top + window.pageYOffset, width: Math.round(obj.width), height: Math.round(obj.height) } }, css: function(property, value) { if (arguments.length < 2) { var element = this[0] if (typeof property === 'string') { if (!element) return return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property) } else if (isArray(property)) { if (!element) return var props = {} var computedStyle = getComputedStyle(element, '') $.each(property, function(_, prop) { props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop)) }) return props } } var css = '' if (type(property) == 'string') { if (!value && value !== 0) { this.each(function() { this.style.removeProperty(dasherize(property)) }) } else { css = dasherize(property) + ':' + maybeAddPx(property, value) } } else { for (key in property) { if (!property[key] && property[key] !== 0) { this.each(function() { this.style.removeProperty(dasherize(key)) }) } else { css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';' } } } return this.each(function() { this.style.cssText += ';' + css }) }, index: function(element) { return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0]) }, hasClass: function(name) { if (!name) return false return emptyArray.some.call(this, function(el) { return this.test(className(el)) }, classRE(name)) }, addClass: function(name) { if (!name) return this return this.each(function(idx) { if (!('className' in this)) return classList = [] var cls = className(this); var newName = funcArg(this, name, idx, cls) newName.split(/\s+/g).forEach(function(klass) { if (!$(this).hasClass(klass)) classList.push(klass) }, this) classList.length && className(this, cls + (cls ? ' ' : '') + classList.join(' ')) }) }, removeClass: function(name) { return this.each(function(idx) { if (!('className' in this)) return if (name === undefined) return className(this, '') classList = className(this) funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass) { classList = classList.replace(classRE(klass), ' ') }) className(this, classList.trim()) }) }, toggleClass: function(name, when) { if (!name) return this return this.each(function(idx) { var $this = $(this); var names = funcArg(this, name, idx, className(this)) names.split(/\s+/g).forEach(function(klass) { (when === undefined ? !$this.hasClass(klass) : when) ? $this.addClass(klass) : $this.removeClass(klass) }) }) }, scrollTop: function(value) { if (!this.length) return var hasScrollTop = 'scrollTop' in this[0] if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset return this.each(hasScrollTop ? function() { this.scrollTop = value } : function() { this.scrollTo(this.scrollX, value) }) }, scrollLeft: function(value) { if (!this.length) return var hasScrollLeft = 'scrollLeft' in this[0] if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset return this.each(hasScrollLeft ? function() { this.scrollLeft = value } : function() { this.scrollTo(value, this.scrollY) }) }, position: function() { if (!this.length) return var elem = this[0]; // Get *real* offsetParent var offsetParent = this.offsetParent(); // Get correct offsets var offset = this.offset(); var parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat($(elem).css('margin-top')) || 0 offset.left -= parseFloat($(elem).css('margin-left')) || 0 // Add offsetParent borders parentOffset.top += parseFloat($(offsetParent[0]).css('border-top-width')) || 0 parentOffset.left += parseFloat($(offsetParent[0]).css('border-left-width')) || 0 // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } }, offsetParent: function() { return this.map(function() { var parent = this.offsetParent || document.body while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css('position') == 'static') { parent = parent.offsetParent } return parent }) } } // for now $.fn.detach = $.fn.remove // Generate the `width` and `height` functions ;['width', 'height'].forEach(function(dimension) { var dimensionProperty = dimension.replace(/./, function(m) { return m[0].toUpperCase() }) $.fn[dimension] = function(value) { var offset; var el = this[0] if (value === undefined) { return isWindow(el) ? el['inner' + dimensionProperty] : isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : (offset = this.offset()) && offset[dimension] } else { return this.each(function(idx) { el = $(this) el.css(dimension, funcArg(this, value, idx, el[dimension]())) }) } } }) function traverseNode(node, fun) { fun(node) for (var i = 0, len = node.childNodes.length; i < len; i++) { traverseNode(node.childNodes[i], fun) } } // Generate the `after`, `prepend`, `before`, `append`, // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods. adjacencyOperators.forEach(function(operator, operatorIndex) { var inside = operatorIndex % 2 //= > prepend, append $.fn[operator] = function() { // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings var argType; var nodes = $.map(arguments, function(arg) { var arr = [] argType = type(arg) if (argType == 'array') { arg.forEach(function(el) { if (el.nodeType !== undefined) return arr.push(el) else if ($.zepto.isZ(el)) return arr = arr.concat(el.get()) arr = arr.concat(zepto.fragment(el)) }) return arr } return argType == 'object' || arg == null ? arg : zepto.fragment(arg) }); var parent; var copyByClone = this.length > 1 if (nodes.length < 1) return this return this.each(function(_, target) { parent = inside ? target : target.parentNode // convert all methods to a "before" operation target = operatorIndex == 0 ? target.nextSibling : operatorIndex == 1 ? target.firstChild : operatorIndex == 2 ? target : null var parentInDocument = $.contains(document.documentElement, parent) nodes.forEach(function(node) { if (copyByClone) node = node.cloneNode(true) else if (!parent) return $(node).remove() parent.insertBefore(node, target) if (parentInDocument) { traverseNode(node, function(el) { if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' && (!el.type || el.type === 'text/javascript') && !el.src) { var target = el.ownerDocument ? el.ownerDocument.defaultView : window target.eval.call(target, el.innerHTML) } }) } }) }) } // after => insertAfter // prepend => prependTo // before => insertBefore // append => appendTo $.fn[inside ? operator + 'To' : 'insert' + (operatorIndex ? 'Before' : 'After')] = function(html) { $(html)[operator](this) return this } }) zepto.Z.prototype = Z.prototype = $.fn // Export internal API functions in the `$.zepto` namespace zepto.uniq = uniq zepto.deserializeValue = deserializeValue $.zepto = zepto export default $
the_stack
module RongIMLib { export class PublicServiceMap { publicServiceList: Array<any>; constructor() { this.publicServiceList = []; } get(publicServiceType: ConversationType, publicServiceId: string): PublicServiceProfile { for (let i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } } add(publicServiceProfile: PublicServiceProfile) { var isAdd: boolean = true, me = this; for (let i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } } replace(publicServiceProfile: PublicServiceProfile) { var me = this; for (let i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } } remove(conversationType: ConversationType, publicServiceId: string) { var me = this; for (let i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } } } /** * 会话工具类。 */ export class ConversationMap { conversationList: Array<Conversation>; constructor() { this.conversationList = []; } get(conversavtionType: number, targetId: string): Conversation { for (let i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; } add(conversation: Conversation): void { var isAdd: boolean = true; for (let i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } } /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ replace(conversation: Conversation) { for (let i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } } remove(conversation: Conversation) { for (let i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } } } export class CheckParam { static _instance: CheckParam; static getInstance(): CheckParam { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; } logger(code: any, funcName: string, msg: string) { RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); } check(f: any, position: string, d?: any, c?: any) { if (RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); // throw new Error("The parameter is incorrect or was not yet instantiated RongIMClient -> position:" + position); } } getType(str: string): string { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); } checkCookieDisable(): boolean { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; } } export class LimitableMap { map: any; keys: any; limit: number; constructor(limit?: number) { this.map = {}; this.keys = []; this.limit = limit || 10; } set(key: string, value: any): void { this.map[key] = value; } get(key: string): number { return this.map[key] || 0; } remove(key: string): void { delete this.map[key]; } } export class MemoryCache { cache: any = {}; set(key: string, value: any) { this.cache[key] = value; } get(key: string): any { return this.cache[key]; } remove(key: string) { delete this.cache[key]; } } export class RongAjax { options: any; xmlhttp: any; constructor(options: any) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } send(callback: any): void { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "&timestamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); } } function Prosumer() { let data: Array<any> = [], isConsuming: boolean = false; this.produce = (res: any) => { data.push(res); }; this.consume = (callback: any, finished: any) => { if (isConsuming) { return; } isConsuming = true; let next = () => { let res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } export class RongUtil { static noop() { } static isEmpty(obj: any): boolean { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, () => { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; } static isLengthLimit(str: string, maxLen: number, minLen?: number) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; } static MD5(str: string, key?: string, raw?: string) { return md5(str, key, raw); } static isObject(obj: any) { return Object.prototype.toString.call(obj) == '[object Object]'; } static isArray(array: any) { return Object.prototype.toString.call(array) == '[object Array]'; } static isString(array: any) { return Object.prototype.toString.call(array) == '[object String]'; } static isFunction(fun: any) { return Object.prototype.toString.call(fun) == '[object Function]'; }; static isUndefined(str: any) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; static isEqual(a: any, b: any) { return a === b; }; static indexOf(arrs: any, item: any) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; } static stringFormat(tmpl: string, vals: any) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; } static tplEngine(temp: any, data: any, regexp?: any) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret: any[] = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object: any) { return temp.replace(regexp || (/{([^}]+)}/g), function (match: any, name: any) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; static forEach(obj: any, callback: Function) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } } static extend(source: any, target: any, callback?: any, force?: boolean) { RongUtil.forEach(source, function (val: any, key: string) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; } static createXHR() { var item: { [key: string]: any } = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = (typeof XMLHttpRequest == 'function'); if(window.navigator) { var browserAgent = window.navigator.userAgent.toLowerCase(); var isIPhone = browserAgent.indexOf('iphone') > -1; if (isIPhone && isXHR == false) { isXHR = (typeof XMLHttpRequest == 'object') } } var isXDR = (typeof XDomainRequest == 'function'); var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject' return item[key](); } static request(opts: any) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; xhr.open(method, url, true); xhr.send(null); return xhr; } static formatProtoclPath(config: any) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; static getUrlHost(url: any): any { let index = RongUtil.indexOf(url, '/'); return url.substring(0, index); } static supportLocalStorage(): boolean { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; } /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ static rename(origin: any, newNames: any): any { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val: any, key: string, obj: any) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item: any) { RongUtil.forEach(item, function (val: any, key: string, obj: any) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; } static some(arrs: any, callback: Function): boolean { var has: boolean = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; } static keys(obj: any): string[] { var props: string[] = []; for (var key in obj) { props.push(key); } return props; } static isNumber(num: number): boolean { return Object.prototype.toString.call(num) == '[object Number]'; } static getTimestamp(): number { var date = new Date(); return date.getTime() } static isSupportRequestHeaders(): boolean { var userAgent = navigator.userAgent; var isIE = (<any>window).ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; } static Prosumer: any = Prosumer; static hasValidWsUrl(urls: any): boolean { try { urls = JSON.parse(urls); } catch(e) { return false; } let validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; } static getValidWsUrlList(urls: Array<string>) { const invalidWsUrls = RongIMClient.invalidWsUrls; let validUrlList: any = []; RongUtil.forEach(urls, function (url:string) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; } } /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ export class RongObserver { watchers: { [key: string]: any } = {}; genUId(key: string): string { var time = new Date().getTime(); return [key, time].join('_'); } watch(params: any): void { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k: any) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); } notify(params: any): void { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } } remove(): void { } } export class Observer { observers: any[] = []; add(observer: any, force?: any) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } } emit(data: any) { RongUtil.forEach(this.observers, function (observer: any) { observer(data); }); } clear() { this.observers = []; } checkIndexOutBound(index: number, bound: number) { let isOutBound = (index > -1 && index < bound); return isOutBound; } removeAt(index: number) { let isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } } remove(observer: any) { let me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } let observerList = me.observers; for (let i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } } } export class Timer { timeout: number = 0; timers: any = []; constructor(config: any) { this.timeout = config.timeout; } resume(callback: Function) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); } pause() { RongUtil.forEach(this.timers, function (timer: number) { clearTimeout(timer); }); } } export class IndexTools { items: any = []; index: number = 0; onwheel: Function = function () { }; constructor(config: any) { this.items = config.items; this.onwheel = config.onwheel; } get() { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; } add() { this.index += 1; } } export class InnerUtil { static getUId(token: string) { return md5(token).slice(8, 16) } } }
the_stack
import React, { Suspense } from 'react'; import SharedElement from './SharedElement'; import { RouterDataContext } from './RouterData'; import { AnimationConfig, AnimationConfigFactory, AnimationConfigSet, AnimationKeyframeEffectConfig, ReducedAnimationConfigSet, SwipeDirection } from './common/types'; import {Vec2} from './common/types'; import AnimationProvider from './AnimationProvider'; export interface ScreenProps { out?: boolean; in?: boolean; component: React.JSXElementConstructor<any>; fallback?: React.ReactNode; path?: string | RegExp; defaultParams?: {[key:string]: any}; name?: string; config?: { animation?: ReducedAnimationConfigSet | AnimationConfig | AnimationKeyframeEffectConfig | AnimationConfigFactory; keepAlive?: boolean; swipeDirection?: SwipeDirection; swipeAreaWidth?: number; minFlingVelocity?: number; hysteresis?: number; disableDiscovery?: boolean; } } interface ScreenState { fallback?: React.ReactNode; shouldKeepAlive: boolean; } export namespace Stack { export class Screen extends React.Component<ScreenProps, ScreenState> { private sharedElementScene: SharedElement.Scene = new SharedElement.Scene(this.props.component.name || this.props.path?.toString() || 'not-found'); private name = this.props.name || this.props.component.name || this.props.path?.toString().slice(1).replace('/', '-') || 'not-found'; private ref: HTMLElement | null = null; private contextParams = this.context.routesData.get(this.props.path)?.params; private onRef = this.setRef.bind(this); private animation: AnimationConfigSet | (() => AnimationConfigSet) = { in: { type: 'none', duration: 0 }, out: { type: 'none', duration: 0 } }; private scrollPos: Vec2 = {x: 0, y: 0}; static contextType = RouterDataContext; context!: React.ContextType<typeof RouterDataContext>; static defaultProps = { route: { params: {} } }; state: ScreenState = { shouldKeepAlive: false, } componentDidMount() { this.sharedElementScene.keepAlive = this.props.config?.keepAlive || false; if (this.props.fallback && React.isValidElement(this.props.fallback)) { this.setState({ fallback: React.cloneElement<any>(this.props.fallback, { navigation: this.context.navigation, route: { params: { ...this.props.defaultParams, ...this.contextParams } } }) }); } else { this.setState({fallback: this.props.fallback}); } if (this.props.config?.animation) { if (typeof this.props.config.animation === "function") { this.animation = this.animationFactory.bind(this); } else { if ('in' in this.props.config.animation) { this.animation = { in: this.props.config.animation.in, out: this.props.config.animation.out || this.props.config.animation.in }; } else { this.animation = { in: this.props.config.animation, out: this.props.config.animation }; } } } else { this.animation = this.context.animation; } this.contextParams = this.context.routesData.get(this.props.path)?.params; this.forceUpdate(); } shouldComponentUpdate(nextProps: ScreenProps) { if (this.context.routesData.get(this.props.path)?.params !== this.contextParams) { this.contextParams = this.context.routesData.get(this.props.path)?.params; return true; } if (nextProps.out && !nextProps.in) { return true; } if (nextProps.in && !nextProps.out) { return true; } if (nextProps.in !== this.props.in || nextProps.out !== this.props.out) { return true; } return false; } componentDidUpdate(prevProps: ScreenProps) { if (prevProps.config?.keepAlive !== this.props.config?.keepAlive) { this.sharedElementScene.keepAlive = this.props.config?.keepAlive || false; } if (prevProps.fallback !== this.props.fallback) { if (this.props.fallback && React.isValidElement(this.props.fallback)) { this.setState({ fallback: React.cloneElement<any>(this.props.fallback, { navigation: this.context.navigation, route: { params: { ...this.props.defaultParams, ...this.contextParams } } }) }); } else { this.setState({fallback: this.props.fallback}); } } } animationFactory(): AnimationConfigSet { if (typeof this.props.config?.animation === "function") { let currentPath = this.context.navigation.history.next; if (!this.context.backNavigating) { currentPath = this.context.navigation.history.previous; } let nextPath = this.context.navigation.history.current; const animationConfig = this.props.config.animation( currentPath || '', nextPath, this.context.gestureNavigating ); if ('in' in animationConfig) { return { in: animationConfig.in, out: animationConfig.out || animationConfig.in }; } else { return { in: animationConfig, out: animationConfig }; } } return this.context.animation; } onExit = () => { if (this.context.backNavigating) this.setState({shouldKeepAlive: false}); else { if (this.ref) { this.setTransforms(this.ref); // replace stale transforms window.addEventListener('page-animation-end', () => { // scale transforms were stale after animation if (this.ref) this.setTransforms(this.ref); }, {once: true}); } this.setState({shouldKeepAlive: true}); } if (this.ref) { this.scrollPos = { x: this.ref.scrollLeft, y: this.ref.scrollTop } this.sharedElementScene.scrollPos = this.scrollPos; } if (this.context.ghostLayer) { this.context.ghostLayer.currentScene = this.sharedElementScene; } } onEnter = (shouldScroll: boolean) => { if (shouldScroll) this.ref?.scrollTo(this.scrollPos.x, this.scrollPos.y); if (this.context.ghostLayer) { this.context.ghostLayer.nextScene = this.sharedElementScene; } } private setTransforms(ref: HTMLElement) { const clientRect = ref.getBoundingClientRect(); const xRatio = (clientRect.width / window.innerWidth).toFixed(2); // transform scale factor due to zoom animation const yRatio = (clientRect.height / window.innerHeight).toFixed(2); this.sharedElementScene.x = clientRect.x; this.sharedElementScene.y = clientRect.y; this.sharedElementScene.xRatio = parseFloat(xRatio); this.sharedElementScene.yRatio = parseFloat(yRatio); } private setRef(ref: HTMLElement | null) { if (this.ref !== ref) { this.ref = ref; if (ref) { this.setTransforms(ref); } } } render() { return ( <AnimationProvider onExit={this.onExit} onEnter={this.onEnter} in={this.props.in || false} out={this.props.out || false} name={this.name} animation={this.animation} backNavigating={this.context.backNavigating} keepAlive={this.state.shouldKeepAlive ? this.props.config?.keepAlive || false : false} > <div ref={this.onRef} className="screen" style={{ height: '100%', width: '100%', display: 'flex', flexDirection: 'column', pointerEvents: 'inherit', overflowX: 'auto', overflowY: 'auto' }} > <SharedElement.SceneContext.Provider value={this.sharedElementScene}> <Suspense fallback={this.state.fallback}> <this.props.component route={{ params: { ...this.props.defaultParams, ...this.contextParams } }} navigation={this.context.navigation} /> </Suspense> </SharedElement.SceneContext.Provider> </div> </AnimationProvider> ); } } }
the_stack
import { Node, NodeTypes, Statement, BodyStatement, RuleStatement, IncludeStatement, MixinStatement, IfStatement, EachStatement, FunctionStatement, ReturnStatement, TextNode, createTextNode, createEmptyNode, createSelectorNode, Atrule, MediaStatement, createRuleStatement, Keyframes, ContentPlaceholder, DeclarationStatement } from '../parse/ast' import { deepClone, isEmptyNode, isKeyframesName } from '../parse/util'; import { processExpression, callFunctionWithArgs } from './processExpression'; import { ErrorCodes, createCompilerError } from '../parse/errors'; import { loadPlugin } from './loadPlugin'; import { isBrowser } from '../global'; import { NodeTransform, TransformContext } from '@/type'; export const transformStatement: NodeTransform = (node, context) => { return processStatement(node as Statement, context) } const loadPluginProxy = !isBrowser() ? loadPlugin : (node, context) => createEmptyNode() export function processStatement( node: Statement, context: TransformContext, ) { function dispatchStatement(node: Statement | ContentPlaceholder, context: TransformContext) { switch (node.type) { case NodeTypes.DECLARATION: return transformDeclaration(node, context); case NodeTypes.MIXIN: case NodeTypes.FUNCTION: return transformMixnOrFunction(node, context); case NodeTypes.RETURN: return transformReturn(node, context); case NodeTypes.CONTENT: return transformContent(context); case NodeTypes.INCLUDE: return transformInclude(node, context); case NodeTypes.RULE: case NodeTypes.BODY: return transformChildOrBody(node, context); case NodeTypes.EXTEND: return node; case NodeTypes.IFSTATEMENT: return transformIf(node, context); case NodeTypes.EACHSTATEMENT: return transformEach(node, context); case NodeTypes.Atrule: return transformAtRule(node, context); case NodeTypes.PLUGIN: return loadPluginProxy(node, context); case NodeTypes.ERROR: throw new Error(processExpression(node.value, context).value) default: throw createCompilerError(ErrorCodes.UNKNOWN_STATEMENT_TYPE, (node as Node).loc, (node as Node).type) } } function transformDeclaration(node: DeclarationStatement, context: TransformContext) { if (node.left.type === NodeTypes.VARIABLE) { context.env.def(node.left.value, processExpression(node.right, context).value) return createEmptyNode(); } if (node.left.type === NodeTypes.VAR_KEY) { node.left = processExpression(node.left, context); } node.right = processExpression(node.right, context); return node; } function transformMedia(node: MediaStatement, context: TransformContext): MediaStatement { // Todos: skip parseExpression for now, mainly to test media bubble node.prelude.children = node.prelude.children.map(mediaQuery => { mediaQuery.children = mediaQuery.children.map(node => { if (node.type === NodeTypes.MediaFeature) { node.value = processExpression(node.value, context) } return node; }) return mediaQuery; }) node.block = dispatchStatement(node.block, context) return node } function transformKeyframes(node: Keyframes, context: TransformContext): Keyframes { node.prelude.children = node.prelude.children.map((keyframesPreludeChild) => { if (keyframesPreludeChild.type === NodeTypes.VAR_KEY) { keyframesPreludeChild = processExpression(keyframesPreludeChild, context) } return keyframesPreludeChild; }) node.block = dispatchStatement(node.block, context) return node; } function transformAtRule(node: Atrule, context: TransformContext) { if (node.name === 'media') { return transformMedia(node as MediaStatement, context); } else if (isKeyframesName(node.name)) { return transformKeyframes(node as Keyframes, context) } } /** * any expressions separated with spaces or commas count as a list */ function transformEach(node: EachStatement, context: TransformContext) { let restoredContext = deepClone(node), right = processExpression(restoredContext.right, context), scope = context.env.extend(), list: string[] = []; if (right.type === NodeTypes.TEXT) { list = right.value.split(/,|\s+/).filter(val => val !== '') } let children = list.map(val => { /** * restore context with iterate multiple times */ restoredContext = deepClone(node); scope.def(restoredContext.left.value, val); return dispatchStatement(restoredContext.body, { ...context, env: scope }) }) /** * return a created an empty selector RULE whose children will be flattened in transform_nest */ return createRuleStatement( createSelectorNode(createTextNode('')), children, node.loc ); } /** * context will be restored with function */ function transformIf(node: IfStatement, context: TransformContext) { function is_true_exp(expression, context: TransformContext) { let resultExp = expression; /** * 1. if $bool { } * 2. if true { } */ if (resultExp.type === NodeTypes.VARIABLE || resultExp.type === NodeTypes.BINARY) { resultExp = processExpression(expression, context); } if (resultExp.value === "0" || resultExp.value === "false") { return false; } return true } if (is_true_exp(node.test, context)) { return dispatchStatement(node.consequent, context); } else if (node.alternate) { return dispatchStatement(node.alternate, context) } else { return createEmptyNode(); } } /** * transform @mixin/@function -> set to env -> delete @mixin ast */ function transformMixnOrFunction(node: MixinStatement | FunctionStatement, context: TransformContext) { function make_function() { /** * deep clone function statement to restore context when called multiple times */ let restoredContext: MixinStatement | FunctionStatement = deepClone(node), params = restoredContext.params, scope = context.env.extend(); function handle_params_default_value(params) { return params.map((param) => { let ret = param; if (param.type === NodeTypes.DECLARATION) { ret = { type: NodeTypes.VARIABLE, value: param.left.value } dispatchStatement(param, { ...context, env: scope }) } return ret; }) } params = handle_params_default_value(params); params.forEach((param, i) => { if (param.type === NodeTypes.VARIABLE && arguments[i]) { scope.def(param.value, arguments[i]) } }) if (node.type === NodeTypes.FUNCTION) { dispatchStatement(restoredContext.body, { ...context, env: scope }) return scope.get('@return', NodeTypes.RETURN) } else if (node.type === NodeTypes.MIXIN) { return dispatchStatement(restoredContext.body, { ...context, env: scope }); } } context.env.def(node.id.name, make_function, node.type) return createEmptyNode(); } /** * @return only be evaluated in a @function body */ function transformReturn(node: ReturnStatement, context: TransformContext) { let result: TextNode = processExpression(node.argument, context); context.env.def('@return', result.value, node.type); return createEmptyNode(); } function transformContent(context: TransformContext) { return context.env.get('@content', NodeTypes.CONTENT) } function transformInclude(node: IncludeStatement, context: TransformContext) { let func = context.env.get({ name: node.id.name, namespace: node.id.namespace }, NodeTypes.MIXIN); node.content && context.env.def('@content', dispatchStatement(node.content, context), NodeTypes.CONTENT) return callFunctionWithArgs(func, node, context) // call mixin which will use just defined @content if mixin contains } function transformChildOrBody(node: RuleStatement | BodyStatement, context: TransformContext): RuleStatement | BodyStatement { function flatten_included_body(children: Statement[]): Statement[] { let arr: Statement[] = [] children.forEach(child => { if (child.type === NodeTypes.BODY) { arr = arr.concat(flatten_included_body(child.children as Statement[])) } else { arr.push(child) } }) return arr; } let scope = context.env; /** * only extend a new child env when evaluate css child, but in program body, we do not extend */ if (node.type === NodeTypes.RULE) { scope = context.env.extend(); } node.children = (node.children as Statement[]).map(child => dispatchStatement(child, { ...context, env: scope })).filter(node => !isEmptyNode(node)); if (node.type === NodeTypes.RULE) { // have selector if (node.selector.value.type === NodeTypes.LIST) { node.selector.value = processExpression(node.selector.value, { ...context, env: scope }) } } /** * * @include include_function_body * @if which contain bodyStatement */ node.children = flatten_included_body(node.children as Statement[]); return node; } return dispatchStatement(node, context) }
the_stack
import * as React from "react"; import * as ReactDom from "react-dom"; import { Version, DisplayMode } from "@microsoft/sp-core-library"; import { IPropertyPaneConfiguration, PropertyPaneTextField, PropertyPaneDropdown, IPropertyPaneDropdownOption, IPropertyPaneField, IPropertyPaneGroup, PropertyPaneLabel, } from "@microsoft/sp-property-pane"; import { BaseClientSideWebPart, IPropertyPaneAccessor, PropertyPaneToggle } from "@microsoft/sp-webpart-base"; import { IFieldInfo, FieldTypes } from "@pnp/sp/fields/types"; import * as strings from "RestaurantMenuWebPartStrings"; import { RestaurantMenu } from "./components/RestaurantMenu"; import { IRestaurantMenuProps } from "./components/IRestaurantMenuProps"; import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy, } from "@pnp/spfx-property-controls/lib/PropertyFieldListPicker"; import { PropertyFieldSitePicker, IPropertyFieldSite, } from "@pnp/spfx-property-controls/lib/PropertyFieldSitePicker"; import { PropertyFieldMessage} from '@pnp/spfx-property-controls/lib/PropertyFieldMessage'; import { sp } from "@pnp/sp"; import { ThemeProvider, ThemeChangedEventArgs, IReadonlyTheme, } from "@microsoft/sp-component-base"; import { loadTheme, IDropdownOption, MessageBarType } from "office-ui-fabric-react"; import { useGetListFields } from "../../hooks/useSPList"; import { filter, Dictionary } from "lodash"; const teamsDefaultTheme = require('../../Common/TeamsDefaultTheme.json'); const teamsDarkTheme = require('../../Common/TeamsDarkTheme.json'); const teamsContrastTheme = require('../../Common/TeamsContrastTheme.json'); export interface IRestaurantMenuWebPartProps { title: string; site: IPropertyFieldSite[]; listId: string; dateFieldName: string; dietFieldName: string; soupFieldName: string; meatFieldName: string; fishFieldName: string; veganFieldName: string; dessertFieldName: string; displayMode: DisplayMode; updateProperty: (value: string) => void; propertyPanel: IPropertyPaneAccessor; showBox: boolean; } export default class RestaurantMenuWebPart extends BaseClientSideWebPart< IRestaurantMenuWebPartProps > { private fieldDateOptions: IPropertyPaneDropdownOption[] = []; private fieldSoupOptions: IPropertyPaneDropdownOption[] = []; private fieldMeatOptions: IPropertyPaneDropdownOption[] = []; private fieldFishOptions: IPropertyPaneDropdownOption[] = []; private fieldDietOptions: IPropertyPaneDropdownOption[] = []; private fieldVeganOptions: IPropertyPaneDropdownOption[] = []; private fieldDessertOptions: IPropertyPaneDropdownOption[] = []; private _themeProvider: ThemeProvider; private _themeVariant: IReadonlyTheme | undefined; private _listProperty: IPropertyPaneField<any> = {} as IPropertyPaneField< any >; private listFieldProperties: IPropertyPaneField<any>[] = []; protected async onInit(): Promise<void> { sp.setup({ spfxContext: this.context, }); this._themeProvider = this.context.serviceScope.consume( ThemeProvider.serviceKey ); // If it exists, get the theme variant this._themeVariant = this._themeProvider.tryGetTheme(); // Register a handler to be notified if the theme variant changes this._themeProvider.themeChangedEvent.add( this, this._handleThemeChangedEvent ); if (this.context.sdks.microsoftTeams) { // in teams ? const context = this.context.sdks.microsoftTeams!.context; console.log("theme", this._themeVariant); this._applyTheme(context.theme || "default"); this.context.sdks.microsoftTeams.teamsJs.registerOnThemeChangeHandler( this._applyTheme ); } return Promise.resolve(); } /** * Update the current theme variant reference and re-render. * * @param args The new theme */ private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void { this._themeVariant = args.theme; console.log("theme", this._themeVariant); this.render(); } // Apply btheme id in Teams private _applyTheme = (theme: string): void => { this.context.domElement.setAttribute("data-theme", theme); document.body.setAttribute("data-theme", theme); if (theme == "dark") { loadTheme({ palette: teamsDarkTheme, }); } if (theme == "default") { loadTheme({ palette: teamsDefaultTheme, }); } if (theme == "contrast") { loadTheme({ palette: teamsContrastTheme, }); } } protected get disableReactivePropertyChanges() { return true; } public render(): void { const element: React.ReactElement<IRestaurantMenuProps> = React.createElement( RestaurantMenu, { title: this.properties.title, site: this.properties.site, listId: this.properties.listId, propertyPanel: this.context.propertyPane, dateFieldName: this.properties.dateFieldName, dietFieldName: this.properties.dietFieldName, soupFieldName: this.properties.soupFieldName, meatFieldName: this.properties.meatFieldName, fishFieldName: this.properties.fishFieldName, veganFieldName: this.properties.veganFieldName, dessertFieldName: this.properties.dessertFieldName, showBox: this.properties.showBox, themeVariant: this._themeVariant, displayMode: this.displayMode, updateProperty: (value: string) => { this.properties.title = value; }, } ); ReactDom.render(element, this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse("1.0"); } protected async onPropertyPaneFieldChanged( propertyPath: string, oldValue: any, newValue: any ): Promise<void> { let _fieldsOptions: IPropertyPaneDropdownOption[] = []; if (propertyPath === "site" && newValue) { this.properties.listId = undefined; this.properties.fishFieldName= ''; this.properties.dateFieldName= ''; this.properties.dessertFieldName= ''; this.properties.soupFieldName= ''; this.properties.meatFieldName= ''; this.properties.veganFieldName= ''; this.context.propertyPane.refresh; } if (propertyPath === "listId" && newValue) { this.properties.listId = newValue; super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); this.properties.fishFieldName= ''; this.properties.dateFieldName= ''; this.properties.dessertFieldName= ''; this.properties.soupFieldName= ''; this.properties.meatFieldName= ''; this.properties.veganFieldName= ''; this.fieldSoupOptions = []; this.fieldDessertOptions = []; this.fieldDietOptions = []; this.fieldFishOptions = []; this.fieldMeatOptions = []; this.fieldVeganOptions = []; this.fieldDateOptions = []; this.context.propertyPane.refresh(); const fields: IFieldInfo[] = await useGetListFields( this.properties.site[0].url, newValue ); for (const field of fields) { if (field.FieldTypeKind == FieldTypes.DateTime) { this.fieldDateOptions.push({ key: field.InternalName, text: field.Title, }); } if ( field.FieldTypeKind == FieldTypes.Text || field.FieldTypeKind == FieldTypes.Note ) { _fieldsOptions.push({ key: field.InternalName, text: field.Title }); } } this.fieldDessertOptions = _fieldsOptions; this.fieldDietOptions = _fieldsOptions; this.fieldFishOptions = _fieldsOptions; this.fieldMeatOptions = _fieldsOptions; this.fieldSoupOptions = _fieldsOptions; this.fieldVeganOptions = _fieldsOptions; this.context.propertyPane.refresh(); } } protected async onPropertyPaneConfigurationStart(): Promise<void> { if (this.properties.listId) { if (this.fieldDateOptions.length > 0) { return; } const fields: IFieldInfo[] = await useGetListFields( this.properties.site[0].url, this.properties.listId ); const _fieldsOptions: IPropertyPaneDropdownOption[] = []; for (const field of fields) { if (field.FieldTypeKind == FieldTypes.DateTime) { this.fieldDateOptions.push({ key: field.InternalName, text: field.Title, }); } if ( field.FieldTypeKind == FieldTypes.Text || field.FieldTypeKind == FieldTypes.Note ) { _fieldsOptions.push({ key: field.InternalName, text: field.Title }); } } this.fieldDessertOptions = _fieldsOptions; this.fieldDietOptions = _fieldsOptions; this.fieldFishOptions = _fieldsOptions; this.fieldMeatOptions = _fieldsOptions; this.fieldSoupOptions = _fieldsOptions; this.fieldVeganOptions = _fieldsOptions; this.context.propertyPane.refresh(); } } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { if (this.properties.site.length > 0) { this._listProperty = PropertyFieldListPicker("listId", { context: this.context, label: "Select List", onPropertyChange: this.onPropertyPaneFieldChanged, properties: this.properties, baseTemplate: 100, deferredValidationTime: 300, key: "listfilter", selectedList: this.properties.listId, multiSelect: false, webAbsoluteUrl: this.properties.site[0].url, orderBy: PropertyFieldListPickerOrderBy.Title, }); } else { this._listProperty = {} as IPropertyPaneField<any>; } // new List if (this.properties.listId) { this.listFieldProperties = []; this.listFieldProperties = [ PropertyPaneLabel('',{ text: "" }), PropertyPaneLabel('',{ text: "Field Mapping" }), PropertyPaneLabel('',{ text: "" }), PropertyPaneDropdown("dateFieldName", { options: [{ key: "N/A", text: "Not available" },...this.fieldDateOptions], label: strings.DateFieldPropertyLabel, selectedKey: this.properties.dateFieldName || "N/A", }), PropertyFieldMessage("", { key: "MessageKey", text:strings.DateInformationMessage, messageType: MessageBarType.info, isVisible: this.properties.dateFieldName === "N/A" , }), PropertyPaneDropdown("soupFieldName", { options: [{ key: "N/A", text: "Not available" }, ...this.fieldSoupOptions], label: strings.SoupFieldPropertyLabel, selectedKey: this.properties.soupFieldName || "N/A", }), PropertyPaneDropdown("meatFieldName", { options:[{ key: "N/A", text: "Not available" },...this.fieldMeatOptions], label: strings.MeatFieldPropertyLabel, selectedKey: this.properties.meatFieldName || "N/A", }), PropertyPaneDropdown("fishFieldName", { options: [ { key: "N/A", text: "Not available" }, ...this.fieldFishOptions] , label: strings.FishFieldPropertyLabel, selectedKey: this.properties.fishFieldName || "N/A", }), PropertyPaneDropdown("dietFieldName", { options: [ { key: "N/A", text: "Not available" }, ...this.fieldDietOptions] , label: strings.DietFieldPropertyLabel, selectedKey: this.properties.dietFieldName || "N/A", }), PropertyPaneDropdown("veganFieldName", { options: [ { key: "N/A", text: "Not available" }, ...this.fieldVeganOptions, ], label: strings.VeganFieldPropertyLabel, selectedKey: this.properties.veganFieldName || "N/A", }), PropertyPaneDropdown("dessertFieldName", { options: [{ key: "N/A", text: "Not available" },...this.fieldDessertOptions], label: strings.DessertFieldPropertyLabel, selectedKey: this.properties.dessertFieldName || "N/A", }), ]; } else { this.listFieldProperties = []; } // configuration panel default options const configuration: IPropertyPaneConfiguration = { pages: [ { header: { description: strings.PropertyPaneDescription, }, displayGroupsAsAccordion: true, groups: [ { groupName: strings.BasicGroupName, isCollapsed: true, groupFields: [ PropertyPaneTextField("title", { label: strings.DescriptionFieldLabel, }), PropertyPaneToggle("showBox", { label: "Show background box ?", checked: this.properties.showBox }), ], }, ], }, ], }; // get groups first page const { groups } = configuration.pages[0]; // SourceDataGroup const sourceDataGroup: IPropertyPaneGroup = { groupName: "Source of data", isCollapsed: true, groupFields: [ PropertyFieldSitePicker("site", { label: "Select site", initialSites: this.properties.site || [], context: this.context, deferredValidationTime: 500, multiSelect: false, onPropertyChange: this.onPropertyPaneFieldChanged, properties: this.properties, key: "sitesFieldId", }), this._listProperty, ...this.listFieldProperties, ], }; // Add aditional groups groups.push(sourceDataGroup); // return configuration return configuration; } }
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { IconLoaderService } from '../../../index'; import { AmexioFilterTreeComponent } from './filter.tree.component'; import { AmexioTreeViewComponent } from './tree.component'; import { AmexioContextMenuComponent } from '../../base/base.contextmenu.component'; import { CommonDataService } from '../../services/data/common.data.service'; import { HttpClient, HttpHandler } from '@angular/common/http'; import { Renderer2, Renderer, TemplateRef } from '@angular/core'; import { CommonIconComponent } from './../../base/components/common.icon.component'; import { equal } from 'assert'; describe('amexio-tree-filter-view', () => { let comp: AmexioFilterTreeComponent; let fixture: ComponentFixture<AmexioFilterTreeComponent>; let comp1: AmexioTreeViewComponent; let fixture1: ComponentFixture<AmexioTreeViewComponent>; let checkD: any; let data: any; beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule], declarations: [CommonIconComponent, AmexioTreeViewComponent, AmexioFilterTreeComponent, AmexioContextMenuComponent], providers: [IconLoaderService, CommonDataService, Renderer2, HttpClient, HttpHandler], }); fixture = TestBed.createComponent(AmexioFilterTreeComponent); comp = fixture.componentInstance; fixture.detectChanges(); fixture1 = TestBed.createComponent(AmexioTreeViewComponent); comp1 = fixture1.componentInstance; fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']); let renderer = Renderer2; // let fixture1 = TestBed.createComponent(WrapperComponent); // let wrapperComponent = fixture.componentInstance; // let component = fixture1.componentInstance.myCustomComponent; // comp.httpurl = "sample.json"; // comp.httpmethod = "get"; checkD = [{ "text": "Web App", "expand": true, "children": [ { "text": "app", "expand": true, "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; }); it('fliter tree check variables ', () => { comp.isDataFound = true; expect(comp.isDataFound).toEqual(true); // comp.onClickSearch = false; // expect(comp.onClickSearch).toEqual(false); comp.mask = true; expect(comp.mask).toEqual(true); comp.isexpandAll = false; expect(comp.isexpandAll).toEqual(false); }); it('ngoninit() first else', () => { comp.ngOnInit(); expect(comp.parentTmp).toBeUndefined(); comp.ngAfterViewInit() expect(comp.parentTmp).toBeUndefined(); comp.parentTmp = null; comp.ngOnInit(); expect(comp.parentTmp).toBeNull(); comp.ngAfterViewInit() expect(comp.parentTmp).toBeNull(); }); // it('ngoninit() else', () => { // comp.ngOnInit(); // expect(comp.parentTmp).toBeUndefined(); // comp.ngAfterViewInit() // expect(comp.parentTmp).toBeUndefined(); // comp.parentTmp = null; // comp.ngOnInit(); // expect(comp.parentTmp).toBeNull(); // comp.ngAfterViewInit() // expect(comp.parentTmp).toBeNull(); // }); // it('ngAfterViewInit() first else', () => { // // comp.parentRef = null; // comp.ngAfterViewInit() // expect(comp.parentTmp).toBeNull(); // }); it('ngoninit() first if', () => { // comp.parentTmp = new insertte let fixture1 = TestBed.createComponent(AmexioFilterTreeComponent); let wrapperComponent = fixture1.componentInstance; // get a reference to the actual component we want let component = fixture1.componentInstance.templates; comp.parentTmp = component; comp.ngOnInit(); expect(comp.parentTmp).not.toBeNull(); comp.templates = { treeNodeTemplate: comp.parentTmp }; }); it('ngoninit() second elseif', () => { let fixture1 = TestBed.createComponent(AmexioFilterTreeComponent); let wrapperComponent = fixture1.componentInstance; // get a reference to the actual component we want let component = fixture1.componentInstance.templates; comp.templates = component; comp.templates = { treeNodeTemplate: comp.parentTmp }; comp.ngOnInit(); expect(comp.templates).not.toBeNull(); comp.parentTmp = comp.templates.treeNodeTemplate; }); it('ngoninit() second elseif else', () => { comp.templates = null; comp.ngOnInit(); expect(comp.templates).toBeNull(); }); it('ngoninit() inverse if', () => { comp.templates = [{ "text": "Web App", "children": [ { "text": "app", "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; comp.ngOnInit(); comp.parentTmp = null; expect(comp.parentTmp).toBeNull(); expect(comp.templates).not.toEqual(null); }); it('ngAfterViewInit() second elseif else', () => { comp.templates = null; comp.ngAfterViewInit() expect(comp.templates).toBeNull(); }); it('ngAfterViewInit() first if', () => { // comp.parentTmp = new insertte let fixture1 = TestBed.createComponent(AmexioFilterTreeComponent); let wrapperComponent = fixture1.componentInstance; // get a reference to the actual component we want let component = fixture1.componentInstance.templates; comp.parentRef = component; comp.ngAfterViewInit() // if (this.parentTmp != null) { expect(comp.parentTmp).not.toBeNull(); comp.templates = { treeNodeTemplate: comp.parentTmp }; }); it('ngAfterViewInit() first if inverse', () => { comp.ngAfterViewInit(); comp.parentTmp = null; expect(comp.parentTmp).toBeNull(); }); it('ngAfterViewInit() second elseif', () => { let fixture1 = TestBed.createComponent(AmexioFilterTreeComponent); let wrapperComponent = fixture1.componentInstance; // get a reference to the actual component we want let component = fixture1.componentInstance.templates; comp.templates = component; comp.templates = { treeNodeTemplate: comp.parentTmp }; comp.ngAfterViewInit() // } else if (this.templates != null) { expect(comp.templates).not.toBeNull(); comp.parentTmp = comp.templates.treeNodeTemplate; }); it('ngAfterViewInit() third else', () => { comp.ngAfterViewInit() // if (this.httpmethod && this.httpurl) { expect(comp.httpmethod).not.toBeDefined(); expect(comp.httpurl).not.toBeDefined(); }); it('ngAfterViewInit() third if', () => { comp.httpmethod = 'get'; comp.httpurl = 'asd.json' comp.ngAfterViewInit() // if (this.httpmethod && this.httpurl) { expect(comp.httpmethod).toBeDefined(); expect(comp.httpurl).toBeDefined(); comp.callService(); }); it('ngAfterViewInit() forth elseif else', () => { comp.ngAfterViewInit() // } else if (this.data) { expect(comp.data).not.toBeDefined(); }); it('updateComponent() method if call ', () => { comp.data = [{ "text": "Web App", "children": [ { "text": "app", "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; comp.updateComponent(); comp.previousValue = null; expect(comp.data).not.toBeNull(); expect(JSON.stringify(comp.previousValue)).not.toEqual(JSON.stringify(comp.data)); comp.previousValue = JSON.parse(JSON.stringify(comp.data)); comp.setData(comp.data); }); it('updateComponent() method else call ', () => { comp.updateComponent(); comp.previousValue = null; comp.data = null expect(comp.data).toBeNull(); expect(JSON.stringify(comp.previousValue)).toEqual(JSON.stringify(comp.data)); }); it('ngAfterViewInit() forth elseif ', () => { comp.data = [{ a: 'a' }] comp.ngAfterViewInit() // } else if (this.data) { expect(comp.data).toBeDefined(); comp.previousValue = JSON.parse(JSON.stringify(comp.data)); comp.setData(comp.data); }); it('fliter tree expandAll() on method call', () => { let node = { "text": "Home", "icon": "fa fa-home fa-fw", "mdaIcon": "home", "link": "/home/dashboard", "selected": true, "badge": "12" }; comp.isexpandAll = true; comp.expandAll(node); comp.destroyExpandAll = setTimeout(() => { comp.expandAllCall(checkD); }, 0); }); it('fliter tree expandAllCall() on method call', () => { let node1 = [{ "text": "Web App", "children": [ { "text": "app", "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; comp.childarraykey = 'children'; let node = [{ "text": "Web App", "expand": true, "children": [ { "text": "app", "expand": true, "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; comp.expandAllCall(node); node.forEach((childCheck: any) => { expect(childCheck.hasOwnProperty('expand')).toEqual(true); childCheck.expand = false; expect(childCheck.expand).not.toEqual(true); childCheck.expand = true; expect(childCheck.hasOwnProperty(comp.childarraykey)).toEqual(true); expect(childCheck[comp.childarraykey]).not.toEqual(null); comp.expandAllCall(childCheck[comp.childarraykey]); }); comp.expandAllCall(node1); node1.forEach((childCheck: any) => { expect(childCheck.hasOwnProperty('expand')).toBeUndefined; childCheck['expand'] = true; expect(childCheck.hasOwnProperty(comp.childarraykey)).toEqual(true); expect(childCheck[comp.childarraykey]).not.toEqual(null); comp.expandAllCall(childCheck[comp.childarraykey]); }); }); it('fliter tree expandAllCall() on method call else block', () => { let node1 = [{ "text": "Web App", "children": [ { "text": "app", "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; comp.childarraykey = 'children'; let node = [{ "text": "Web App", "expand": true, "children": [ { "text": "app", "expand": true, "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; comp.expandAllCall(node); node.forEach((childCheck: any) => { expect(childCheck.hasOwnProperty('expand')).toEqual(true); // childCheck.expand = false; expect(childCheck.expand).toEqual(true); childCheck['expand'] = true; expect(childCheck.hasOwnProperty(comp.childarraykey)).toEqual(true); expect(childCheck[comp.childarraykey]).not.toEqual(null); comp.expandAllCall(childCheck[comp.childarraykey]); }); comp.expandAllCall(node1); node1.forEach((childCheck: any) => { expect(childCheck.hasOwnProperty('expand')).toBeUndefined; childCheck['expand'] = true; expect(childCheck.hasOwnProperty(comp.childarraykey)).toEqual(true); expect(childCheck[comp.childarraykey]).not.toEqual(null); comp.expandAllCall(childCheck[comp.childarraykey]); }); }); // it('fliter tree getData()if on method call', () => { // if (this.datareader != null) { let httpResponse = [ { "text": "Home", "icon": "fa fa-home fa-fw", "mdaIcon": "home", "link": "/home/dashboard", "selected": true, "badge": "12" }, { "text": "Email", "icon": "fa fa-envelope fa-fw", "mdaIcon": "email", "link": "/home/email", "badge": "21" }, { "text": "Profile", "icon": "fa fa-user fa-fw", "mdaIcon": "account_box", "link": "/home/profile", "badge": "32" }]; let responsedata: any = httpResponse; comp.datareader = null; expect(comp.datareader).toBeNull(); responsedata = httpResponse; return responsedata; }); // it('fliter tree getData()if on method call', () => { let httpResponse = { 'data': [ { "text": "Home", "icon": "fa fa-home fa-fw", "mdaIcon": "home", "link": "/home/dashboard", "selected": true, "badge": "12" }, { "text": "Email", "icon": "fa fa-envelope fa-fw", "mdaIcon": "email", "link": "/home/email", "badge": "21" }, { "text": "Profile", "icon": "fa fa-user fa-fw", "mdaIcon": "account_box", "link": "/home/profile", "badge": "32" } ] }; comp.getData(httpResponse); let responsedata: any = httpResponse; comp.datareader = 'data'; expect(comp.datareader).not.toEqual(null); const dr = comp.datareader.split('.'); for (const ir of dr) { responsedata = responsedata[ir]; } return responsedata; }); it('fliter tree getData() else on method call', () => { let httpResponse = [ { "text": "Home", "icon": "fa fa-home fa-fw", "mdaIcon": "home", "link": "/home/dashboard", "selected": true, "badge": "12" }, { "text": "Email", "icon": "fa fa-envelope fa-fw", "mdaIcon": "email", "link": "/home/email", "badge": "21" }, { "text": "Profile", "icon": "fa fa-user fa-fw", "mdaIcon": "account_box", "link": "/home/profile", "badge": "32" }]; comp.getData(httpResponse); comp.datareader = null; expect(comp.datareader).toEqual(null); let responsedata = httpResponse; return responsedata; }); it('fliter tree setData() method call', () => { let httpResponse = [ { "text": "Home", "icon": "fa fa-home fa-fw", "mdaIcon": "home", "link": "/home/dashboard", "selected": true, "badge": "12" }, { "text": "Email", "icon": "fa fa-envelope fa-fw", "mdaIcon": "email", "link": "/home/email", "badge": "21" }, { "text": "Profile", "icon": "fa fa-user fa-fw", "mdaIcon": "account_box", "link": "/home/profile", "badge": "32" }]; comp.setData(httpResponse); const tdata = comp.getData(httpResponse); expect(tdata).toBeDefined(); comp.orgTreeData = JSON.parse(JSON.stringify(tdata)); comp.treeData = tdata; comp.mask = false; }); it('fliter Tree OnRightClickMenu() on method call', () => { comp.OnRightClickMenu(checkD); comp1.rightClick.subscribe((g: any) => { expect(comp1.rightClick).toEqual(g); }); }); it('fliter Tree onRowSelect() on method call', () => { comp.onRowSelect(checkD); comp1.nodeClick.subscribe((g: any) => { expect(comp1.nodeClick).toEqual(g); }); }); it('fliter Tree onCheckSelect() on method call', () => { comp.onCheckSelect(checkD); comp1.onTreeNodeChecked.subscribe((g: any) => { expect(comp1.onTreeNodeChecked).toEqual(g); }); }); it('fliter Tree loadContextMenu() on method call', () => { comp.loadContextMenu(checkD); comp1.nodeRightClick.subscribe((g: any) => { expect(comp1.nodeRightClick).toEqual(g); }); }); it('callService()', () => { comp.httpurl = "sample.json"; comp.httpmethod = "get"; comp.callService(); comp['treeViewFilterService'].fetchData(comp.httpurl, comp.httpmethod).subscribe((response: any) => { comp.data = response; }, () => { comp.renderServiceData(); }); }); it('filterData() second if', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.filterData(); // if (this.treeData.length === 0) { comp.treeData = []; expect(comp.treeData.length).toEqual(0) comp.isDataFound = false; }); it('filterData() first else', () => { comp.filterText = "h"; comp.triggerchar = 4; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.filterData(); // if (this.filterText.length >= this.triggerchar) { expect(comp.filterText.length).not.toBeGreaterThanOrEqual(comp.triggerchar); comp.isDataFound = true; comp.treeData = comp.orgTreeData; }); // it('filterData() first if', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.filterData(); comp.showToolTip = false; // if (this.filterText.length >= this.triggerchar) { expect(comp.filterText.length).toBeGreaterThanOrEqual(comp.triggerchar); const tData = JSON.parse(JSON.stringify(comp.orgTreeData)); const treeNodes = comp.searchTree(tData, comp.filterText); comp.treeData = treeNodes; }); it('filterData() first if inside if', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = []; comp.filterData(); comp.showToolTip = false; expect(comp.filterText.length).toBeGreaterThanOrEqual(comp.triggerchar); const tData = JSON.parse(JSON.stringify(comp.orgTreeData)); const treeNodes = comp.searchTree(tData, comp.filterText); comp.treeData = treeNodes; expect(comp.treeData.length).toEqual(0); comp.isDataFound = false; }); it('filterData() second else', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.filterData(); // if (this.treeData.length === 0) { expect(comp.treeData.length).not.toEqual(0); comp.isDataFound = true; }); it('filterData() third elseif', () => { comp.filterText = "h"; comp.triggerchar = 4; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.onClickSearch = true; comp.filterData(); expect(comp.filterText.length).not.toBeGreaterThanOrEqual(comp.triggerchar); comp.onClickSearch = true; expect(comp.onClickSearch).toEqual(true); const tData = JSON.parse(JSON.stringify(comp.orgTreeData)); const treeNodes = comp.searchTree(tData, comp.filterText); comp.treeData = treeNodes; comp.onClickSearch = false; }); it('filterData() third 0 length else ', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [{ text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }]; comp.onClickSearch = true; comp.filterData(); expect(comp.onClickSearch).toEqual(true); const tData = JSON.parse(JSON.stringify(comp.orgTreeData)); const treeNodes = comp.searchTree(tData, comp.filterText); comp.treeData = treeNodes; comp.onClickSearch = false; comp.filterData(); expect(comp.treeData.length).not.toEqual(0); comp.isDataFound = true; }); it('filterData() else if inverse ', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [{ text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }]; comp.onClickSearch = false; comp.filterData(); expect(comp.onClickSearch).toEqual(false); comp.isDataFound = true; comp.treeData = comp.orgTreeData; }); it('filterData() third 0 length if this.onClickSearch true condition', () => { comp.filterText = "h"; comp.triggerchar = 4; comp.orgTreeData = []; comp.onClickSearch = true; comp.filterData(); expect(comp.filterText.length).not.toBeGreaterThanOrEqual(comp.triggerchar); comp.onClickSearch = true; expect(comp.onClickSearch).toEqual(true); const tData = JSON.parse(JSON.stringify(comp.orgTreeData)); const treeNodes = comp.searchTree(tData, comp.filterText); comp.treeData = treeNodes; comp.onClickSearch = false; comp.filterData(); expect(comp.treeData.length).toEqual(0); comp.isDataFound = false; }); it('filterData() third elseif else', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.onClickSearch = false; comp.filterData(); comp.onClickSearch = false; expect(comp.onClickSearch).toEqual(false); }); it('filterData() third last if', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.isexpandAll = true; comp.filterData(); // if (this.isexpandAll) { expect(comp.isexpandAll).toEqual(true); comp.expandAll(comp.treeData); }); it('filterData() third last else', () => { comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.isexpandAll = false; comp.filterData(); // if (this.isexpandAll) { expect(comp.isexpandAll).not.toEqual(true); comp.generatefilterIndex(comp.treeData, 1, Math.floor(Math.random() * 1000 + 999 + 1)); }); // it('filterOption() first for if', () => { let data = { key: "Is Not Equal To", value: 2, type: "string", checkedStatus: "" }; comp.filterOptionData = [ // {key: "Is Equal To", value: "1", type: "string", checkedStatus: ""}, { key: "Is Not Equal To", value: 2, type: "string", checkedStatus: "" } ]; comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.filterOption(data); comp.onClickSearch = true; comp.filterIndex = data.value; comp.filterOptionData.forEach((opt: any) => { // if (opt.value !== data.value) { expect(opt.value).toEqual(data.value); opt.checkedStatus = ''; }); comp.filterData(); comp.showToolTip = false; }); it('filterOption() first for else', () => { let data = { key: "Is Not Equal To", value: 2, type: "string", checkedStatus: "" }; comp.filterOptionData = [ { key: "Is Equal To", value: "1", type: "string", checkedStatus: "" } // {key: "Is Not Equal To", value: 2, type: "string", checkedStatus: ""} ]; comp.filterText = "h"; comp.triggerchar = 1; comp.orgTreeData = [ { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" }, { text: "Home", icon: "fa fa-home fa-fw", mdaIcon: "home", link: "/home/dashboard", selected: true, badge: "21" } ]; comp.filterOption(data); comp.onClickSearch = true; comp.filterIndex = data.value; comp.filterOptionData.forEach((opt: any) => { // if (opt.value !== data.value) { expect(opt.value).not.toEqual(data.value); opt.checkedStatus = 'fa fa-check'; }); comp.filterData(); comp.showToolTip = false; }); it('generatefilterIndex method call', () => { let data = [ { "text": "Web App", "expand": true, "children": [ { "text": "app", "expand": true, "children": [ { "leaf": true, "text": "Application.js", } ] }, { "text": "button", "expand": true, "children": [ { "leaf": true, "text": "Button.js", } ] }] }] let index = 0; comp.childarraykey = 'children'; let parentId = 1; let rannumber = Math.floor(Math.random() * 1000 + 999 + 1); comp.generatefilterIndex(data, parentId, rannumber); data.forEach((element: any, index: any) => { element['elementId'] = '' + rannumber + '-' + parentId + (index + 1); expect(element[comp.childarraykey]).toBeDefined(); comp.generatefilterIndex(element[comp.childarraykey], element.elementId.split('-')[1], rannumber); }); }); it('fliter tree filterActualData() method node[tempchildarrayKey] call', () => { // if (this.datareader != null) { let filterData = [ { "text": "Web App", "expand": true, "children": [ { "text": "app", "expand": true, "children": [ { "leaf": true, "text": "Application.js", } ] }, { "text": "button", "expand": true, "children": [ { "leaf": true, "text": "Button.js", } ] }] }] let fi = 1; let matchingTitle = 'H'; comp.displaykey = 'text'; comp.childarraykey = 'children'; comp.filterActualData(filterData, fi, matchingTitle); let tempdisplay: string; let tempchildarrayKey: string; tempdisplay = comp.displaykey; tempchildarrayKey = comp.childarraykey; return filterData.filter(function f(node) { expect(node[tempchildarrayKey]).toBeDefined(); return (node[tempchildarrayKey] = node[tempchildarrayKey].filter(f)).length; }); }); it('fliter tree expandAllCall() on expand false method call', () => { let node1 = [{ "text": "Web App", "expand": false, "children": [ { "text": "app", "expand": false, "children": [ { "leaf": true, "text": "Application.js" } ] } ] } ]; comp.expandAllCall(node1); node1.forEach((childCheck: any) => { expect(childCheck.hasOwnProperty('expand')).toEqual(true); childCheck.expand = false; expect(childCheck.expand).not.toEqual(true); childCheck.expand = true; }); }); });
the_stack
import expect from 'expect'; import { JingleAction } from '../../src/Constants'; import { Session as GenericSession, SessionManager } from '../../src/jingle'; // tslint:disable no-identical-functions const selfID = 'zuser@example.com'; const peerID = 'peer@example.com'; // We need a Stub Session that acts more like how we'd // expect real session types to work, instead of ending // itself when trying to start/accept like the GenericSession. class StubSession extends GenericSession { constructor(opts: any) { super(opts); } public start() { this.state = 'pending'; this.send(JingleAction.SessionInitiate, { contents: [ { application: { applicationType: 'stub' }, creator: 'initiator', name: 'test', transport: { transportType: 'stub' } } ] }); } public accept() { this.state = 'active'; this.send(JingleAction.SessionAccept, { contents: [ { application: { applicationType: 'stub' }, creator: 'initiator', name: 'test', transport: { transportType: 'stub' } } ] }); } } test('Test accepting base session', done => { expect.assertions(3); const jingle = new SessionManager({ selfID }); let sentResult = false; jingle.on('send', data => { if (!sentResult) { expect(data).toEqual({ id: '123', to: peerID, type: 'result' }); sentResult = true; } else { // The GenericSession instance doesn't allow for accepting // sessions, so we'll test that we successfully terminated // the session instead. delete data.id; expect(data).toEqual({ jingle: { action: JingleAction.SessionTerminate, reason: { condition: 'unsupported-applications' }, sid: 'sid123' }, to: peerID, type: 'set' }); done(); } }); jingle.on('incoming', session => { expect(session).toBeTruthy(); session.accept(); }); jingle.process({ from: peerID, id: '123', jingle: { action: JingleAction.SessionInitiate, contents: [ { application: { applicationType: 'test' }, creator: 'initiator', name: 'test', transport: { transportType: 'test' } } ], sid: 'sid123' }, to: selfID, type: 'set' }); }); test('Test accepting stub session', done => { expect.assertions(3); const jingle = new SessionManager({ prepareSession: meta => { if (meta.applicationTypes.indexOf('stub') >= 0) { return new StubSession(meta); } }, selfID }); let sentResult = false; jingle.on('send', data => { if (!sentResult) { expect(data).toEqual({ id: '123', to: peerID, type: 'result' }); sentResult = true; } else { delete data.id; expect(data).toEqual({ jingle: { action: JingleAction.SessionAccept, contents: [ { application: { applicationType: 'stub' }, creator: 'initiator', name: 'test', transport: { transportType: 'stub' } } ], sid: 'sid123' }, to: peerID, type: 'set' }); done(); } }); jingle.on('incoming', session => { expect(session).toBeTruthy(); session.accept(); }); jingle.process({ from: peerID, id: '123', jingle: { action: JingleAction.SessionInitiate, contents: [ { application: { applicationType: 'stub' }, creator: 'initiator', name: 'test', transport: { transportType: 'stub' } } ], sid: 'sid123' }, to: selfID, type: 'set' }); }); test('Test starting base session', done => { expect.assertions(2); const jingle = new SessionManager({ selfID }); const sess = new GenericSession({ initiator: true, parent: jingle, peerID }); // Base sessions can't be started, and will terminate // on .start() jingle.on('terminated', session => { expect(session.sid).toBe(sess.sid); expect(session.state).toBe('ended'); done(); }); jingle.addSession(sess); sess.start(); }); test('Test starting stub session', done => { expect.assertions(3); const jingle = new SessionManager({ selfID }); const sess = new StubSession({ initiator: true, peerID }); jingle.on('send', data => { delete data.id; expect(data).toEqual({ jingle: { action: JingleAction.SessionInitiate, contents: [ { application: { applicationType: 'stub' }, creator: 'initiator', name: 'test', transport: { transportType: 'stub' } } ], sid: sess.sid }, to: peerID, type: 'set' }); done(); }); jingle.on('outgoing', session => { expect(session.sid).toBe(sess.sid); expect(session.state).toBe('pending'); }); jingle.addSession(sess); sess.start(); }); test('Test declining a session', done => { expect.assertions(3); const jingle = new SessionManager({ prepareSession: meta => { if (meta.applicationTypes.indexOf('stub') >= 0) { return new StubSession(meta); } }, selfID }); let sentResult = false; jingle.on('send', data => { if (!sentResult) { expect(data).toEqual({ id: '123', to: peerID, type: 'result' }); sentResult = true; } else { delete data.id; expect(data).toEqual({ jingle: { action: JingleAction.SessionTerminate, reason: { condition: 'decline' }, sid: 'sid123' }, to: peerID, type: 'set' }); done(); } }); jingle.on('incoming', session => { expect(session).toBeTruthy(); session.decline(); }); jingle.process({ from: peerID, id: '123', jingle: { action: JingleAction.SessionInitiate, contents: [ { application: { applicationType: 'stub' }, creator: 'initiator', name: 'test', transport: { transportType: 'stub' } } ], sid: 'sid123' }, to: selfID, type: 'set' }); }); test('Test cancelling a pending session', done => { expect.assertions(2); const jingle = new SessionManager({ selfID }); const sess = new StubSession({ initiator: true, peerID }); let started = false; jingle.on('send', data => { delete data.id; if (!started) { expect(data).toEqual({ jingle: { action: JingleAction.SessionInitiate, contents: [ { application: { applicationType: 'stub' }, creator: 'initiator', name: 'test', transport: { transportType: 'stub' } } ], sid: sess.sid }, to: peerID, type: 'set' }); started = true; } else { expect(data).toEqual({ jingle: { action: JingleAction.SessionTerminate, reason: { condition: 'cancel' }, sid: sess.sid }, to: peerID, type: 'set' }); done(); } }); jingle.addSession(sess); sess.start(); sess.cancel(); }); test('Test ending a session (successful session)', done => { expect.assertions(3); const jingle = new SessionManager({ selfID }); const sess = new StubSession({ initiator: true, peerID }); jingle.addSession(sess); sess.state = 'active'; jingle.on('send', data => { delete data.id; expect(data).toEqual({ jingle: { action: JingleAction.SessionTerminate, reason: { condition: 'success' }, sid: sess.sid }, to: peerID, type: 'set' }); done(); }); jingle.on('terminated', session => { expect(session.sid).toBe(sess.sid); expect(session.state).toBe('ended'); }); sess.end(); }); test('Test ending a session (non-successful session)', done => { expect.assertions(3); const jingle = new SessionManager({ selfID }); const sess = new StubSession({ initiator: true, peerID }); jingle.addSession(sess); sess.state = 'active'; jingle.on('send', data => { delete data.id; expect(data).toEqual({ jingle: { action: JingleAction.SessionTerminate, reason: { condition: 'failed-application', text: 'not working' }, sid: sess.sid }, to: peerID, type: 'set' }); done(); }); jingle.on('terminated', session => { expect(session.sid).toBe(sess.sid); expect(session.state).toBe('ended'); }); sess.end({ condition: 'failed-application', text: 'not working' }); }); test('Test pending actions', () => { const jingle = new SessionManager({ selfID }); const sess = new StubSession({ initiator: true, peerID, sid: 'sid123' }); jingle.addSession(sess); sess.state = 'active'; expect(sess.pendingAction).toBeFalsy(); sess.send(JingleAction.TransportReplace, {}); expect(sess.pendingAction).toBe(JingleAction.TransportReplace); jingle.process({ from: peerID, jingle: { sid: 'sid123' }, type: 'result' }); expect(sess.pendingAction).toBeFalsy(); sess.send(JingleAction.TransportReplace, {}); expect(sess.pendingAction).toBe(JingleAction.TransportReplace); jingle.process({ from: peerID, jingle: { sid: 'sid123' }, type: 'error' }); expect(sess.pendingAction).toBeFalsy(); }); test('Test connectionState', () => { const jingle = new SessionManager({ selfID }); const sess = new StubSession({ initiator: true, parent: jingle, peerID, sid: 'sid123' }); jingle.on('connectionState', (session, connectionState) => { expect(session.sid).toBe(sess.sid); expect(connectionState).toBeTruthy(); }); expect(sess.connectionState).toBe('starting'); // Should only trigger a change event once sess.connectionState = 'connecting'; sess.connectionState = 'connecting'; sess.connectionState = 'connecting'; sess.connectionState = 'connecting'; sess.connectionState = 'connecting'; expect(sess.connectionState).toBe('connecting'); sess.connectionState = 'connected'; expect(sess.connectionState).toBe('connected'); sess.connectionState = 'disconnected'; expect(sess.connectionState).toBe('disconnected'); sess.connectionState = 'interrupted'; expect(sess.connectionState).toBe('interrupted'); });
the_stack
declare var Vue: any; declare var vuedraggable: any; module schema_editor { type ResponseCallback = (any) => void; interface MessageWithCallback { message: any; on_response: ResponseCallback; } interface MessageBlock { id: string; messages: any[]; } interface ResponseBlock { id: string; responses: any[]; } type UpdateCallback = (MessageBlock) => void; export class SchemaEditor { // We put updates in a queue that we can send private update_timeout_id: number = null; private update_callback: UpdateCallback; private update_delay_ms: number; private message_response_callbacks_by_id: any = {}; private app: any = null; private get_schema: () => any = null; /** * Constructor * @param schema_js - JSON representation of the schema to be edited * @param update_callback - a callback function to invoke to notify the backend of updates due to user actions. * A function of the form `fn(messages)` where `messages` is a message block that takes the form * {id: <message_block_uuid>, messages_json: object[]}. * Reply to the tool via invoking the `notify_responses` method, proving a responses block that has * the layout {id: <message_block_uuid>, responses_json: object[]} * @param update_delay_ms - the delay in milliseconds to wait after user actions before sending an update * via `update_callback` */ constructor(schema_js: any, update_callback: UpdateCallback, update_delay_ms: number) { let self = this; if (update_delay_ms === undefined) { update_delay_ms = 1500; } this.update_callback = update_callback; this.update_delay_ms = update_delay_ms; const RootComponent = { el: '#schema_editor', data() { return { schema: schema_js } }, created: function() { let component = this; self.get_schema = function(): any { return component.schema; } } }; self.app = Vue.createApp(RootComponent); // Register draggable component so we can use it in the templates self.app.component('draggable', vuedraggable); // Update mixin self.app.mixin({ methods: { queue_send_schema_update: function() { self.enqueue_update_schema(self.update_delay_ms); }, send_create_colour_scheme: function(colour_scheme) { self.send_create_colour_scheme(colour_scheme); }, send_delete_colour_scheme: function(colour_scheme) { self.send_delete_colour_scheme(colour_scheme); }, send_create_group: function(group) { self.send_create_group(group); }, send_delete_group: function(group) { self.send_delete_group(group); }, send_create_label_class: function(label_class, containing_group) { self.send_create_label_class(label_class, containing_group); }, send_delete_label_class: function(label_class, containing_group) { self.send_delete_label_class(label_class, containing_group); }, } }); /* Colour schemes component */ self.app.component('colour-schemes', { template: '#colour_schemes_template', props: { schema: Object, }, data: function() { return { 'show_new_form': false, 'new_form_data': { 'name': '', 'human_name': '' } }; }, methods: { on_new: function() { this.show_new_form = true; }, on_cancel_new: function() { this.show_new_form = false; }, on_create_new: function() { if (this.new_form_data.name !== '') { var scheme = { id: labelling_tool.ObjectIDTable.uuidv4(), name: this.new_form_data.name, human_name: this.new_form_data.human_name }; this.send_create_colour_scheme(scheme); this.schema.colour_schemes.push(scheme); this.new_form_data.name = ''; this.new_form_data.human_name = ''; } this.show_new_form = false; }, open_delete_modal: function(col_scheme) { let component = this; SchemaEditor.confirm_deletion('colour scheme', col_scheme.human_name, function() { for (var i = 0; i < component.schema.colour_schemes.length; i++) { if (component.schema.colour_schemes[i] === col_scheme) { component.schema.colour_schemes.splice(i, 1); component.send_delete_colour_scheme(col_scheme); break; } } }); }, on_reorder: function() { this.queue_send_schema_update(); } }, created: function() { Vue.watch(this.schema.colour_schemes, (x, prev_x) => { this.queue_send_schema_update(); }); }, computed: { new_name_state: function(): string { if (this.new_form_data.name === '') { return 'empty'; } else if (!SchemaEditor.check_identifier(this.new_form_data.name)) { return 'invalid' } else { for (let col_scheme of this.schema.colour_schemes) { if (this.new_form_data.name === col_scheme.name) { return 'in_use'; } } return 'ok' } }, } }); /* All label classes component */ self.app.component('all-label-classes', { template: '#all_label_classes_template', props: { schema: Object, }, data: function() { return { 'show_new_form': false, 'new_form_data': { 'group_name': '', } }; }, methods: { on_new: function() { this.show_new_form = true; }, on_cancel_new: function() { this.show_new_form = false; }, on_create_new: function() { if (this.new_form_data.name !== '') { var new_group = { id: labelling_tool.ObjectIDTable.uuidv4(), group_name: this.new_form_data.group_name, group_classes: [], }; this.send_create_group(new_group); this.schema.label_class_groups.push(new_group); this.new_form_data.group_name = ''; } this.show_new_form = false; }, }, created: function() { Vue.watch(this.schema.label_class_groups, (x, prev_x) => { this.queue_send_schema_update(); }); } }); /* Label class group template new_lcls_form_data is the form data for creating a new label class */ self.app.component('label-class-group', { template: '#label_class_group_template', props: { group: Object, schema: Object }, data: function() { return { 'show_new_form': false, 'new_lcls_form_data': { 'name': '', 'human_name': '' } }; }, methods: { on_new: function() { this.show_new_form = true; }, on_cancel_new: function() { this.show_new_form = false; }, on_create_new: function() { if (this.new_lcls_form_data.name !== '') { var colours = {}; for (let scheme of this.schema.colour_schemes) { colours[scheme.name] = [128, 128, 128]; } colours['default'] = [128, 128, 128]; var lcls = { id: labelling_tool.ObjectIDTable.uuidv4(), name: this.new_lcls_form_data.name, human_name: this.new_lcls_form_data.human_name, colours: colours }; this.send_create_label_class(lcls, this.group); this.group.group_classes.push(lcls); this.new_lcls_form_data.name = ''; this.new_lcls_form_data.human_name = ''; } this.show_new_form = false; }, open_delete_group_modal: function() { let component = this; let group = this.group; SchemaEditor.confirm_deletion('group', group.human_name, function() { if (group.group_classes.length === 0) { for (var i = 0; i < component.schema.label_class_groups.length; i++) { if (component.schema.label_class_groups[i] === group) { component.schema.label_class_groups.splice(i, 1); component.send_delete_group(group); break; } } } }); }, open_delete_lcls_modal: function(label_class) { let component = this; SchemaEditor.confirm_deletion('label class', label_class.human_name, function() { for (var i = 0; i < component.group.group_classes.length; i++) { if (component.group.group_classes[i] === label_class) { component.group.group_classes.splice(i, 1); component.send_delete_label_class(label_class, component.group); break; } } }); } }, created: function() { Vue.watch(this.group, (x, prev_x) => { this.queue_send_schema_update(); }); }, computed: { new_lcls_name_state: function(): string { if (this.new_lcls_form_data.name === '') { return 'empty'; } else if (!SchemaEditor.check_identifier(this.new_lcls_form_data.name)) { return 'invalid' } else { for (let group of this.schema.label_class_groups) { for (let lcls of group.group_classes) { if (this.new_lcls_form_data.name === lcls.name) { return 'in_use'; } } } return 'ok' } }, can_delete: function(): boolean { return this.group.group_classes.length === 0; }, } }); /* Colour editor text entry */ self.app.component('colour-editor', { template: '#colour_editor_template', props: { colour_table: Object, scheme_name: String, }, data: function() { return { _text_value: '', _colour_value: '' } }, emits: ['update:modelValue'], methods: { on_text_input(e) { if (SchemaEditor.check_colour(e.target.value)) { this.update(e.target.value); } }, on_colour_input(e) { this.update(e.target.value); }, update(colour) { var rgb = SchemaEditor.hex_to_rgb(colour); this.colour_table[this.scheme_name] = rgb; this._colour_value = colour; this._text_value = colour; this.queue_send_schema_update(); } }, computed: { html_colour: function() { if (this.colour_table.hasOwnProperty(this.scheme_name)) { return SchemaEditor.rgb_to_hex(this.colour_table[this.scheme_name]) as string; } else { return '#808080'; } }, is_text_valid: function() { return SchemaEditor.check_colour(this._text_value); }, tracked_scheme_name: function() { this._text_value = this.html_colour; this._colour_value = this.html_colour; return this.scheme_name; }, text_value: function() { // We wrap the `_text_value` data attribute in this computed value so that we can access // the `tracked_scheme_name` computed value, that will update the underlying `_text_value` // and `_colour_value` attributes when the scheme name changes. Otherwise, re-ordering // the colour schemes will not cause the colour swatches to swap over. let name = this.tracked_scheme_name; return this._text_value; }, colour_value: function() { // We wrap the `_colour_value` data attribute in this computed value so that we can access // the `tracked_scheme_name` computed value, that will update the underlying `_text_value` // and `_colour_value` attributes when the scheme name changes. Otherwise, re-ordering // the colour schemes will not cause the colour swatches to swap over. let name = this.tracked_scheme_name; return this._colour_value; } }, }); /* Mount the app */ const vm = self.app.mount('#schema_editor'); } /** * Notify the tool of responses to messages sent out via the update_callback passed to the constructor * @param response_block responses in the form of an object: * {id: <message_block_uuid>, responses: <array_of_json_objects>} * where id is the message block ID from the message block that is being responded to, and * responses contains a response for each message from the message block */ public notify_responses(response_block: ResponseBlock) { // Get the callbacks and then remove let callbacks = this.message_response_callbacks_by_id[response_block.id]; delete this.message_response_callbacks_by_id[response_block.id]; let responses = response_block.responses; for (var i = 0; i < responses.length; i++) { let cb: ResponseCallback = null; if (callbacks !== undefined) { if (i < callbacks.length) { cb = callbacks[i]; } } if (cb !== undefined && cb !== null) { cb(responses[i]); } } } // private send_messages(messages_and_callbacks: MessageWithCallback[]) { // let self = this; // // let messages: any[] = []; // for (let msg_cb of messages_and_callbacks) { // console.log('Sending ' + msg_cb.message.method); // messages.push(msg_cb.message); // } // // let post_data = { // messages: JSON.stringify(messages) // }; // // $.ajax({ // type: 'POST', // url: self.update_url, // data: post_data, // success: function (reply: any) { // let responses = reply.responses; // for (var i = 0; i < responses.length; i++) { // let msg_cb = messages_and_callbacks[i]; // if (msg_cb.on_response !== undefined && msg_cb.on_response !== null) { // msg_cb.on_response(responses[i]); // } // } // }, // dataType: 'json' // }); // } /** * Send an update to the backend in the form of a message block that consists of * a message block ID and an array of messages * @param messages_and_callbacks - array of objects with layout: * {message: <message_as_json>, on_response: <>callback function that takes a single parameter>} * @private */ private send_messages(messages_and_callbacks: MessageWithCallback[]) { let messages: any[] = []; let callbacks: ResponseCallback[] = []; for (let msg_cb of messages_and_callbacks) { console.log('Sending ' + msg_cb.message.method); messages.push(msg_cb.message); callbacks.push(msg_cb.on_response); } let message_block: MessageBlock = { id: labelling_tool.ObjectIDTable.uuidv4(), messages: messages }; this.message_response_callbacks_by_id[message_block.id] = callbacks; this.update_callback(message_block); } /** * Queue a schema update to execute after a provided delay * * @param milliseconds - delay after which the task is to be executed */ enqueue_update_schema(milliseconds: number) { let self = this; this.dequeue_update_schema(); this.update_timeout_id = setTimeout(function() { self.send_update_schema_message(); self.update_timeout_id = null; }, milliseconds); } /** * Dequeue any queued schema update */ dequeue_update_schema() { if (this.update_timeout_id !== null) { clearTimeout(this.update_timeout_id); this.update_timeout_id = null; } } /** * Determine if a schema update is queued */ is_update_schema_queued(): boolean { return this.update_timeout_id !== null; } /** * Send a schema update message immediately */ send_update_schema_message() { this.send_messages([this.create_update_schema_message()]); } /** * Create a schema update message */ private create_update_schema_message(): MessageWithCallback { let self = this; let schema = self.get_schema(); return { message: {method: 'update_schema', params: {schema: schema}}, on_response: function (msg) { if (msg.status === 'success') { console.log('Schema update successful'); let colour_scheme_id_mapping = msg.colour_scheme_id_mapping; let group_id_mapping = msg.group_id_mapping; let label_class_id_mapping = msg.label_class_id_mapping; if (colour_scheme_id_mapping !== undefined) { for (let scheme of schema.colour_schemes) { if (colour_scheme_id_mapping[scheme.id] !== undefined) { console.log('Remapping colour scheme ID ' + scheme.id + ' to ' + colour_scheme_id_mapping[scheme.id]); scheme.id = colour_scheme_id_mapping[scheme.id]; } } } for (let group of schema.label_class_groups) { if (group_id_mapping !== undefined) { if (group_id_mapping[group.id] !== undefined) { console.log('Remapping group ID ' + group.id + ' to ' + group_id_mapping[group.id]); group.id = group_id_mapping[group.id]; } } if (label_class_id_mapping !== undefined) { for (let lcls of group.group_classes) { if (label_class_id_mapping[lcls.id] !== undefined) { console.log('Remapping label class ID ' + lcls.id + ' to ' + label_class_id_mapping[lcls.id]); lcls.id = label_class_id_mapping[lcls.id]; } } } } } else { SchemaEditor.error_from_server(msg.status); } } }; } private send_queued_update_followed_by(msg_cb: MessageWithCallback) { let messages: MessageWithCallback[] = []; if (this.is_update_schema_queued()) { let msg = this.create_update_schema_message(); messages.push(msg); this.dequeue_update_schema(); } messages.push(msg_cb); this.send_messages(messages); } private send_create_colour_scheme(colour_scheme) { this.send_queued_update_followed_by( {message: {method: 'create_colour_scheme', params: {colour_scheme: colour_scheme}}, on_response: function(msg) { if (msg.status === 'success') { if (msg.new_colour_scheme_id !== undefined) { console.log('Remapping colour scheme id ' + colour_scheme.id + ' to ' + msg.new_colour_scheme_id); colour_scheme.id = msg.new_colour_scheme_id; } } else { SchemaEditor.error_from_server(msg.status); } }}); } send_delete_colour_scheme(colour_scheme) { this.send_queued_update_followed_by( {message: {method: 'delete_colour_scheme', params:{colour_scheme: colour_scheme}}, on_response: function(msg) { if (msg.status !== 'success') { SchemaEditor.error_from_server(msg.status); } }}); } send_create_group(group) { this.send_queued_update_followed_by( {message: {method: 'create_group', params:{group: group}}, on_response: function(msg) { if (msg.status === 'success') { if (msg.new_group_id !== undefined) { console.log('Remapping group id ' + group.id + ' to ' + msg.new_group_id); group.id = msg.new_group_id; } } else { SchemaEditor.error_from_server(msg.status); } }}); } send_delete_group(group) { this.send_queued_update_followed_by( {message: {method: 'delete_group', params:{group: group}}, on_response: function(msg) { if (msg.status !== 'success') { SchemaEditor.error_from_server(msg.status); } }}); } send_create_label_class(label_class, containing_group) { this.send_queued_update_followed_by( {message: {method: 'create_label_class', params:{label_class: label_class, containing_group: containing_group}}, on_response: function(msg) { if (msg.status === 'success') { if (msg.new_label_class_id !== undefined) { console.log('Remapping label class id ' + label_class.id + ' to ' + msg.new_label_class_id); label_class.id = msg.new_label_class_id; } } else { SchemaEditor.error_from_server(msg.status); } }}); } send_delete_label_class(label_class, containing_group) { this.send_queued_update_followed_by( {message: {method: 'delete_label_class', params: {label_class: label_class, containing_group: containing_group}}, on_response: function (msg) { if (msg.status !== 'success') { SchemaEditor.error_from_server(msg.status); } }}); } private static confirm_deletion(entity_type: string, entity_name: string, on_delete: () => void) { let modal = $('#delete_modal'); modal.find('.delete_target_type').text(entity_type); modal.find('#delete_target_name').text(entity_name); let confirm_button = modal.find('#delete_confirm_button'); confirm_button.on('click', function() { on_delete(); modal.modal('hide'); }); modal.modal(); } private static error_from_server(error_code: string) { let modal = $('#error_modal'); modal.find('#error_modal_code').text(error_code); let confirm_button = modal.find('#error_reload_button'); confirm_button.on('click', function() { window.location.reload(); modal.modal('hide'); }); modal.modal(); } private static colour_regex = /#[A-Fa-f0-9]{6}/; private static identifier_regex = /[A-Za-z_]\w*/; private static matches(pattern: RegExp, x: string): boolean { var match = pattern.exec(x); if (match !== null) { return match.toString() === x; } return false; } private static check_colour(col: string): boolean { return SchemaEditor.matches(SchemaEditor.colour_regex, col); } private static check_identifier(identifier: string): boolean { return SchemaEditor.matches(SchemaEditor.identifier_regex, identifier); } private static rgb_to_hex(col: number[]): string { return "#" + ((1 << 24) + (col[0] << 16) + (col[1] << 8) + col[2]).toString(16).slice(1); } private static hex_to_rgb(hex: string): number[] { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16) ] : null; } } }
the_stack
import * as doctrine from 'doctrine'; import * as ts from './ts-ast'; const {parseType, parseParamType} = require('doctrine/lib/typed.js'); /** * Convert a Closure type expression string to its equivalent TypeScript AST * node. * * Note that function and method parameters should instead use * `closureParamToTypeScript`. */ export function closureTypeToTypeScript( closureType: string|null|undefined, templateTypes: string[] = []): ts.Type { if (!closureType) { return ts.anyType; } let ast; try { ast = parseType(closureType); } catch { return ts.anyType; } return convert(ast, templateTypes); } /** * Convert a Closure function or method parameter type expression string to its * equivalent TypeScript AST node. * * This differs from `closureTypeToTypeScript` in that it always returns a * `ParamType`, and can parse the optional (`foo=`) and rest (`...foo`) * syntaxes, which only apply when parsing an expression in the context of a * parameter. */ export function closureParamToTypeScript( name: string, closureType: string|null|undefined, templateTypes: string[] = [], ): ts.ParamType { if (!closureType) { return new ts.ParamType({ name, type: ts.anyType, optional: false, rest: false, }); } let ast; try { ast = parseParamType(closureType); } catch { return new ts.ParamType({ name, type: ts.anyType, // It's important we try to get optional right even if we can't parse // the annotation, because non-optional arguments can't follow optional // ones. optional: closureType.endsWith('='), rest: false, }); } return convertParam(name, ast, templateTypes); } /** * Convert a doctrine function or method parameter AST node to its equivalent * TypeScript parameter AST node. */ function convertParam( name: string, node: doctrine.Type, templateTypes: string[]): ts.ParamType { switch (node.type) { case 'OptionalType': return new ts.ParamType({ name, type: convert(node.expression, templateTypes), optional: true, rest: false, }); case 'RestType': return new ts.ParamType({ name, // The Closure type annotation for a rest parameter looks like // `...foo`, where `foo` is implicitly an array. The TypeScript // equivalent is explicitly an array, so we wrap it in one here. type: new ts.ArrayType( node.expression !== undefined ? convert(node.expression, templateTypes) : ts.anyType), optional: false, rest: true, }); default: return new ts.ParamType({ name, type: convert(node, templateTypes), optional: false, rest: false, }); } } /** * Convert a doctrine AST node to its equivalent TypeScript AST node. */ function convert(node: doctrine.Type, templateTypes: string[]): ts.Type { let nullable; if (isNullable(node)) { // ?foo nullable = true; node = node.expression; } else if (isNonNullable(node)) { // !foo nullable = false; node = node.expression; } else if (isName(node) && templateTypes.includes(node.name)) { // A template type "T" looks naively like a regular name type to doctrine // (e.g. a class called "T"), which would be nullable by default. However, // template types are not nullable by default. nullable = false; } else { nullable = nullableByDefault(node); } let t: ts.Type; if (isParameterizedArray(node)) { // Array<foo> t = convertArray(node, templateTypes); } else if (isParameterizedObject(node)) { // Object<foo, bar> t = convertIndexableObject(node, templateTypes); } else if (isBarePromise(node)) { // Promise // In Closure, `Promise` is ok, but in TypeScript this is invalid and must // be explicitly parameterized as `Promise<any>`. t = new ts.ParameterizedType('Promise', [ts.anyType]); } else if (isParameterizedType(node)) { // foo<T> t = convertParameterizedType(node, templateTypes); } else if (isUnion(node)) { // foo|bar t = convertUnion(node, templateTypes); } else if (isFunction(node)) { // function(foo): bar t = convertFunction(node, templateTypes); } else if (isBareArray(node)) { // Array t = new ts.ArrayType(ts.anyType); } else if (isRecordType(node)) { // {foo:bar} t = convertRecord(node, templateTypes); } else if (isAllLiteral(node)) { // * t = ts.anyType; } else if (isNullableLiteral(node)) { // ? t = ts.anyType; } else if (isNullLiteral(node)) { // null t = ts.nullType; } else if (isUndefinedLiteral(node)) { // undefined t = ts.undefinedType; } else if (isVoidLiteral(node)) { // void t = new ts.NameType('void'); } else if (isName(node)) { // string, Object, MyClass, etc. t = new ts.NameType(renameMap.get(node.name) || node.name); } else { console.error('Unknown syntax.'); return ts.anyType; } if (nullable) { t = new ts.UnionType([t, ts.nullType]); } return t; } /** * Special cases where a named type in Closure maps to something different in * TypeScript. */ const renameMap = new Map<string, string>([ // Closure's `Object` type excludes primitives, so it is closest to // TypeScript's `object`. (Technically this should be `object|Symbol`, but we // will concede that technicality.) ['Object', 'object'], // The tagged template literal function argument. ['ITemplateArray', 'TemplateStringsArray'], ]); /* * As above but only applicable when parameterized (`Foo<T>`) */ const parameterizedRenameMap = new Map<string, string>([ ['HTMLCollection', 'HTMLCollectionOf'], ['NodeList', 'NodeListOf'], ]); /** * Return whether the given AST node is an expression that is nullable by * default in the Closure type system. */ function nullableByDefault(node: doctrine.Type): boolean { if (isName(node)) { switch (node.name) { case 'string': case 'number': case 'boolean': case 'void': return false; } return true; } return isParameterizedArray(node); } function convertArray( node: doctrine.type.TypeApplication, templateTypes: string[]): ts.Type { const applications = node.applications; return new ts.ArrayType( applications.length === 1 ? convert(applications[0], templateTypes) : ts.anyType); } function convertIndexableObject( node: doctrine.type.TypeApplication, templateTypes: string[]): ts.IndexableObjectType|ts.NameType { if (node.applications.length !== 2) { console.error('Parameterized Object must have two parameters.'); return ts.anyType; } return new ts.IndexableObjectType( convert(node.applications[0], templateTypes), convert(node.applications[1], templateTypes)); } function convertParameterizedType( node: doctrine.type.TypeApplication, templateTypes: string[]): ts.ParameterizedType|ts.NameType { if (!isName(node.expression)) { console.error('Could not find name of parameterized type'); return ts.anyType; } const types = node.applications.map( (application) => convert(application, templateTypes)); const name = renameMap.get(node.expression.name) || parameterizedRenameMap.get(node.expression.name) || node.expression.name; return new ts.ParameterizedType(name, types); } function convertUnion( node: doctrine.type.UnionType, templateTypes: string[]): ts.Type { return new ts.UnionType( node.elements.map((element) => convert(element, templateTypes))); } function convertFunction( node: doctrine.type.FunctionType, templateTypes: string[]): ts.FunctionType|ts.ConstructorType { const params = node.params.map( (param, idx) => convertParam( // TypeScript wants named parameters, but we don't have names. 'p' + idx, param, templateTypes)); if (node.new) { return new ts.ConstructorType( params, // It doesn't make sense for a constructor to return something other // than a named type. Also, in this context the name type is not // nullable by default, so it's simpler to just directly convert here. isName(node.this) ? new ts.NameType(node.this.name) : ts.anyType); } else { return new ts.FunctionType( params, // Cast because type is wrong: `FunctionType.result` is not an array. node.result ? convert(node.result as {} as doctrine.Type, templateTypes) : ts.anyType); } } function convertRecord(node: doctrine.type.RecordType, templateTypes: string[]): ts.RecordType|ts.NameType { const fields = []; for (const field of node.fields) { if (field.type !== 'FieldType') { return ts.anyType; } const fieldType = field.value ? convert(field.value, templateTypes) : ts.anyType; // In Closure you can't declare a record field optional, instead you // declare `foo: bar|undefined`. In TypeScript we can represent this as // `foo?: bar`. This also matches the semantics better, since Closure would // allow the field to be omitted when it is `|undefined`, but TypeScript // would require it to be explicitly set to `undefined`. let optional = false; if (fieldType.kind === 'union') { fieldType.members = fieldType.members.filter((member) => { if (member.kind === 'name' && member.name === 'undefined') { optional = true; return false; } return true; }); // No need for a union if we collapsed it to one member. fieldType.simplify(); } fields.push(new ts.ParamType({name: field.key, type: fieldType, optional})); } return new ts.RecordType(fields); } function isParameterizedArray(node: doctrine.Type): node is doctrine.type.TypeApplication { return node.type === 'TypeApplication' && node.expression.type === 'NameExpression' && node.expression.name === 'Array'; } function isParameterizedType(node: doctrine.Type): node is doctrine.type.TypeApplication { return node.type === 'TypeApplication'; } function isBareArray(node: doctrine.Type): node is doctrine.type.NameExpression { return node.type === 'NameExpression' && node.name === 'Array'; } function isBarePromise(node: doctrine.Type): node is doctrine.type.NameExpression { return node.type === 'NameExpression' && node.name === 'Promise'; } /** * Matches `Object<foo, bar>` but not `Object` (which is a NameExpression). */ function isParameterizedObject(node: doctrine.Type): node is doctrine.type.TypeApplication { return node.type === 'TypeApplication' && node.expression.type === 'NameExpression' && node.expression.name === 'Object'; } function isUnion(node: doctrine.Type): node is doctrine.type.UnionType { return node.type === 'UnionType'; } function isFunction(node: doctrine.Type): node is doctrine.type.FunctionType { return node.type === 'FunctionType'; } function isRecordType(node: doctrine.Type): node is doctrine.type.RecordType { return node.type === 'RecordType'; } function isNullable(node: doctrine.Type): node is doctrine.type.NullableType { return node.type === 'NullableType'; } function isNonNullable(node: doctrine.Type): node is doctrine.type.NonNullableType { return node.type === 'NonNullableType'; } function isAllLiteral(node: doctrine.Type): node is doctrine.type.AllLiteral { return node.type === 'AllLiteral'; } function isNullLiteral(node: doctrine.Type): node is doctrine.type.NullLiteral { return node.type === 'NullLiteral'; } function isNullableLiteral(node: doctrine.Type): node is doctrine.type.NullableLiteral { return node.type === 'NullableLiteral'; } function isUndefinedLiteral(node: doctrine.Type): node is doctrine.type.UndefinedLiteral { return node.type === 'UndefinedLiteral'; } function isVoidLiteral(node: doctrine.Type): node is doctrine.type.VoidLiteral { return node.type === 'VoidLiteral'; } function isName(node: doctrine.Type): node is doctrine.type.NameExpression { return node.type === 'NameExpression'; }
the_stack
import {Inferred} from 'typings/Inferred' import {TestInput} from 'typings/TestInput' import * as p from './mocks/octokit/payloads' /** * Events to Test */ export const testEvents: string[] = [ 'issue_comment_created', 'issue_comment_edited', 'pull_request_opened', 'pull_request_reopened', 'pull_request_synchronize', 'push_merge', 'push', 'schedule' ] export function changedFilesInput( event = 'pull', files: string[] = p.normalFileArray, formats: string[] = ['json', ',', ' ', '_<br />&nbsp;&nbsp;_'] ): TestInput[] { return formats.map(format => { if (format === 'json') return { inputs: [format, files, JSON.stringify(files)], events: event } as TestInput return { inputs: [format, files, files.join(format)], events: event } as TestInput }) } /** * FilesHelper Test inputs */ export const getFormatExtInputs: TestInput[] = [ {inputs: ['json', 'json', '.json'], events: 'push'}, {inputs: ['csv', ',', '.csv'], events: 'push'}, {inputs: ['txt', ' ', '.txt'], events: 'push'}, {inputs: ['txt_hard', '_<br />&nbsp;&nbsp;_', '.txt'], events: 'push'} ] /** * GithubHelper Test inputs */ export const initClientTestInputs: TestInput[] = [ { inputs: [ 'calls the Github client constructor with a token', '12345abcde', '12345abcde' ], events: 'all' }, { inputs: ['calls the Github client constructor without a token', '', ''], events: 'all' } ] export const getChangedPRFilesTestInputs: TestInput[] = [ { inputs: [ 'gets changed files for a pull request', {owner: 'trilom', repo: 'file-changes-action', pullNumber: 83}, p.OctokitPaginatePrResponse ], events: 'all' }, { inputs: [ 'throws an error with no pull request', {owner: 'trilom', repo: 'file-changes-action', pullNumber: NaN}, { error: '404/HttpError', from: 'getChangedPRFiles', message: 'There was an error getting change files for repo:file-changes-action owner:trilom pr:NaN', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with invalid repo for pull request', { owner: 'trilom', repo: 'file-chandkdk-action-thatdoesntreallyexist', pullNumber: 83 }, { error: '404/HttpError', from: 'getChangedPRFiles', message: 'There was an error getting change files for repo:file-chandkdk-action-thatdoesntreallyexist owner:trilom pr:83', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with invalid owner for pull request', { owner: 'this-isntareal-githubowner', repo: 'file-changes-action', pullNumber: 83 }, { error: '404/HttpError', from: 'getChangedPRFiles', message: 'There was an error getting change files for repo:file-changes-action owner:this-isntareal-githubowner pr:83', payload: {name: 'HttpError', status: '404'} } ], events: 'all' } ] export const getChangedPushFilesTestInputs: TestInput[] = [ { inputs: [ 'gets changed files for a push', { owner: 'trilom', repo: 'file-changes-action', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' }, p.OctokitPaginatePushResponse ], events: 'all' }, { inputs: [ 'throws an error with no before for a push', { owner: 'trilom', repo: 'file-changes-action', before: '', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' }, { error: '404/HttpError', from: 'getChangedPushFiles', message: 'There was an error getting change files for repo:file-changes-action owner:trilom base: head:4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with no after for a push', { owner: 'trilom', repo: 'file-changes-action', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '' }, { error: '404/HttpError', from: 'getChangedPushFiles', message: 'There was an error getting change files for repo:file-changes-action owner:trilom base:6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2 head:', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with invalid repo for a push', { owner: 'trilom', repo: 'file-chandkdk-action-thatdoesntreallyexist', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' }, { error: '404/HttpError', from: 'getChangedPushFiles', message: 'There was an error getting change files for repo:file-chandkdk-action-thatdoesntreallyexist owner:trilom base:6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2 head:4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with invalid owner for a push', { owner: 'this-isntareal-githubowner', repo: 'file-changes-action', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' }, { error: '404/HttpError', from: 'getChangedPushFiles', message: 'There was an error getting change files for repo:file-changes-action owner:this-isntareal-githubowner base:6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2 head:4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', payload: {name: 'HttpError', status: '404'} } ], events: 'all' } ] export const getChangedFilesTestInputs: TestInput[] = [ { inputs: [ 'gets changed files for a push', { repo: 'trilom/file-changes-action', ...({ before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred) }, p.OctokitPaginatePushResponse ], events: 'all' }, { inputs: [ 'throws an error with a malformed owner/repo for a push', { repo: 'trilom/testing/afew/backslash', ...({ before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred) }, { error: '500/Unknown Error:Error', from: 'getChangedFiles', message: 'There was an error getting change files outputs pr: NaN before: 6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2 after: 4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', payload: JSON.stringify( { error: '500/Bad-Repo', from: 'self', message: 'Repo input of trilom/testing/afew/backslash has more than 2 length after splitting.', payload: '' }, null, 2 ) } ], events: 'all' }, { inputs: [ 'throws an error with invalid owner for a push', { repo: 'trilom-NOTREAL/backslash', ...({ before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred) }, { error: '404/HttpError', from: 'undefined/Error', message: 'There was an error getting change files for repo:backslash owner:trilom-NOTREAL base:6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2 head:4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with no after for a push', { repo: 'trilom/cloudformation', ...({before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2'} as Inferred) }, { error: '404/HttpError', from: 'undefined/Error', message: 'There was an error getting change files for repo:cloudformation owner:trilom base:6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2 head:', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with no before for a push', { repo: 'trilom/cloudformation', ...({after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968'} as Inferred) }, { error: '404/HttpError', from: 'undefined/Error', message: 'There was an error getting change files for repo:cloudformation owner:trilom base: head:4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'gets changed files for a pull request', {repo: 'trilom/file-changes-action', ...({pr: 83} as Inferred)}, p.OctokitPaginatePrResponse ], events: 'all' }, { inputs: [ 'throws an error with a malformed owner/repo for a pr', {repo: 'trilom/testing/afew/backslash', ...({pr: 83} as Inferred)}, { error: '500/Unknown Error:Error', from: 'getChangedFiles', message: 'There was an error getting change files outputs pr: 83 before: undefined after: undefined', payload: JSON.stringify( { error: '500/Bad-Repo', from: 'self', message: 'Repo input of trilom/testing/afew/backslash has more than 2 length after splitting.', payload: '' }, null, 2 ) } ], events: 'all' }, { inputs: [ 'throws an error with invalid owner for a pr', {repo: 'trilom-NOTREAL/backslash', ...({pr: 80} as Inferred)}, { error: '404/HttpError', from: 'undefined/Error', message: 'There was an error getting change files for repo:backslash owner:trilom-NOTREAL pr:80', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with no pull request', {repo: 'trilom/cloudformation', ...({} as Inferred)}, { error: '404/HttpError', from: 'undefined/Error', message: 'There was an error getting change files for repo:cloudformation owner:trilom base: head:', payload: {name: 'HttpError', status: '404'} } ], events: 'all' }, { inputs: [ 'throws an error with no pull request', {repo: 'trilom/cloudformation', ...({} as Inferred)}, { error: '404/HttpError', from: 'undefined/Error', message: 'There was an error getting change files for repo:cloudformation owner:trilom base: head:', payload: {name: 'HttpError', status: '404'} } ], events: 'all' } ] /** * InputHelper Test inputs */ export const inputTestInputs: TestInput[] = [ { inputs: [ 'githubRepo', 'trilom-test/file-changes-action', 'trilom-test/file-changes-action' ], events: 'all' }, {inputs: ['githubToken', 'InputTestToken', 'InputTestToken'], events: 'all'}, { inputs: [ 'pushBefore', '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2' ], events: 'all' }, { inputs: [ 'pushAfter', '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' ], events: 'all' }, {inputs: ['prNumber', '83', 83], events: 'all'}, {inputs: ['output', 'json', 'json'], events: 'all'}, {inputs: ['fileOutput', 'json', 'json'], events: 'all'} ] export const inferTestInputs: TestInput[] = [ { inputs: [ 'sets PUSH inferred outputs with pr inputs and PUSH inputs and PULL_REQUEST event', { event: 'pull_request', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: 83 }, { before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred ], events: ['pull_request_opened', 'pull_request_reopened'] }, { inputs: [ 'sets PR inferred outputs with pr inputs and PUSH inputs and PULL_REQUEST_SYNCHRONIZE event', { event: 'pull_request', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: 83 }, { before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred ], events: ['pull_request_synchronize'] }, { inputs: [ 'sets PULL_REQUEST inferred outputs with single PUSH input and PULL_REQUEST event, ALSO WARN weird', { event: 'pull_request', before: '787a72d40923de2f5308e7095ff9e6063fdbc219', after: '', pr: 83 }, {pr: 83} as Inferred ], events: [ 'pull_request_opened', 'pull_request_reopened', 'pull_request_synchronize' ] }, { inputs: [ 'sets PULL_REQUEST inferred outputs with no PUSH inputs and PULL_REQUEST event', {event: 'pull_request', before: '', after: '', pr: 83}, {pr: 83} as Inferred ], events: [ 'pull_request_opened', 'pull_request_reopened', 'pull_request_synchronize' ] }, { inputs: [ 'sets PULL_REQUEST inferred outputs with pr input and PUSH event', { event: 'push', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: 83 }, {pr: 83} as Inferred ], events: ['push', 'push_merge'] }, { inputs: [ 'sets PUSH inferred outputs with no pr input and PUSH event', { event: 'push', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: NaN }, { before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred ], events: ['push', 'push_merge'] }, { inputs: [ 'sets PUSH inferred outputs with PUSH and PULL_REQUEST inputs NOT PUSH or PULL_REQUEST event, ALSO WARN all', { event: 'schedule', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: 83 }, { before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred ], events: ['issue_comment_created', 'issue_comment_edited'] }, { inputs: [ 'sets PUSH inferred outputs with PUSH and PULL_REQUEST inputs NOT PUSH or PULL_REQUEST event, ALSO WARN all', { event: 'schedule', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: 83 }, {pr: 83} as Inferred ], events: ['schedule'] }, { inputs: [ 'sets PULL_REQUEST inferred outputs with single PUSH and PULL_REQUEST inputs NOT PUSH or PULL_REQUEST event, ALSO WARN weird', { event: 'schedule', before: '', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: 83 }, {pr: 83} as Inferred ], events: ['issue_comment_created', 'issue_comment_edited', 'schedule'] }, { inputs: [ 'sets PULL_REQUEST inferred outputs with PULL_REQUEST input NOT PUSH or PULL_REQUEST event', {event: 'schedule', before: '', after: '', pr: 83}, {pr: 83} as Inferred ], events: ['issue_comment_created', 'issue_comment_edited', 'schedule'] }, { inputs: [ 'sets PUSH inferred outputs with PUSH inputs NOT PUSH or PULL_REQUEST event', { event: 'schedule', before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: NaN }, { before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' } as Inferred ], events: ['issue_comment_created', 'issue_comment_edited', 'schedule'] }, { inputs: [ 'throws ERROR with no inputs NOT PUSH or PULL_REQUEST event', {before: '', after: '', pr: NaN}, {} as Inferred ], events: ['issue_comment_created', 'issue_comment_edited', 'schedule'] }, { inputs: [ 'throws ERROR with single only before NOT PUSH or PULL_REQUEST event', {before: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', pr: NaN}, {} as Inferred ], events: ['issue_comment_created', 'issue_comment_edited', 'schedule'] }, { inputs: [ 'throws ERROR with single only after NOT PUSH or PULL_REQUEST event', {after: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968', pr: NaN}, {} as Inferred ], events: ['issue_comment_created', 'issue_comment_edited', 'schedule'] } ] /** * UtilsHelper Test inputs */ export const errorMessageInputs: TestInput[] = [ { inputs: [ 'getInputs', JSON.stringify( {name: 'Error', message: 'Error', from: 'getInputs'}, null, 2 ), 'There was an getting action inputs.' ], events: 'all' }, { inputs: [ 'inferInput', JSON.stringify( {name: 'Error', message: 'Error', from: 'inferInput'}, null, 2 ), 'There was an issue inferring inputs to the action.' ], events: 'all' }, { inputs: [ 'initClient', JSON.stringify( {name: 'Error', message: 'Error', from: 'initClient'}, null, 2 ), 'There was an issue initilizing the github client.' ], events: 'all' }, { inputs: [ 'getChangedFiles', JSON.stringify( {name: 'Error', message: 'Error', from: 'getChangedFiles'}, null, 2 ), 'There was an issue getting changed files from Github.' ], events: 'all' }, { inputs: [ 'sortChangedFiles', JSON.stringify( {name: 'Error', message: 'Error', from: 'sortChangedFiles'}, null, 2 ), 'There was an issue sorting changed files from Github.' ], events: 'all' }, { inputs: [ 'writeFiles', JSON.stringify( {name: 'Error', message: 'Error', from: 'writeFiles'}, null, 2 ), 'There was an issue writing output files.' ], events: 'all' }, { inputs: [ 'writeOutput', JSON.stringify( {name: 'Error', message: 'Error', from: 'writeOutput'}, null, 2 ), 'There was an issue writing output variables.' ], events: 'all' } ] /** * main Test inputs */ export const mainInputs: TestInput[] = [ { inputs: [ 'push', { pushBefore: '6ac7697cd1c4f23a08d4d4edbe7dab06b34c58a2', pushAfter: '4ee1a1a2515f4ac1b90a56aaeb060b97f20c8968' }, 'push' ], events: 'all' }, {inputs: ['pull_request', {prNumber: '83'}, 'pull_request'], events: 'all'} ] export {errorMessageInputs as mainErrorInputs}
the_stack
import * as React from 'react'; /** * Omits keys K from T */ export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; /** * Represents a HoC, whose wrapped component props are inferable. */ export interface InferableHOC<ProvidedProps extends {}> { <B extends ProvidedProps>( c: React.ComponentType<B>, ): React.ComponentType<Omit<B, keyof ProvidedProps>>; } /** * Represents a HoC, whose wrapped component props are inferable. */ export interface InferableHOCWithProps<ProvidedProps, NeededProps> { <B extends ProvidedProps>( c: React.ComponentType<B>, ): React.ComponentType<Omit<B, keyof ProvidedProps> & NeededProps>; } /** * A composable wrapper around React effects. * */ export type ChainableComponent<A> = { /** * Renders this chainable into a ReactNode, which can be embedded inside the render * method of another component. * @param f A function which is used to render the contextual value. * This method returns another ReactNode, possibly wrapped with * additional functionality. */ render(f: (a: A) => React.ReactNode): React.ReactNode; /** * Renders this chainable into a render prop component. */ toRenderProp(): React.ComponentType<ChildrenProp<A>>; /** * Renders this chainable into a Higher Order Component. * @param propMapper A function which maps chainable arguments into props */ toHigherOrderComponent<B extends object>( propMapper: (a: A) => B ): InferableHOC<B>; /** * Converts the value inside this Chainable Component. * * @param f A function which is used to convert this value. The result of * f will replace the existing in a new Chainable Component which is returned. */ map<B>(f: (a: A) => B): ChainableComponent<B>; /** * @deprecated: use fantasy-land/map instead */ 'fantasyland/map'<B>(f: (a: A) => B): ChainableComponent<B>; 'fantasy-land/map'<B>(f: (a: A) => B): ChainableComponent<B>; /** * Converts the value inside this Chainable Component. * @param c Apply the function inside of c to the value inside of this Chainable Component */ ap<B>(c: ChainableComponent<(a: A) => B>): ChainableComponent<B>; /** * @deprecated: use fantasy-land/ap instead */ 'fantasyland/ap'<B>( c: ChainableComponent<(a: A) => B> ): ChainableComponent<B>; 'fantasy-land/ap'<B>( c: ChainableComponent<(a: A) => B> ): ChainableComponent<B>; /** * Composes or 'chains' another Chainable Component along with this one. * @param f A function which is provided the contextual value, and returns a chainable component * The result if this function will be returned. */ chain<B>(f: (a: A) => ChainableComponent<B>): ChainableComponent<B>; /** * @deprecated: use fantasy-land/ap instead */ 'fantasyland/chain'<B>( f: (a: A) => ChainableComponent<B> ): ChainableComponent<B>; 'fantasy-land/chain'<B>( f: (a: A) => ChainableComponent<B> ): ChainableComponent<B>; }; /** * Represents the props used by a Render Props component. * @template P represents the props used to configure the Render Prop component. * @template A represents the type of the contextual value of the Render Props component. */ export type RenderPropsProps<P, A> = P & ChildrenProp<A>; /** * A standard Render Prop's children property which doesn't pass a value */ export type ChildrenProp<A> = { children: (a: A) => React.ReactNode; }; /** * Represents a function that takes a value A and returns a renderable ReactNode. */ type Applied<A> = (f: (a: A) => React.ReactNode) => React.ReactNode; /** * Infers the type of the parameter to the 'children' function */ export type InferChildren<P> = P extends { children: (a: infer A) => React.ReactNode; } ? A : never; /** * Represents an un-parameterized Render Prop component. * @template P encapsulates the props used to configure this Render Prop * @template A represents the type of the contextual value of the Render Props component. */ export type UnParameterizedRenderPropsComponent<A> = React.ComponentType< ChildrenProp<A> >; /** * Converts a Render Prop Component into a Chainable Component. * @template A The type of the parameter of the 'children' prop * @param Inner the render prop component */ export function fromRenderProp<A>( Inner: UnParameterizedRenderPropsComponent<A> ): ChainableComponent<A>; /** * Converts a Render Prop Component into a Chainable Component. * @template A The type of the parameter of the 'children' prop * @param Inner the render prop component * @param parameters an object containing the props that shoud be applied to this render prop component. */ export function fromRenderProp<P extends ChildrenProp<any>>( Inner: React.ComponentType<P>, parameters: Omit<P, 'children'> ): ChainableComponent<InferChildren<P>>; export function fromRenderProp<P extends ChildrenProp<A>, A>( Inner: React.ComponentType<P> | UnParameterizedRenderPropsComponent<A>, parameters?: Omit<P, 'children'> ): ChainableComponent<A> { return fromRender(f => { const apply = React.createFactory<P>(Inner as any); if (parameters) { return apply({ ...(parameters as any), // todo: we have any until https://github.com/Microsoft/TypeScript/pull/13288 is merged children: f }); } else { return apply({ children: f } as any); } }); } /** * Converts a ChainableComponent to a render prop component * @param chainable The chainable component * @param {string} [prop=children] defaults to children */ export function toRenderProp<A>( chainable: ChainableComponent<A> ): React.ComponentType<ChildrenProp<A>> { // typecast here because of: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18051 return props => chainable.render(props.children) as React.ReactElement<any> | null; } /** * Converts a ChainableComponent to a HigherOrderComponent * @param chainable The ChainableComponent * @param propMapper convert the value inside this chainable to props * that will be supplied by the created HoC */ export function toHigherOrderComponent<A, B extends object>( chainable: ChainableComponent<A>, propMapper: (a: A) => B ): InferableHOC<B> { return component => ownProps => chainable.render(a => React.createElement(component, { ...(ownProps as object), ...(propMapper(a) as object) } as any) ) as React.ReactElement<any> | null; } type DummyRenderPropProps<A, B> = A & { children: (b: B) => React.ReactNode; }; /** * Converts a HigherOrderComponent to a ChainableComponent * @param hoc The HigherOrderComponent */ export function fromHigherOrderComponent<P extends {}>( hoc: InferableHOC<P> ): () => ChainableComponent<P> export function fromHigherOrderComponent<P extends {}>( hoc: InferableHOCWithProps<P, {}> ): () => ChainableComponent<P> export function fromHigherOrderComponent<P extends {}, N extends {}>( hoc: InferableHOCWithProps<P, N> ): (n: N) => ChainableComponent<P> { const Dummy: React.StatelessComponent<DummyRenderPropProps<P, P>> = props => props.children(props) as React.ReactElement<any> | null; const RenderPropComponent = hoc(Dummy as any as React.ComponentType<P>); const apply = React.createFactory<P>(RenderPropComponent as any as React.FunctionComponent<P>); return (n) => fromRender(f => { if(n) { return apply({...(n as any), children:f}); } else { return apply({children:f} as any); } }); } /** * Extracts a parameter type from the render prop function. */ type RenderPropContext<P, S extends keyof P> = P extends {[K in S]?: (a: infer U) => React.ReactNode} ? U : never; /** * Converts a Render Prop Component into a function that can be used to build a ChainableComponent * If a renderMethod name is not provided, it defaults to `children`. * A "non-standard" render prop is any render prop that does not use the 'children' prop as the render method. * @param Inner the render prop component */ export function fromNonStandardRenderProp<P, S extends keyof P>( renderMethod: S, Inner: React.ComponentType<P>, parameters?: Omit<P, S> ): ChainableComponent<RenderPropContext<P, S>> { return fromRender(f => { const apply = React.createFactory<P>( Inner as any ); return apply({ ...(parameters as any), [renderMethod]: f }); }); } /** * Converts a render function to a ChainableComponent * @param render */ export function fromRender<A>( render: (f: (a: A) => React.ReactNode) => React.ReactNode ): ChainableComponent<A> { const cc = { render, map<B>(f: (a: A) => B): ChainableComponent<B> { const Mapped: Applied<B> = g => this.render(a => g(f(a))); return fromRender(Mapped); }, ap<B>(c: ChainableComponent<(a: A) => B>): ChainableComponent<B> { const Apped: Applied<B> = g => this.render(a => c.render(f => g(f(a)))); return fromRender(Apped); }, chain<B>(f: (a: A) => ChainableComponent<B>): ChainableComponent<B> { const FlatMapped: Applied<B> = g => this.render(a => f(a).render(g)); return fromRender(FlatMapped); } }; // https://github.com/fantasyland/fantasy-land/blob/master/README.md#prefixed-method-names return { ...cc, 'fantasyland/map': cc.map, 'fantasy-land/map': cc.map, 'fantasyland/ap': cc.ap, 'fantasy-land/ap': cc.ap, 'fantasyland/chain': cc.chain, 'fantasy-land/chain': cc.chain, toRenderProp() { return toRenderProp(this); }, toHigherOrderComponent(mapper) { return toHigherOrderComponent(this, mapper); } }; } type CC<A> = ChainableComponent<A>; type Unchained<A> = A extends ChainableComponent<infer U> ? U : never; type Unchainified<A> = { [K in keyof A]: Unchained<A[K]> }; function allT<A extends ChainableComponent<any>[]>(...values: A): ChainableComponent<Unchainified<A>> { return all(values) as unknown as ChainableComponent<Unchainified<A>>; } function all<T1, T2, T3, T4, T5, T6, T7, T8, T9>( values: [ CC<T1>, CC<T2>, CC<T3>, CC<T4>, CC<T5>, CC<T6>, CC<T7>, CC<T8>, CC<T9> ] ): CC<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; function all<T1, T2, T3, T4, T5, T6, T7, T8>( values: [CC<T1>, CC<T2>, CC<T3>, CC<T4>, CC<T5>, CC<T6>, CC<T7>, CC<T8>] ): CC<[T1, T2, T3, T4, T5, T6, T7, T8]>; function all<T1, T2, T3, T4, T5, T6, T7>( values: [CC<T1>, CC<T2>, CC<T3>, CC<T4>, CC<T5>, CC<T6>, CC<T7>] ): CC<[T1, T2, T3, T4, T5, T6, T7]>; function all<T1, T2, T3, T4, T5, T6>( values: [CC<T1>, CC<T2>, CC<T3>, CC<T4>, CC<T5>, CC<T6>] ): CC<[T1, T2, T3, T4, T5, T6]>; function all<T1, T2, T3, T4, T5>( values: [CC<T1>, CC<T2>, CC<T3>, CC<T4>, CC<T5>] ): CC<[T1, T2, T3, T4, T5]>; function all<T1, T2, T3, T4>( values: [CC<T1>, CC<T2>, CC<T3>, CC<T4>] ): CC<[T1, T2, T3, T4]>; function all<T1, T2, T3>(values: [CC<T1>, CC<T2>, CC<T3>]): CC<[T1, T2, T3]>; function all<T1, T2>(values: [CC<T1>, CC<T2>]): CC<[T1, T2]>; function all<T>(values: (CC<T>)[]): CC<T[]>; function all(values: CC<any>[]) { return values.reduce((aggOp: CC<any[]>, aOp: CC<any>) => { return aggOp.ap( aOp.map(a => { const g: (a: any[]) => any = agg => agg.concat([a]); return g; }) ); }, ChainableComponent.of([])); } function of<A>(a: A): ChainableComponent<A> { return fromRender(f => f(a)); } function Do<T1, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<Z> ): ChainableComponent<Z>; function Do<T1, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => Z ): ChainableComponent<Z>; function Do<T1, T2, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, z: (t2: T2, t1: T1) => ChainableComponent<Z> ): ChainableComponent<Z>; function Do<T1, T2, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, z: (t2: T2, t1: T1) => Z ): ChainableComponent<Z>; function Do<T1, T2, T3, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, z: (t3: T3, t2: T2, t1: T1) => ChainableComponent<Z> ): ChainableComponent<Z>; function Do<T1, T2, T3, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, z: (t3: T3, t2: T2, t1: T1) => Z ): ChainableComponent<Z>; function Do<T1, T2, T3, T4, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, z: (t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<Z> ): ChainableComponent<Z>; function Do<T1, T2, T3, T4, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, z: (t4: T4, t3: T3, t2: T2, t1: T1) => Z ): ChainableComponent<Z>; function Do<T1, T2, T3, T4, T5, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, f4: (t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T5>, z: (t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<Z> ): ChainableComponent<Z>; function Do<T1, T2, T3, T4, T5, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, f4: (t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T5>, z: (t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => Z ): ChainableComponent<Z>; function Do<T1, T2, T3, T4, T5, T6, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, f4: (t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T5>, f5: (t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T6>, z: (t6: T6, t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<Z> ): ChainableComponent<Z>; function Do<T1, T2, T3, T4, T5, T6, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, f4: (t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T5>, f5: (t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T6>, z: (t6: T6, t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => Z ): ChainableComponent<Z>; function Do( a: ChainableComponent<any>, ...fns: Function[] ): ChainableComponent<any> { function doIt(as: ChainableComponent<any[]>, fns: Function[]): any { const [fn, ...rest] = fns; if (rest.length === 0) { return as.chain(a2s => { const aPrime = fn.apply(null, a2s); if (isChainableComponent(aPrime)) { return aPrime; } else { return of(aPrime); } }); } else { return as.chain(a2s => { const aPrime = fn.apply(null, a2s); return doIt(aPrime.map((aP: any) => [aP, ...a2s]), rest); }); } } return doIt(a.map(a2 => [a2]), fns); } function DoRender<T1, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => React.ReactNode ): React.ReactNode; function DoRender<T1, T2, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, z: (t2: T2, t1: T1) => React.ReactNode ): React.ReactNode; function DoRender<T1, T2, T3, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, z: (t3: T3, t2: T2, t1: T1) => React.ReactNode ): React.ReactNode; function DoRender<T1, T2, T3, T4, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, z: (t4: T4, t3: T3, t2: T2, t1: T1) => React.ReactNode ): React.ReactNode; function DoRender<T1, T2, T3, T4, T5, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, f4: (t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T5>, z: (t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => React.ReactNode ): React.ReactNode; function DoRender<T1, T2, T3, T4, T5, T6, Z>( c: ChainableComponent<T1>, f1: (t1: T1) => ChainableComponent<T2>, f2: (t2: T2, t1: T1) => ChainableComponent<T3>, f3: (t3: T3, t2: T2, t1: T1) => ChainableComponent<T4>, f4: (t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T5>, f5: (t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => ChainableComponent<T6>, z: (t6: T6, t5: T5, t4: T4, t3: T3, t2: T2, t1: T1) => React.ReactNode ): React.ReactNode; function DoRender( a: ChainableComponent<any>, ...fns: Function[] ): React.ReactNode { function doIt(as: ChainableComponent<any[]>, fns: Function[]): any { const [fn, ...rest] = fns; if (rest.length === 0) { return as.render(a2s => fn.apply(null, a2s)); } else { return as.render(a2s => { const aPrime = fn.apply(null, a2s); return doIt(aPrime.map((aP: any) => [aP, ...a2s]), rest); }); } } return doIt(a.map(a2 => [a2]), fns); } export const fork = <T>(f: () => React.ReactNode): ChainableComponent<T> => { return fromRender(() => f()) } const isChainableComponent = (a: any) => { return ( typeof a.chain === 'function' && typeof a.map === 'function' && typeof a.ap === 'function' && typeof a.render === 'function' ); }; export const ChainableComponent = { /** * Wraps any value 'A' into a chainable component. * @param a the value that provides the context. */ of, /** * @deprecated: use fantasy-land/of instead */ 'fantasyland/of': of, 'fantasy-land/of': of, all, allT, fork, Do, DoRender };
the_stack
import { Component, forwardRef, Input, OnInit, Output, EventEmitter, ViewChild, ComponentRef, ComponentFactoryResolver, ViewContainerRef, ReflectiveInjector, OnDestroy, AfterContentInit, ChangeDetectionStrategy, } from "@angular/core"; import { NG_VALUE_ACCESSOR, ControlValueAccessor, NG_VALIDATORS, Validator } from "@angular/forms"; import { InlineEditorService } from "./inline-editor.service"; import { InlineConfig } from "./types/inline-configs"; import { InputNumberComponent } from "./inputs/input-number.component"; import { InputBase } from "./inputs/input-base"; import { InputTextComponent } from "./inputs/input-text.component"; import { InputPasswordComponent } from "./inputs/input-password.component"; import { InputRangeComponent } from "./inputs/input-range.component"; import { InputCheckboxComponent } from "./inputs/input-checkbox.component"; import { InputTextareaComponent } from "./inputs/input-textarea.component"; import { InputSelectComponent } from "./inputs/input-select.component"; import { InputDateComponent } from "./inputs/input-date.component"; import { InputTimeComponent } from "./inputs/input-time.component"; import { InputDatetimeComponent } from "./inputs/input-datetime.component"; import { Subscription } from "rxjs/Subscription"; import { SelectOptions } from "./types/select-options.interface"; import { InlineEditorError } from "./types/inline-editor-error.interface"; import { InlineEditorEvent, InternalEvent, Events, InternalEvents, ExternalEvents, ExternalEvent, } from "./types/inline-editor-events.class"; import { InlineEditorState, InlineEditorStateOptions } from "./types/inline-editor-state.class"; import { EditOptions } from "./types/edit-options.interface"; import { InputType } from "./types/input-type.type"; import { InputConfig } from "./configs"; const defaultConfig: InlineConfig = { name: "", required: false, options: { data: [], text: "text", value: "value", }, empty: "empty", placeholder: "placeholder", type: "text", size: 8, min: 0, max: Infinity, cols: 10, rows: 4, pattern: "", disabled: false, saveOnBlur: false, saveOnChange: false, saveOnEnter: true, editOnClick: true, cancelOnEscape: true, hideButtons: false, onlyValue: true, checkedText: "Check", uncheckedText: "Uncheck", }; @Component({ selector: "inline-editor", templateUrl: "./inline-editor.component.html", providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InlineEditorComponent), multi: true, }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => InlineEditorComponent), multi: true, }, ], entryComponents: [ InputTextComponent, InputNumberComponent, InputPasswordComponent, InputRangeComponent, InputTextareaComponent, InputSelectComponent, InputDateComponent, InputTimeComponent, InputDatetimeComponent, InputCheckboxComponent, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class InlineEditorComponent implements OnInit, AfterContentInit, OnDestroy, ControlValueAccessor, Validator { constructor(protected componentFactoryResolver: ComponentFactoryResolver) { } public service: InlineEditorService; public state: InlineEditorState; public currentComponent: ComponentRef<InputBase>; public events: Events = { internal: new InternalEvents(), external: new ExternalEvents(), }; @Input() public type?: InputType; @Input() public config: InlineConfig; @Output() public onChange: EventEmitter<InlineEditorEvent | any> = this.events.external.onChange; @Output() public onSave: EventEmitter<InlineEditorEvent | any> = this.events.external.onSave; @Output() public onEdit: EventEmitter<InlineEditorEvent | any> = this.events.external.onEdit; @Output() public onCancel: EventEmitter<InlineEditorEvent | any> = this.events.external.onCancel; @Output() public onError: EventEmitter<InlineEditorError | InlineEditorError[]> = this.events.external.onError; @Output() public onEnter: EventEmitter<InlineEditorEvent | any> = this.events.external.onEnter; @Output() public onEscape: EventEmitter<InlineEditorEvent | any> = this.events.external.onEscape; @Output() public onKeyPress: EventEmitter<InlineEditorEvent | any> = this.events.external.onKeyPress; @Output() public onFocus: EventEmitter<InlineEditorEvent | any> = this.events.external.onFocus; @Output() public onBlur: EventEmitter<InlineEditorEvent | any> = this.events.external.onBlur; @Output() public onClick: EventEmitter<InlineEditorEvent | any> = this.events.external.onClick; // input's attribute private _empty?: string; @Input() public set empty(empty: string | undefined) { this._empty = empty; this.updateConfig(undefined, "empty", empty); } public get empty(): string | undefined { return this._empty; } private _checkedText?: string; @Input() public set checkedText(checkedText: string | undefined) { this._checkedText = checkedText; this.updateConfig(undefined, "checkedText", checkedText); } public get checkedText(): string | undefined { return this._checkedText; } private _uncheckedText?: string; @Input() public set uncheckedText(uncheckedText: string | undefined) { this._uncheckedText = uncheckedText; this.updateConfig(undefined, "uncheckedText", uncheckedText); } public get uncheckedText(): string | undefined { return this._uncheckedText; } private _saveOnEnter?: boolean; @Input() public set saveOnEnter(saveOnEnter: boolean | undefined) { this._saveOnEnter = saveOnEnter; this.updateConfig(undefined, "saveOnEnter", saveOnEnter); } public get saveOnEnter(): boolean | undefined { return this._saveOnEnter; } private _saveOnBlur?: boolean; @Input() public set saveOnBlur(saveOnBlur: boolean | undefined) { this._saveOnBlur = saveOnBlur; this.updateConfig(undefined, "saveOnBlur", saveOnBlur); } public get saveOnBlur(): boolean | undefined { return this._saveOnBlur; } private _saveOnChange?: boolean; @Input() public set saveOnChange(saveOnChange: boolean | undefined) { this._saveOnChange = saveOnChange; this.updateConfig(undefined, "saveOnChange", saveOnChange); } public get saveOnChange(): boolean | undefined { return this._saveOnChange; } private _editOnClick?: boolean; @Input() public set editOnClick(editOnClick: boolean | undefined) { this._editOnClick = editOnClick; this.updateConfig(undefined, "editOnClick", editOnClick); } public get editOnClick(): boolean | undefined { return this._editOnClick; } private _cancelOnEscape?: boolean; @Input() public set cancelOnEscape(cancelOnEscape: boolean | undefined) { this._cancelOnEscape = cancelOnEscape; this.updateConfig(undefined, "cancelOnEscape", cancelOnEscape); } public get cancelOnEscape(): boolean | undefined { return this._cancelOnEscape; } private _hideButtons?: boolean; @Input() public set hideButtons(hideButtons: boolean | undefined) { this._hideButtons = hideButtons; this.updateConfig(undefined, "hideButtons", hideButtons); } public get hideButtons(): boolean | undefined { return this._hideButtons; } private _disabled?: boolean; @Input() public set disabled(disabled: boolean | undefined) { this._disabled = disabled; this.updateConfig(undefined, "disabled", disabled); } public get disabled(): boolean | undefined { return this._disabled; } private _required?: boolean; @Input() public set required(required: boolean | undefined) { this._required = required; this.updateConfig(undefined, "required", required); } public get required(): boolean | undefined { return this._required; } private _onlyValue?: boolean; @Input() public set onlyValue(onlyValue: boolean | undefined) { this._onlyValue = onlyValue; this.updateConfig(undefined, "onlyValue", onlyValue); } public get onlyValue(): boolean | undefined { return this._onlyValue; } private _placeholder?: string; @Input() public set placeholder(placeholder: string | undefined) { this._placeholder = placeholder; this.updateConfig(undefined, "placeholder", placeholder); } public get placeholder(): string | undefined { return this._placeholder; } private _name?: string; @Input() public set name(name: string | undefined) { this._name = name; this.updateConfig(undefined, "name", name); } public get name(): string | undefined { return this._name; } private _pattern?: string; @Input() public set pattern(pattern: string | undefined) { this._pattern = pattern; this.updateConfig(undefined, "pattern", pattern); } public get pattern(): string | undefined { return this._pattern; } private _size?: number; @Input() public set size(size: number | undefined) { this._size = size; this.updateConfig(undefined, "size", size); } public get size(): number | undefined { return this._size; } private _min?: number; @Input() public set min(min: number | undefined) { this._min = min; this.updateConfig(undefined, "min", min); } public get min(): number | undefined { return this._min; } private _max?: number; @Input() public set max(max: number | undefined) { this._max = max; this.updateConfig(undefined, "max", max); } public get max(): number | undefined { return this._max; } private _cols?: number; @Input() public set cols(cols: number | undefined) { this._cols = cols; this.updateConfig(undefined, "cols", cols); } public get cols(): number | undefined { return this._cols; } private _rows?: number; @Input() public set rows(rows: number | undefined) { this._rows = rows; this.updateConfig(undefined, "rows", rows); } public get rows(): number | undefined { return this._rows; } private _options?: SelectOptions; @Input() public set options(options: SelectOptions | undefined) { this._options = options; this.updateConfig(undefined, "options", options); } public get options(): SelectOptions | undefined { return this._options; } private subscriptions: { [key: string]: Subscription } = {}; private componentRef: ComponentRef<InputBase>; @ViewChild("container", { read: ViewContainerRef }) private container: ViewContainerRef; private inputInstance: InputBase; // Inputs implemented private components: { [key: string]: any } = { text: InputTextComponent, number: InputNumberComponent, password: InputPasswordComponent, range: InputRangeComponent, textarea: InputTextareaComponent, select: InputSelectComponent, date: InputDateComponent, time: InputTimeComponent, datetime: InputDatetimeComponent, checkbox: InputCheckboxComponent, }; private refreshNGModel: (_: any) => void; private isEnterKeyPressed = false; ngOnInit() { this.config = this.generateSafeConfig(); this.state = new InlineEditorState({ disabled: this.config.disabled, value: "", }); this.service = new InlineEditorService(this.events, { ...this.config }); this.subscriptions.onUpdateStateSubcription = this.events.internal.onUpdateStateOfParent.subscribe( (state: InlineEditorState) => this.state = state, ); this.subscriptions.onSaveSubscription = this.events.internal.onSave.subscribe( ({ event, state }: InternalEvent) => this.save({ event, state: state.getState(), }), ); this.subscriptions.onCancelSubscription = this.events.internal.onCancel.subscribe( ({ event, state }: InternalEvent) => this.cancel({ event, state: state.getState(), }), ); this.subscriptions.onChangeSubcription = this.events.internal.onChange.subscribe( ({ event, state }: InternalEvent) => { if (this.config.saveOnChange) { this.saveAndClose({ event, state: state.getState(), }); } this.emit(this.onChange, { event, state: state.getState(), }); }, ); this.subscriptions.onKeyPressSubcription = this.events.internal.onKeyPress.subscribe( ({ event, state }: InternalEvent) => this.emit(this.onKeyPress, { event, state: state.getState(), }), ); this.subscriptions.onBlurSubscription = this.events.internal.onBlur.subscribe( ({ event, state }: InternalEvent) => { // TODO (xxxtonixx): Maybe, this approach is not the best, // because we need to set a class property and it is dangerous. // We should search for one better. const isSavedByEnterKey = this.isEnterKeyPressed && this.config.saveOnEnter; if (this.config.saveOnBlur && !isSavedByEnterKey) { this.saveAndClose({ event, state: state.getState(), }); } this.isEnterKeyPressed = false; this.emit(this.onBlur, { event, state: state.getState(), }); }, ); this.subscriptions.onClickSubcription = this.events.internal.onClick.subscribe( ({ event, state }: InternalEvent) => this.emit(this.onClick, { event, state: state.getState(), }), ); this.subscriptions.onFocusSubcription = this.events.internal.onFocus.subscribe( ({ event, state }: InternalEvent) => this.emit(this.onFocus, { event, state: state.getState(), }), ); this.subscriptions.onEnterSubscription = this.events.internal.onEnter.subscribe( ({ event, state }: InternalEvent) => { this.isEnterKeyPressed = true; if (this.config.saveOnEnter) { this.save({ event, state: state.getState(), }); this.edit({ editing: false }); } this.emit(this.onEnter, { event, state: state.getState(), }); }, ); this.subscriptions.onEscapeSubscription = this.events.internal.onEscape.subscribe( ({ event, state }: InternalEvent) => { if (this.config.cancelOnEscape) { this.cancel({ event, state: state.getState(), }); } this.emit(this.onEscape, { event, state: state.getState(), }); }, ); } ngAfterContentInit() { this.service.onUpdateStateOfService.emit(this.state.clone()); this.generateComponent(this.config.type); } ngOnDestroy() { Object.values(this.subscriptions).forEach(subscription => subscription.unsubscribe()); this.currentComponent.destroy(); this.service.destroy(); } validate(): { [key: string]: any; } | null { const errors = this.inputInstance ? this.inputInstance.checkValue() : []; return errors.length === 0 ? null : { InlineEditorError: { valid: false, }, }; } writeValue(value: any) { this.state = this.state.newState({ ...this.state.getState(), value, }); this.events.internal.onUpdateStateOfChild.emit(this.state.clone()); } registerOnChange(refreshNGModel: (_: any) => void) { this.refreshNGModel = refreshNGModel; } registerOnTouched() { } // Method to display the inline editor form and hide the <a> element public edit({ editing = true, focus = true, select = false, event }: EditOptions = {}) { this.state = this.state.newState({ ...this.state.getState(), editing, }); this.events.internal.onUpdateStateOfChild.emit(this.state.clone()); if (editing) { this.emit(this.onEdit, { event, state: this.state.getState(), }); } if (editing && focus) { this.inputInstance.focus(); } if (editing && select) { this.inputInstance.select(); } } public save({ event, state: hotState }: ExternalEvent) { const prevState = this.state.getState(); const state = { ...prevState, ...hotState, }; const errors = this.inputInstance.checkValue(); if (errors.length !== 0) { this.onError.emit(errors); } else { this.state = this.state.newState(state); this.refreshNGModel(state.value); this.emit(this.onSave, { event, state, }); } } public saveAndClose(outsideEvent: ExternalEvent) { this.save(outsideEvent); this.edit({ editing: false }); } // Method to reset the editable value public cancel(outsideEvent: ExternalEvent) { this.edit({ editing: false }); this.emit(this.onCancel, outsideEvent); } public getHotState(): InlineEditorStateOptions { return this.inputInstance.state.getState(); } public showText(): string { return this.inputInstance ? this.inputInstance.showText() : "Loading..."; } private getComponentType(typeName: InputType): string | never { const type = this.components[typeName]; if (!type) { throw new Error("That type does not exist or it is not implemented yet!"); } return type; } private generateComponent(type: InputType) { const componentType = this.getComponentType(type); this.inputInstance = this.createInputInstance(componentType); } private createInputInstance(componentType): InputBase { const providers = ReflectiveInjector.resolve([{ provide: InlineEditorService, useValue: this.service, }]); const injector = ReflectiveInjector.fromResolvedProviders(providers, this.container.parentInjector); const factory = this.componentFactoryResolver.resolveComponentFactory<InputBase>(componentType); this.componentRef = factory.create(injector); this.container.insert(this.componentRef.hostView); if (this.currentComponent) { this.currentComponent.destroy(); } this.currentComponent = this.componentRef; return <InputBase>this.componentRef.instance; } private removeUndefinedProperties<T>(object: Object): T { return JSON.parse( JSON.stringify( typeof object === "object" ? object : {}, ), ); } private generateSafeConfig(): InlineConfig { const configFromAttrs: InlineConfig = { type: this.type!, name: this.name!, size: this.size!, placeholder: this.placeholder!, empty: this.empty!, required: this.required!, disabled: this.disabled!, hideButtons: this.hideButtons!, min: this.min!, max: this.max!, cols: this.cols!, rows: this.rows!, options: this.options!, pattern: this.pattern!, saveOnEnter: this.saveOnEnter!, saveOnBlur: this.saveOnBlur!, saveOnChange: this.saveOnChange!, editOnClick: this.editOnClick!, cancelOnEscape: this.cancelOnEscape!, onlyValue: this.onlyValue!, checkedText: this.checkedText!, uncheckedText: this.uncheckedText!, }; return { // First default config ...defaultConfig, // Default config is overwritten by [config] attr ...this.removeUndefinedProperties<InputConfig>(this.config), // Config from attributes have preference over all others ...this.removeUndefinedProperties<InputConfig>(configFromAttrs), }; } private updateConfig(config?: InlineConfig, property?: string, value?: any) { if (this.config) { config = config || this.config; if (property) { config[property] = value; } this.config = { ...config }; this.events.internal.onUpdateConfig.emit(this.config); } } private emit(event: EventEmitter<InlineEditorEvent | any>, data: ExternalEvent) { if (this.config.onlyValue) { event.emit(data.state.value); } else { (event as EventEmitter<InlineEditorEvent>) .emit({ ...data, instance: this, }); } } }
the_stack
import * as Enquirer from 'enquirer'; import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; import { Tree, readProjectConfiguration, readJson, stripIndents, addProjectConfiguration, readWorkspaceConfiguration, updateJson, logger, updateProjectConfiguration, serializeJson, names, visitNotIgnoredFiles, writeJson, WorkspaceConfiguration, } from '@nrwl/devkit'; import { PackageJson, TsConfig } from '../../types'; import generator from './index'; import { MigrateConvergedPkgGeneratorSchema } from './schema'; interface AssertedSchema extends MigrateConvergedPkgGeneratorSchema { name: string; } type ReadProjectConfiguration = ReturnType<typeof readProjectConfiguration>; jest.mock( 'enquirer', () => ({ prompt: async () => ({ name: '', }), } as Pick<Enquirer, 'prompt'>), ); describe('migrate-converged-pkg generator', () => { // eslint-disable-next-line @typescript-eslint/no-empty-function const noop = () => {}; let tree: Tree; const options = { name: '@proj/react-dummy' } as const; beforeEach(() => { jest.restoreAllMocks(); jest.spyOn(console, 'log').mockImplementation(noop); jest.spyOn(console, 'info').mockImplementation(noop); jest.spyOn(console, 'warn').mockImplementation(noop); tree = createTreeWithEmptyWorkspace(); tree.write( 'jest.config.js', stripIndents` module.exports = { projects: [] }`, ); tree = setupDummyPackage(tree, options); tree = setupDummyPackage(tree, { name: '@proj/babel-make-styles', version: '9.0.0-alpha.0', dependencies: { '@proj/make-styles': '^9.0.0-alpha.1', }, tsConfig: { extends: '../../tsconfig.base.json', compilerOptions: {}, include: ['src'] }, projectConfiguration: { tags: ['vNext', 'platform:node'], sourceRoot: 'packages/babel-make-styles/src' }, }); }); describe('general', () => { describe('schema validation', () => { it('should throw if --name && --stats are both specified', async () => { await expect( generator(tree, { ...options, stats: true, }), ).rejects.toMatchInlineSnapshot(`[Error: --name and --stats are mutually exclusive]`); }); it('should throw if --name && --all are both specified', async () => { await expect( generator(tree, { ...options, all: true, }), ).rejects.toMatchInlineSnapshot(`[Error: --name and --all are mutually exclusive]`); }); it('should throw if --stats && --all are both specified', async () => { await expect( generator(tree, { stats: true, all: true, }), ).rejects.toMatchInlineSnapshot(`[Error: --stats and --all are mutually exclusive]`); }); it(`should throw error if name is empty`, async () => { await expect(generator(tree, { name: '' })).rejects.toMatchInlineSnapshot( `[Error: --name cannot be empty. Please provide name of the package.]`, ); }); it(`should throw error if provided name doesn't match existing package`, async () => { await expect(generator(tree, { name: '@proj/non-existent-lib' })).rejects.toMatchInlineSnapshot( `[Error: Cannot find configuration for '@proj/non-existent-lib' in /workspace.json.]`, ); }); it(`should throw error if user wants migrate non converged package`, async () => { const projectConfig = readProjectConfiguration(tree, options.name); updateJson(tree, `${projectConfig.root}/package.json`, json => { json.version = '8.0.0'; return json; }); /* eslint-disable @fluentui/max-len */ await expect(generator(tree, options)).rejects.toMatchInlineSnapshot( `[Error: @proj/react-dummy is not converged package. Make sure to run the migration on packages with version 9.x.x]`, ); /* eslint-enable @fluentui/max-len */ }); }); describe('prompts', () => { function setup(config: { promptResponse: Pick<MigrateConvergedPkgGeneratorSchema, 'name'> }) { const promptSpy = jest.spyOn(Enquirer, 'prompt').mockImplementation(async () => { return { ...config.promptResponse }; }); return { promptSpy }; } it('should prompt for a name if neither "name" OR "all" OR "stats" are specified', async () => { const { promptSpy } = setup({ promptResponse: options }); await generator(tree, {}); expect(promptSpy).toHaveBeenCalledTimes(1); }); it('should not prompt for a name if "all" OR "stats" is specified', async () => { const { promptSpy } = setup({ promptResponse: options }); await generator(tree, { stats: true }); expect(promptSpy).toHaveBeenCalledTimes(0); await generator(tree, { all: true }); expect(promptSpy).toHaveBeenCalledTimes(0); }); }); }); describe(`tsconfig updates`, () => { function getBaseTsConfig() { return readJson<TsConfig>(tree, `/tsconfig.base.json`); } function setup(config: { projectName: string }) { const projectConfig = readProjectConfiguration(tree, config.projectName); const paths = { main: `${projectConfig.root}/tsconfig.json`, lib: `${projectConfig.root}/tsconfig.lib.json`, test: `${projectConfig.root}/tsconfig.spec.json`, }; const getTsConfig = { main: () => readJson<TsConfig>(tree, paths.main), lib: () => readJson<TsConfig>(tree, paths.lib), test: () => readJson<TsConfig>(tree, paths.test), }; return { projectConfig, paths, getTsConfig }; } it(`should setup TS solution config files`, async () => { const { paths, getTsConfig, projectConfig } = setup({ projectName: options.name }); addConformanceSetup(tree, projectConfig); addUnstableSetup(tree, projectConfig); let tsConfigMain = getTsConfig.main(); expect(tsConfigMain).toEqual({ compilerOptions: { baseUrl: '.', typeRoots: ['../../node_modules/@types', '../../typings'], }, }); expect(tree.exists(paths.lib)).toBeFalsy(); expect(tree.exists(paths.test)).toBeFalsy(); await generator(tree, options); tsConfigMain = getTsConfig.main(); const tsConfigLib = getTsConfig.lib(); const tsConfigTest = getTsConfig.test(); expect(tsConfigMain).toEqual({ extends: '../../tsconfig.base.json', compilerOptions: { importHelpers: true, isolatedModules: true, jsx: 'react', noEmit: true, noUnusedLocals: true, target: 'ES2019', preserveConstEnums: true, }, files: [], include: [], references: [ { path: './tsconfig.lib.json', }, { path: './tsconfig.spec.json', }, ], }); expect(tsConfigLib).toEqual({ extends: './tsconfig.json', compilerOptions: { declaration: true, lib: ['ES2019', 'dom'], noEmit: false, outDir: 'dist', types: ['static-assets', 'environment', 'inline-style-expand-shorthand'], }, exclude: ['./src/common/**', '**/*.spec.ts', '**/*.spec.tsx', '**/*.test.ts', '**/*.test.tsx'], include: ['./src/**/*.ts', './src/**/*.tsx'], }); expect(tsConfigTest).toEqual({ extends: './tsconfig.json', compilerOptions: { module: 'CommonJS', outDir: 'dist', types: ['jest', 'node', 'inline-style-expand-shorthand'], }, include: ['**/*.spec.ts', '**/*.spec.tsx', '**/*.test.ts', '**/*.test.tsx', '**/*.d.ts'], }); }); it(`should setup TS solution config files for JS project`, async () => { const { getTsConfig, projectConfig } = setup({ projectName: options.name }); const sourceRoot = `${projectConfig.root}/src`; addConformanceSetup(tree, projectConfig); addUnstableSetup(tree, projectConfig); visitNotIgnoredFiles(tree, sourceRoot, treePath => { const jsPath = treePath.replace(/ts(x)?$/, 'js$1'); tree.rename(treePath, jsPath); }); await generator(tree, options); const tsConfigMain = getTsConfig.main(); const tsConfigLib = getTsConfig.lib(); const tsConfigTest = getTsConfig.test(); expect(tsConfigMain.compilerOptions).toEqual( expect.objectContaining({ allowJs: true, checkJs: true, }), ); expect(tsConfigMain.compilerOptions.preserveConstEnums).toBeUndefined(); expect(tsConfigLib.include).toEqual(['./src/**/*.js', './src/**/*.jsx']); expect(tsConfigLib.exclude).toEqual(['**/*.spec.js', '**/*.spec.jsx', '**/*.test.js', '**/*.test.jsx']); expect(tsConfigTest.include).toEqual([ '**/*.spec.js', '**/*.spec.jsx', '**/*.test.js', '**/*.test.jsx', '**/*.d.ts', ]); }); describe('setup additional global types', () => { it(`should setup '@testing-library/jest-dom'`, async () => { const { getTsConfig, projectConfig } = setup({ projectName: options.name }); const jestSetupFilePath = `${projectConfig.root}/config/tests.js`; append( tree, jestSetupFilePath, stripIndents` \n require('@testing-library/jest-dom'); `, ); await generator(tree, options); const tsConfigTest = getTsConfig.test(); expect(tsConfigTest.compilerOptions.types).toContain('@testing-library/jest-dom'); }); }); // eslint-disable-next-line @fluentui/max-len it('should update root tsconfig.base.json with migrated package alias including all missing aliases based on packages dependencies list', async () => { setupDummyPackage(tree, { name: '@proj/react-make-styles', dependencies: {} }); setupDummyPackage(tree, { name: '@proj/react-theme', dependencies: {} }); setupDummyPackage(tree, { name: '@proj/react-utilities', dependencies: {} }); let rootTsConfig = getBaseTsConfig(); expect(rootTsConfig).toEqual({ compilerOptions: { paths: {}, }, }); await generator(tree, options); rootTsConfig = getBaseTsConfig(); expect(rootTsConfig.compilerOptions.paths).toEqual( expect.objectContaining({ '@proj/react-dummy': ['packages/react-dummy/src/index.ts'], '@proj/react-make-styles': ['packages/react-make-styles/src/index.ts'], '@proj/react-theme': ['packages/react-theme/src/index.ts'], '@proj/react-utilities': ['packages/react-utilities/src/index.ts'], }), ); expect( Object.keys( rootTsConfig.compilerOptions.paths as Required<Pick<TsConfig['compilerOptions'], 'paths'>>['paths'], ), ).not.toContain(['tslib', 'someThirdPartyDep']); }); it(`should not add 3rd party packages that use same scope as our repo `, async () => { const workspaceConfig = readWorkspaceConfiguration(tree); const normalizedPkgName = getNormalizedPkgName({ pkgName: options.name, workspaceConfig }); const thirdPartyPackageName = '@proj/jango-fet'; updateJson(tree, `./packages/${normalizedPkgName}/package.json`, (json: PackageJson) => { json.dependencies = json.dependencies || {}; json.dependencies[thirdPartyPackageName] = '1.2.3'; return json; }); updateJson(tree, './package.json', (json: PackageJson) => { json.devDependencies = json.devDependencies || {}; json.devDependencies[thirdPartyPackageName] = '1.2.3'; return json; }); await generator(tree, options); const rootTsConfig = getBaseTsConfig(); rootTsConfig.compilerOptions.paths = rootTsConfig.compilerOptions.paths || {}; expect(rootTsConfig.compilerOptions.paths[thirdPartyPackageName]).toBeUndefined(); }); }); describe(`jest config updates`, () => { function getProjectJestConfig(projectConfig: ReadProjectConfiguration) { return tree.read(`${projectConfig.root}/jest.config.js`)?.toString('utf-8'); } it(`should setup new local jest config which extends from root `, async () => { const projectConfig = readProjectConfiguration(tree, options.name); let jestConfig = getProjectJestConfig(projectConfig); expect(jestConfig).toMatchInlineSnapshot(` "const { createConfig } = require('@fluentui/scripts/jest/jest-resources'); const path = require('path'); const config = createConfig({ setupFiles: [path.resolve(path.join(__dirname, 'config', 'tests.js'))], snapshotSerializers: ['@fluentui/jest-serializer-make-styles'], }); module.exports = config;" `); await generator(tree, options); jestConfig = getProjectJestConfig(projectConfig); expect(jestConfig).toMatchInlineSnapshot(` "// @ts-check /** * @type {jest.InitialOptions} */ module.exports = { displayName: 'react-dummy', preset: '../../jest.preset.js', globals: { 'ts-jest': { tsConfig: '<rootDir>/tsconfig.spec.json', diagnostics: false, }, }, transform: { '^.+\\\\\\\\.tsx?$': 'ts-jest', }, coverageDirectory: './coverage', setupFilesAfterEnv: ['./config/tests.js'], snapshotSerializers: ['@fluentui/jest-serializer-make-styles'], };" `); }); it(`should add 'snapshotSerializers' to jest.config.js only when needed`, async () => { const projectConfig = readProjectConfiguration(tree, options.name); function removePkgDependenciesThatTriggerSnapshotSerializersAddition() { const workspaceConfig = readWorkspaceConfiguration(tree); const packagesThatTriggerAddingSnapshots = [`@${workspaceConfig.npmScope}/react-make-styles`]; updateJson(tree, `${projectConfig.root}/package.json`, (json: PackageJson) => { packagesThatTriggerAddingSnapshots.forEach(pkgName => { delete (json.dependencies ?? {})[pkgName]; }); return json; }); } removePkgDependenciesThatTriggerSnapshotSerializersAddition(); await generator(tree, options); const jestConfig = getProjectJestConfig(projectConfig); expect(jestConfig).not.toContain('snapshotSerializers'); }); it(`should create local ./config/tests.js file if missing that is used for "setupFilesAfterEnv"`, async () => { const projectConfig = readProjectConfiguration(tree, options.name); const jestSetupFilePath = `${projectConfig.root}/config/tests.js`; function getJestSetupFile() { return tree.read(jestSetupFilePath)?.toString('utf-8'); } let content = getJestSetupFile(); expect(content).toMatchInlineSnapshot(` "/** Jest test setup file. */ const { configure } = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); // Configure enzyme. configure({ adapter: new Adapter() });" `); await generator(tree, options); content = getJestSetupFile(); expect(content).toMatchInlineSnapshot(` "/** Jest test setup file. */ const { configure } = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); // Configure enzyme. configure({ adapter: new Adapter() });" `); tree.delete(jestSetupFilePath); expect(tree.exists(jestSetupFilePath)).toBeFalsy(); await generator(tree, options); content = getJestSetupFile(); expect(content).toMatchInlineSnapshot(`"/** Jest test setup file. */"`); }); it(`should add project to root jest.config.js`, async () => { function getJestConfig() { return tree.read(`/jest.config.js`)?.toString('utf-8'); } let jestConfig = getJestConfig(); expect(jestConfig).toMatchInlineSnapshot(` "module.exports = { projects: [] }" `); await generator(tree, options); jestConfig = getJestConfig(); expect(jestConfig).toMatchInlineSnapshot(` "module.exports = { projects: [\\"<rootDir>/packages/react-dummy\\"] }" `); }); }); describe(`storybook updates`, () => { function setup(config: Partial<{ createDummyStories: boolean }> = {}) { const workspaceConfig = readWorkspaceConfiguration(tree); const projectConfig = readProjectConfiguration(tree, options.name); const normalizedProjectName = options.name.replace(`@${workspaceConfig.npmScope}/`, ''); const projectStorybookConfigPath = `${projectConfig.root}/.storybook`; const normalizedProjectNameNamesVariants = names(normalizedProjectName); const paths = { storyOne: `${projectConfig.root}/src/${normalizedProjectNameNamesVariants.className}.stories.tsx`, storyTwo: `${projectConfig.root}/src/${normalizedProjectNameNamesVariants.className}Other.stories.tsx`, tsconfig: { storybook: `${projectStorybookConfigPath}/tsconfig.json`, main: `${projectConfig.root}/tsconfig.json`, lib: `${projectConfig.root}/tsconfig.lib.json`, test: `${projectConfig.root}/tsconfig.spec.json`, }, }; if (config.createDummyStories) { tree.write( paths.storyOne, stripIndents` import * as Implementation from './index'; export const Foo = (props: FooProps) => { return <div>Foo</div>; } `, ); tree.write( paths.storyTwo, stripIndents` import * as Implementation from './index'; export const FooOther = (props: FooPropsOther) => { return <div>FooOther</div>; } `, ); } return { paths, projectConfig, workspaceConfig, normalizedProjectName, projectStorybookConfigPath, }; } it(`should setup package storybook when needed`, async () => { const { projectStorybookConfigPath, paths, projectConfig } = setup({ createDummyStories: true }); addConformanceSetup(tree, projectConfig); expect(tree.exists(projectStorybookConfigPath)).toBeFalsy(); await generator(tree, options); expect(tree.exists(projectStorybookConfigPath)).toBeTruthy(); expect(readJson(tree, paths.tsconfig.storybook)).toEqual({ extends: '../tsconfig.json', compilerOptions: { allowJs: true, checkJs: true, outDir: '', types: ['static-assets', 'environment', 'inline-style-expand-shorthand', 'storybook__addons'], }, include: ['../src/**/*.stories.ts', '../src/**/*.stories.tsx', '*.js'], }); expect(readJson<TsConfig>(tree, paths.tsconfig.lib).exclude).toEqual( expect.arrayContaining(['**/*.stories.ts', '**/*.stories.tsx']), ); expect(readJson<TsConfig>(tree, paths.tsconfig.main).references).toEqual( expect.arrayContaining([ { path: './.storybook/tsconfig.json', }, ]), ); expect(tree.read(`${projectStorybookConfigPath}/main.js`)?.toString('utf-8')).toMatchInlineSnapshot(` "const rootMain = require('../../../.storybook/main'); module.exports = /** @type {Omit<import('../../../.storybook/main'), 'typescript'|'babel'>} */ ({ ...rootMain, stories: [...rootMain.stories, '../src/**/*.stories.mdx', '../src/**/*.stories.@(ts|tsx)'], addons: [...rootMain.addons], webpackFinal: (config, options) => { const localConfig = { ...rootMain.webpackFinal(config, options) }; // add your own webpack tweaks if needed return localConfig; }, });" `); expect(tree.read(`${projectStorybookConfigPath}/preview.js`)?.toString('utf-8')).toMatchInlineSnapshot(` "import * as rootPreview from '../../../.storybook/preview'; /** @type {typeof rootPreview.decorators} */ export const decorators = [...rootPreview.decorators]; /** @type {typeof rootPreview.parameters} */ export const parameters = { ...rootPreview.parameters };" `); }); it(`should remove unused existing storybook setup`, async () => { const { projectStorybookConfigPath, projectConfig, paths } = setup({ createDummyStories: false }); const mainJsFilePath = `${projectStorybookConfigPath}/main.js`; const packageJsonPath = `${projectConfig.root}/package.json`; let pkgJson: PackageJson = readJson(tree, packageJsonPath); tree.write(mainJsFilePath, 'module.exports = {}'); // artificially add storybook scripts updateJson(tree, packageJsonPath, (json: PackageJson) => { json.scripts = json.scripts || {}; Object.assign(json.scripts, { start: 'echo "hello"', storybook: 'echo "hello"', 'build-storybook': 'echo "hello"', }); return json; }); // artificially add storybook to project references updateJson(tree, paths.tsconfig.main, (json: TsConfig) => { json.references = json.references || []; json.references.push({ path: './.storybook/tsconfig.json' }); return json; }); // artificially add stories globs to exclude writeJson<TsConfig>(tree, paths.tsconfig.lib, { compilerOptions: {}, exclude: ['../src/common/**', '**/*.test.ts', '**/*.test.tsx', '**/*.stories.ts', '**/*.stories.tsx'], }); // artificially create spec ts config writeJson<TsConfig>(tree, paths.tsconfig.test, { compilerOptions: {}, include: ['**/*.test.ts', '**/*.test.tsx'], }); pkgJson = readJson(tree, packageJsonPath); expect(tree.exists(projectStorybookConfigPath)).toBeTruthy(); expect(tree.exists(mainJsFilePath)).toBeTruthy(); await generator(tree, options); expect(tree.exists(mainJsFilePath)).toBeFalsy(); expect(Object.keys(pkgJson.scripts || [])).not.toContain(['start', 'storybook', 'build-storybook']); expect(tree.exists(projectStorybookConfigPath)).toBeFalsy(); expect(readJson<TsConfig>(tree, paths.tsconfig.lib).exclude).not.toEqual( expect.arrayContaining(['**/*.stories.ts', '**/*.stories.tsx']), ); expect(readJson<TsConfig>(tree, paths.tsconfig.main).references).not.toEqual( expect.arrayContaining([ { path: './.storybook/tsconfig.json', }, ]), ); }); it(`should remove @ts-ignore pragmas from all stories`, async () => { const { paths } = setup({ createDummyStories: true }); append( tree, paths.storyOne, stripIndents` // https://github.com/microsoft/fluentui/pull/18695#issuecomment-868432982 // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import { Button } from '@fluentui/react-button'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import { Text } from '@fluentui/react-text'; `, ); await generator(tree, options); expect(tree.read(paths.storyOne)?.toString('utf-8')).toMatchInlineSnapshot(` "import * as Implementation from './index'; export const Foo = (props: FooProps) => { return <div>Foo</div>; }\\\\n import { Button } from '@fluentui/react-button'; import { Text } from '@fluentui/react-text';" `); }); }); describe(`e2e config`, () => { function setup(config: { projectName: string }) { const projectConfig = readProjectConfiguration(tree, config.projectName); const paths = { e2eRoot: `${projectConfig.root}/e2e`, packageJson: `${projectConfig.root}/package.json`, tsconfig: { main: `${projectConfig.root}/tsconfig.json`, lib: `${projectConfig.root}/tsconfig.lib.json`, test: `${projectConfig.root}/tsconfig.spec.json`, e2e: `${projectConfig.root}/e2e/tsconfig.json`, }, }; function createE2eSetup() { writeJson<TsConfig>(tree, paths.tsconfig.e2e, { extends: '../../tsconfig.base.json', compilerOptions: {}, }); tree.write( `${paths.e2eRoot}/index.e2e.ts`, stripIndents` describe('E2E test', () => { before(() => { cy.visitStorybook(); }); }); `, ); return tree; } return { projectConfig, paths, createE2eSetup }; } it(`should do nothing if e2e setup is missing`, async () => { const { paths } = setup({ projectName: options.name }); await generator(tree, { name: options.name }); expect(tree.exists(paths.tsconfig.e2e)).toBeFalsy(); }); it(`should setup e2e if present`, async () => { const { paths, createE2eSetup } = setup({ projectName: options.name }); createE2eSetup(); expect(tree.exists(paths.tsconfig.e2e)).toBeTruthy(); await generator(tree, { name: options.name }); // // TS Updates const e2eTsConfig: TsConfig = readJson(tree, paths.tsconfig.e2e); const mainTsConfig: TsConfig = readJson(tree, paths.tsconfig.main); expect(e2eTsConfig).toEqual({ extends: '../tsconfig.json', compilerOptions: { isolatedModules: false, lib: ['ES2019', 'dom'], types: ['node', 'cypress', 'cypress-storybook/cypress', 'cypress-real-events'], }, include: ['**/*.ts'], }); expect(mainTsConfig.references).toEqual(expect.arrayContaining([{ path: './e2e/tsconfig.json' }])); // package.json updates const packageJson: PackageJson = readJson(tree, paths.packageJson); expect(packageJson.scripts).toEqual(expect.objectContaining({ e2e: 'e2e' })); }); }); describe('package.json updates', () => { it(`should update package npm scripts`, async () => { const projectConfig = readProjectConfiguration(tree, options.name); let pkgJson = readJson(tree, `${projectConfig.root}/package.json`); expect(pkgJson.scripts).toMatchInlineSnapshot(` Object { "build": "just-scripts build", "clean": "just-scripts clean", "code-style": "just-scripts code-style", "just": "just-scripts", "lint": "just-scripts lint", "start": "just-scripts dev:storybook", "start-test": "just-scripts jest-watch", "test": "just-scripts test", "test:watch": "just-scripts jest-watch", "update-snapshots": "just-scripts jest -u", } `); await generator(tree, options); pkgJson = readJson(tree, `${projectConfig.root}/package.json`); expect(pkgJson.scripts).toEqual({ docs: 'api-extractor run --config=config/api-extractor.local.json --local', // eslint-disable-next-line @fluentui/max-len 'build:local': `tsc -p ./tsconfig.lib.json --module esnext --emitDeclarationOnly && node ../../scripts/typescript/normalize-import --output ./dist/packages/react-dummy/src && yarn docs`, build: 'just-scripts build', clean: 'just-scripts clean', 'code-style': 'just-scripts code-style', just: 'just-scripts', lint: 'just-scripts lint', start: 'yarn storybook', storybook: 'start-storybook', test: 'jest --passWithNoTests', 'type-check': 'tsc -b tsconfig.json', }); }); it(`should not add start scripts to node packages`, async () => { const nodePackageName = getScopedPkgName(tree, 'babel-make-styles'); const projectConfig = readProjectConfiguration(tree, nodePackageName); let pkgJson = readJson(tree, `${projectConfig.root}/package.json`); expect(pkgJson.scripts).toMatchInlineSnapshot(` Object { "build": "just-scripts build", "clean": "just-scripts clean", "code-style": "just-scripts code-style", "just": "just-scripts", "lint": "just-scripts lint", "start": "just-scripts dev:storybook", "start-test": "just-scripts jest-watch", "test": "just-scripts test", "test:watch": "just-scripts jest-watch", "update-snapshots": "just-scripts jest -u", } `); await generator(tree, { name: nodePackageName, }); pkgJson = readJson(tree, `${projectConfig.root}/package.json`); expect(pkgJson.scripts).toEqual({ build: 'just-scripts build', // eslint-disable-next-line @fluentui/max-len 'build:local': `tsc -p ./tsconfig.lib.json --module esnext --emitDeclarationOnly && node ../../scripts/typescript/normalize-import --output ./dist/packages/babel-make-styles/src && yarn docs`, clean: 'just-scripts clean', 'code-style': 'just-scripts code-style', docs: 'api-extractor run --config=config/api-extractor.local.json --local', just: 'just-scripts', lint: 'just-scripts lint', test: 'jest --passWithNoTests', 'type-check': 'tsc -b tsconfig.json', }); }); it(`should create api-extractor.json`, async () => { const projectConfig = readProjectConfiguration(tree, options.name); expect(tree.exists(`${projectConfig.root}/config/api-extractor.json`)).toBeFalsy(); await generator(tree, options); expect(tree.exists(`${projectConfig.root}/config/api-extractor.json`)).toBeTruthy(); }); it(`should create api-extractor.local.json for scripts:docs task consumption`, async () => { const projectConfig = readProjectConfiguration(tree, options.name); expect(tree.exists(`${projectConfig.root}/config/api-extractor.local.json`)).toBeFalsy(); await generator(tree, options); expect(tree.exists(`${projectConfig.root}/config/api-extractor.local.json`)).toBeTruthy(); }); }); describe(`npm config setup`, () => { it(`should update .npmignore config`, async () => { function getNpmIgnoreConfig(projectConfig: ReadProjectConfiguration) { return tree.read(`${projectConfig.root}/.npmignore`)?.toString('utf-8'); } const projectConfig = readProjectConfiguration(tree, options.name); let npmIgnoreConfig = getNpmIgnoreConfig(projectConfig); expect(npmIgnoreConfig).toMatchInlineSnapshot(` "*.api.json *.config.js *.log *.nuspec *.test.* *.yml .editorconfig .eslintrc* .eslintcache .gitattributes .gitignore .vscode coverage dist/storybook dist/*.stats.html dist/*.stats.json dist/demo fabric-test* gulpfile.js images index.html jsconfig.json node_modules results src/**/* !src/**/examples/*.tsx !src/**/docs/**/*.md !src/**/*.types.ts temp tsconfig.json tsd.json tslint.json typings visualtests" `); await generator(tree, options); npmIgnoreConfig = getNpmIgnoreConfig(projectConfig); expect(npmIgnoreConfig).toMatchInlineSnapshot(` ".storybook/ .vscode/ bundle-size/ config/ coverage/ e2e/ etc/ node_modules/ src/ temp/ __fixtures__ __mocks__ __tests__ *.api.json *.log *.spec.* *.stories.* *.test.* *.yml # config files *config.* *rc.* .editorconfig .eslint* .git* .prettierignore " `); }); }); describe(`babel config setup`, () => { function getBabelConfig(projectConfig: ReadProjectConfiguration) { const babelConfigPath = `${projectConfig.root}/.babelrc.json`; return readJson(tree, babelConfigPath); } function getPackageJson(projectConfig: ReadProjectConfiguration) { const packageJsonPath = `${projectConfig.root}/package.json`; return readJson<PackageJson>(tree, packageJsonPath); } it(`should setup .babelrc.json`, async () => { const babelMakeStylesPkg = getScopedPkgName(tree, 'babel-make-styles'); const projectConfig = readProjectConfiguration(tree, options.name); let packageJson = getPackageJson(projectConfig); let devDeps = packageJson.devDependencies || {}; expect(devDeps[babelMakeStylesPkg]).toBe(undefined); await generator(tree, options); let babelConfig = getBabelConfig(projectConfig); expect(babelConfig).toEqual({ plugins: [ 'module:@fluentui/babel-make-styles', 'annotate-pure-calls', '@babel/transform-react-pure-annotations', ], }); tree.delete(`${projectConfig.root}/.babelrc.json`); await generator(tree, options); babelConfig = getBabelConfig(projectConfig); packageJson = getPackageJson(projectConfig); devDeps = packageJson.devDependencies || {}; expect(babelConfig).toEqual({ plugins: [ 'module:@fluentui/babel-make-styles', 'annotate-pure-calls', '@babel/transform-react-pure-annotations', ], }); expect(devDeps[babelMakeStylesPkg]).toBe('9.0.0-alpha.0'); }); it(`should add @fluentui/babel-make-styles plugin only if needed`, async () => { let projectConfig = readProjectConfiguration(tree, options.name); const babelMakeStylesPkg = getScopedPkgName(tree, 'babel-make-styles'); updateJson(tree, `${projectConfig.root}/package.json`, (json: PackageJson) => { if (json.dependencies) { delete json.dependencies[getScopedPkgName(tree, 'react-make-styles')]; delete json.dependencies[getScopedPkgName(tree, 'make-styles')]; } json.devDependencies = json.devDependencies || {}; json.devDependencies[babelMakeStylesPkg] = '^9.0.0-alpha.0'; return json; }); let babelConfig = getBabelConfig(projectConfig); let packageJson = getPackageJson(projectConfig); let devDeps = packageJson.devDependencies || {}; expect(babelConfig).toEqual({ plugins: [ 'module:@fluentui/babel-make-styles', 'annotate-pure-calls', '@babel/transform-react-pure-annotations', ], }); expect(devDeps[babelMakeStylesPkg]).toBe('^9.0.0-alpha.0'); await generator(tree, options); babelConfig = getBabelConfig(projectConfig); packageJson = getPackageJson(projectConfig); devDeps = packageJson.devDependencies || {}; expect(babelConfig).toEqual({ plugins: ['annotate-pure-calls', '@babel/transform-react-pure-annotations'], }); expect(devDeps[babelMakeStylesPkg]).toBe(undefined); projectConfig = readProjectConfiguration(tree, '@proj/babel-make-styles'); await generator(tree, { name: '@proj/babel-make-styles' }); babelConfig = getBabelConfig(projectConfig); packageJson = getPackageJson(projectConfig); devDeps = packageJson.devDependencies || {}; expect(babelConfig).toEqual({ plugins: ['annotate-pure-calls', '@babel/transform-react-pure-annotations'], }); expect(devDeps[babelMakeStylesPkg]).toBe(undefined); }); }); describe(`nx workspace updates`, () => { it(`should set project 'sourceRoot' in workspace.json`, async () => { let projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.sourceRoot).toBe(undefined); await generator(tree, options); projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.sourceRoot).toBe(`${projectConfig.root}/src`); }); it(`should set project 'vNext' and 'platform:web' tag in nx.json if its a web package`, async () => { let projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.tags).toBe(undefined); await generator(tree, options); projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.tags).toEqual(['vNext', 'platform:web']); }); it(`should set project 'platform:node' tag in nx.json if its a node package`, async () => { let projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.tags).toBe(undefined); updateJson(tree, `${projectConfig.root}/package.json`, (json: PackageJson) => { json.scripts = json.scripts || {}; json.scripts.build = 'just-scripts build --commonjs'; return json; }); await generator(tree, options); projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.tags).toEqual(['vNext', 'platform:node']); }); it(`should update project tags in nx.json if they already exist`, async () => { let projectConfig = readProjectConfiguration(tree, options.name); updateProjectConfiguration(tree, options.name, { ...projectConfig, tags: ['vNext'] }); projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.tags).toEqual(['vNext']); await generator(tree, options); projectConfig = readProjectConfiguration(tree, options.name); expect(projectConfig.tags).toEqual(['vNext', 'platform:web']); }); }); describe(`--stats`, () => { beforeEach(() => { setupDummyPackage(tree, { name: '@proj/react-foo', version: '9.0.22' }); setupDummyPackage(tree, { name: '@proj/react-bar', version: '9.0.31' }); setupDummyPackage(tree, { name: '@proj/react-old', version: '8.1.12' }); setupDummyPackage(tree, { name: '@proj/react-older', version: '8.9.12' }); }); it(`should print project names and count of how many have been migrated`, async () => { const loggerInfoSpy = jest.spyOn(logger, 'info'); await generator(tree, { stats: true }); expect(loggerInfoSpy.mock.calls[5][0]).toEqual(`Not migrated (4):`); expect(loggerInfoSpy.mock.calls[6][0]).toEqual( expect.stringContaining(stripIndents` - @proj/react-dummy - @proj/babel-make-styles - @proj/react-foo - @proj/react-bar `), ); loggerInfoSpy.mockClear(); await generator(tree, options); await generator(tree, { stats: true }); expect(loggerInfoSpy.mock.calls[2][0]).toEqual('Migrated (1):'); expect(loggerInfoSpy.mock.calls[5][0]).toEqual(`Not migrated (3):`); }); }); describe(`--all`, () => { beforeEach(() => { setupDummyPackage(tree, { name: '@proj/react-foo', version: '9.0.22' }); setupDummyPackage(tree, { name: '@proj/react-bar', version: '9.0.31' }); setupDummyPackage(tree, { name: '@proj/react-moo', version: '9.0.12' }); setupDummyPackage(tree, { name: '@proj/react-old', version: '8.0.1' }); }); it(`should run migration on all vNext packages in batch`, async () => { const projects = [ options.name, '@proj/react-foo', '@proj/react-bar', '@proj/react-moo', '@proj/react-old', ] as const; await generator(tree, { all: true }); const configs = projects.reduce((acc, projectName) => { acc[projectName] = readProjectConfiguration(tree, projectName); return acc; }, {} as Record<typeof projects[number], ReadProjectConfiguration>); expect(configs['@proj/react-foo'].sourceRoot).toBeDefined(); expect(configs['@proj/react-bar'].sourceRoot).toBeDefined(); expect(configs['@proj/react-moo'].sourceRoot).toBeDefined(); expect(configs['@proj/react-dummy'].sourceRoot).toBeDefined(); expect(configs['@proj/react-old'].sourceRoot).not.toBeDefined(); }); }); describe(`--name`, () => { it(`should accept comma separated string to exec on multiple projects`, async () => { const projects = [options.name, '@proj/react-one', '@proj/react-two', '@proj/react-old'] as const; setupDummyPackage(tree, { name: projects[1], version: '9.0.22' }); setupDummyPackage(tree, { name: projects[2], version: '9.0.31' }); setupDummyPackage(tree, { name: projects[3], version: '8.0.1' }); await generator(tree, { name: `${projects[0]},${projects[1]}` }); const configs = projects.reduce((acc, projectName) => { acc[projectName] = readProjectConfiguration(tree, projectName); return acc; }, {} as Record<typeof projects[number], ReadProjectConfiguration>); expect(configs[projects[0]].sourceRoot).toBeDefined(); expect(configs[projects[1]].sourceRoot).toBeDefined(); expect(configs[projects[2]].sourceRoot).not.toBeDefined(); expect(configs[projects[3]].sourceRoot).not.toBeDefined(); }); }); }); // ==== helpers ==== function getScopedPkgName(tree: Tree, pkgName: string) { const workspaceConfig = readWorkspaceConfiguration(tree); return `@${workspaceConfig.npmScope}/${pkgName}`; } function setupDummyPackage( tree: Tree, options: AssertedSchema & Partial<{ version: string; dependencies: Record<string, string>; tsConfig: TsConfig; babelConfig: Partial<{ presets: string[]; plugins: string[] }>; projectConfiguration: Partial<ReadProjectConfiguration>; }>, ) { const workspaceConfig = readWorkspaceConfiguration(tree); const defaults = { version: '9.0.0-alpha.40', dependencies: { [`@${workspaceConfig.npmScope}/react-make-styles`]: '^9.0.0-alpha.38', [`@${workspaceConfig.npmScope}/react-theme`]: '^9.0.0-alpha.13', [`@${workspaceConfig.npmScope}/react-utilities`]: '^9.0.0-alpha.25', tslib: '^2.1.0', someThirdPartyDep: '^11.1.2', }, babelConfig: { plugins: ['module:@fluentui/babel-make-styles', 'annotate-pure-calls', '@babel/transform-react-pure-annotations'], }, tsConfig: { compilerOptions: { baseUrl: '.', typeRoots: ['../../node_modules/@types', '../../typings'] } }, }; const normalizedOptions = { ...defaults, ...options }; const pkgName = normalizedOptions.name; const normalizedPkgName = getNormalizedPkgName({ pkgName, workspaceConfig }); const paths = { root: `packages/${normalizedPkgName}`, }; const templates = { packageJson: { name: pkgName, version: normalizedOptions.version, scripts: { build: 'just-scripts build', clean: 'just-scripts clean', 'code-style': 'just-scripts code-style', just: 'just-scripts', lint: 'just-scripts lint', start: 'just-scripts dev:storybook', 'start-test': 'just-scripts jest-watch', test: 'just-scripts test', 'test:watch': 'just-scripts jest-watch', 'update-snapshots': 'just-scripts jest -u', }, dependencies: normalizedOptions.dependencies, }, tsConfig: { ...normalizedOptions.tsConfig, }, jestConfig: stripIndents` const { createConfig } = require('@fluentui/scripts/jest/jest-resources'); const path = require('path'); const config = createConfig({ setupFiles: [path.resolve(path.join(__dirname, 'config', 'tests.js'))], snapshotSerializers: ['@fluentui/jest-serializer-make-styles'], }); module.exports = config; `, jestSetupFile: stripIndents` /** Jest test setup file. */ const { configure } = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); // Configure enzyme. configure({ adapter: new Adapter() }); `, npmConfig: stripIndents` *.api.json *.config.js *.log *.nuspec *.test.* *.yml .editorconfig .eslintrc* .eslintcache .gitattributes .gitignore .vscode coverage dist/storybook dist/*.stats.html dist/*.stats.json dist/demo fabric-test* gulpfile.js images index.html jsconfig.json node_modules results src/**/* !src/**/examples/*.tsx !src/**/docs/**/*.md !src/**/*.types.ts temp tsconfig.json tsd.json tslint.json typings visualtests `, babelConfig: { ...normalizedOptions.babelConfig, }, }; tree.write(`${paths.root}/package.json`, serializeJson(templates.packageJson)); tree.write(`${paths.root}/tsconfig.json`, serializeJson(templates.tsConfig)); tree.write(`${paths.root}/.babelrc.json`, serializeJson(templates.babelConfig)); tree.write(`${paths.root}/jest.config.js`, templates.jestConfig); tree.write(`${paths.root}/config/tests.js`, templates.jestSetupFile); tree.write(`${paths.root}/.npmignore`, templates.npmConfig); tree.write(`${paths.root}/src/index.ts`, `export const greet = 'hello' `); tree.write( `${paths.root}/src/index.test.ts`, ` import {greet} from './index'; describe('test me', () => { it('should greet', () => { expect(greet).toBe('hello'); }); }); `, ); addProjectConfiguration(tree, pkgName, { root: paths.root, projectType: 'library', targets: {}, ...options.projectConfiguration, }); return tree; } function addConformanceSetup(tree: Tree, projectConfig: ReadProjectConfiguration) { tree.write( `${projectConfig.root}/src/common/isConformant.ts`, stripIndents` import { isConformant as baseIsConformant } from '@fluentui/react-conformance'; export function isConformant<TProps = {}>( testInfo: Omit<IsConformantOptions<TProps>, 'componentPath'> & { componentPath?: string } ){} `, ); } function addUnstableSetup(tree: Tree, projectConfig: ReadProjectConfiguration) { const unstableRootPath = `${projectConfig.root}/src/unstable`; writeJson(tree, `${unstableRootPath}/package.json`, { description: 'Separate entrypoint for unstable version', main: '../lib-commonjs/unstable/index.js', module: '../lib/unstable/index.js', typings: '../lib/unstable/index.d.ts', sideEffects: false, license: 'MIT', }); writeJson(tree, `${unstableRootPath}/tsconfig.json`, { extends: '../../tsconfig.json', include: ['index.ts'] }); tree.write( `${unstableRootPath}/index.ts`, stripIndents` // Stub for unstable exports export {} `, ); } function append(tree: Tree, filePath: string, content: string) { if (!tree.exists(filePath)) { throw new Error(`${filePath} doesn't exists`); } tree.write( filePath, stripIndents` ${tree.read(filePath)?.toString('utf-8')}\n ${content} `, ); return tree; } function getNormalizedPkgName(options: { pkgName: string; workspaceConfig: WorkspaceConfiguration }) { return options.pkgName.replace(`@${options.workspaceConfig.npmScope}/`, ''); }
the_stack
import * as React from 'react'; import { observer } from 'mobx-react'; import { FormHelperText, IconButton, InputAdornment, Link, Paper, Table, TableBody, TableCell, TableHead, TableRow, TableSortLabel, TextField, Typography } from '@material-ui/core'; import CloseIcon from '@material-ui/icons/Close'; import { IBackendClient } from '../../services/IBackendClient'; import { DurableOrchestrationStatusFields } from '../../states/DurableOrchestrationStatus'; import { OrchestrationLink } from '../OrchestrationLink'; import { ResultsListTabState } from '../../states/results-view/ResultsListTabState'; import { DfmContextType } from '../../DfmContext'; import { RuntimeStatusToStyle } from '../../theme'; import { DateTimeHelpers } from '../../DateTimeHelpers'; import { LongJsonDialog } from '../dialogs/LongJsonDialog'; import { Theme } from '../../theme'; import { FunnelIcon } from './FunnelIcon'; import { renderFilteredField } from '../RenderHelpers'; // Orchestrations list view @observer export class OrchestrationsList extends React.Component<{ state: ResultsListTabState, showLastEventColumn: boolean, backendClient: IBackendClient }> { static contextType = DfmContextType; context!: React.ContextType<typeof DfmContextType>; render(): JSX.Element { const state = this.props.state; return (<> <FormHelperText className="items-count-label"> {state.orchestrations.length} items shown {!!state.hiddenColumns.length && (<> , {state.hiddenColumns.length} columns hidden (<Link color={Theme.palette.type === 'dark' ? 'inherit' : 'primary'} className="unhide-button" component="button" variant="inherit" onClick={() => state.unhide()} > unhide </Link>) </>)} {!!state.orderBy && (<> , sorted by <strong>{state.orderBy} {state.orderByDirection}</strong> (<Link color={Theme.palette.type === 'dark' ? 'inherit' : 'primary'} className="unhide-button" component="button" variant="inherit" onClick={() => state.resetOrderBy()} > reset </Link>) </>)} {!!state.clientFilteredColumn && (<> , filter <strong>{state.clientFilteredColumn}</strong> with: <TextField className='column-filter-input' autoFocus hiddenLabel variant='outlined' size='small' value={state.clientFilterValue} onChange={(evt) => state.clientFilterValue = evt.target.value as string} onKeyDown={(evt) => { if (evt.key === 'Enter') { // Otherwise the event will bubble up and the form will be submitted evt.preventDefault(); state.applyFilter(); } else if (evt.key === 'Escape') { state.resetFilter(); } }} onBlur={(evt) => { // this check is needed, because otherwise .applyFilter() will overshadow the CloseButton's click if (!evt.relatedTarget) { state.applyFilter(); } }} InputProps={{ endAdornment: <InputAdornment position="end"> <IconButton color="inherit" size="small" onClick={() => state.resetFilter()} > <CloseIcon /> </IconButton> </InputAdornment>, }} /> </>)} </FormHelperText> <Paper elevation={0}> {this.renderTable(state)} </Paper> <LongJsonDialog state={state.longJsonDialogState} /> </>); } private renderTable(state: ResultsListTabState): JSX.Element { if (!state.orchestrations.length) { return ( <Typography variant="h5" className="empty-table-placeholder" > This list is empty </Typography> ); } const visibleColumns = DurableOrchestrationStatusFields // hiding artificial 'lastEvent' column, when not used .filter(f => this.props.showLastEventColumn ? true : f !== 'lastEvent'); return ( <Table size="small"> <TableHead> <TableRow> {visibleColumns.map(col => { const onlyOneVisibleColumnLeft = visibleColumns.length <= state.hiddenColumns.length + 1; return !state.hiddenColumns.includes(col) && ( <TableCell key={col} onMouseEnter={() => state.columnUnderMouse = col} onMouseLeave={() => state.columnUnderMouse = ''} className="instances-list-header-cell" > <TableSortLabel active={state.orderBy === col} direction={state.orderByDirection} onClick={() => state.orderBy = col} > {col} {['createdTime', 'lastUpdatedTime'].includes(col) && (<span className="time-zone-name-span">({this.context.timeZoneName})</span>)} </TableSortLabel> {state.columnUnderMouse === col && (<> <IconButton color="inherit" size="small" className="column-filter-button" onClick={() => state.setClientFilteredColumn(col)} > <FunnelIcon/> </IconButton> {!onlyOneVisibleColumnLeft && ( <IconButton color="inherit" size="small" className="column-hide-button" onClick={() => state.hideColumn(col)} > <CloseIcon className="columnt-filter-button-img" /> </IconButton> )} </>)} </TableCell> ); })} </TableRow> </TableHead> <TableBody> {state.orchestrations.map(orchestration => { const rowStyle = RuntimeStatusToStyle(orchestration.runtimeStatus); const cellStyle = { verticalAlign: 'top' }; return ( <TableRow key={orchestration.instanceId} style={rowStyle} > {!state.hiddenColumns.includes('instanceId') && ( <TableCell className="instance-id-cell" style={cellStyle}> <OrchestrationLink orchestrationId={orchestration.instanceId} backendClient={this.props.backendClient} filterValue={state.clientFilteredColumn === 'instanceId' ? state.clientFilterValue : ''} /> </TableCell> )} {!state.hiddenColumns.includes('name') && ( <TableCell className="name-cell" style={cellStyle}> {renderFilteredField(orchestration.name, state.clientFilteredColumn === 'name' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('createdTime') && ( <TableCell className="datetime-cell" style={cellStyle}> {renderFilteredField(this.context.formatDateTimeString(orchestration.createdTime), state.clientFilteredColumn === 'createdTime' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('lastUpdatedTime') && ( <TableCell className="datetime-cell" style={cellStyle}> {renderFilteredField(this.context.formatDateTimeString(orchestration.lastUpdatedTime), state.clientFilteredColumn === 'lastUpdatedTime' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('duration') && ( <TableCell style={cellStyle}> {renderFilteredField(DateTimeHelpers.formatDuration(orchestration.duration), state.clientFilteredColumn === 'duration' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('runtimeStatus') && ( <TableCell style={cellStyle}> {renderFilteredField(orchestration.runtimeStatus, state.clientFilteredColumn === 'runtimeStatus' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('lastEvent') && this.props.showLastEventColumn && ( <TableCell style={cellStyle}> {renderFilteredField(orchestration.lastEvent, state.clientFilteredColumn === 'lastEvent' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('input') && ( <TableCell className="output-cell" style={cellStyle}> {LongJsonDialog.renderJson(orchestration.input, `${orchestration.instanceId} / input`, state.longJsonDialogState, state.clientFilteredColumn === 'input' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('output') && ( <TableCell className="output-cell" style={cellStyle}> {LongJsonDialog.renderJson(orchestration.output, `${orchestration.instanceId} / output`, state.longJsonDialogState, state.clientFilteredColumn === 'output' ? state.clientFilterValue : '')} </TableCell> )} {!state.hiddenColumns.includes('customStatus') && ( <TableCell className="output-cell" style={cellStyle}> {LongJsonDialog.renderJson(orchestration.customStatus, `${orchestration.instanceId} / customStatus`, state.longJsonDialogState, state.clientFilteredColumn === 'customStatus' ? state.clientFilterValue : '')} </TableCell> )} </TableRow> ); })} </TableBody> </Table> ); } }
the_stack
import { Component, NgZone, ViewEncapsulation } from '@angular/core'; import { ComponentFixture, fakeAsync, flush, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { dispatchFakeEvent, MockNgZone } from 'ng-zorro-antd/core/testing'; import { NzAutosizeDirective } from './autosize.directive'; import { NzInputModule } from './input.module'; describe('autoresize', () => { let zone: MockNgZone; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [NzInputModule, FormsModule, ReactiveFormsModule], declarations: [ NzTestInputWithTextAreaAutoSizeStringComponent, NzTestInputWithTextAreaAutoSizeObjectComponent, NzTestInputWithTextAreaAutoSizeBooleanComponent ], providers: [ { provide: NgZone, useFactory: () => { zone = new MockNgZone(); return zone; } } ] }).compileComponents(); }) ); describe('single input', () => { describe('textarea autosize string', () => { let fixture: ComponentFixture<NzTestInputWithTextAreaAutoSizeStringComponent>; let testComponent: NzTestInputWithTextAreaAutoSizeStringComponent; let textarea: HTMLTextAreaElement; let autosize: NzAutosizeDirective; beforeEach(() => { fixture = TestBed.createComponent(NzTestInputWithTextAreaAutoSizeStringComponent); testComponent = fixture.debugElement.componentInstance; fixture.detectChanges(); textarea = fixture.debugElement.query(By.directive(NzAutosizeDirective)).nativeElement; autosize = fixture.debugElement.query(By.directive(NzAutosizeDirective)).injector.get(NzAutosizeDirective); }); it('should resize the textarea based on its ngModel', fakeAsync(() => { let previousHeight = textarea.clientHeight; testComponent.value = ` Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore— While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. “’Tis some visitor,” I muttered, “tapping at my chamber door— Only this and nothing more.”`; flush(); // Manually call resizeTextArea instead of faking an `input` event. fixture.detectChanges(); flush(); autosize.resizeToFitContent(); zone.simulateZoneExit(); fixture.detectChanges(); expect(textarea.clientHeight).toBeGreaterThan( previousHeight, 'Expected textarea to have grown with added content.' ); expect(textarea.clientHeight).toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); previousHeight = textarea.clientHeight; testComponent.value += ` Ah, distinctly I remember it was in the bleak December; And each separate dying ember wrought its ghost upon the floor. Eagerly I wished the morrow;—vainly I had sought to borrow From my books surcease of sorrow—sorrow for the lost Lenore— For the rare and radiant maiden whom the angels name Lenore— Nameless here for evermore.`; fixture.detectChanges(); flush(); fixture.detectChanges(); autosize.resizeToFitContent(true); zone.simulateZoneExit(); fixture.detectChanges(); expect(textarea.clientHeight).toBeGreaterThan( previousHeight, 'Expected textarea to have grown with added content.' ); expect(textarea.clientHeight).toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); })); it('should trigger a resize when the window is resized', fakeAsync(() => { spyOn(autosize, 'resizeToFitContent'); dispatchFakeEvent(window, 'resize'); tick(16); expect(autosize.resizeToFitContent).toHaveBeenCalled(); })); }); describe('textarea autosize object', () => { let fixture: ComponentFixture<NzTestInputWithTextAreaAutoSizeObjectComponent>; let testComponent: NzTestInputWithTextAreaAutoSizeObjectComponent; let textarea: HTMLTextAreaElement; let autosize: NzAutosizeDirective; beforeEach(() => { fixture = TestBed.createComponent(NzTestInputWithTextAreaAutoSizeObjectComponent); testComponent = fixture.debugElement.componentInstance; fixture.detectChanges(); textarea = fixture.debugElement.query(By.directive(NzAutosizeDirective)).nativeElement; autosize = fixture.debugElement.query(By.directive(NzAutosizeDirective)).injector.get(NzAutosizeDirective); }); it('should set a min-height based on minRows', fakeAsync(() => { autosize.resizeToFitContent(true); fixture.detectChanges(); flush(); fixture.detectChanges(); const previousMinHeight = parseInt(textarea.style.minHeight as string, 10); testComponent.minRows = 6; fixture.detectChanges(); flush(); fixture.detectChanges(); autosize.resizeToFitContent(true); expect(parseInt(textarea.style.minHeight as string, 10)).toBeGreaterThan( previousMinHeight, 'Expected increased min-height with minRows increase.' ); })); it('should set a max-height based on maxRows', fakeAsync(() => { autosize.resizeToFitContent(true); fixture.detectChanges(); flush(); fixture.detectChanges(); const previousMaxHeight = parseInt(textarea.style.maxHeight as string, 10); testComponent.maxRows = 6; fixture.detectChanges(); flush(); fixture.detectChanges(); autosize.resizeToFitContent(true); expect(parseInt(textarea.style.maxHeight as string, 10)).toBeGreaterThan( previousMaxHeight, 'Expected increased max-height with maxRows increase.' ); })); }); describe('textarea autosize boolean', () => { let fixture: ComponentFixture<NzTestInputWithTextAreaAutoSizeBooleanComponent>; let testComponent: NzTestInputWithTextAreaAutoSizeBooleanComponent; let textarea: HTMLTextAreaElement; let autosize: NzAutosizeDirective; beforeEach(() => { fixture = TestBed.createComponent(NzTestInputWithTextAreaAutoSizeBooleanComponent); testComponent = fixture.debugElement.componentInstance; fixture.detectChanges(); textarea = fixture.debugElement.query(By.directive(NzAutosizeDirective)).nativeElement; autosize = fixture.debugElement.query(By.directive(NzAutosizeDirective)).injector.get(NzAutosizeDirective); }); it('should resize the textarea based on its ngModel', fakeAsync(() => { let previousHeight = textarea.clientHeight; testComponent.value = ` Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore— While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. “’Tis some visitor,” I muttered, “tapping at my chamber door— Only this and nothing more.”`; flush(); // Manually call resizeTextArea instead of faking an `input` event. fixture.detectChanges(); flush(); autosize.resizeToFitContent(); zone.simulateZoneExit(); fixture.detectChanges(); expect(textarea.clientHeight).toBeGreaterThan( previousHeight, 'Expected textarea to have grown with added content.' ); expect(textarea.clientHeight).toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); previousHeight = textarea.clientHeight; testComponent.value += ` Ah, distinctly I remember it was in the bleak December; And each separate dying ember wrought its ghost upon the floor. Eagerly I wished the morrow;—vainly I had sought to borrow From my books surcease of sorrow—sorrow for the lost Lenore— For the rare and radiant maiden whom the angels name Lenore— Nameless here for evermore.`; fixture.detectChanges(); flush(); fixture.detectChanges(); autosize.resizeToFitContent(true); zone.simulateZoneExit(); fixture.detectChanges(); expect(textarea.clientHeight).toBeGreaterThan( previousHeight, 'Expected textarea to have grown with added content.' ); expect(textarea.clientHeight).toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); })); it('should trigger a resize when the window is resized', fakeAsync(() => { spyOn(autosize, 'resizeToFitContent'); dispatchFakeEvent(window, 'resize'); tick(16); expect(autosize.resizeToFitContent).toHaveBeenCalled(); })); }); }); }); @Component({ template: ` <textarea nz-input nzAutosize [ngModel]="value"></textarea> `, encapsulation: ViewEncapsulation.None, styles: [ ` textarea.cdk-textarea-autosize-measuring { height: auto !important; overflow: hidden !important; padding: 2px 0 !important; box-sizing: content-box !important; } ` ] }) export class NzTestInputWithTextAreaAutoSizeStringComponent { value = ''; } @Component({ template: ` <textarea nz-input ngModel [nzAutosize]="{ minRows: minRows, maxRows: maxRows }"></textarea> `, encapsulation: ViewEncapsulation.None, styles: [ ` textarea.cdk-textarea-autosize-measuring { height: auto !important; overflow: hidden !important; padding: 2px 0 !important; box-sizing: content-box !important; } ` ] }) export class NzTestInputWithTextAreaAutoSizeObjectComponent { minRows = 2; maxRows = 2; } @Component({ template: ` <textarea nz-input [nzAutosize]="true" [ngModel]="value"></textarea> `, encapsulation: ViewEncapsulation.None, styles: [ ` textarea.cdk-textarea-autosize-measuring { height: auto !important; overflow: hidden !important; padding: 2px 0 !important; box-sizing: content-box !important; } ` ] }) export class NzTestInputWithTextAreaAutoSizeBooleanComponent { value = ''; }
the_stack
import * as test_util from "../test_util"; import { MathTests } from "../test_util"; import * as util from "../util"; // tslint:disable-next-line:max-line-length import { Array1D, Array2D, Array3D, Array4D, DType, NDArray, Scalar } from "./ndarray"; const tests: MathTests = it => { it("NDArrays of arbitrary size", () => { // [1, 2, 3] let t: NDArray = Array1D.new([1, 2, 3]); expect(t instanceof Array1D).toBe(true); expect(t.rank).toBe(1); expect(t.size).toBe(3); test_util.expectArraysClose(t, [1, 2, 3]); // Out of bounds indexing. expect(t.get(4)).toBeUndefined(); // [[1, 2, 3]] t = Array2D.new([1, 3], [1, 2, 3]); expect(t instanceof Array2D).toBe(true); expect(t.rank).toBe(2); expect(t.size).toBe(3); test_util.expectArraysClose(t, [1, 2, 3]); // Out of bounds indexing. expect(t.get(4)).toBeUndefined(); // [[1, 2, 3], // [4, 5, 6]] t = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]); expect(t instanceof Array2D).toBe(true); expect(t.rank).toBe(2); expect(t.size).toBe(6); test_util.expectArraysClose(t, [1, 2, 3, 4, 5, 6]); // Out of bounds indexing. expect(t.get(5, 3)).toBeUndefined(); // Shape mismatch with the values. expect(() => Array2D.new([1, 2], [1])).toThrowError(); }); it("NDArrays of explicit size", () => { const t = Array1D.new([5, 3, 2]); expect(t.rank).toBe(1); expect(t.shape).toEqual([3]); test_util.expectNumbersClose(t.get(1), 3); expect(() => Array4D.new([1, 2, 3, 5], [ 1, 2 ])).toThrowError(); const t4 = Array4D.new([1, 2, 1, 2], [1, 2, 3, 4]); test_util.expectNumbersClose(t4.get(0, 0, 0, 0), 1); test_util.expectNumbersClose(t4.get(0, 0, 0, 1), 2); test_util.expectNumbersClose(t4.get(0, 1, 0, 0), 3); test_util.expectNumbersClose(t4.get(0, 1, 0, 1), 4); const t4Like = NDArray.like(t4); // Change t4. t4.set(10, 0, 0, 0, 1); test_util.expectNumbersClose(t4.get(0, 0, 0, 1), 10); // Make suree t4_like hasn't changed. test_util.expectNumbersClose(t4Like.get(0, 0, 0, 1), 2); // NDArray of ones. const x = Array3D.ones([3, 4, 2]); expect(x.rank).toBe(3); expect(x.size).toBe(24); for (let i = 0; i < 3; i++) { for (let j = 0; j < 4; j++) { for (let k = 0; k < 2; k++) { test_util.expectNumbersClose(x.get(i, j, k), 1); } } } // NDArray of zeros. const z = Array3D.zeros([3, 4, 2]); expect(z.rank).toBe(3); expect(z.size).toBe(24); for (let i = 0; i < 3; i++) { for (let j = 0; j < 4; j++) { for (let k = 0; k < 2; k++) { test_util.expectNumbersClose(z.get(i, j, k), 0); } } } // Reshaping ndarrays. const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]); const b = a.reshape([3, 2, 1]); test_util.expectNumbersClose(a.get(1, 2), 6); // Modify the reshaped ndarray. b.set(10, 2, 1, 0); // Make sure the original ndarray is also modified. test_util.expectNumbersClose(a.get(1, 2), 10); }); it("NDArray dataSync CPU --> GPU", () => { const a = Array2D.new([3, 2], [1, 2, 3, 4, 5, 6]); test_util.expectArraysClose( a.dataSync(), new Float32Array([1, 2, 3, 4, 5, 6])); }); it("NDArray.data() CPU --> GPU", async() => { const a = Array2D.new([3, 2], [1, 2, 3, 4, 5, 6]); test_util.expectArraysClose( await a.data(), new Float32Array([1, 2, 3, 4, 5, 6])); }); it("Scalar basic methods", () => { const a = Scalar.new(5); test_util.expectNumbersClose(a.get(), 5); test_util.expectArraysClose(a, [5]); expect(a.rank).toBe(0); expect(a.size).toBe(1); expect(a.shape).toEqual([]); }); it("index2Loc Array1D", () => { const t = Array1D.zeros([3]); expect(t.indexToLoc(0)).toEqual([0]); expect(t.indexToLoc(1)).toEqual([1]); expect(t.indexToLoc(2)).toEqual([2]); }); it("index2Loc Array2D", () => { const t = Array2D.zeros([3, 2]); expect(t.indexToLoc(0)).toEqual([0, 0]); expect(t.indexToLoc(1)).toEqual([0, 1]); expect(t.indexToLoc(2)).toEqual([1, 0]); expect(t.indexToLoc(3)).toEqual([1, 1]); expect(t.indexToLoc(4)).toEqual([2, 0]); expect(t.indexToLoc(5)).toEqual([2, 1]); }); it("index2Loc Array3D", () => { const t = Array3D.zeros([3, 2, 2]); expect(t.indexToLoc(0)).toEqual([0, 0, 0]); expect(t.indexToLoc(1)).toEqual([0, 0, 1]); expect(t.indexToLoc(2)).toEqual([0, 1, 0]); expect(t.indexToLoc(3)).toEqual([0, 1, 1]); expect(t.indexToLoc(4)).toEqual([1, 0, 0]); expect(t.indexToLoc(5)).toEqual([1, 0, 1]); expect(t.indexToLoc(11)).toEqual([2, 1, 1]); }); it("index2Loc NDArray 5D", () => { const values = new Float32Array([1, 2, 3, 4]); const t = NDArray.make([2, 1, 1, 1, 2], {values}); expect(t.indexToLoc(0)).toEqual([0, 0, 0, 0, 0]); expect(t.indexToLoc(1)).toEqual([0, 0, 0, 0, 1]); expect(t.indexToLoc(2)).toEqual([1, 0, 0, 0, 0]); expect(t.indexToLoc(3)).toEqual([1, 0, 0, 0, 1]); }); it("NDArray<D, X> is assignable to Scalar/ArrayXD", math => { // This test asserts compilation, not doing any run-time assertion. const a: NDArray<"float32", "0"> = null; const b: Scalar<"float32"> = a; expect(b).toBeNull(); const a1: NDArray<"float32", "1"> = null; const b1: Array1D<"float32"> = a1; expect(b1).toBeNull(); const a2: NDArray<"float32", "2"> = null; const b2: Array2D<"float32"> = a2; expect(b2).toBeNull(); const a3: NDArray<"float32", "3"> = null; const b3: Array3D<"float32"> = a3; expect(b3).toBeNull(); const a4: NDArray<"float32", "4"> = null; const b4: Array4D<"float32"> = a4; expect(b4).toBeNull(); }); }; const testsNew: MathTests = it => { it("Array1D.new() from number[]", () => { const a = Array1D.new([1, 2, 3]); test_util.expectArraysClose(a, [1, 2, 3]); }); it("Array1D.new() from number[][], shape mismatch", () => { // tslint:disable-next-line:no-any expect(() => Array1D.new([[1], [2], [3]] as any)).toThrowError(); }); it("Array2D.new() from number[][]", () => { const a = Array2D.new([2, 3], [[1, 2, 3], [4, 5, 6]]); test_util.expectArraysClose(a, [1, 2, 3, 4, 5, 6]); }); it("Array2D.new() from number[][], but shape does not match", () => { // Actual shape is [2, 3]. expect(() => Array2D.new([3, 2], [[1, 2, 3], [4, 5, 6]])).toThrowError(); }); it("Array3D.new() from number[][][]", () => { const a = Array3D.new([2, 3, 1], [[[1], [2], [3]], [[4], [5], [6]]]); test_util.expectArraysClose(a, [1, 2, 3, 4, 5, 6]); }); it("Array3D.new() from number[][][], but shape does not match", () => { const values = [[[1], [2], [3]], [[4], [5], [6]]]; // Actual shape is [2, 3, 1]. expect(() => Array3D.new([3, 2, 1], values)).toThrowError(); }); it("Array4D.new() from number[][][][]", () => { const a = Array4D.new([2, 2, 1, 1], [[[[1]], [[2]]], [[[4]], [[5]]]]); test_util.expectArraysClose(a, [1, 2, 4, 5]); }); it("Array4D.new() from number[][][][], but shape does not match", () => { const f = () => { // Actual shape is [2, 2, 1, 1]. Array4D.new([2, 1, 2, 1], [[[[1]], [[2]]], [[[4]], [[5]]]]); }; expect(f).toThrowError(); }); }; const testsZeros: MathTests = it => { it("1D default dtype", () => { const a = Array1D.zeros([3]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3]); test_util.expectArraysClose(a, [0, 0, 0]); }); it("1D float32 dtype", () => { const a = Array1D.zeros([3], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3]); test_util.expectArraysClose(a, [0, 0, 0]); }); it("1D int32 dtype", () => { const a = Array1D.zeros([3], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [0, 0, 0]); }); it("1D bool dtype", () => { const a = Array1D.zeros([3], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [0, 0, 0]); }); it("1D uint8 dtype", () => { const a = Array1D.zeros([3], "uint8"); expect(a.dtype).toBe("uint8"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [0, 0, 0]); }); it("2D default dtype", () => { const a = Array2D.zeros([3, 2]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysClose(a, [0, 0, 0, 0, 0, 0]); }); it("2D float32 dtype", () => { const a = Array2D.zeros([3, 2], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysClose(a, [0, 0, 0, 0, 0, 0]); }); it("2D int32 dtype", () => { const a = Array2D.zeros([3, 2], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysEqual(a, [0, 0, 0, 0, 0, 0]); }); it("2D bool dtype", () => { const a = Array2D.zeros([3, 2], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysEqual(a, [0, 0, 0, 0, 0, 0]); }); it("3D default dtype", () => { const a = Array3D.zeros([2, 2, 2]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysClose(a, [0, 0, 0, 0, 0, 0, 0, 0]); }); it("3D float32 dtype", () => { const a = Array3D.zeros([2, 2, 2], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysClose(a, [0, 0, 0, 0, 0, 0, 0, 0]); }); it("3D int32 dtype", () => { const a = Array3D.zeros([2, 2, 2], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysEqual(a, [0, 0, 0, 0, 0, 0, 0, 0]); }); it("3D bool dtype", () => { const a = Array3D.zeros([2, 2, 2], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysEqual(a, [0, 0, 0, 0, 0, 0, 0, 0]); }); it("4D default dtype", () => { const a = Array4D.zeros([3, 2, 1, 1]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysClose(a, [0, 0, 0, 0, 0, 0]); }); it("4D float32 dtype", () => { const a = Array4D.zeros([3, 2, 1, 1], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysClose(a, [0, 0, 0, 0, 0, 0]); }); it("4D int32 dtype", () => { const a = Array4D.zeros([3, 2, 1, 1], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysEqual(a, [0, 0, 0, 0, 0, 0]); }); it("4D bool dtype", () => { const a = Array4D.zeros([3, 2, 1, 1], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysEqual(a, [0, 0, 0, 0, 0, 0]); }); }; const testsOnes: MathTests = it => { it("1D default dtype", () => { const a = Array1D.ones([3]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3]); test_util.expectArraysClose(a, [1, 1, 1]); }); it("1D float32 dtype", () => { const a = Array1D.ones([3], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3]); test_util.expectArraysClose(a, [1, 1, 1]); }); it("1D int32 dtype", () => { const a = Array1D.ones([3], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [1, 1, 1]); }); it("1D bool dtype", () => { const a = Array1D.ones([3], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [1, 1, 1]); }); it("2D default dtype", () => { const a = Array2D.ones([3, 2]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysClose(a, [1, 1, 1, 1, 1, 1]); }); it("2D float32 dtype", () => { const a = Array2D.ones([3, 2], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysClose(a, [1, 1, 1, 1, 1, 1]); }); it("2D int32 dtype", () => { const a = Array2D.ones([3, 2], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysEqual(a, [1, 1, 1, 1, 1, 1]); }); it("2D bool dtype", () => { const a = Array2D.ones([3, 2], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysEqual(a, [1, 1, 1, 1, 1, 1]); }); it("3D default dtype", () => { const a = Array3D.ones([2, 2, 2]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysClose(a, [1, 1, 1, 1, 1, 1, 1, 1]); }); it("3D float32 dtype", () => { const a = Array3D.ones([2, 2, 2], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysClose(a, [1, 1, 1, 1, 1, 1, 1, 1]); }); it("3D int32 dtype", () => { const a = Array3D.ones([2, 2, 2], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysEqual(a, [1, 1, 1, 1, 1, 1, 1, 1]); }); it("3D bool dtype", () => { const a = Array3D.ones([2, 2, 2], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([2, 2, 2]); test_util.expectArraysEqual(a, [1, 1, 1, 1, 1, 1, 1, 1]); }); it("4D default dtype", () => { const a = Array4D.ones([3, 2, 1, 1]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysClose(a, [1, 1, 1, 1, 1, 1]); }); it("4D float32 dtype", () => { const a = Array4D.ones([3, 2, 1, 1], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysClose(a, [1, 1, 1, 1, 1, 1]); }); it("4D int32 dtype", () => { const a = Array4D.ones([3, 2, 1, 1], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysEqual(a, [1, 1, 1, 1, 1, 1]); }); it("4D bool dtype", () => { const a = Array4D.ones([3, 2, 1, 1], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([3, 2, 1, 1]); test_util.expectArraysEqual(a, [1, 1, 1, 1, 1, 1]); }); }; const testsZerosLike: MathTests = it => { it("1D default dtype", () => { const a = Array1D.new([1, 2, 3]); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([3]); test_util.expectArraysClose(b, [0, 0, 0]); }); it("1D float32 dtype", () => { const a = Array1D.new([1, 2, 3], "float32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([3]); test_util.expectArraysClose(b, [0, 0, 0]); }); it("1D int32 dtype", () => { const a = Array1D.new([1, 2, 3], "int32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([3]); test_util.expectArraysEqual(b, [0, 0, 0]); }); it("1D bool dtype", () => { const a = Array1D.new([1, 2, 3], "bool"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([3]); test_util.expectArraysEqual(b, [0, 0, 0]); }); it("2D default dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4]); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysClose(b, [0, 0, 0, 0]); }); it("2D float32 dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "float32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysClose(b, [0, 0, 0, 0]); }); it("2D int32 dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "int32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysEqual(b, [0, 0, 0, 0]); }); it("2D bool dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "bool"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysEqual(b, [0, 0, 0, 0]); }); it("3D default dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4]); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(b, [0, 0, 0, 0]); }); it("3D float32 dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "float32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(b, [0, 0, 0, 0]); }); it("3D int32 dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "int32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(b, [0, 0, 0, 0]); }); it("3D bool dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "bool"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(b, [0, 0, 0, 0]); }); it("4D default dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4]); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(b, [0, 0, 0, 0]); }); it("4D float32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "float32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(b, [0, 0, 0, 0]); }); it("4D int32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "int32"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(b, [0, 0, 0, 0]); }); it("4D bool dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "bool"); const b = NDArray.zerosLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(b, [0, 0, 0, 0]); }); }; const testsOnesLike: MathTests = it => { it("1D default dtype", () => { const a = Array1D.new([1, 2, 3]); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([3]); test_util.expectArraysClose(b, [1, 1, 1]); }); it("1D float32 dtype", () => { const a = Array1D.new([1, 2, 3], "float32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([3]); test_util.expectArraysClose(b, [1, 1, 1]); }); it("1D int32 dtype", () => { const a = Array1D.new([1, 2, 3], "int32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([3]); test_util.expectArraysEqual(b, [1, 1, 1]); }); it("1D bool dtype", () => { const a = Array1D.new([1, 2, 3], "bool"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([3]); test_util.expectArraysEqual(b, [1, 1, 1]); }); it("2D default dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4]); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysClose(b, [1, 1, 1, 1]); }); it("2D float32 dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "float32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysClose(b, [1, 1, 1, 1]); }); it("2D int32 dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "int32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); it("2D bool dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "bool"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); it("3D default dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4]); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(b, [1, 1, 1, 1]); }); it("3D float32 dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "float32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(b, [1, 1, 1, 1]); }); it("3D int32 dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "int32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); it("3D bool dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "bool"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); it("4D default dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4]); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(b, [1, 1, 1, 1]); }); it("4D float32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "float32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(b, [1, 1, 1, 1]); }); it("4D int32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "int32"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); it("4D bool dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "bool"); const b = NDArray.onesLike(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); }; const testsFill: MathTests = it => { it("1D fill", () => { const a = Array1D.zeros([3]); a.fill(2); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3]); test_util.expectArraysClose(a, [2, 2, 2]); }); it("2D fill", () => { const a = Array2D.zeros([3, 2]); a.fill(2); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2]); test_util.expectArraysClose(a, [2, 2, 2, 2, 2, 2]); }); it("3D fill", () => { const a = Array3D.zeros([3, 2, 1]); a.fill(2); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2, 1]); test_util.expectArraysClose(a, [2, 2, 2, 2, 2, 2]); }); it("4D fill", () => { const a = Array4D.zeros([3, 2, 1, 2]); a.fill(2); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3, 2, 1, 2]); test_util.expectArraysClose(a, [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]); }); }; const testsLike: MathTests = it => { it("1D default dtype", () => { const a = Array1D.new([1, 2, 3]); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([3]); test_util.expectArraysClose(b, [1, 2, 3]); }); it("1D float32 dtype", () => { const a = Array1D.new([1, 2, 3], "float32"); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([3]); test_util.expectArraysClose(b, [1, 2, 3]); }); it("1D int32 dtype", () => { const a = Array1D.new([1, 2, 3], "int32"); const b = NDArray.like(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([3]); test_util.expectArraysEqual(b, [1, 2, 3]); }); it("1D bool dtype", () => { const a = Array1D.new([1, 2, 3], "bool"); const b = NDArray.like(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([3]); test_util.expectArraysEqual(b, [1, 1, 1]); }); it("2D default dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4]); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysClose(b, [1, 2, 3, 4]); }); it("2D float32 dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "float32"); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysClose(b, [1, 2, 3, 4]); }); it("2D int32 dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "int32"); const b = NDArray.like(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysEqual(b, [1, 2, 3, 4]); }); it("2D bool dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4], "bool"); const b = NDArray.like(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); it("3D default dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4]); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(b, [1, 2, 3, 4]); }); it("3D float32 dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "float32"); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(b, [1, 2, 3, 4]); }); it("3D int32 dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "int32"); const b = NDArray.like(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(b, [1, 2, 3, 4]); }); it("3D bool dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4], "bool"); const b = NDArray.like(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); it("4D default dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4]); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(b, [1, 2, 3, 4]); }); it("4D float32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "float32"); const b = NDArray.like(a); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(b, [1, 2, 3, 4]); }); it("4D int32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "int32"); const b = NDArray.like(a); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(b, [1, 2, 3, 4]); }); it("4D bool dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4], "bool"); const b = NDArray.like(a); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(b, [1, 1, 1, 1]); }); }; const testsScalarNew: MathTests = it => { it("default dtype", () => { const a = Scalar.new(3); expect(a.dtype).toBe("float32"); test_util.expectArraysClose(a, [3]); }); it("float32 dtype", () => { const a = Scalar.new(3, "float32"); expect(a.dtype).toBe("float32"); test_util.expectArraysClose(a, [3]); }); it("int32 dtype", () => { const a = Scalar.new(3, "int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [3]); }); it("int32 dtype, 3.9 => 3, like numpy", () => { const a = Scalar.new(3.9, "int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [3]); }); it("int32 dtype, -3.9 => -3, like numpy", () => { const a = Scalar.new(-3.9, "int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [-3]); }); it("bool dtype, 3 => true, like numpy", () => { const a = Scalar.new(3, "bool"); expect(a.dtype).toBe("bool"); expect(a.get()).toBe(1); }); it("bool dtype, -2 => true, like numpy", () => { const a = Scalar.new(-2, "bool"); expect(a.dtype).toBe("bool"); expect(a.get()).toBe(1); }); it("bool dtype, 0 => false, like numpy", () => { const a = Scalar.new(0, "bool"); expect(a.dtype).toBe("bool"); expect(a.get()).toBe(0); }); it("bool dtype from boolean", () => { const a = Scalar.new(false, "bool"); expect(a.get()).toBe(0); expect(a.dtype).toBe("bool"); const b = Scalar.new(true, "bool"); expect(b.get()).toBe(1); expect(b.dtype).toBe("bool"); }); it("int32 dtype from boolean", () => { const a = Scalar.new(true, "int32"); expect(a.get()).toBe(1); expect(a.dtype).toBe("int32"); }); it("default dtype from boolean", () => { const a = Scalar.new(false); test_util.expectNumbersClose(a.get(), 0); expect(a.dtype).toBe("float32"); }); }; const testsArray1DNew: MathTests = it => { it("default dtype", () => { const a = Array1D.new([1, 2, 3]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3]); test_util.expectArraysClose(a, [1, 2, 3]); }); it("float32 dtype", () => { const a = Array1D.new([1, 2, 3], "float32"); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([3]); test_util.expectArraysClose(a, [1, 2, 3]); }); it("int32 dtype", () => { const a = Array1D.new([1, 2, 3], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [1, 2, 3]); }); it("int32 dtype, non-ints get floored, like numpy", () => { const a = Array1D.new([1.1, 2.5, 3.9], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [1, 2, 3]); }); it("int32 dtype, negative non-ints get ceiled, like numpy", () => { const a = Array1D.new([-1.1, -2.5, -3.9], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([3]); test_util.expectArraysEqual(a, [-1, -2, -3]); }); it("bool dtype, !=0 is truthy, 0 is falsy, like numpy", () => { const a = Array1D.new([1, -2, 0, 3], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([4]); expect(a.get(0)).toBe(1); expect(a.get(1)).toBe(1); expect(a.get(2)).toBe(0); expect(a.get(3)).toBe(1); }); it("default dtype from boolean[]", () => { const a = Array1D.new([false, false, true]); expect(a.dtype).toBe("float32"); test_util.expectArraysClose(a, [0, 0, 1]); }); it("int32 dtype from boolean[]", () => { const a = Array1D.new([false, false, true], "int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [0, 0, 1]); }); it("bool dtype from boolean[]", () => { const a = Array1D.new([false, false, true], "bool"); expect(a.dtype).toBe("bool"); test_util.expectArraysEqual(a, [0, 0, 1]); }); }; const testsArray2DNew: MathTests = it => { it("default dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2]); test_util.expectArraysClose(a, [1, 2, 3, 4]); }); it("float32 dtype", () => { const a = Array2D.new([2, 2], [1, 2, 3, 4]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2]); test_util.expectArraysClose(a, [1, 2, 3, 4]); }); it("int32 dtype", () => { const a = Array2D.new([2, 2], [[1, 2], [3, 4]], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2]); test_util.expectArraysEqual(a, [1, 2, 3, 4]); }); it("int32 dtype, non-ints get floored, like numpy", () => { const a = Array2D.new([2, 2], [1.1, 2.5, 3.9, 4.0], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2]); test_util.expectArraysEqual(a, [1, 2, 3, 4]); }); it("int32 dtype, negative non-ints get ceiled, like numpy", () => { const a = Array2D.new([2, 2], [-1.1, -2.5, -3.9, -4.0], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2]); test_util.expectArraysEqual(a, [-1, -2, -3, -4]); }); it("bool dtype, !=0 is truthy, 0 is falsy, like numpy", () => { const a = Array2D.new([2, 2], [1, -2, 0, 3], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([2, 2]); expect(a.get(0, 0)).toBe(1); expect(a.get(0, 1)).toBe(1); expect(a.get(1, 0)).toBe(0); expect(a.get(1, 1)).toBe(1); }); it("default dtype from boolean[]", () => { const a = Array2D.new([2, 2], [[false, false], [true, false]]); expect(a.dtype).toBe("float32"); test_util.expectArraysClose(a, [0, 0, 1, 0]); }); it("int32 dtype from boolean[]", () => { const a = Array2D.new([2, 2], [[false, false], [true, false]], "int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [0, 0, 1, 0]); }); it("bool dtype from boolean[]", () => { const a = Array2D.new([2, 2], [[false, false], [true, false]], "bool"); expect(a.dtype).toBe("bool"); test_util.expectArraysEqual(a, [0, 0, 1, 0]); }); }; const testsArray3DNew: MathTests = it => { it("default dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(a, [1, 2, 3, 4]); }); it("float32 dtype", () => { const a = Array3D.new([2, 2, 1], [1, 2, 3, 4]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 1]); test_util.expectArraysClose(a, [1, 2, 3, 4]); }); it("int32 dtype", () => { const a = Array3D.new([2, 2, 1], [[[1], [2]], [[3], [4]]], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(a, [1, 2, 3, 4]); }); it("int32 dtype, non-ints get floored, like numpy", () => { const a = Array3D.new([2, 2, 1], [1.1, 2.5, 3.9, 4.0], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(a, [1, 2, 3, 4]); }); it("int32 dtype, negative non-ints get ceiled, like numpy", () => { const a = Array3D.new([2, 2, 1], [-1.1, -2.5, -3.9, -4.0], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 1]); test_util.expectArraysEqual(a, [-1, -2, -3, -4]); }); it("bool dtype, !=0 is truthy, 0 is falsy, like numpy", () => { const a = Array3D.new([2, 2, 1], [1, -2, 0, 3], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([2, 2, 1]); expect(a.get(0, 0, 0)).toBe(1); expect(a.get(0, 1, 0)).toBe(1); expect(a.get(1, 0, 0)).toBe(0); expect(a.get(1, 1, 0)).toBe(1); }); it("default dtype from boolean[]", () => { const a = Array3D.new([2, 2, 1], [[[false], [false]], [[true], [false]]]); expect(a.dtype).toBe("float32"); test_util.expectArraysClose(a, [0, 0, 1, 0]); }); it("int32 dtype from boolean[]", () => { const a = Array3D.new( [2, 2, 1], [[[false], [false]], [[true], [false]]], "int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [0, 0, 1, 0]); }); it("bool dtype from boolean[]", () => { const a = Array3D.new([2, 2, 1], [[[false], [false]], [[true], [false]]], "bool"); expect(a.dtype).toBe("bool"); test_util.expectArraysEqual(a, [0, 0, 1, 0]); }); }; const testsArray4DNew: MathTests = it => { it("default dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(a, [1, 2, 3, 4]); }); it("float32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [1, 2, 3, 4]); expect(a.dtype).toBe("float32"); expect(a.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysClose(a, [1, 2, 3, 4]); }); it("int32 dtype", () => { const a = Array4D.new([2, 2, 1, 1], [[[[1]], [[2]]], [[[3]], [[4]]]], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(a, [1, 2, 3, 4]); }); it("int32 dtype, non-ints get floored, like numpy", () => { const a = Array4D.new([2, 2, 1, 1], [1.1, 2.5, 3.9, 4.0], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(a, [1, 2, 3, 4]); }); it("int32 dtype, negative non-ints get ceiled, like numpy", () => { const a = Array4D.new([2, 2, 1, 1], [-1.1, -2.5, -3.9, -4.0], "int32"); expect(a.dtype).toBe("int32"); expect(a.shape).toEqual([2, 2, 1, 1]); test_util.expectArraysEqual(a, [-1, -2, -3, -4]); }); it("bool dtype, !=0 is truthy, 0 is falsy, like numpy", () => { const a = Array4D.new([2, 2, 1, 1], [1, -2, 0, 3], "bool"); expect(a.dtype).toBe("bool"); expect(a.shape).toEqual([2, 2, 1, 1]); expect(a.get(0, 0, 0, 0)).toBe(1); expect(a.get(0, 1, 0, 0)).toBe(1); expect(a.get(1, 0, 0, 0)).toBe(0); expect(a.get(1, 1, 0, 0)).toBe(1); }); it("default dtype from boolean[]", () => { const a = Array4D.new([1, 2, 2, 1], [[[[false], [false]], [[true], [false]]]]); expect(a.dtype).toBe("float32"); test_util.expectArraysClose(a, [0, 0, 1, 0]); }); it("int32 dtype from boolean[]", () => { const a = Array4D.new( [1, 2, 2, 1], [[[[false], [false]], [[true], [false]]]], "int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [0, 0, 1, 0]); }); it("bool dtype from boolean[]", () => { const a = Array4D.new( [1, 2, 2, 1], [[[[false], [false]], [[true], [false]]]], "bool"); expect(a.dtype).toBe("bool"); test_util.expectArraysEqual(a, [0, 0, 1, 0]); }); }; const testsReshape: MathTests = it => { it("Scalar default dtype", () => { const a = Scalar.new(4); const b = a.reshape([1, 1]); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([1, 1]); }); it("Scalar bool dtype", () => { const a = Scalar.new(4, "bool"); const b = a.reshape([1, 1, 1]); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([1, 1, 1]); }); it("Array1D default dtype", () => { const a = Array1D.new([1, 2, 3, 4]); const b = a.reshape([2, 2]); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); }); it("Array1D int32 dtype", () => { const a = Array1D.new([1, 2, 3, 4], "int32"); const b = a.reshape([2, 2]); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([2, 2]); }); it("Array2D default dtype", () => { const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]); const b = a.reshape([6]); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([6]); }); it("Array2D bool dtype", () => { const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6], "bool"); const b = a.reshape([6]); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([6]); }); it("Array3D default dtype", () => { const a = Array3D.new([2, 3, 1], [1, 2, 3, 4, 5, 6]); const b = a.reshape([6]); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([6]); }); it("Array3D bool dtype", () => { const a = Array3D.new([2, 3, 1], [1, 2, 3, 4, 5, 6], "bool"); const b = a.reshape([6]); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([6]); }); it("Array4D default dtype", () => { const a = Array4D.new([2, 3, 1, 1], [1, 2, 3, 4, 5, 6]); const b = a.reshape([2, 3]); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 3]); }); it("Array4D int32 dtype", () => { const a = Array4D.new([2, 3, 1, 1], [1, 2, 3, 4, 5, 6], "int32"); const b = a.reshape([3, 2]); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([3, 2]); }); it("reshape is functional", math => { const a = Scalar.new(2.4); const b = a.reshape([]); expect(a.id).not.toBe(b.id); b.dispose(); test_util.expectArraysClose(a, [2.4]); }); }; const testsAsType: MathTests = it => { it("scalar bool -> int32", () => { const a = Scalar.new(true, "bool").asType("int32"); expect(a.dtype).toBe("int32"); expect(a.get()).toBe(1); }); it("asType uint8", math => { const a = Scalar.new(2.4); const b = a.asType("uint8"); expect(b.dtype).toEqual("uint8"); test_util.expectArraysClose(b, [2]); }); it("array1d float32 -> int32", () => { const a = Array1D.new([1.1, 3.9, -2.9, 0]).asType("int32"); expect(a.dtype).toBe("int32"); test_util.expectArraysEqual(a, [1, 3, -2, 0]); }); it("array2d float32 -> bool", () => { const a = Array2D.new([2, 2], [1.1, 3.9, -2.9, 0]).asType(DType.bool); expect(a.dtype).toBe("bool"); expect(a.get(0, 0)).toBe(1); expect(a.get(0, 1)).toBe(1); expect(a.get(1, 0)).toBe(1); expect(a.get(1, 1)).toBe(0); }); it("array2d int32 -> bool", () => { const a = Array2D.new([2, 2], [1, 3, 0, -1], "int32").asType("bool"); expect(a.dtype).toBe("bool"); expect(a.get(0, 0)).toBe(1); expect(a.get(0, 1)).toBe(1); expect(a.get(1, 0)).toBe(0); expect(a.get(1, 1)).toBe(1); }); it("array3d bool -> float32", () => { const a = Array3D.new([2, 2, 1], [true, false, false, true], "bool") .asType("float32"); expect(a.dtype).toBe("float32"); test_util.expectArraysClose(a, [1, 0, 0, 1]); }); it("bool CPU -> GPU -> CPU", () => { const a = Array1D.new([1, 2, 0, 0, 5], "bool"); test_util.expectArraysEqual(a, [1, 1, 0, 0, 1]); }); it("int32 CPU -> GPU -> CPU", () => { const a = Array1D.new([1, 2, 0, 0, 5], "int32"); test_util.expectArraysEqual(a, [1, 2, 0, 0, 5]); }); it("asType is functional", math => { const a = Scalar.new(2.4, "float32"); const b = a.asType("float32"); expect(a.id).not.toBe(b.id); b.dispose(); test_util.expectArraysClose(a, [2.4]); }); }; const testsAsXD: MathTests = it => { it("scalar -> 2d", () => { const a = Scalar.new(4, "int32"); const b = a.as2D(1, 1); expect(b.dtype).toBe("int32"); expect(b.shape).toEqual([1, 1]); }); it("1d -> 2d", () => { const a = Array1D.new([4, 2, 1], "bool"); const b = a.as2D(3, 1); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([3, 1]); }); it("2d -> 4d", () => { const a = Array2D.new([2, 2], [4, 2, 1, 3]); const b = a.as4D(1, 1, 2, 2); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([1, 1, 2, 2]); }); it("3d -> 2d", () => { const a = Array3D.new([2, 2, 1], [4, 2, 1, 3], "float32"); const b = a.as2D(2, 2); expect(b.dtype).toBe("float32"); expect(b.shape).toEqual([2, 2]); }); it("4d -> 1d", () => { const a = Array4D.new([2, 2, 1, 1], [4, 2, 1, 3], "bool"); const b = a.as1D(); expect(b.dtype).toBe("bool"); expect(b.shape).toEqual([4]); }); }; const testsRand: MathTests = it => { it("should return a random 1D float32 array", () => { const shape: [number] = [10]; // Enusre defaults to float32 w/o type: let result = NDArray.rand(shape, () => util.randUniform(0, 2)); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2); result = NDArray.rand(shape, () => util.randUniform(0, 1.5)); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 1D int32 array", () => { const shape: [number] = [10]; const result = NDArray.rand(shape, () => util.randUniform(0, 2), "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 1D bool array", () => { const shape: [number] = [10]; const result = NDArray.rand(shape, () => util.randUniform(0, 1), "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); it("should return a random 2D float32 array", () => { const shape: number[] = [3, 4]; // Enusre defaults to float32 w/o type: let result = NDArray.rand(shape, () => util.randUniform(0, 2.5)); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2.5); result = NDArray.rand(shape, () => util.randUniform(0, 1.5), "float32"); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 2D int32 array", () => { const shape: number[] = [3, 4]; const result = NDArray.rand(shape, () => util.randUniform(0, 2), "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 2D bool array", () => { const shape: number[] = [3, 4]; const result = NDArray.rand(shape, () => util.randUniform(0, 1), "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); it("should return a random 3D float32 array", () => { const shape: number[] = [3, 4, 5]; // Enusre defaults to float32 w/o type: let result = NDArray.rand(shape, () => util.randUniform(0, 2.5)); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2.5); result = NDArray.rand(shape, () => util.randUniform(0, 1.5), "float32"); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 3D int32 array", () => { const shape: number[] = [3, 4, 5]; const result = NDArray.rand(shape, () => util.randUniform(0, 2), "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 3D bool array", () => { const shape: number[] = [3, 4, 5]; const result = NDArray.rand(shape, () => util.randUniform(0, 1), "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); it("should return a random 4D float32 array", () => { const shape: number[] = [3, 4, 5, 6]; // Enusre defaults to float32 w/o type: let result = NDArray.rand(shape, () => util.randUniform(0, 2.5)); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2.5); result = NDArray.rand(shape, () => util.randUniform(0, 1.5)); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 4D int32 array", () => { const shape: number[] = [3, 4, 5, 6]; const result = NDArray.rand(shape, () => util.randUniform(0, 2), "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 4D bool array", () => { const shape: number[] = [3, 4, 5, 6]; const result = NDArray.rand(shape, () => util.randUniform(0, 1), "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); }; const testsRandNormal: MathTests = it => { const SEED = 2002; const EPSILON = 0.05; it("should return a float32 1D of random normal values", () => { const SAMPLES = 10000; // Ensure defaults to float32. let result = NDArray.randNormal([SAMPLES], 0, 0.5, null, SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 0.5, EPSILON); result = NDArray.randNormal([SAMPLES], 0, 1.5, "float32", SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 1.5, EPSILON); }); it("should return a int32 1D of random normal values", () => { const SAMPLES = 10000; const result = NDArray.randNormal([SAMPLES], 0, 2, "int32", SEED); expect(result.dtype).toBe("int32"); expect(result.shape).toEqual([SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 2, EPSILON); }); it("should return a float32 2D of random normal values", () => { const SAMPLES = 250; // Ensure defaults to float32. let result = Array2D.randNormal([SAMPLES, SAMPLES], 0, 2.5, null, SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 2.5, EPSILON); result = Array2D.randNormal([SAMPLES, SAMPLES], 0, 3.5, "float32", SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 3.5, EPSILON); }); it("should return a int32 2D of random normal values", () => { const SAMPLES = 100; const result = Array2D.randNormal([SAMPLES, SAMPLES], 0, 2, "int32", SEED); expect(result.dtype).toBe("int32"); expect(result.shape).toEqual([SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 2, EPSILON); }); it("should return a float32 3D of random normal values", () => { const SAMPLES = 50; // Ensure defaults to float32. let result = Array3D.randNormal([SAMPLES, SAMPLES, SAMPLES], 0, 0.5, null, SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES, SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 0.5, EPSILON); result = Array3D.randNormal( [SAMPLES, SAMPLES, SAMPLES], 0, 1.5, "float32", SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES, SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 1.5, EPSILON); }); it("should return a int32 3D of random normal values", () => { const SAMPLES = 50; const result = Array3D.randNormal([SAMPLES, SAMPLES, SAMPLES], 0, 2, "int32", SEED); expect(result.dtype).toBe("int32"); expect(result.shape).toEqual([SAMPLES, SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 2, EPSILON); }); it("should return a float32 4D of random normal values", () => { const SAMPLES = 25; // Ensure defaults to float32. let result = Array4D.randNormal( [SAMPLES, SAMPLES, SAMPLES, SAMPLES], 0, 0.5, null, SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES, SAMPLES, SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 0.5, EPSILON); result = Array4D.randNormal( [SAMPLES, SAMPLES, SAMPLES, SAMPLES], 0, 1.5, "float32", SEED); expect(result.dtype).toBe("float32"); expect(result.shape).toEqual([SAMPLES, SAMPLES, SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 1.5, EPSILON); }); it("should return a int32 4D of random normal values", () => { const SAMPLES = 25; const result = Array4D.randNormal( [SAMPLES, SAMPLES, SAMPLES, SAMPLES], 0, 2, "int32", SEED); expect(result.dtype).toBe("int32"); expect(result.shape).toEqual([SAMPLES, SAMPLES, SAMPLES, SAMPLES]); test_util.jarqueBeraNormalityTest(result); test_util.expectArrayInMeanStdRange(result, 0, 2, EPSILON); }); }; const testsRandTruncNormal: MathTests = it => { // Expect slightly higher variances for truncated values. const EPSILON = 0.60; const SEED = 2002; function assertTruncatedValues(array: NDArray, mean: number, stdv: number) { const bounds = mean + stdv * 2; const values = array.dataSync(); for (let i = 0; i < values.length; i++) { expect(Math.abs(values[i])).toBeLessThanOrEqual(bounds); } } it("should return a random 1D float32 array", () => { const shape: [number] = [1000]; // Ensure defaults to float32 w/o type: let result = NDArray.randTruncatedNormal(shape, 0, 3.5, null, SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 3.5); test_util.expectArrayInMeanStdRange(result, 0, 3.5, EPSILON); result = NDArray.randTruncatedNormal(shape, 0, 4.5, "float32", SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 4.5); test_util.expectArrayInMeanStdRange(result, 0, 4.5, EPSILON); }); it("should return a randon 1D int32 array", () => { const shape: [number] = [1000]; const result = NDArray.randTruncatedNormal(shape, 0, 5, "int32", SEED); expect(result.dtype).toBe("int32"); assertTruncatedValues(result, 0, 5); test_util.expectArrayInMeanStdRange(result, 0, 5, EPSILON); }); it("should return a 2D float32 array", () => { const shape: [number, number] = [50, 50]; // Ensure defaults to float32 w/o type: let result = Array2D.randTruncatedNormal(shape, 0, 3.5, null, SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 3.5); test_util.expectArrayInMeanStdRange(result, 0, 3.5, EPSILON); result = Array2D.randTruncatedNormal(shape, 0, 4.5, "float32", SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 4.5); test_util.expectArrayInMeanStdRange(result, 0, 4.5, EPSILON); }); it("should return a 2D int32 array KREEGER", () => { const shape: [number, number] = [50, 50]; const result = Array2D.randTruncatedNormal(shape, 0, 5, "int32", SEED); expect(result.dtype).toBe("int32"); assertTruncatedValues(result, 0, 5); test_util.expectArrayInMeanStdRange(result, 0, 5, EPSILON); }); it("should return a 3D float32 array", () => { const shape: [number, number, number] = [10, 10, 10]; // Ensure defaults to float32 w/o type: let result = Array3D.randTruncatedNormal(shape, 0, 3.5, null, SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 3.5); test_util.expectArrayInMeanStdRange(result, 0, 3.5, EPSILON); result = Array3D.randTruncatedNormal(shape, 0, 4.5, "float32", SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 4.5); test_util.expectArrayInMeanStdRange(result, 0, 4.5, EPSILON); }); it("should return a 3D int32 array", () => { const shape: [number, number, number] = [10, 10, 10]; const result = Array3D.randTruncatedNormal(shape, 0, 5, "int32", SEED); expect(result.dtype).toBe("int32"); assertTruncatedValues(result, 0, 5); test_util.expectArrayInMeanStdRange(result, 0, 5, EPSILON); }); it("should return a 4D float32 array", () => { const shape: [number, number, number, number] = [5, 5, 5, 5]; // Ensure defaults to float32 w/o type: let result = Array4D.randTruncatedNormal(shape, 0, 3.5, null, SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 3.5); test_util.expectArrayInMeanStdRange(result, 0, 3.5, EPSILON); result = Array4D.randTruncatedNormal(shape, 0, 4.5, "float32", SEED); expect(result.dtype).toBe("float32"); assertTruncatedValues(result, 0, 4.5); test_util.expectArrayInMeanStdRange(result, 0, 4.5, EPSILON); }); it("should return a 4D int32 array", () => { const shape: [number, number, number, number] = [5, 5, 5, 5]; const result = Array4D.randTruncatedNormal(shape, 0, 5, "int32", SEED); expect(result.dtype).toBe("int32"); assertTruncatedValues(result, 0, 5); test_util.expectArrayInMeanStdRange(result, 0, 5, EPSILON); }); }; const testsRandUniform: MathTests = it => { it("should return a random 1D float32 array", () => { const shape: [number] = [10]; // Enusre defaults to float32 w/o type: let result = NDArray.randUniform(shape, 0, 2.5); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2.5); result = NDArray.randUniform(shape, 0, 1.5, "float32"); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 1D int32 array", () => { const shape: [number] = [10]; const result = NDArray.randUniform(shape, 0, 2, "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 1D bool array", () => { const shape: [number] = [10]; const result = NDArray.randUniform(shape, 0, 1, "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); it("should return a random 2D float32 array", () => { const shape: [number, number] = [3, 4]; // Enusre defaults to float32 w/o type: let result = Array2D.randUniform(shape, 0, 2.5); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2.5); result = Array2D.randUniform(shape, 0, 1.5, "float32"); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 2D int32 array", () => { const shape: [number, number] = [3, 4]; const result = Array2D.randUniform(shape, 0, 2, "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 2D bool array", () => { const shape: [number, number] = [3, 4]; const result = Array2D.randUniform(shape, 0, 1, "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); it("should return a random 3D float32 array", () => { const shape: [number, number, number] = [3, 4, 5]; // Enusre defaults to float32 w/o type: let result = Array3D.randUniform(shape, 0, 2.5); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2.5); result = Array3D.randUniform(shape, 0, 1.5, "float32"); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 3D int32 array", () => { const shape: [number, number, number] = [3, 4, 5]; const result = Array3D.randUniform(shape, 0, 2, "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 3D bool array", () => { const shape: [number, number, number] = [3, 4, 5]; const result = Array3D.randUniform(shape, 0, 1, "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); it("should return a random 4D float32 array", () => { const shape: [number, number, number, number] = [3, 4, 5, 6]; // Enusre defaults to float32 w/o type: let result = Array4D.randUniform(shape, 0, 2.5); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 2.5); result = Array4D.randUniform(shape, 0, 1.5, "float32"); expect(result.dtype).toBe("float32"); test_util.expectValuesInRange(result, 0, 1.5); }); it("should return a random 4D int32 array", () => { const shape: [number, number, number, number] = [3, 4, 5, 6]; const result = Array4D.randUniform(shape, 0, 2, "int32"); expect(result.dtype).toBe("int32"); test_util.expectValuesInRange(result, 0, 2); }); it("should return a random 4D bool array", () => { const shape: [number, number, number, number] = [3, 4, 5, 6]; const result = Array4D.randUniform(shape, 0, 1, "bool"); expect(result.dtype).toBe("bool"); test_util.expectValuesInRange(result, 0, 1); }); }; const testsFromPixels: MathTests = it => { beforeEach(() => {}); afterEach(() => {}); it("ImageData 1x1x3", () => { const pixels = new ImageData(1, 1); pixels.data[0] = 0; pixels.data[1] = 80; pixels.data[2] = 160; pixels.data[3] = 240; const array = Array3D.fromPixels(pixels, 3); test_util.expectArraysEqual(array, [0, 80, 160]); }); it("ImageData 1x1x4", () => { const pixels = new ImageData(1, 1); pixels.data[0] = 0; pixels.data[1] = 80; pixels.data[2] = 160; pixels.data[3] = 240; const array = Array3D.fromPixels(pixels, 4); test_util.expectArraysEqual(array, [0, 80, 160, 240]); }); it("ImageData 2x2x3", () => { const pixels = new ImageData(2, 2); for (let i = 0; i < 8; i++) { pixels.data[i] = i * 2; } for (let i = 8; i < 16; i++) { pixels.data[i] = i * 2; } const array = Array3D.fromPixels(pixels, 3); test_util.expectArraysEqual( array, [0, 2, 4, 8, 10, 12, 16, 18, 20, 24, 26, 28]); }); it("ImageData 2x2x4", () => { const pixels = new ImageData(2, 2); for (let i = 0; i < 8; i++) { pixels.data[i] = i * 2; } for (let i = 8; i < 16; i++) { pixels.data[i] = i * 2; } const array = Array3D.fromPixels(pixels, 4); test_util.expectArraysClose( array, new Int32Array( [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30])); }); }; const allTests = [ tests, testsNew, testsZeros, testsOnes, testsZerosLike, testsOnesLike, testsFill, testsLike, testsScalarNew, testsArray1DNew, testsArray2DNew, testsArray3DNew, testsArray4DNew, testsReshape, testsAsType, testsAsXD, testsRand, testsRandNormal, testsRandTruncNormal, testsRandUniform, testsFromPixels ]; test_util.describeMathCPU("NDArray", allTests); test_util.describeMathGPU("NDArray", allTests, [ {"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true}, {"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true}, {"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false} ]);
the_stack
import { SharePointQueryable, SharePointQueryableCollection, SharePointQueryableInstance } from "./sharepointqueryable"; import { SharePointQueryableShareableItem } from "./sharepointqueryableshareable"; import { Folder } from "./folders"; import { File } from "./files"; import { ContentType } from "./contenttypes"; import { TypedHash } from "../collections/collections"; import { Util } from "../utils/util"; import { ListItemFormUpdateValue } from "./types"; import { ODataParserBase } from "../odata/core"; import { AttachmentFiles } from "./attachmentfiles"; import { List } from "./lists"; import { Logger, LogLevel } from "../pnp"; /** * Describes a collection of Item objects * */ export class Items extends SharePointQueryableCollection { /** * Creates a new instance of the Items class * * @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection */ constructor(baseUrl: string | SharePointQueryable, path = "items") { super(baseUrl, path); } /** * Gets an Item by id * * @param id The integer id of the item to retrieve */ public getById(id: number): Item { const i = new Item(this); i.concat(`(${id})`); return i; } /** * Gets BCS Item by string id * * @param stringId The string id of the BCS item to retrieve */ public getItemByStringId(stringId: string): Item { const i = new Item(this); i.concat(`/../getItemByStringId('${stringId}')`); return i; } /** * Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6) * * @param skip The starting id where the page should start, use with top to specify pages * @param reverse It true the PagedPrev=true parameter is added allowing backwards navigation in the collection */ public skip(skip: number, reverse = false): this { if (reverse) { this._query.add("$skiptoken", encodeURIComponent(`Paged=TRUE&PagedPrev=TRUE&p_ID=${skip}`)); } else { this._query.add("$skiptoken", encodeURIComponent(`Paged=TRUE&p_ID=${skip}`)); } return this; } /** * Gets a collection designed to aid in paging through data * */ public getPaged(): Promise<PagedItemCollection<any>> { return this.getAs(new PagedItemCollectionParser()); } /** * Gets all the items in a list, regardless of count. Does not support batching or caching * * @param requestSize Number of items to return in each request (Default: 2000) */ public getAll(requestSize = 2000): Promise<any[]> { Logger.write("Calling items.getAll should be done sparingly. Ensure this is the correct choice. If you are unsure, it is not.", LogLevel.Warning); // this will be used for the actual query // and we set no metadata here to try and reduce traffic const items = new Items(this, "").top(requestSize).configure({ headers: { "Accept": "application/json;odata=nometadata", }, }); // let's copy over the odata query params that can be applied // $top - allow setting the page size this way (override what we did above) // $select - allow picking the return fields (good behavior) // $filter - allow setting a filter, though this may fail for large lists this.query.getKeys() .filter(k => /^\$select$|^\$filter$|^\$top$|^\$expand$/.test(k.toLowerCase())) .reduce((i, k) => { i.query.add(k, this.query.get(k)); return i; }, items); // give back the promise return new Promise((resolve, reject) => { // this will eventually hold the items we return const itemsCollector: any[] = []; // action that will gather up our results recursively const gatherer = (last: PagedItemCollection<any>) => { // collect that set of results [].push.apply(itemsCollector, last.results); // if we have more, repeat - otherwise resolve with the collected items if (last.hasNext) { last.getNext().then(gatherer).catch(reject); } else { resolve(itemsCollector); } }; // start the cycle items.getPaged().then(gatherer).catch(reject); }); } /** * Adds a new item to the collection * * @param properties The new items's properties */ public add(properties: TypedHash<any> = {}, listItemEntityTypeFullName: string = null): Promise<ItemAddResult> { const removeDependency = this.addBatchDependency(); return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(listItemEntityType => { const postBody = JSON.stringify(Util.extend({ "__metadata": { "type": listItemEntityType }, }, properties)); const promise = this.clone(Items, null).postAsCore<{ Id: number }>({ body: postBody }).then((data) => { return { data: data, item: this.getById(data.Id), }; }); removeDependency(); return promise; }); } /** * Ensures we have the proper list item entity type name, either from the value provided or from the list * * @param candidatelistItemEntityTypeFullName The potential type name */ private ensureListItemEntityTypeName(candidatelistItemEntityTypeFullName: string): Promise<string> { return candidatelistItemEntityTypeFullName ? Promise.resolve(candidatelistItemEntityTypeFullName) : this.getParent(List).getListItemEntityTypeFullName(); } } /** * Descrines a single Item instance * */ export class Item extends SharePointQueryableShareableItem { /** * Gets the set of attachments for this item * */ public get attachmentFiles(): AttachmentFiles { return new AttachmentFiles(this); } /** * Gets the content type for this item * */ public get contentType(): ContentType { return new ContentType(this, "ContentType"); } /** * Gets the effective base permissions for the item * */ public get effectiveBasePermissions(): SharePointQueryable { return new SharePointQueryable(this, "EffectiveBasePermissions"); } /** * Gets the effective base permissions for the item in a UI context * */ public get effectiveBasePermissionsForUI(): SharePointQueryable { return new SharePointQueryable(this, "EffectiveBasePermissionsForUI"); } /** * Gets the field values for this list item in their HTML representation * */ public get fieldValuesAsHTML(): SharePointQueryableInstance { return new SharePointQueryableInstance(this, "FieldValuesAsHTML"); } /** * Gets the field values for this list item in their text representation * */ public get fieldValuesAsText(): SharePointQueryableInstance { return new SharePointQueryableInstance(this, "FieldValuesAsText"); } /** * Gets the field values for this list item for use in editing controls * */ public get fieldValuesForEdit(): SharePointQueryableInstance { return new SharePointQueryableInstance(this, "FieldValuesForEdit"); } /** * Gets the folder associated with this list item (if this item represents a folder) * */ public get folder(): Folder { return new Folder(this, "folder"); } /** * Gets the folder associated with this list item (if this item represents a folder) * */ public get file(): File { return new File(this, "file"); } /** * Gets the collection of versions associated with this item */ public get versions(): ItemVersions { return new ItemVersions(this); } /** * Updates this list intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param eTag Value used in the IF-Match header, by default "*" */ public update(properties: TypedHash<any>, eTag = "*", listItemEntityTypeFullName: string = null): Promise<ItemUpdateResult> { return new Promise<ItemUpdateResult>((resolve, reject) => { const removeDependency = this.addBatchDependency(); return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(listItemEntityType => { const postBody = JSON.stringify(Util.extend({ "__metadata": { "type": listItemEntityType }, }, properties)); removeDependency(); return this.postCore({ body: postBody, headers: { "IF-Match": eTag, "X-HTTP-Method": "MERGE", }, }, new ItemUpdatedParser()).then((data) => { resolve({ data: data, item: this, }); }); }).catch(e => reject(e)); }); } /** * Delete this item * * @param eTag Value used in the IF-Match header, by default "*" */ public delete(eTag = "*"): Promise<void> { return this.postCore({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); } /** * Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ public recycle(): Promise<string> { return this.clone(Item, "recycle").postCore(); } /** * Gets a string representation of the full URL to the WOPI frame. * If there is no associated WOPI application, or no associated action, an empty string is returned. * * @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview */ public getWopiFrameUrl(action = 0): Promise<string> { const i = this.clone(Item, "getWOPIFrameUrl(@action)"); i._query.add("@action", <any>action); return i.postCore().then((data: any) => { // handle verbose mode if (data.hasOwnProperty("GetWOPIFrameUrl")) { return data.GetWOPIFrameUrl; } return data; }); } /** * Validates and sets the values of the specified collection of fields for the list item. * * @param formValues The fields to change and their new values. * @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false. */ public validateUpdateListItem(formValues: ListItemFormUpdateValue[], newDocumentUpdate = false): Promise<ListItemFormUpdateValue[]> { return this.clone(Item, "validateupdatelistitem").postCore({ body: JSON.stringify({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }), }); } /** * Ensures we have the proper list item entity type name, either from the value provided or from the list * * @param candidatelistItemEntityTypeFullName The potential type name */ private ensureListItemEntityTypeName(candidatelistItemEntityTypeFullName: string): Promise<string> { return candidatelistItemEntityTypeFullName ? Promise.resolve(candidatelistItemEntityTypeFullName) : this.getParent(List, this.parentUrl.substr(0, this.parentUrl.lastIndexOf("/"))).getListItemEntityTypeFullName(); } } export interface ItemAddResult { item: Item; data: any; } export interface ItemUpdateResult { item: Item; data: ItemUpdateResultData; } export interface ItemUpdateResultData { "odata.etag": string; } /** * Provides paging functionality for list items */ export class PagedItemCollection<T> { constructor(private nextUrl: string, public results: T) { } /** * If true there are more results available in the set, otherwise there are not */ public get hasNext(): boolean { return typeof this.nextUrl === "string" && this.nextUrl.length > 0; } /** * Gets the next set of results, or resolves to null if no results are available */ public getNext(): Promise<PagedItemCollection<any>> { if (this.hasNext) { const items = new Items(this.nextUrl, null); return items.getPaged(); } return new Promise<any>(r => r(null)); } } /** * Describes a collection of Version objects * */ export class ItemVersions extends SharePointQueryableCollection { /** * Creates a new instance of the File class * * @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection */ constructor(baseUrl: string | SharePointQueryable, path = "versions") { super(baseUrl, path); } /** * Gets a version by id * * @param versionId The id of the version to retrieve */ public getById(versionId: number): ItemVersion { const v = new ItemVersion(this); v.concat(`(${versionId})`); return v; } } /** * Describes a single Version instance * */ export class ItemVersion extends SharePointQueryableInstance { /** * Delete a specific version of a file. * * @param eTag Value used in the IF-Match header, by default "*" */ public delete(): Promise<void> { return this.postCore({ headers: { "X-HTTP-Method": "DELETE", }, }); } } class PagedItemCollectionParser extends ODataParserBase<PagedItemCollection<any>> { public parse(r: Response): Promise<PagedItemCollection<any>> { return new Promise<PagedItemCollection<any>>((resolve, reject) => { if (this.handleError(r, reject)) { r.json().then(json => { const nextUrl = json.hasOwnProperty("d") && json.d.hasOwnProperty("__next") ? json.d.__next : json["odata.nextLink"]; resolve(new PagedItemCollection(nextUrl, this.parseODataJSON(json))); }); } }); } } class ItemUpdatedParser extends ODataParserBase<ItemUpdateResultData> { public parse(r: Response): Promise<ItemUpdateResultData> { return new Promise<ItemUpdateResultData>((resolve, reject) => { if (this.handleError(r, reject)) { resolve({ "odata.etag": r.headers.get("etag"), }); } }); } }
the_stack
import { Component, Input, OnInit, OnDestroy } from '@angular/core'; import { Route, Router, ActivatedRoute } from '@angular/router'; import { Subscription, concat, EMPTY, Observable, throwError, of } from 'rxjs'; import { tap, catchError, map, switchMap } from 'rxjs/operators'; import { PoBreadcrumb, PoDialogConfirmOptions, PoDialogService, PoLanguageService, PoNotificationService, PoPageAction, poLocaleDefault } from '@po-ui/ng-components'; import { convertToBoolean, mapObjectByProperties, valuesFromObject } from '../../utils/util'; import { PoPageDynamicDetailActions } from './interfaces/po-page-dynamic-detail-actions.interface'; import { PoPageDynamicDetailField } from './interfaces/po-page-dynamic-detail-field.interface'; import { PoPageDynamicService } from '../../services/po-page-dynamic/po-page-dynamic.service'; import { PoPageDynamicDetailActionsService } from './po-page-dynamic-detail-actions.service'; import { PoPageDynamicDetailOptions } from './interfaces/po-page-dynamic-detail-options.interface'; import { PoPageCustomizationService } from './../../services/po-page-customization/po-page-customization.service'; import { PoPageDynamicOptionsSchema } from './../../services/po-page-customization/po-page-dynamic-options.interface'; import { PoPageDynamicDetailMetaData } from './interfaces/po-page-dynamic-detail-metadata.interface'; import { PoPageDynamicDetailBeforeBack } from './interfaces/po-page-dynamic-detail-before-back.interface'; import { PoPageDynamicDetailBeforeRemove } from './interfaces/po-page-dynamic-detail-before-remove.interface'; import { PoPageDynamicDetailBeforeEdit } from './interfaces/po-page-dynamic-detail-before-edit.interface'; type UrlOrPoCustomizationFunction = string | (() => PoPageDynamicDetailOptions); export const poPageDynamicDetailLiteralsDefault = { en: { pageActionEdit: 'Edit', pageActionRemove: 'Delete', pageActionBack: 'Back', confirmRemoveTitle: 'Confirm delete', confirmRemoveMessage: 'Are you sure you want to delete this record? You can not undo this action.', removeNotificationSuccess: 'Item deleted successfully.', registerNotFound: 'Register not found.' }, es: { pageActionEdit: 'Editar', pageActionRemove: 'Borrar', pageActionBack: 'Regreso', confirmRemoveTitle: 'Confirmar la exclusión', confirmRemoveMessage: '¿Está seguro de que desea eliminar este registro? No puede deshacer esta acción.', removeNotificationSuccess: 'Elemento eliminado con éxito.', registerNotFound: 'Registro no encontrado.' }, pt: { pageActionEdit: 'Editar', pageActionRemove: 'Excluir', pageActionBack: 'Voltar', confirmRemoveTitle: 'Confirmar exclusão', confirmRemoveMessage: 'Tem certeza de que deseja excluir esse registro? Você não poderá desfazer essa ação.', removeNotificationSuccess: 'Item excluído com sucesso.', registerNotFound: 'Registro não encontrado.' }, ru: { pageActionEdit: 'Редактировать', pageActionRemove: 'Удалить', pageActionBack: 'Назад', confirmRemoveTitle: 'Подтверждение удаления', confirmRemoveMessage: 'Вы уверены, что хотите удалить эту запись? Вы не можете отменить это действие.', removeNotificationSuccess: 'Элемент успешно удален.', registerNotFound: 'Запись не найдена.' } }; /** * @description * * O `po-page-dynamic-detail` é uma página que serve para exibir registros em detalhes, * o mesmo também suporta metadados conforme especificado na documentação. * * * ### Utilização via rota * * Ao utilizar as rotas para carregar o template, o `page-dynamic-detail` disponibiliza propriedades para * poder especificar o endpoint dos dados e dos metadados. Exemplo de utilização: * * O componente primeiro irá carregar o metadado da rota definida na propriedade serviceMetadataApi * e depois irá buscar da rota definida na propriedade serviceLoadApi. * * > Caso o servidor retornar um erro ao recuperar o metadados, será repassado o metadados salvo em cache, * se o cache não existe será disparado uma notificação. * * ``` * { * path: 'people/:id', * component: PoPageDynamicDetailComponent, * data: { * serviceApi: 'http://localhost:3000/v1/people', // endpoint dos dados * serviceMetadataApi: 'http://localhost:3000/v1/metadata', // endpoint dos metadados * serviceLoadApi: 'http://localhost:3000/load-metadata' // endpoint de customizações dos metadados * } * } * ``` * * A requisição dos metadados é feita na inicialização do template para buscar os metadados da página passando o * tipo do metadado esperado e a versão cacheada pelo browser. * * O formato esperado na resposta da requisição está especificado na interface * [PoPageDynamicDetailMetadata](/documentation/po-page-dynamic-detail#po-page-dynamic-detail-metadata). Por exemplo: * * ``` * { * version: 1, * title: 'Person Detail', * fields: [ * { property: 'id', key: true, disabled: true }, * { property: 'status' }, * { property: 'name' }, * { property: 'nickname' }, * { property: 'birthdate', label: 'Birth date' }, * { property: 'genre' }, * { property: 'city' }, * { property: 'country' } * ] * } * ``` * * > Caso o endpoint dos metadados não seja especificado, será feito uma requisição utilizando o `serviceApi` da seguinte forma: * ``` * GET {end-point}/metadata?type=detail&version={version} * ``` * * @example * * <example name="po-page-dynamic-detail-user" title="PO Page Dynamic Detail User"> * <file name="sample-po-page-dynamic-detail-user/sample-po-page-dynamic-detail-user.component.html"> </file> * <file name="sample-po-page-dynamic-detail-user/sample-po-page-dynamic-detail-user.component.ts"> </file> * </example> */ @Component({ selector: 'po-page-dynamic-detail', templateUrl: './po-page-dynamic-detail.component.html', providers: [PoPageDynamicService, PoPageDynamicDetailActionsService] }) export class PoPageDynamicDetailComponent implements OnInit, OnDestroy { /** Objeto com propriedades do breadcrumb. */ @Input('p-breadcrumb') breadcrumb?: PoBreadcrumb = { items: [] }; /** * Função ou serviço que será executado na inicialização do componente. * * A propriedade aceita os seguintes tipos: * - `string`: *Endpoint* usado pelo componente para requisição via `POST`. * - `function`: Método que será executado. * * O retorno desta função deve ser do tipo `PoPageDynamicDetailOptions`, * onde o usuário poderá customizar novos campos, breadcrumb, title e actions * * Por exemplo: * * ``` * getPageOptions(): PoPageDynamicDetailOptions { * return { * actions: * { new: 'new', edit: 'edit/:id', remove: true }, * fields: [ * { property: 'idCard', gridColumns: 6 } * ] * }; * } * * ``` * Para referenciar a sua função utilize a propriedade `bind`, por exemplo: * ``` * [p-load]="onLoadOptions.bind(this)" * ``` */ @Input('p-load') onLoad: string | (() => PoPageDynamicDetailOptions); /** Título da página. */ @Input('p-title') title: string; /** * @description * * Endpoint usado pelo template para requisição do recurso que serão exibido. * * Caso a ação `remove` estiver configurada, será feito uma requisição de exclusão nesse mesmo endpoint passando os campos * setados como `key: true`. * * > `DELETE {end-point}/{keys}` * * ``` * <po-page-dynamic-detail * [p-actions]="{ remove: '/' }" * [p-fields]="[ { property: 'id', key: true } ]" * p-service="/api/po-samples/v1/people" * ...> * </po-page-dynamic-detail> * ``` * * Resquisição disparada, onde a propriedade `id` é igual a 2: * * ``` * DELETE /api/po-samples/v1/people/2 HTTP/1.1 * Host: localhost:4000 * Connection: keep-alive * Accept: application/json, text/plain * ... * ``` * * > Caso esteja usando metadados com o template, será disparado uma requisição na inicialização do template para buscar * > os metadados da página passando o tipo do metadado esperado e a versão cacheada pelo browser. * > * > `GET {end-point}/metadata?type=detail&version={version}` */ @Input('p-service-api') serviceApi: string; literals; model: any = {}; private subscriptions: Array<Subscription> = []; private _actions: PoPageDynamicDetailActions = {}; private _autoRouter: boolean = false; private _duplicates: Array<any> = []; private _fields: Array<any> = []; private _keys: Array<any> = []; private _pageActions: Array<PoPageAction> = []; /** * @optional * * @description * * Define as ações da página de acordo com a interface `PoPageDynamicDetailActions`. */ @Input('p-actions') set actions(value: PoPageDynamicDetailActions) { this._actions = this.isObject(value) ? value : {}; this._pageActions = this.getPageActions(this._actions); } get actions() { return { ...this._actions }; } /** * @todo Validar rotas na mão pois se existir uma rota '**' o catch do navigation não funciona. * * @optional * * @description * * Cria automaticamente as rotas de edição (novo/duplicate) e detalhes caso as ações * estejam definidas nas ações. * * > Para o correto funcionamento não pode haver nenhum rota coringa (`**`) especificada. * * @default false */ @Input('p-auto-router') set autoRouter(value: boolean) { this._autoRouter = convertToBoolean(value); } get autoRouter(): boolean { return this._autoRouter; } /** Lista dos campos exibidos na página. */ @Input('p-fields') set fields(value: Array<PoPageDynamicDetailField>) { this._fields = Array.isArray(value) ? [...value] : []; this._keys = this.getKeysByFields(this.fields); this._duplicates = this.getDuplicatesByFields(this.fields); } get fields(): Array<PoPageDynamicDetailField> { return this._fields; } constructor( private router: Router, private activatedRoute: ActivatedRoute, private poNotification: PoNotificationService, private poDialogService: PoDialogService, private poPageDynamicService: PoPageDynamicService, private poPageDynamicDetailActionsService: PoPageDynamicDetailActionsService, private poPageCustomizationService: PoPageCustomizationService, languageService: PoLanguageService ) { const language = languageService.getShortLanguage(); this.literals = { ...poPageDynamicDetailLiteralsDefault[poLocaleDefault], ...poPageDynamicDetailLiteralsDefault[language] }; } ngOnInit(): void { this.loadDataFromAPI(); } ngOnDestroy() { if (this.subscriptions) { this.subscriptions.forEach(subscription => { subscription.unsubscribe(); }); } } get duplicates() { return [...this._duplicates]; } get keys() { return [...this._keys]; } get pageActions() { return [...this._pageActions]; } private remove( actionRemove: PoPageDynamicDetailActions['remove'], actionBeforeRemove?: PoPageDynamicDetailActions['beforeRemove'] ) { const uniqueKey = this.formatUniqueKey(this.model); this.subscriptions.push( this.poPageDynamicDetailActionsService .beforeRemove(actionBeforeRemove, uniqueKey, { ...this.model }) .pipe( switchMap((beforeRemoveResult: PoPageDynamicDetailBeforeRemove) => { const newRemoveAction = beforeRemoveResult?.newUrl ?? actionRemove; const allowAction = beforeRemoveResult?.allowAction ?? true; if (!allowAction) { return of({}); } if (typeof newRemoveAction === 'string') { return this.executeRemove(newRemoveAction, uniqueKey); } else { newRemoveAction(uniqueKey, { ...this.model }); return EMPTY; } }) ) .subscribe() ); } private confirmRemove( actionRemove: PoPageDynamicDetailActions['remove'], actionBeforeRemove: PoPageDynamicDetailActions['beforeRemove'] ) { const confirmOptions: PoDialogConfirmOptions = { title: this.literals.confirmRemoveTitle, message: this.literals.confirmRemoveMessage, confirm: this.remove.bind(this, actionRemove, actionBeforeRemove) }; this.poDialogService.confirm(confirmOptions); } private executeRemove(path, uniqueKey: any) { return this.poPageDynamicService.deleteResource(uniqueKey).pipe( map(() => { this.poNotification.success(this.literals.removeNotificationSuccess); this.navigateTo({ path: path }); }) ); } private formatUniqueKey(item) { const keys = mapObjectByProperties(item, this.keys); return valuesFromObject(keys).join('|'); } private goBack(actionBack: PoPageDynamicDetailActions['back']) { this.subscriptions.push( this.poPageDynamicDetailActionsService .beforeBack(this.actions.beforeBack) .subscribe((beforeBackResult: PoPageDynamicDetailBeforeBack) => this.executeBackAction(actionBack, beforeBackResult?.allowAction, beforeBackResult?.newUrl) ) ); } private executeBackAction(actionBack: PoPageDynamicDetailActions['back'], allowAction?, newUrl?: string) { const isAllowedAction = typeof allowAction === 'boolean' ? allowAction : true; if (isAllowedAction) { if (actionBack === undefined || typeof actionBack === 'boolean') { return window.history.back(); } if (typeof actionBack === 'string' || newUrl) { return this.router.navigate([newUrl || actionBack]); } return actionBack(); } } private loadData(id) { return this.poPageDynamicService.getResource(id).pipe( tap(response => { if (!response) { this.setUndefinedToModelAndActions(); } else { this.model = response; } }), catchError(error => { this.setUndefinedToModelAndActions(); return throwError(error); }) ); } private setUndefinedToModelAndActions() { this.model = undefined; this.actions = undefined; } private getMetadata( serviceApiFromRoute: string, onLoad: UrlOrPoCustomizationFunction ): Observable<PoPageDynamicDetailMetaData> { if (serviceApiFromRoute) { return this.poPageDynamicService.getMetadata<PoPageDynamicDetailMetaData>('detail').pipe( tap(response => { this.autoRouter = response.autoRouter || this.autoRouter; this.actions = response.actions || this.actions; this.breadcrumb = response.breadcrumb || this.breadcrumb; this.fields = response.fields || this.fields; this.title = response.title || this.title; }), switchMap(() => this.loadOptionsOnInitialize(onLoad)) ); } return this.loadOptionsOnInitialize(onLoad); } // @todo Validar rotas na mão pois se existir uma rota '**' o catch do navigation não funciona. private navigateTo( route: { path: string; component?; url?: string; params?: any }, forceStopAutoRouter: boolean = false ) { this.router.navigate([route.url || route.path], { queryParams: route.params }).catch(() => { if (forceStopAutoRouter || !this.autoRouter) { return; } this.router.config.unshift(<Route>{ path: route.path, component: route.component, data: { serviceApi: this.serviceApi, autoRouter: true } }); this.navigateTo(route, true); }); } private openEdit(action: PoPageDynamicDetailActions['edit']) { const id = this.formatUniqueKey(this.model); this.subscriptions.push( this.poPageDynamicDetailActionsService .beforeEdit(this.actions.beforeEdit, id, this.model) .pipe( switchMap((beforeEditResult: PoPageDynamicDetailBeforeEdit) => this.executeEditAction(action, beforeEditResult, id) ) ) .subscribe() ); } private executeEditAction( action: PoPageDynamicDetailActions['edit'], beforeEditResult: PoPageDynamicDetailBeforeEdit, id: any ) { const newEditAction = beforeEditResult?.newUrl ?? action; const allowAction = beforeEditResult?.allowAction ?? true; if (!allowAction) { return of({}); } if (typeof newEditAction === 'string') { this.openEditUrl(newEditAction); } else { newEditAction(id, { ...this.model }); } return EMPTY; } private openEditUrl(path: string) { const url = this.resolveUrl(this.model, path); this.navigateTo({ path, url }); } private resolveUrl(item: any, path: string) { const uniqueKey = this.formatUniqueKey(item); return path.replace(/:id/g, uniqueKey); } private getPageActions(actions: PoPageDynamicDetailActions = {}): Array<PoPageAction> { const pageActions = []; if (actions.edit) { pageActions.push({ label: this.literals.pageActionEdit, action: this.openEdit.bind(this, actions.edit) }); } if (actions.remove) { pageActions.push({ label: this.literals.pageActionRemove, action: this.confirmRemove.bind(this, actions.remove, this.actions.beforeRemove) }); } if (actions.back === undefined || actions.back) { pageActions.push({ label: this.literals.pageActionBack, action: this.goBack.bind(this, actions.back) }); } return pageActions; } private getKeysByFields(fields: Array<any> = []) { return fields.filter(field => field.key === true).map(field => field.property); } private getDuplicatesByFields(fields: Array<any> = []) { return fields.filter(field => field.duplicate === true).map(field => field.property); } private isObject(value: any): boolean { return !!value && typeof value === 'object' && !Array.isArray(value); } private loadDataFromAPI() { const { serviceApi: serviceApiFromRoute, serviceMetadataApi, serviceLoadApi } = this.activatedRoute.snapshot.data; const { id } = this.activatedRoute.snapshot.params; const onLoad = serviceLoadApi || this.onLoad; this.serviceApi = serviceApiFromRoute || this.serviceApi; this.poPageDynamicService.configServiceApi({ endpoint: this.serviceApi, metadata: serviceMetadataApi }); const metadata$ = this.getMetadata(serviceApiFromRoute, onLoad); const data$ = this.loadData(id); this.subscriptions.push(concat(metadata$, data$).subscribe()); } private loadOptionsOnInitialize(onLoad: UrlOrPoCustomizationFunction) { if (onLoad) { return this.getPoDynamicPageOptions(onLoad).pipe( tap(responsePoOption => this.poPageCustomizationService.changeOriginalOptionsToNewOptions(this, responsePoOption) ) ); } return EMPTY; } private getPoDynamicPageOptions(onLoad: UrlOrPoCustomizationFunction): Observable<PoPageDynamicDetailOptions> { const originalOption: PoPageDynamicDetailOptions = { fields: this.fields, actions: this.actions, breadcrumb: this.breadcrumb, title: this.title }; const pageOptionSchema: PoPageDynamicOptionsSchema<PoPageDynamicDetailOptions> = { schema: [ { nameProp: 'fields', merge: true, keyForMerge: 'property' }, { nameProp: 'actions', merge: true }, { nameProp: 'breadcrumb' }, { nameProp: 'title' } ] }; return this.poPageCustomizationService.getCustomOptions(onLoad, originalOption, pageOptionSchema); } }
the_stack
import type {TemplateResult, ChildPart} from 'lit'; import type { Directive, DirectiveClass, DirectiveResult, } from 'lit/directive.js'; import {nothing, noChange} from 'lit'; import {PartType} from 'lit/directive.js'; import {isTemplateResult, getDirectiveClass} from 'lit/directive-helpers.js'; import {_$LH} from 'lit-html/private-ssr-support.js'; const { getTemplateHtml, marker, markerMatch, boundAttributeSuffix, overrideDirectiveResolve, setDirectiveClass, getAttributePartCommittedValue, resolveDirective, AttributePart, PropertyPart, BooleanAttributePart, EventPart, connectedDisconnectable, } = _$LH; import {digestForTemplateResult} from 'lit/experimental-hydrate.js'; import { ElementRenderer, ElementRendererConstructor, getElementRenderer, } from './element-renderer.js'; import {escapeHtml} from './util/escape-html.js'; import { traverse, parseFragment, isCommentNode, isElement, } from './util/parse5-utils.js'; import {isRenderLightDirective} from '@lit-labs/ssr-client/directives/render-light.js'; import {reflectedAttributeName} from './reflected-attributes.js'; import {LitElementRenderer} from './lit-element-renderer.js'; declare module 'parse5' { interface Element { isDefinedCustomElement?: boolean; } } const patchedDirectiveCache: WeakMap<DirectiveClass, DirectiveClass> = new Map(); /** * Looks for values of type `DirectiveResult` and replaces its Directive class * with a subclass that calls `render` rather than `update` */ const patchIfDirective = (value: unknown) => { // This property needs to remain unminified. const directiveCtor = getDirectiveClass(value); if (directiveCtor !== undefined) { let patchedCtor = patchedDirectiveCache.get(directiveCtor); if (patchedCtor === undefined) { patchedCtor = overrideDirectiveResolve( directiveCtor, (directive: Directive, values: unknown[]) => { // Since the return value may also be a directive result in the case of // nested directives, we may need to patch that as well return patchIfDirective(directive.render(...values)); } ); patchedDirectiveCache.set(directiveCtor, patchedCtor); } // This property needs to remain unminified. setDirectiveClass(value as DirectiveResult, patchedCtor); } return value; }; /** * Patches `DirectiveResult` `Directive` classes for AttributePart values, which * may be an array */ const patchAnyDirectives = ( part: InstanceType<typeof AttributePart>, value: unknown, valueIndex: number ) => { if (part.strings !== undefined) { for (let i = 0; i < part.strings.length - 1; i++) { patchIfDirective((value as unknown[])[valueIndex + i]); } } else { patchIfDirective(value); } }; const templateCache = new Map<TemplateStringsArray, Array<Op>>(); /** * Operation to output static text */ type TextOp = { type: 'text'; value: string; }; /** * Operation to output dynamic text from the associated template result value */ type ChildPartOp = { type: 'child-part'; index: number; useCustomElementInstance?: boolean; }; /** * Operation to output an attribute with bindings. Includes all bindings for an * attribute. */ type AttributePartOp = { type: 'attribute-part'; index: number; name: string; ctor: typeof AttributePart; strings: Array<string>; tagName: string; useCustomElementInstance?: boolean; }; /** * Operation for an element binding. Although we only support directives in * element position which cannot emit anything, the opcode needs to index past * the part value */ type ElementPartOp = { type: 'element-part'; index: number; }; /** * Operator to create a custom element instance. */ type CustomElementOpenOp = { type: 'custom-element-open'; tagName: string; ctor: {new (): HTMLElement}; staticAttributes: Map<string, string>; }; /** * Operation to render a custom element's attributes. This is separate from * `custom-element-open` because attribute/property parts go in between and need * to run and be set on the instance before we render the element's final * attributes. */ type CustomElementAttributesOp = { type: 'custom-element-attributes'; }; /** * Operation to render a custom element's children, usually its shadow root. */ type CustomElementShadowOp = { type: 'custom-element-shadow'; }; /** * Operation to close a custom element so that its no longer available for * bindings. */ type CustomElementClosedOp = { type: 'custom-element-close'; }; /** * Operation to possibly emit the `<!--lit-node-->` marker; the operation * always emits if there were attribtue parts, and may emit if the node * was a custom element and it needed `defer-hydration` because it was * rendered in the shadow root of another custom element host; we don't * know the latter at opcode generation time, and so that test is done at * runtime in the opcode. */ type PossibleNodeMarkerOp = { type: 'possible-node-marker'; boundAttributesCount: number; nodeIndex: number; }; type Op = | TextOp | ChildPartOp | AttributePartOp | ElementPartOp | CustomElementOpenOp | CustomElementAttributesOp | CustomElementShadowOp | CustomElementClosedOp | PossibleNodeMarkerOp; /** * For a given TemplateResult, generates and/or returns a cached list of opcodes * for the associated Template. Opcodes are designed to allow emitting * contiguous static text from the template as much as possible, with specific * non-`text` opcodes interleaved to perform dynamic work, such as emitting * values for ChildParts or AttributeParts, and handling custom elements. * * For the following example template, an opcode list may look like this: * * ```js * html`<div><span>Hello</span><span class=${'bold'}>${template()}</span></div>` * ``` * * - `text` * - Emit run of static text: `<div><span>Hello</span><span` * - `attribute-part` * - Emit an AttributePart's value, e.g. ` class="bold"` * - `text` * - Emit run of static text: `>` * - `child-part` * - Emit the ChildPart's value, in this case a TemplateResult, thus we recurse * into that template's opcodes * - `text` * - Emit run of static text: `/span></div>` * * When a custom-element is encountered, the flow looks like this: * * ```js * html`<x-foo staticAttr dynamicAttr=${value}><div>child</div>...</x-foo>` * ``` * * - `text` * - Emit open tag `<x-foo` * - `custom-element-open` * - Create the CE `instance`+`renderer` and put on * `customElementInstanceStack` * - Call `renderer.setAttribute()` for any `staticAttributes` (e.g. * 'staticAttr`) * - `attribute-part`(s) * - Call `renderer.setAttribute()` or `renderer.setProperty()` for * `AttributePart`/`PropertyPart`s (e.g. for `dynamicAttr`) * - `custom-element-attributes` * - Call `renderer.connectedCallback()` * - Emit `renderer.renderAttributes()` * - `text` * - Emit end of of open tag `>` * - `possible-node-marker` * - Emit `<!--lit-node n-->` marker if there were attribute parts or * we needed to emit the `defer-hydration` attribute * - `custom-element-shadow` * - Emit `renderer.renderShadow()` (emits `<template shadowroot>` + * recurses to emit `render()`) * - `text` * - Emit run of static text within tag: `<div>child</div>...` * - ...(recurse to render more parts/children)... * - `custom-element-close` * - Pop the CE `instance`+`renderer` off the `customElementInstanceStack` */ const getTemplateOpcodes = (result: TemplateResult) => { const template = templateCache.get(result.strings); if (template !== undefined) { return template; } // The property '_$litType$' needs to remain unminified. const [html, attrNames] = getTemplateHtml( result.strings, result['_$litType$'] ); /** * The html string is parsed into a parse5 AST with source code information * on; this lets us skip over certain ast nodes by string character position * while walking the AST. */ const ast = parseFragment(String(html), { sourceCodeLocationInfo: true, }); const ops: Array<Op> = []; /* The last offset of html written to the stream */ let lastOffset: number | undefined = 0; /* Current attribute part index, for indexing attrNames */ let attrIndex = 0; /** * Sets `lastOffset` to `offset`, skipping a range of characters. This is * useful for skipping and re-writing lit-html marker nodes, bound attribute * suffix, etc. */ const skipTo = (offset: number) => { if (lastOffset === undefined) { throw new Error('lastOffset is undefined'); } if (offset < lastOffset) { throw new Error(`offset must be greater than lastOffset. offset: ${offset} lastOffset: ${lastOffset} `); } lastOffset = offset; }; /** * Records the given string to the output, either by appending to the current * opcode (if already `text`) or by creating a new `text` opcode (if the * previous opocde was not `text) */ const flush = (value: string) => { const op = getLast(ops); if (op !== undefined && op.type === 'text') { op.value += value; } else { ops.push({ type: 'text', value, }); } }; /** * Creates or appends to a text opcode with a substring of the html from the * `lastOffset` flushed to `offset`. */ const flushTo = (offset?: number) => { if (lastOffset === undefined) { throw new Error('lastOffset is undefined'); } const previousLastOffset = lastOffset; lastOffset = offset; const value = String(html).substring(previousLastOffset, offset); flush(value); }; // Depth-first node index, counting only comment and element nodes, to match // client-side lit-html. let nodeIndex = 0; traverse(ast, { pre(node, parent) { if (isCommentNode(node)) { if (node.data === markerMatch) { flushTo(node.sourceCodeLocation!.startOffset); skipTo(node.sourceCodeLocation!.endOffset); ops.push({ type: 'child-part', index: nodeIndex, useCustomElementInstance: parent && isElement(parent) && parent.isDefinedCustomElement, }); } nodeIndex++; } else if (isElement(node)) { // Whether to flush the start tag. This is necessary if we're changing // any of the attributes in the tag, so it's true for custom-elements // which might reflect their own state, or any element with a binding. let writeTag = false; let boundAttributesCount = 0; const tagName = node.tagName; let ctor; if (tagName.indexOf('-') !== -1) { // Looking up the constructor here means that custom elements must be // registered before rendering the first template that contains them. ctor = customElements.get(tagName); if (ctor !== undefined) { // Write the start tag writeTag = true; // Mark that this is a custom element node.isDefinedCustomElement = true; ops.push({ type: 'custom-element-open', tagName, ctor, staticAttributes: new Map( node.attrs .filter((attr) => !attr.name.endsWith(boundAttributeSuffix)) .map((attr) => [attr.name, attr.value]) ), }); } } if (node.attrs.length > 0) { for (const attr of node.attrs) { const isAttrBinding = attr.name.endsWith(boundAttributeSuffix); const isElementBinding = attr.name.startsWith(marker); if (isAttrBinding || isElementBinding) { writeTag = true; boundAttributesCount += 1; // Note that although we emit a lit-node comment marker for any // nodes with bindings, we don't account for it in the nodeIndex because // that will not be injected into the client template const strings = attr.value.split(marker); // We store the case-sensitive name from `attrNames` (generated // while parsing the template strings); note that this assumes // parse5 attribute ordering matches string ordering const name = attrNames[attrIndex++]; const attrSourceLocation = node.sourceCodeLocation!.attrs![attr.name]!; const attrNameStartOffset = attrSourceLocation.startOffset; const attrEndOffset = attrSourceLocation.endOffset; flushTo(attrNameStartOffset); if (isAttrBinding) { const [, prefix, caseSensitiveName] = /([.?@])?(.*)/.exec( name as string )!; ops.push({ type: 'attribute-part', index: nodeIndex, name: caseSensitiveName, ctor: prefix === '.' ? PropertyPart : prefix === '?' ? BooleanAttributePart : prefix === '@' ? EventPart : AttributePart, strings, tagName: tagName.toUpperCase(), useCustomElementInstance: ctor !== undefined, }); } else { ops.push({ type: 'element-part', index: nodeIndex, }); } skipTo(attrEndOffset); } else if (node.isDefinedCustomElement) { // For custom elements, all static attributes are stored along // with the `custom-element-open` opcode so that we can set them // into the custom element instance, and then serialize them back // out along with any manually-reflected attributes. As such, we // skip over static attribute text here. const attrSourceLocation = node.sourceCodeLocation!.attrs![attr.name]!; flushTo(attrSourceLocation.startOffset); skipTo(attrSourceLocation.endOffset); } } } if (writeTag) { if (node.isDefinedCustomElement) { flushTo(node.sourceCodeLocation!.startTag.endOffset - 1); ops.push({ type: 'custom-element-attributes', }); flush('>'); skipTo(node.sourceCodeLocation!.startTag.endOffset); } else { flushTo(node.sourceCodeLocation!.startTag.endOffset); } ops.push({ type: 'possible-node-marker', boundAttributesCount, nodeIndex, }); } if (ctor !== undefined) { ops.push({ type: 'custom-element-shadow', }); } nodeIndex++; } }, post(node) { if (isElement(node) && node.isDefinedCustomElement) { ops.push({ type: 'custom-element-close', }); } }, }); // Flush remaining static text in the template (e.g. closing tags) flushTo(); templateCache.set(result.strings, ops); return ops; }; export type RenderInfo = { /** * Element renderers to use */ elementRenderers: ElementRendererConstructor[]; /** * Stack of open custom elements (in light dom or shadow dom) */ customElementInstanceStack: Array<ElementRenderer | undefined>; /** * Stack of open host custom elements (n-1 will be n's host) */ customElementHostStack: Array<ElementRenderer | undefined>; /** * An optional callback to notifiy when a custom element has been rendered. * * This allows servers to know what specific tags were rendered for a given * template, even in the case of conditional templates. */ customElementRendered?: (tagName: string) => void; }; const defaultRenderInfo = { elementRenderers: [LitElementRenderer], customElementInstanceStack: [], customElementHostStack: [], }; declare global { interface Array<T> { flat(depth: number): Array<T>; } } /** * Renders a lit-html template (or any renderable lit-html value) to a string * iterator. Any custom elements encountered will be rendered if a matching * ElementRenderer is found. * * This method is suitable for streaming the contents of the element. * * @param value Value to render * @param renderInfo Optional render context object that should be passed * to any re-entrant calls to `render`, e.g. from a `renderShadow` callback * on an ElementRenderer. */ export function* render( value: unknown, renderInfo?: Partial<RenderInfo> ): IterableIterator<string> { renderInfo = {...defaultRenderInfo, ...renderInfo}; yield* renderValue(value, renderInfo as RenderInfo); } function* renderValue( value: unknown, renderInfo: RenderInfo ): IterableIterator<string> { patchIfDirective(value); if (isRenderLightDirective(value)) { // If a value was produced with renderLight(), we want to call and render // the renderLight() method. const instance = getLast(renderInfo.customElementInstanceStack); if (instance !== undefined) { yield* instance.renderLight(renderInfo); } value = null; } else { value = resolveDirective( connectedDisconnectable({type: PartType.CHILD}) as ChildPart, value ); } if (value != null && isTemplateResult(value)) { yield `<!--lit-part ${digestForTemplateResult(value as TemplateResult)}-->`; yield* renderTemplateResult(value as TemplateResult, renderInfo); } else { yield `<!--lit-part-->`; if ( value === undefined || value === null || value === nothing || value === noChange ) { // yield nothing } else if (Array.isArray(value)) { for (const item of value) { yield* renderValue(item, renderInfo); } } else { yield escapeHtml(String(value)); } } yield `<!--/lit-part-->`; } function* renderTemplateResult( result: TemplateResult, renderInfo: RenderInfo ): IterableIterator<string> { // In order to render a TemplateResult we have to handle and stream out // different parts of the result separately: // - Literal sections of the template // - Defined custom element within the literal sections // - Values in the result // // This means we can't just iterate through the template literals and values, // we must parse and traverse the template's HTML. But we don't want to pay // the cost of serializing the HTML node-by-node when we already have the // template in string form. So we parse with location info turned on and use // that to index into the HTML string generated by TemplateResult.getHTML(). // During the tree walk we will handle expression marker nodes and custom // elements. For each we will record the offset of the node, and output the // previous span of HTML. const ops = getTemplateOpcodes(result); /* The next value in result.values to render */ let partIndex = 0; for (const op of ops) { switch (op.type) { case 'text': yield op.value; break; case 'child-part': { const value = result.values[partIndex++]; yield* renderValue(value, renderInfo); break; } case 'attribute-part': { const statics = op.strings; const part = new op.ctor( // Passing only object with tagName for the element is fine since the // directive only gets PartInfo without the node available in the // constructor {tagName: op.tagName} as HTMLElement, op.name, statics, connectedDisconnectable(), {} ); const value = part.strings === undefined ? result.values[partIndex] : result.values; patchAnyDirectives(part, value, partIndex); let committedValue: unknown = noChange; // Values for EventParts are never emitted if (!(part.type === PartType.EVENT)) { committedValue = getAttributePartCommittedValue( part, value, partIndex ); } // We don't emit anything on the server when value is `noChange` or // `nothing` if (committedValue !== noChange) { const instance = op.useCustomElementInstance ? getLast(renderInfo.customElementInstanceStack) : undefined; if (part.type === PartType.PROPERTY) { yield* renderPropertyPart(instance, op, committedValue); } else if (part.type === PartType.BOOLEAN_ATTRIBUTE) { // Boolean attribute binding yield* renderBooleanAttributePart(instance, op, committedValue); } else { yield* renderAttributePart(instance, op, committedValue); } } partIndex += statics.length - 1; break; } case 'element-part': { // We don't emit anything for element parts (since we only support // directives for now; since they can't render, we don't even bother // running them), but we still need to advance the part index partIndex++; break; } case 'custom-element-open': { // Instantiate the element and its renderer const instance = getElementRenderer( renderInfo, op.tagName, op.ctor, op.staticAttributes ); // Set static attributes to the element renderer for (const [name, value] of op.staticAttributes) { instance.setAttribute(name, value); } renderInfo.customElementInstanceStack.push(instance); renderInfo.customElementRendered?.(op.tagName); break; } case 'custom-element-attributes': { const instance = getLast(renderInfo.customElementInstanceStack); if (instance === undefined) { throw new Error( `Internal error: ${op.type} outside of custom element context` ); } // Perform any connect-time work via the renderer (e.g. reflecting any // properties to attributes, for example) if (instance.connectedCallback) { instance.connectedCallback(); } // Render out any attributes on the instance (both static and those // that may have been dynamically set by the renderer) yield* instance.renderAttributes(); // If this element is nested in another, add the `defer-hydration` // attribute, so that it does not enable before the host element // hydrates if (renderInfo.customElementHostStack.length > 0) { yield ' defer-hydration'; } break; } case 'possible-node-marker': { // Add a node marker if this element had attribute bindings or if it // was nested in another and we rendered the `defer-hydration` attribute // since the hydration node walk will need to stop at this element // to hydrate it if ( op.boundAttributesCount > 0 || renderInfo.customElementHostStack.length > 0 ) { yield `<!--lit-node ${op.nodeIndex}-->`; } break; } case 'custom-element-shadow': { const instance = getLast(renderInfo.customElementInstanceStack); if (instance === undefined) { throw new Error( `Internal error: ${op.type} outside of custom element context` ); } if (instance.renderShadow !== undefined) { renderInfo.customElementHostStack.push(instance); const shadowContents = instance.renderShadow(renderInfo); // Only emit a DSR if renderShadow() emitted something (returning // undefined allows effectively no-op rendering the element) if (shadowContents !== undefined) { yield '<template shadowroot="open">'; yield* shadowContents; yield '</template>'; } renderInfo.customElementHostStack.pop(); } break; } case 'custom-element-close': renderInfo.customElementInstanceStack.pop(); break; default: throw new Error('internal error'); } } if (partIndex !== result.values.length) { throw new Error( `unexpected final partIndex: ${partIndex} !== ${result.values.length}` ); } } function* renderPropertyPart( instance: ElementRenderer | undefined, op: AttributePartOp, value: unknown ) { value = value === nothing ? undefined : value; // Property should be reflected to attribute const reflectedName = reflectedAttributeName(op.tagName, op.name); if (instance !== undefined) { instance.setProperty(op.name, value); } if (reflectedName !== undefined) { yield `${reflectedName}="${escapeHtml(String(value))}"`; } } function* renderBooleanAttributePart( instance: ElementRenderer | undefined, op: AttributePartOp, value: unknown ) { if (value && value !== nothing) { if (instance !== undefined) { instance.setAttribute(op.name, ''); } else { yield op.name; } } } function* renderAttributePart( instance: ElementRenderer | undefined, op: AttributePartOp, value: unknown ) { if (value !== nothing) { if (instance !== undefined) { instance.setAttribute(op.name, value as string); } else { yield `${op.name}="${escapeHtml(String(value ?? ''))}"`; } } } const getLast = <T>(a: Array<T>) => a[a.length - 1];
the_stack
import { PuppetBridge } from "./puppetbridge"; import { IRemoteGroup, RemoteGroupResolvable, RemoteRoomResolvable } from "./interfaces"; import { DbGroupStore } from "./db/groupstore"; import { IGroupStoreEntry, IProfileDbEntry } from "./db/interfaces"; import { Log } from "./log"; import { Lock } from "./structures/lock"; import { Util } from "./util"; import { StringFormatter } from "./structures/stringformatter"; const log = new Log("GroupSync"); // tslint:disable-next-line:no-magic-numbers const GROUP_LOOKUP_LOCK_TIMEOUT = 1000 * 60; const GROUP_ID_LENGTH = 30; const MATRIX_URL_SCHEME_MASK = "https://matrix.to/#/"; export class GroupSyncroniser { private groupStore: DbGroupStore; private mxidLock: Lock<string>; constructor( private bridge: PuppetBridge, ) { this.groupStore = this.bridge.groupStore; this.mxidLock = new Lock(GROUP_LOOKUP_LOCK_TIMEOUT); } public async maybeGet(data: IRemoteGroup): Promise<IGroupStoreEntry | null> { const dbPuppetId = await this.bridge.namespaceHandler.getDbPuppetId(data.puppetId); const lockKey = `${dbPuppetId};${data.groupId}`; await this.mxidLock.wait(lockKey); return await this.groupStore.getByRemote(dbPuppetId, data.groupId); } public async maybeGetMxid(data: IRemoteGroup): Promise<string | null> { const group = await this.maybeGet(data); if (!group) { return null; } return group.mxid; } public async getMxid(data: IRemoteGroup, doCreate: boolean = true): Promise<string> { const dbPuppetId = await this.bridge.namespaceHandler.getDbPuppetId(data.puppetId); const lockKey = `${dbPuppetId};${data.groupId}`; await this.mxidLock.wait(lockKey); this.mxidLock.set(lockKey); log.info(`Fetching mxid for groupId ${data.groupId} and puppetId ${dbPuppetId}`); let invites = new Set<string>(); try { // groups are always handled by the AS bot const client = this.bridge.botIntent.underlyingClient; const clientUnstable = client.unstableApis; let group = await this.groupStore.getByRemote(dbPuppetId, data.groupId); const update = { name: false, avatar: false, shortDescription: false, longDescription: false, }; let mxid = ""; let doUpdate = false; let oldProfile: IProfileDbEntry | null = null; let newRooms: string[] = []; const removedRooms: string[] = []; if (!group) { if (!doCreate) { this.mxidLock.release(lockKey); return ""; } log.info("Group doesn't exist yet, creating entry..."); const createInfo = await this.bridge.namespaceHandler.getGroupCreateInfo(data); invites = createInfo.invites; doUpdate = true; // let's fetch the create data via hook const newData = await this.bridge.namespaceHandler.createGroup(data); if (newData) { data = newData; } log.verbose("Creation data:", data); update.shortDescription = data.shortDescription ? true : false; update.longDescription = data.longDescription ? true : false; if (data.roomIds) { newRooms = data.roomIds; } // now create the group while (mxid === "") { try { const localpart = this.makeRandomId(GROUP_ID_LENGTH); mxid = await clientUnstable.createGroup(localpart); } catch (err) { if (err.body.errcode === "M_UNKNOWN" && err.body.error.toLowerCase().includes("group already exists")) { mxid = ""; } else { throw err; } } } if (createInfo.public) { // set it to public await clientUnstable.setGroupJoinPolicy(mxid, "open"); } else { // set it to invite only await clientUnstable.setGroupJoinPolicy(mxid, "invite"); } group = this.groupStore.newData(mxid, data.groupId, dbPuppetId); } else { oldProfile = group; update.shortDescription = data.shortDescription !== undefined && data.shortDescription !== null && data.shortDescription !== group.shortDescription; update.longDescription = data.longDescription !== undefined && data.longDescription !== null && data.longDescription !== group.longDescription; if (data.roomIds) { for (const r of data.roomIds) { if (!group.roomIds.includes(r)) { // new room newRooms.push(r); } } for (const r of group.roomIds) { if (!data.roomIds.includes(r)) { // removed room removedRooms.push(r); break; } } } mxid = group.mxid; } const updateProfile = await Util.ProcessProfileUpdate( oldProfile, data, this.bridge.protocol.namePatterns.group, async (buffer: Buffer, mimetype?: string, filename?: string) => { return await this.bridge.uploadContent(client, buffer, mimetype, filename); }, ); group = Object.assign(group, updateProfile); const groupProfile = { name: group.name || "", avatar_url: group.avatarMxc || "", short_description: group.shortDescription || "", long_description: group.longDescription || "", }; if (updateProfile.hasOwnProperty("name")) { doUpdate = true; groupProfile.name = group.name || ""; } if (updateProfile.hasOwnProperty("avatarMxc")) { log.verbose("Updating avatar"); doUpdate = true; groupProfile.avatar_url = group.avatarMxc || ""; } if (update.shortDescription) { doUpdate = true; groupProfile.short_description = data.shortDescription || ""; group.shortDescription = data.shortDescription; } if (update.longDescription) { doUpdate = true; groupProfile.long_description = data.longDescription || ""; group.longDescription = data.longDescription; } if (data.roomIds && (newRooms.length > 0 || removedRooms.length > 0)) { group.roomIds = data.roomIds; doUpdate = true; } if (doUpdate) { log.verbose("Sending update to matrix server"); await clientUnstable.setGroupProfile(mxid, groupProfile); } if (doUpdate || newRooms.length > 0 || removedRooms.length > 0) { log.verbose("Storing update to DB"); await this.groupStore.set(group); } for (const invite of invites) { await clientUnstable.inviteUserToGroup(mxid, invite); } this.mxidLock.release(lockKey); // update associated rooms only after lock is released if (newRooms.length > 0 || removedRooms.length > 0) { for (const roomId of newRooms) { const roomMxid = await this.bridge.roomSync.maybeGetMxid({ puppetId: group.puppetId, roomId, }); if (roomMxid) { try { await clientUnstable.addRoomToGroup(mxid, roomMxid, false); } catch (err) { } } } for (const roomId of removedRooms) { const roomMxid = await this.bridge.roomSync.maybeGetMxid({ puppetId: group.puppetId, roomId, }); if (roomMxid) { try { await clientUnstable.removeRoomFromGroup(mxid, roomMxid); } catch (err) { } } } } log.verbose("Returning mxid"); return mxid; } catch (err) { log.error("Failed fetching mxid:", err.error || err.body || err); this.mxidLock.release(lockKey); throw err; } } public async addRoomToGroup(group: IRemoteGroup, roomId: string, recursionStop: boolean = false) { log.verbose(`Adding rooom ${roomId} to group ${group.groupId}`); // here we can't just invoke getMxid with the diff to add the room // as it might already be in the array but not actually part of the group const roomMxid = await this.bridge.roomSync.maybeGetMxid({ puppetId: group.puppetId, roomId, }); if (!roomMxid) { log.silly("room not found"); return; } const mxid = await this.getMxid(group); const dbGroup = await this.maybeGet(group); if (dbGroup) { if (!dbGroup.roomIds.includes(roomId)) { dbGroup.roomIds.push(roomId); } await this.groupStore.set(dbGroup); } const clientUnstable = this.bridge.botIntent.underlyingClient.unstableApis; try { await clientUnstable.addRoomToGroup(mxid, roomMxid, false); } catch (err) { } } public async removeRoomFromGroup(group: IRemoteGroup, roomId: string) { log.info(`Removing room ${roomId} from group ${group.groupId}`); // as before, we don't invoke via getMxid as maybe the room is still // wrongfully in the group const roomMxid = await this.bridge.roomSync.maybeGetMxid({ puppetId: group.puppetId, roomId, }); if (!roomMxid) { return; } const dbGroup = await this.maybeGet(group); if (!dbGroup) { return; } group.roomIds = dbGroup.roomIds; const foundIndex = group.roomIds.indexOf(roomId); if (foundIndex === -1) { return; } group.roomIds.splice(foundIndex, 1); await this.groupStore.set(dbGroup); const clientUnstable = this.bridge.botIntent.underlyingClient.unstableApis; try { await clientUnstable.removeRoomFromGroup(dbGroup.mxid, roomMxid); } catch (err) { } } public async getPartsFromMxid(mxid: string): Promise<IRemoteGroup | null> { const ret = await this.groupStore.getByMxid(mxid); if (!ret) { return null; } return { puppetId: ret.puppetId, groupId: ret.groupId, }; } public async resolve(str: RemoteGroupResolvable): Promise<IRemoteGroup | null> { const remoteRoomToGroup = async (ident: RemoteRoomResolvable): Promise<IRemoteGroup | null> => { const parts = await this.bridge.roomSync.resolve(ident); if (!parts) { return null; } const room = await this.bridge.roomSync.maybeGet(parts); if (!room || !room.groupId) { return null; } return { puppetId: room.puppetId, groupId: room.groupId, }; }; if (!str) { return null; } if (typeof str !== "string") { if ((str as IRemoteGroup).groupId) { return str as IRemoteGroup; } return await remoteRoomToGroup(str as RemoteRoomResolvable); } str = str.trim(); if (str.startsWith(MATRIX_URL_SCHEME_MASK)) { str = str.slice(MATRIX_URL_SCHEME_MASK.length); } switch (str[0]) { case "#": case "!": case "@": return await remoteRoomToGroup(str); case "+": return await this.getPartsFromMxid(str); default: { const parts = str.split(" "); const puppetId = Number(parts[0]); if (!isNaN(puppetId)) { return { puppetId, groupId: parts[1], }; } return null; } } return null; } private makeRandomId(length: number): string { let result = ""; // uppercase chars aren't allowed in MXIDs const chars = "abcdefghijklmnopqrstuvwxyz-_1234567890="; const charsLen = chars.length; for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * charsLen)); } return result; } }
the_stack
import ManagedArray from '../../utils/managed-array'; import {TILE_REFINEMENT} from '../../constants'; export type TilesetTraverserProps = { loadSiblings?: boolean; skipLevelOfDetail?: boolean; maximumScreenSpaceError?: number; onTraversalEnd?: (frameState) => any; viewportTraversersMap?: {[key: string]: any}; basePath?: string; }; export type Props = { loadSiblings: boolean; skipLevelOfDetail: boolean; updateTransforms: boolean; maximumScreenSpaceError: number; onTraversalEnd: (frameState) => any; viewportTraversersMap: {[key: string]: any}; basePath: string; }; export const DEFAULT_PROPS: Props = { loadSiblings: false, skipLevelOfDetail: false, maximumScreenSpaceError: 2, updateTransforms: true, onTraversalEnd: () => {}, viewportTraversersMap: {}, basePath: '' }; export default class TilesetTraverser { options: Props; root: any; requestedTiles: object; selectedTiles: object; emptyTiles: object; protected _traversalStack: ManagedArray; protected _emptyTraversalStack: ManagedArray; protected _frameNumber: number | null; // TODO nested props constructor(options: TilesetTraverserProps) { this.options = {...DEFAULT_PROPS, ...options}; // TRAVERSAL // temporary storage to hold the traversed tiles during a traversal this._traversalStack = new ManagedArray(); this._emptyTraversalStack = new ManagedArray(); // set in every traverse cycle this._frameNumber = null; // fulfill in traverse call this.root = null; // RESULT // tiles should be rendered this.selectedTiles = {}; // tiles should be loaded from server this.requestedTiles = {}; // tiles does not have render content this.emptyTiles = {}; } // tiles should be visible traverse(root, frameState, options) { this.root = root; // for root screen space error this.options = {...this.options, ...options}; // reset result this.reset(); // update tile (visibility and expiration) this.updateTile(root, frameState); this._frameNumber = frameState.frameNumber; this.executeTraversal(root, frameState); } reset() { this.requestedTiles = {}; this.selectedTiles = {}; this.emptyTiles = {}; this._traversalStack.reset(); this._emptyTraversalStack.reset(); } // execute traverse // Depth-first traversal that traverses all visible tiles and marks tiles for selection. // If skipLevelOfDetail is off then a tile does not refine until all children are loaded. // This is the traditional replacement refinement approach and is called the base traversal. // Tiles that have a greater screen space error than the base screen space error are part of the base traversal, // all other tiles are part of the skip traversal. The skip traversal allows for skipping levels of the tree // and rendering children and parent tiles simultaneously. /* eslint-disable-next-line complexity, max-statements */ executeTraversal(root, frameState) { // stack to store traversed tiles, only visible tiles should be added to stack // visible: visible in the current view frustum const stack = this._traversalStack; root._selectionDepth = 1; stack.push(root); while (stack.length > 0) { // 1. pop tile const tile = stack.pop(); // 2. check if tile needs to be refine, needs refine if a tile's LoD is not sufficient and tile has available children (available content) let shouldRefine = false; if (this.canTraverse(tile, frameState)) { this.updateChildTiles(tile, frameState); shouldRefine = this.updateAndPushChildren( tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth ); } // 3. decide if should render (select) this tile // - tile does not have render content // - tile has render content and tile is `add` type (pointcloud) // - tile has render content and tile is `replace` type (photogrammetry) and can't refine any further const parent = tile.parent; const parentRefines = Boolean(!parent || parent._shouldRefine); const stoppedRefining = !shouldRefine; if (!tile.hasRenderContent) { this.emptyTiles[tile.id] = tile; this.loadTile(tile, frameState); if (stoppedRefining) { this.selectTile(tile, frameState); } // additive tiles } else if (tile.refine === TILE_REFINEMENT.ADD) { // Additive tiles are always loaded and selected this.loadTile(tile, frameState); this.selectTile(tile, frameState); // replace tiles } else if (tile.refine === TILE_REFINEMENT.REPLACE) { // Always load tiles in the base traversal // Select tiles that can't refine further this.loadTile(tile, frameState); if (stoppedRefining) { this.selectTile(tile, frameState); } } // 3. update cache, most recent touched tiles have higher priority to be fetched from server this.touchTile(tile, frameState); // 4. update tile refine prop and parent refinement status to trickle down to the descendants tile._shouldRefine = shouldRefine && parentRefines; } this.options.onTraversalEnd(frameState); } updateChildTiles(tile, frameState) { const children = tile.children; for (const child of children) { this.updateTile(child, frameState); } return true; } /* eslint-disable complexity, max-statements */ updateAndPushChildren(tile, frameState, stack, depth) { const {loadSiblings, skipLevelOfDetail} = this.options; const children = tile.children; // sort children tiles children.sort(this.compareDistanceToCamera.bind(this)); // For traditional replacement refinement only refine if all children are loaded. // Empty tiles are exempt since it looks better if children stream in as they are loaded to fill the empty space. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail; let hasVisibleChild = false; let refines = true; for (const child of children) { child._selectionDepth = depth; if (child.isVisibleAndInRequestVolume) { if (stack.find(child)) { stack.delete(child); } stack.push(child); hasVisibleChild = true; } else if (checkRefines || loadSiblings) { // Keep non-visible children loaded since they are still needed before the parent can refine. // Or loadSiblings is true so always load tiles regardless of visibility. this.loadTile(child, frameState); this.touchTile(child, frameState); } if (checkRefines) { let childRefines; if (!child._inRequestVolume) { childRefines = false; } else if (!child.hasRenderContent) { childRefines = this.executeEmptyTraversal(child, frameState); } else { childRefines = child.contentAvailable; } refines = refines && childRefines; if (!refines) { return false; } } } if (!hasVisibleChild) { refines = false; } return refines; } /* eslint-enable complexity, max-statements */ updateTile(tile, frameState) { this.updateTileVisibility(tile, frameState); } // tile to render in the browser selectTile(tile, frameState) { if (this.shouldSelectTile(tile)) { // The tile can be selected right away and does not require traverseAndSelect tile._selectedFrame = frameState.frameNumber; this.selectedTiles[tile.id] = tile; } } // tile to load from server loadTile(tile, frameState) { if (this.shouldLoadTile(tile)) { tile._requestedFrame = frameState.frameNumber; tile._priority = tile._getPriority(); this.requestedTiles[tile.id] = tile; } } // cache tile touchTile(tile, frameState) { tile.tileset._cache.touch(tile); tile._touchedFrame = frameState.frameNumber; } // tile should be visible // tile should have children // tile LoD (level of detail) is not sufficient under current viewport canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) { if (!tile.hasChildren) { return false; } // cesium specific if (tile.hasTilesetContent) { // Traverse external this to visit its root tile // Don't traverse if the subtree is expired because it will be destroyed return !tile.contentExpired; } if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) { return false; } return this.shouldRefine(tile, frameState, useParentMetric); } shouldLoadTile(tile) { // if request tile is in current frame // and has unexpired render content return tile.hasUnloadedContent || tile.contentExpired; } shouldSelectTile(tile) { // if select tile is in current frame // and content available return tile.contentAvailable && !this.options.skipLevelOfDetail; } // Decide if tile LoD (level of detail) is not sufficient under current viewport shouldRefine(tile, frameState, useParentMetric) { let screenSpaceError = tile._screenSpaceError; if (useParentMetric) { screenSpaceError = tile.getScreenSpaceError(frameState, true); } return screenSpaceError > this.options.maximumScreenSpaceError; } updateTileVisibility(tile, frameState) { const viewportIds: string[] = []; if (this.options.viewportTraversersMap) { for (const key in this.options.viewportTraversersMap) { const value = this.options.viewportTraversersMap[key]; if (value === frameState.viewport.id) { viewportIds.push(key); } } } else { viewportIds.push(frameState.viewport.id); } tile.updateVisibility(frameState, viewportIds); } // UTILITIES compareDistanceToCamera(b, a) { return b._distanceToCamera - a._distanceToCamera; } anyChildrenVisible(tile, frameState) { let anyVisible = false; for (const child of tile.children) { child.updateVisibility(frameState); anyVisible = anyVisible || child.isVisibleAndInRequestVolume; } return anyVisible; } // Depth-first traversal that checks if all nearest descendants with content are loaded. // Ignores visibility. executeEmptyTraversal(root, frameState) { let allDescendantsLoaded = true; const stack = this._emptyTraversalStack; stack.push(root); while (stack.length > 0 && allDescendantsLoaded) { const tile = stack.pop(); this.updateTile(tile, frameState); if (!tile.isVisibleAndInRequestVolume) { // Load tiles that aren't visible since they are still needed for the parent to refine this.loadTile(tile, frameState); } this.touchTile(tile, frameState); // Only traverse if the tile is empty - traversal stop at descendants with content const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true); if (traverse) { const children = tile.children; for (const child of children) { // eslint-disable-next-line max-depth if (stack.find(child)) { stack.delete(child); } stack.push(child); } } else if (!tile.contentAvailable) { allDescendantsLoaded = false; } } return allDescendantsLoaded; } } // TODO // enable expiration // enable optimization hint
the_stack
import {logWarn} from '../../utils/log'; import {throttle} from '../../utils/throttle'; import {forEach} from '../../utils/array'; import {getDuration} from '../../utils/time'; interface CreateNodeAsapParams { selectNode: () => HTMLElement; createNode: (target: HTMLElement) => void; updateNode: (existing: HTMLElement) => void; selectTarget: () => HTMLElement; createTarget: () => HTMLElement; isTargetMutation: (mutation: MutationRecord) => boolean; } export function createNodeAsap({ selectNode, createNode, updateNode, selectTarget, createTarget, isTargetMutation, }: CreateNodeAsapParams) { const target = selectTarget(); if (target) { const prev = selectNode(); if (prev) { updateNode(prev); } else { createNode(target); } } else { const observer = new MutationObserver((mutations) => { const mutation = mutations.find(isTargetMutation); if (mutation) { unsubscribe(); const target = selectTarget(); selectNode() || createNode(target); } }); const ready = () => { if (document.readyState !== 'complete') { return; } unsubscribe(); const target = selectTarget() || createTarget(); selectNode() || createNode(target); }; const unsubscribe = () => { document.removeEventListener('readystatechange', ready); observer.disconnect(); }; if (document.readyState === 'complete') { ready(); } else { document.addEventListener('readystatechange', ready); observer.observe(document, {childList: true, subtree: true}); } } } export function removeNode(node: Node) { node && node.parentNode && node.parentNode.removeChild(node); } export function watchForNodePosition<T extends Node>( node: T, mode: 'parent' | 'prev-sibling', onRestore = Function.prototype, ) { const MAX_ATTEMPTS_COUNT = 10; const RETRY_TIMEOUT = getDuration({seconds: 2}); const ATTEMPTS_INTERVAL = getDuration({seconds: 10}); const prevSibling = node.previousSibling; let parent = node.parentNode; if (!parent) { throw new Error('Unable to watch for node position: parent element not found'); } if (mode === 'prev-sibling' && !prevSibling) { throw new Error('Unable to watch for node position: there is no previous sibling'); } let attempts = 0; let start: number = null; let timeoutId: number = null; const restore = throttle(() => { if (timeoutId) { return; } attempts++; const now = Date.now(); if (start == null) { start = now; } else if (attempts >= MAX_ATTEMPTS_COUNT) { if (now - start < ATTEMPTS_INTERVAL) { logWarn(`Node position watcher paused: retry in ${RETRY_TIMEOUT}ms`, node, prevSibling); timeoutId = setTimeout(() => { start = null; attempts = 0; timeoutId = null; restore(); }, RETRY_TIMEOUT); return; } start = now; attempts = 1; } if (mode === 'parent') { if (prevSibling && prevSibling.parentNode !== parent) { logWarn('Unable to restore node position: sibling parent changed', node, prevSibling, parent); stop(); return; } } if (mode === 'prev-sibling') { if (prevSibling.parentNode == null) { logWarn('Unable to restore node position: sibling was removed', node, prevSibling, parent); stop(); return; } if (prevSibling.parentNode !== parent) { logWarn('Style was moved to another parent', node, prevSibling, parent); updateParent(prevSibling.parentNode); } } logWarn('Restoring node position', node, prevSibling, parent); parent.insertBefore(node, prevSibling ? prevSibling.nextSibling : parent.firstChild); observer.takeRecords(); onRestore && onRestore(); }); const observer = new MutationObserver(() => { if ( (mode === 'parent' && node.parentNode !== parent) || (mode === 'prev-sibling' && node.previousSibling !== prevSibling) ) { restore(); } }); const run = () => { observer.observe(parent, {childList: true}); }; const stop = () => { clearTimeout(timeoutId); observer.disconnect(); restore.cancel(); }; const skip = () => { observer.takeRecords(); }; const updateParent = (parentNode: Node & ParentNode) => { parent = parentNode; stop(); run(); }; run(); return {run, stop, skip}; } export function iterateShadowHosts(root: Node, iterator: (host: Element) => void) { if (root == null) { return; } const walker = document.createTreeWalker( root, NodeFilter.SHOW_ELEMENT, { acceptNode(node) { return (node as Element).shadowRoot == null ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT; } }, ); for ( let node = ((root as Element).shadowRoot ? walker.currentNode : walker.nextNode()) as Element; node != null; node = walker.nextNode() as Element ) { iterator(node); iterateShadowHosts(node.shadowRoot, iterator); } } export function isDOMReady() { return document.readyState === 'complete' || document.readyState === 'interactive'; } const readyStateListeners = new Set<() => void>(); export function addDOMReadyListener(listener: () => void) { readyStateListeners.add(listener); } export function removeDOMReadyListener(listener: () => void) { readyStateListeners.delete(listener); } // `interactive` can and will be fired when their are still stylesheets loading. // We use certain actions that can cause a forced layout change, which is bad. export function isReadyStateComplete() { return document.readyState === 'complete'; } const readyStateCompleteListeners = new Set<() => void>(); export function addReadyStateCompleteListener(listener: () => void) { readyStateCompleteListeners.add(listener); } export function cleanReadyStateCompleteListeners() { readyStateCompleteListeners.clear(); } if (!isDOMReady()) { const onReadyStateChange = () => { if (isDOMReady()) { readyStateListeners.forEach((listener) => listener()); readyStateListeners.clear(); if (isReadyStateComplete()) { document.removeEventListener('readystatechange', onReadyStateChange); readyStateCompleteListeners.forEach((listener) => listener()); readyStateCompleteListeners.clear(); } } }; document.addEventListener('readystatechange', onReadyStateChange); } const HUGE_MUTATIONS_COUNT = 1000; function isHugeMutation(mutations: MutationRecord[]) { if (mutations.length > HUGE_MUTATIONS_COUNT) { return true; } let addedNodesCount = 0; for (let i = 0; i < mutations.length; i++) { addedNodesCount += mutations[i].addedNodes.length; if (addedNodesCount > HUGE_MUTATIONS_COUNT) { return true; } } return false; } export interface ElementsTreeOperations { additions: Set<Element>; moves: Set<Element>; deletions: Set<Element>; } function getElementsTreeOperations(mutations: MutationRecord[]): ElementsTreeOperations { const additions = new Set<Element>(); const deletions = new Set<Element>(); const moves = new Set<Element>(); mutations.forEach((m) => { forEach(m.addedNodes, (n) => { if (n instanceof Element && n.isConnected) { additions.add(n); } }); forEach(m.removedNodes, (n) => { if (n instanceof Element) { if (n.isConnected) { moves.add(n); additions.delete(n); } else { deletions.add(n); } } }); }); const duplicateAdditions = [] as Element[]; const duplicateDeletions = [] as Element[]; additions.forEach((node) => { if (additions.has(node.parentElement)) { duplicateAdditions.push(node); } }); deletions.forEach((node) => { if (deletions.has(node.parentElement)) { duplicateDeletions.push(node); } }); duplicateAdditions.forEach((node) => additions.delete(node)); duplicateDeletions.forEach((node) => deletions.delete(node)); return {additions, moves, deletions}; } interface OptimizedTreeObserverCallbacks { onMinorMutations: (operations: ElementsTreeOperations) => void; onHugeMutations: (root: Document | ShadowRoot) => void; } const optimizedTreeObservers = new Map<Node, MutationObserver>(); const optimizedTreeCallbacks = new WeakMap<MutationObserver, Set<OptimizedTreeObserverCallbacks>>(); // TODO: Use a single function to observe all shadow roots. export function createOptimizedTreeObserver(root: Document | ShadowRoot, callbacks: OptimizedTreeObserverCallbacks) { let observer: MutationObserver; let observerCallbacks: Set<OptimizedTreeObserverCallbacks>; let domReadyListener: () => void; if (optimizedTreeObservers.has(root)) { observer = optimizedTreeObservers.get(root); observerCallbacks = optimizedTreeCallbacks.get(observer); } else { let hadHugeMutationsBefore = false; let subscribedForReadyState = false; observer = new MutationObserver((mutations: MutationRecord[]) => { if (isHugeMutation(mutations)) { if (!hadHugeMutationsBefore || isDOMReady()) { observerCallbacks.forEach(({onHugeMutations}) => onHugeMutations(root)); } else if (!subscribedForReadyState) { domReadyListener = () => observerCallbacks.forEach(({onHugeMutations}) => onHugeMutations(root)); addDOMReadyListener(domReadyListener); subscribedForReadyState = true; } hadHugeMutationsBefore = true; } else { const elementsOperations = getElementsTreeOperations(mutations); observerCallbacks.forEach(({onMinorMutations}) => onMinorMutations(elementsOperations)); } }); observer.observe(root, {childList: true, subtree: true}); optimizedTreeObservers.set(root, observer); observerCallbacks = new Set(); optimizedTreeCallbacks.set(observer, observerCallbacks); } observerCallbacks.add(callbacks); return { disconnect() { observerCallbacks.delete(callbacks); if (domReadyListener) { removeDOMReadyListener(domReadyListener); } if (observerCallbacks.size === 0) { observer.disconnect(); optimizedTreeCallbacks.delete(observer); optimizedTreeObservers.delete(root); } }, }; }
the_stack
import {MetadataAccessor, MetadataInspector} from '@loopback/metadata'; import debugFactory from 'debug'; import { Binding, BindingScope, BindingTag, BindingTemplate, DynamicValueProviderClass, isDynamicValueProviderClass, } from './binding'; import {BindingAddress} from './binding-key'; import {ContextTags} from './keys'; import {Provider} from './provider'; import {Constructor} from './value-promise'; const debug = debugFactory('loopback:context:binding-inspector'); /** * Binding metadata from `@injectable` * * @typeParam T - Value type */ export type BindingMetadata<T = unknown> = { /** * An array of template functions to configure a binding */ templates: BindingTemplate<T>[]; /** * The target class where binding metadata is decorated */ target: Constructor<T>; }; /** * Metadata key for binding metadata */ export const BINDING_METADATA_KEY = MetadataAccessor.create< BindingMetadata, ClassDecorator >('binding.metadata'); /** * An object to configure binding scope and tags */ export type BindingScopeAndTags = { scope?: BindingScope; tags?: BindingTag | BindingTag[]; }; /** * Specification of parameters for `@injectable()` */ export type BindingSpec<T = unknown> = BindingTemplate<T> | BindingScopeAndTags; /** * Check if a class implements `Provider` interface * @param cls - A class * * @typeParam T - Value type */ export function isProviderClass<T>( cls: unknown, ): cls is Constructor<Provider<T>> { return ( typeof cls === 'function' && typeof cls.prototype?.value === 'function' ); } /** * A factory function to create a template function to bind the target class * as a `Provider`. * @param target - Target provider class * * @typeParam T - Value type */ export function asProvider<T>( target: Constructor<Provider<T>>, ): BindingTemplate<T> { return function bindAsProvider(binding) { binding.toProvider(target).tag(ContextTags.PROVIDER, { [ContextTags.TYPE]: ContextTags.PROVIDER, }); }; } /** * A factory function to create a template function to bind the target class * as a class or `Provider`. * @param target - Target class, which can be an implementation of `Provider` * or `DynamicValueProviderClass` * * @typeParam T - Value type */ export function asClassOrProvider<T>( target: Constructor<T | Provider<T>> | DynamicValueProviderClass<T>, ): BindingTemplate<T> { // Add a template to bind to a class or provider return function bindAsClassOrProvider(binding) { if (isProviderClass(target)) { asProvider(target)(binding); } else if (isDynamicValueProviderClass<T>(target)) { binding.toDynamicValue(target).tag(ContextTags.DYNAMIC_VALUE_PROVIDER, { [ContextTags.TYPE]: ContextTags.DYNAMIC_VALUE_PROVIDER, }); } else { binding.toClass(target as Constructor<T>); } }; } /** * Convert binding scope and tags as a template function * @param scopeAndTags - Binding scope and tags * * @typeParam T - Value type */ export function asBindingTemplate<T = unknown>( scopeAndTags: BindingScopeAndTags, ): BindingTemplate<T> { return function applyBindingScopeAndTag(binding) { if (scopeAndTags.scope) { binding.inScope(scopeAndTags.scope); } if (scopeAndTags.tags) { if (Array.isArray(scopeAndTags.tags)) { binding.tag(...scopeAndTags.tags); } else { binding.tag(scopeAndTags.tags); } } }; } /** * Get binding metadata for a class * @param target - The target class * * @typeParam T - Value type */ export function getBindingMetadata<T = unknown>( target: Function, ): BindingMetadata<T> | undefined { return MetadataInspector.getClassMetadata<BindingMetadata<T>>( BINDING_METADATA_KEY, target, ); } /** * A binding template function to delete `name` and `key` tags */ export function removeNameAndKeyTags(binding: Binding<unknown>) { if (binding.tagMap) { delete binding.tagMap.name; delete binding.tagMap.key; } } /** * Get the binding template for a class with binding metadata * * @param cls - A class with optional `@injectable` * * @typeParam T - Value type */ export function bindingTemplateFor<T>( cls: Constructor<T | Provider<T>> | DynamicValueProviderClass<T>, options?: BindingFromClassOptions, ): BindingTemplate<T> { const spec = getBindingMetadata(cls); debug('class %s has binding metadata', cls.name, spec); const templateFunctions = spec?.templates ?? []; if (spec?.target !== cls) { // Make sure the subclass is used as the binding source templateFunctions.push(asClassOrProvider(cls) as BindingTemplate<unknown>); } return function applyBindingTemplatesFromMetadata(binding) { for (const t of templateFunctions) { binding.apply(t); } if (spec?.target !== cls) { // Remove name/key tags inherited from base classes binding.apply(removeNameAndKeyTags); } if (options != null) { applyClassBindingOptions(binding, options); } }; } /** * Mapping artifact types to binding key namespaces (prefixes). * * @example * ```ts * { * repository: 'repositories' * } * ``` */ export type TypeNamespaceMapping = {[name: string]: string}; export const DEFAULT_TYPE_NAMESPACES: TypeNamespaceMapping = { class: 'classes', provider: 'providers', dynamicValueProvider: 'dynamicValueProviders', }; /** * Options to customize the binding created from a class */ export type BindingFromClassOptions = { /** * Binding key */ key?: BindingAddress; /** * Artifact type, such as `server`, `controller`, `repository` or `service` */ type?: string; /** * Artifact name, such as `my-rest-server` and `my-controller`. It * overrides the name tag */ name?: string; /** * Namespace for the binding key, such as `servers` and `controllers`. It * overrides the default namespace or namespace tag */ namespace?: string; /** * Mapping artifact type to binding key namespaces */ typeNamespaceMapping?: TypeNamespaceMapping; /** * Default namespace if the binding does not have an explicit namespace */ defaultNamespace?: string; /** * Default scope if the binding does not have an explicit scope */ defaultScope?: BindingScope; }; /** * Create a binding from a class with decorated metadata. The class is attached * to the binding as follows: * - `binding.toClass(cls)`: if `cls` is a plain class such as `MyController` * - `binding.toProvider(cls)`: if `cls` is a value provider class with a * prototype method `value()` * - `binding.toDynamicValue(cls)`: if `cls` is a dynamic value provider class * with a static method `value()` * * @param cls - A class. It can be either a plain class, a value provider class, * or a dynamic value provider class * @param options - Options to customize the binding key * * @typeParam T - Value type */ export function createBindingFromClass<T>( cls: Constructor<T | Provider<T>> | DynamicValueProviderClass<T>, options: BindingFromClassOptions = {}, ): Binding<T> { debug('create binding from class %s with options', cls.name, options); try { const templateFn = bindingTemplateFor(cls, options); const key = buildBindingKey(cls, options); const binding = Binding.bind<T>(key).apply(templateFn); return binding; } catch (err) { err.message += ` (while building binding for class ${cls.name})`; throw err; } } function applyClassBindingOptions<T>( binding: Binding<T>, options: BindingFromClassOptions, ) { if (options.name) { binding.tag({name: options.name}); } if (options.type) { binding.tag({type: options.type}, options.type); } if (options.defaultScope) { binding.applyDefaultScope(options.defaultScope); } } /** * Find/infer binding key namespace for a type * @param type - Artifact type, such as `controller`, `datasource`, or `server` * @param typeNamespaces - An object mapping type names to namespaces */ function getNamespace(type: string, typeNamespaces = DEFAULT_TYPE_NAMESPACES) { if (type in typeNamespaces) { return typeNamespaces[type]; } else { // Return the plural form return `${type}s`; } } /** * Build the binding key for a class with optional binding metadata. * The binding key is resolved in the following steps: * * 1. Check `options.key`, if it exists, return it * 2. Check if the binding metadata has `key` tag, if yes, return its tag value * 3. Identify `namespace` and `name` to form the binding key as * `<namespace>.<name>`. * - namespace * - `options.namespace` * - `namespace` tag value * - Map `options.type` or `type` tag value to a namespace, for example, * 'controller` to 'controller'. * - name * - `options.name` * - `name` tag value * - the class name * * @param cls - A class to be bound * @param options - Options to customize how to build the key * * @typeParam T - Value type */ function buildBindingKey<T>( cls: Constructor<T | Provider<T>>, options: BindingFromClassOptions = {}, ) { if (options.key) return options.key; const templateFn = bindingTemplateFor(cls); // Create a temporary binding const bindingTemplate = new Binding('template').apply(templateFn); // Is there a `key` tag? let key: string = bindingTemplate.tagMap[ContextTags.KEY]; if (key) return key; let namespace = options.namespace ?? bindingTemplate.tagMap[ContextTags.NAMESPACE] ?? options.defaultNamespace; if (!namespace) { const namespaces = Object.assign( {}, DEFAULT_TYPE_NAMESPACES, options.typeNamespaceMapping, ); // Derive the key from type + name let type = options.type ?? bindingTemplate.tagMap[ContextTags.TYPE]; if (!type) { type = bindingTemplate.tagNames.find(t => namespaces[t] != null) ?? ContextTags.CLASS; } namespace = getNamespace(type, namespaces); } const name = options.name ?? (bindingTemplate.tagMap[ContextTags.NAME] || cls.name); key = `${namespace}.${name}`; return key; }
the_stack
import { TreeGrid } from '..'; import { QueryCellInfoEventArgs, IGrid, RowDataBoundEventArgs, getObject, appendChildren } from '@syncfusion/ej2-grids'; import { templateCompiler, extend } from '@syncfusion/ej2-grids'; import { addClass, createElement, isNullOrUndefined, getValue } from '@syncfusion/ej2-base'; import { ITreeData } from '../base/interface'; import * as events from '../base/constant'; import { isRemoteData, isOffline, getExpandStatus, isFilterChildHierarchy } from '../utils'; import { Column } from '../models'; /** * TreeGrid render module * * @hidden */ export class Render { //Module declarations private parent: TreeGrid; private templateResult: NodeList; /** * Constructor for render module * * @param {TreeGrid} parent - Tree Grid instance */ constructor(parent?: TreeGrid) { this.parent = parent; this.templateResult = null; this.parent.grid.on('template-result', this.columnTemplateResult, this); this.parent.grid.on('reactTemplateRender', this.reactTemplateRender, this); } /** * Updated row elements for TreeGrid * * @param {RowDataBoundEventArgs} args - Row details before its bound to DOM * @returns {void} */ public RowModifier(args: RowDataBoundEventArgs): void { if (!args.data) { return; } const data: ITreeData = <ITreeData>args.data; const parentData: ITreeData = <ITreeData>data.parentItem; if (!isNullOrUndefined(data.parentItem) && !isFilterChildHierarchy(this.parent) && (!(this.parent.allowPaging && !(this.parent.pageSettings.pageSizeMode === 'Root')) || (isRemoteData(this.parent) && !isOffline(this.parent)))) { const collapsed: boolean = (this.parent.initialRender && (!(isNullOrUndefined(parentData[this.parent.expandStateMapping]) || parentData[this.parent.expandStateMapping]) || this.parent.enableCollapseAll)) || !getExpandStatus(this.parent, args.data, this.parent.grid.getCurrentViewRecords()); if (collapsed) { (<HTMLTableRowElement>args.row).style.display = 'none'; } } if (isRemoteData(this.parent) && !isOffline(this.parent)) { const proxy: TreeGrid = this.parent; const parentrec: ITreeData[] = this.parent.getCurrentViewRecords().filter((rec: ITreeData) => { return getValue(proxy.idMapping, rec) === getValue(proxy.parentIdMapping, data); }); if (parentrec.length > 0) { const display: string = parentrec[0].expanded ? 'table-row' : 'none'; args.row.setAttribute('style', 'display: ' + display + ';'); } } //addClass([args.row], 'e-gridrowindex' + index + 'level' + (<ITreeData>args.data).level); const summaryRow: boolean = getObject('isSummaryRow', args.data); if (summaryRow) { addClass([args.row], 'e-summaryrow'); } if (args.row.querySelector('.e-treegridexpand')) { args.row.setAttribute('aria-expanded', 'true'); } else if (args.row.querySelector('.e-treegridcollapse')) { args.row.setAttribute('aria-expanded', 'false'); } if (this.parent.enableCollapseAll && this.parent.initialRender) { if (!isNullOrUndefined(data.parentItem)) { (<HTMLTableRowElement>args.row).style.display = 'none'; } } this.parent.trigger(events.rowDataBound, args); } /** * cell renderer for tree column index cell * * @param {QueryCellInfoEventArgs} args - Cell detail before its bound to DOM * @returns {void} */ public cellRender(args: QueryCellInfoEventArgs): void { if (!args.data) { return; } const grid: IGrid = this.parent.grid; const data: ITreeData = <ITreeData>args.data; let index: number; const ispadfilter: boolean = isNullOrUndefined(data.filterLevel); const pad: number = ispadfilter ? data.level : data.filterLevel; let totalIconsWidth: number = 0; let cellElement: HTMLElement; const column: Column = this.parent.getColumnByUid(args.column.uid); const summaryRow: boolean = data.isSummaryRow; const frozenColumns: number = this.parent.getFrozenColumns(); if (!isNullOrUndefined(data.parentItem)) { index = data.parentItem.index; } else { index = data.index; } if (grid.getColumnIndexByUid(args.column.uid) === this.parent.treeColumnIndex && (args.requestType === 'add' || args.requestType === 'rowDragAndDrop' || args.requestType === 'delete' || isNullOrUndefined(args.cell.querySelector('.e-treecell')))) { const container: Element = createElement('div', { className: 'e-treecolumn-container' }); const emptyExpandIcon: HTMLElement = createElement('span', { className: 'e-icons e-none', styles: 'width: 10px; display: inline-block' }); for (let n: number = 0; n < pad; n++) { totalIconsWidth += 10; container.appendChild(emptyExpandIcon.cloneNode()); } let iconRequired: boolean = !isNullOrUndefined(data.hasFilteredChildRecords) ? data.hasFilteredChildRecords : data.hasChildRecords; if (iconRequired && !isNullOrUndefined(data.childRecords)) { iconRequired = !((<ITreeData>data).childRecords.length === 0 ); } if (iconRequired) { addClass([args.cell], 'e-treerowcell'); const expandIcon: Element = createElement('span', { className: 'e-icons' }); let expand: boolean; if (this.parent.initialRender) { expand = data.expanded && (isNullOrUndefined(data[this.parent.expandStateMapping]) || data[this.parent.expandStateMapping]) && !this.parent.enableCollapseAll; } else { expand = !(!data.expanded || !getExpandStatus(this.parent, data, this.parent.grid.getCurrentViewRecords())); } addClass([expandIcon], (expand ) ? 'e-treegridexpand' : 'e-treegridcollapse'); totalIconsWidth += 18; container.appendChild(expandIcon); emptyExpandIcon.style.width = '7px'; totalIconsWidth += 7; container.appendChild(emptyExpandIcon.cloneNode()); } else if (pad || !pad && !data.level) { // icons width totalIconsWidth += 20; container.appendChild(emptyExpandIcon.cloneNode()); container.appendChild(emptyExpandIcon.cloneNode()); } //should add below code when paging funcitonality implemented // if (data.hasChildRecords) { // addClass([expandIcon], data.expanded ? 'e-treegridexpand' : 'e-treegridcollapse'); // } cellElement = createElement('span', { className: 'e-treecell' }); if (this.parent.allowTextWrap) { cellElement.style.width = 'Calc(100% - ' + totalIconsWidth + 'px)'; } addClass([args.cell], 'e-gridrowindex' + index + 'level' + data.level); this.updateTreeCell(args, cellElement); container.appendChild(cellElement); args.cell.appendChild(container); } else if (this.templateResult) { this.templateResult = null; } let freeze: boolean = (grid.getFrozenLeftColumnsCount() > 0 || grid.getFrozenRightColumnsCount() > 0 ) ? true : false; if (!freeze) { if (frozenColumns > this.parent.treeColumnIndex && frozenColumns > 0 && grid.getColumnIndexByUid(args.column.uid) === frozenColumns) { addClass([args.cell], 'e-gridrowindex' + index + 'level' + data.level); } else if (frozenColumns < this.parent.treeColumnIndex && frozenColumns > 0 && (grid.getColumnIndexByUid(args.column.uid) === frozenColumns || grid.getColumnIndexByUid(args.column.uid) === frozenColumns - 1)) { addClass([args.cell], 'e-gridrowindex' + index + 'level' + data.level); } else if (frozenColumns === this.parent.treeColumnIndex && frozenColumns > 0 && grid.getColumnIndexByUid(args.column.uid) === this.parent.treeColumnIndex - 1) { addClass([args.cell], 'e-gridrowindex' + index + 'level' + data.level); } } else { let freezerightColumns = grid.getFrozenRightColumns(); let freezeLeftColumns = grid.getFrozenLeftColumns(); let movableColumns = grid.getMovableColumns(); if ((freezerightColumns.length > 0) && freezerightColumns[0].field === args.column.field) { addClass([args.cell], 'e-gridrowindex' + index + 'level' + data.level); } else if ((freezeLeftColumns.length > 0) && freezeLeftColumns[0].field === args.column.field) { addClass([args.cell], 'e-gridrowindex' + index + 'level' + data.level); } else if ((movableColumns.length > 0) && movableColumns[0].field === args.column.field) { addClass([args.cell], 'e-gridrowindex' + index + 'level' + data.level); } } if (!isNullOrUndefined(column) && column.showCheckbox) { this.parent.notify('columnCheckbox', args); if (this.parent.allowTextWrap) { const checkboxElement: HTMLElement = <HTMLElement>args.cell.querySelectorAll('.e-frame')[0]; const width: number = parseInt(checkboxElement.style.width, 16); totalIconsWidth += width; totalIconsWidth += 10; if (grid.getColumnIndexByUid(args.column.uid) === this.parent.treeColumnIndex) { cellElement = <HTMLElement>args.cell.querySelector('.e-treecell'); } else { cellElement = <HTMLElement>args.cell.querySelector('.e-treecheckbox'); } cellElement.style.width = 'Calc(100% - ' + totalIconsWidth + 'px)'; } } if (summaryRow) { addClass([args.cell], 'e-summarycell'); const summaryData: string = getObject(args.column.field, args.data); if (args.cell.querySelector('.e-treecell') != null) { args.cell.querySelector('.e-treecell').innerHTML = summaryData; } else { args.cell.innerHTML = summaryData; } } if (isNullOrUndefined(this.parent.rowTemplate)) { this.parent.trigger(events.queryCellInfo, args); } } private updateTreeCell(args: QueryCellInfoEventArgs, cellElement: HTMLElement): void { const columnModel: Column[] = getValue('columnModel', this.parent); const treeColumn: Column = columnModel[this.parent.treeColumnIndex]; const templateFn: string = 'templateFn'; const colindex: number = args.column.index; if (isNullOrUndefined(treeColumn.field)) { args.cell.setAttribute('aria-colindex', colindex + ''); } if (treeColumn.field === args.column.field && !isNullOrUndefined(treeColumn.template)) { args.column.template = treeColumn.template; args.column[templateFn] = templateCompiler(args.column.template); args.cell.classList.add('e-templatecell'); } const textContent: string = args.cell.querySelector('.e-treecell') != null ? args.cell.querySelector('.e-treecell').innerHTML : args.cell.innerHTML; if ( typeof(args.column.template) === 'object' && this.templateResult ) { appendChildren(cellElement , this.templateResult); this.templateResult = null; args.cell.innerHTML = ''; } else if (args.cell.classList.contains('e-templatecell')) { let len: number = args.cell.children.length; const tempID: string = this.parent.element.id + args.column.uid; if (treeColumn.field === args.column.field && !isNullOrUndefined(treeColumn.template)) { const portals: string = 'portals'; const renderReactTemplates: string = 'renderReactTemplates'; if ((<{ isReact?: boolean }>this.parent).isReact && typeof (args.column.template) !== 'string') { args.column[templateFn](args.data, this.parent, 'template', tempID, null, null, cellElement); if (isNullOrUndefined(this.parent.grid[portals])) { this.parent.grid[portals] = this.parent[portals]; } this.parent.notify('renderReactTemplate', this.parent[portals]); this.parent[renderReactTemplates](); } else { const str: string = 'isStringTemplate'; const result: Element[] = args.column[templateFn]( extend({ 'index': '' }, args.data), this.parent, 'template', tempID, this.parent[str]); appendChildren(cellElement, result); } delete args.column.template; delete args.column[templateFn]; args.cell.innerHTML = ''; } else { for (let i: number = 0; i < len; len = args.cell.children.length) { cellElement.appendChild(args.cell.children[i]); } } } else { cellElement.innerHTML = textContent; args.cell.innerHTML = ''; } } private columnTemplateResult(args: {template : NodeList, name: string}): void { this.templateResult = args.template; } private reactTemplateRender(args: Object[]): void { const renderReactTemplates: string = 'renderReactTemplates'; const portals: string = 'portals'; this.parent[portals] = args; this.parent.notify('renderReactTemplate', this.parent[portals]); this.parent[renderReactTemplates](); } public destroy(): void { this.parent.grid.off('template-result', this.columnTemplateResult); this.parent.grid.off('reactTemplateRender', this.reactTemplateRender); } }
the_stack
import { Application } from '../../../declarations' import config from '../../appconfig' import axios, { AxiosRequestConfig } from 'axios' import mimeType from 'mime-types' import { useStorageProvider } from '../../media/storageprovider/storageprovider' import { Agent } from 'https' import { Params } from '@feathersjs/feathers' import { ProjectInterface } from '@xrengine/common/src/interfaces/ProjectInterface' const storageProvider = useStorageProvider() const urlRegex = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_.~#?&//=]*)$/ const thumbnailRegex = /([a-zA-Z0-9_-]+).jpeg/ const avatarRegex = /avatars\/([a-zA-Z0-9_-]+).([a-zA-Z0-9_-]+)/ const getAssetKey = (value: string, packName: string) => `content-pack/${packName}/assets/${value}` const getAssetS3Key = (value: string) => value.replace('/assets', '') const getAvatarKey = (packName: string, key: string) => `content-pack/${packName}/${key}` const getAvatarThumbnailKey = (packName: string, key: string) => `content-pack/${packName}/${key}` const getThumbnailKey = (value: string) => { const regexExec = thumbnailRegex.exec(value) return `${regexExec[0]}` } const getAvatarLinkKey = (value: string) => { const regexExec = avatarRegex.exec(value) return `${regexExec[0]}` } export const getContentType = (url: string) => { if (/.glb$/.test(url) === true) return 'glb' if (/.jpeg$/.test(url) === true) return 'jpeg' if (/.json$/.test(url) === true) return 'json' if (/.ts$/.test(url) === true) return 'ts' if (/.tsx$/.test(url) === true) return 'tsx' return 'octet-stream' } export function getAxiosConfig(responseType?: string): AxiosRequestConfig { const axiosConfig = { responseType: responseType === 'json' ? 'json' : 'arraybuffer' } as AxiosRequestConfig if (config.server.mode === 'local') axiosConfig.httpsAgent = new Agent({ rejectUnauthorized: false }) return axiosConfig } export function assembleScene(scene: any, contentPack: string): any { const uploadPromises = [] const worldFile = { version: 4, root: scene.entities[0].entityId, metadata: JSON.parse(scene.metadata), entities: {} } for (const index in scene.entities) { const entity = scene.entities[index] as any const patchedComponents = [] for (const index in entity.components) { const component = entity.components[index] // eslint-disable-next-line prefer-const for (let [key, value] of Object.entries(component.props) as [string, any]) { if (typeof value === 'string' && key !== 'link') { const regexExec = urlRegex.exec(value) if (regexExec != null) { const promise = new Promise(async (resolve, reject) => { value = regexExec[2] as string component.props[key] = `/assets${value}` if (value[0] === '/') value = value.slice(1) const file = await storageProvider.getObject(value) await storageProvider.putObject({ Body: file.Body, ContentType: file.ContentType, Key: getAssetKey(value as string, contentPack) }) resolve(null) }) uploadPromises.push(promise) } } } const toBePushed = { name: component.name, props: component.props } patchedComponents.push(toBePushed) } worldFile.entities[entity.entityId] = { name: entity.name, parent: entity.parent, index: entity.index, components: patchedComponents } } return { worldFile, uploadPromises } } export function assembleProject(project: any, contentPack: string): Promise<any> { console.log('assembleProject', project, contentPack) return new Promise(async (resolve, reject) => { try { const manifest = await axios.get(project.storageProviderManifest, getAxiosConfig()) const data = JSON.parse(manifest.data.toString()) const files = data.files const uploadPromises = [] uploadPromises.push( storageProvider.putObject({ Body: manifest.data, ContentType: getContentType(project.storageProviderManifest), Key: `content-pack/${contentPack}/project/${project.name}/manifest.json` }) ) files.forEach((file) => { const path = file.replace('./', '') const subFileLink = project.storageProviderManifest.replace('manifest.json', path) uploadPromises.push( new Promise(async (resolve) => { const fileResult = await axios.get(subFileLink, getAxiosConfig()) await storageProvider.putObject({ Body: fileResult.data, ContentType: getContentType(path), Key: `content-pack/${contentPack}/project/${project.name}/${path}` }) resolve(true) }) ) }) resolve({ uploadPromises }) } catch (err) { reject(err) } }) } export async function populateScene( sceneId: string, scene: any, manifestUrl: any, app: Application, thumbnailUrl?: string ): Promise<any> { const promises = [] const rootPackUrl = manifestUrl.replace('/manifest.json', '') const existingSceneResult = await (app.service('collection') as any).Model.findOne({ where: { sid: sceneId } }) if (existingSceneResult != null) { if (existingSceneResult.thumbnailOwnedFileId != null) await app.service('static-resource').remove(existingSceneResult.thumbnailOwnedFileId) const entityResult = (await app.service('entity').find({ query: { collectionId: existingSceneResult.id } })) as any await Promise.all( entityResult.data.map(async (entity) => { await app.service('component').remove(null, { where: { entityId: entity.id } }) return app.service('entity').remove(entity.id) }) ) await app.service('collection').remove(existingSceneResult.id) } const collection = await app.service('collection').create({ sid: sceneId, name: scene.metadata.name, metadata: scene.metadata, version: scene.version, isPublic: true, type: 'scene' }) if (thumbnailUrl != null) { const thumbnailResult = await axios.get(thumbnailUrl, getAxiosConfig()) const thumbnailKey = getThumbnailKey(thumbnailUrl) await storageProvider.putObject({ Body: thumbnailResult.data, ContentType: 'jpeg', Key: thumbnailKey }) await app.service('static-resource').create({ sid: collection.sid, url: `https://${storageProvider.cacheDomain}/${thumbnailKey}`, mimeType: 'image/jpeg' }) const newStaticResource = await app.service('static-resource').find({ query: { sid: collection.sid, mimeType: 'image/jpeg' } }) await app.service('static-resource').patch(newStaticResource.data[0].id, { key: `${newStaticResource.data[0].id}.jpeg` }) await app.service('collection').patch(collection.id, { thumbnailOwnedFileId: newStaticResource.data[0].id }) } for (const [key, value] of Object.entries(scene.entities) as [string, any]) { const entityResult = await app.service('entity').create({ entityId: key, name: value.name, parent: value.parent, collectionId: collection.id, index: value.index }) value.components.forEach(async (component) => { for (const [key, value] of Object.entries(component.props)) { if (typeof value === 'string' && /^\/assets/.test(value) === true) { component.props[key] = rootPackUrl + value // Insert Download/S3 upload const contentType = getContentType(component.props[key]) const downloadResult = await axios.get(component.props[key], getAxiosConfig('json')) await storageProvider.putObject({ Body: downloadResult.data, ContentType: contentType, Key: getAssetS3Key(value as string) }) } } await app.service('component').create({ data: component.props, entityId: entityResult.id, type: component.name }) }) } return Promise.all(promises) } export async function populateAvatar(avatar: any, app: Application): Promise<any> { const avatarPromise = new Promise(async (resolve) => { const avatarResult = await axios.get(avatar.avatar, getAxiosConfig()) const avatarKey = getAvatarLinkKey(avatar.avatar) await storageProvider.putObject({ Body: avatarResult.data, ContentType: mimeType.lookup(avatarKey) as string, Key: avatarKey }) const existingAvatarResult = await (app.service('static-resource') as any).Model.findOne({ where: { name: avatar.name, staticResourceType: 'avatar' } }) if (existingAvatarResult != null) await app.service('static-resource').remove(existingAvatarResult.id) await app.service('static-resource').create({ name: avatar.name, url: `https://${storageProvider.cacheDomain}/${avatarKey}`, key: avatarKey, staticResourceType: 'avatar' }) resolve(true) }) const thumbnailPromise = new Promise(async (resolve) => { const thumbnailResult = await axios.get(avatar.thumbnail, getAxiosConfig()) const thumbnailKey = getAvatarLinkKey(avatar.thumbnail) await storageProvider.putObject({ Body: thumbnailResult.data, ContentType: mimeType.lookup(thumbnailKey) as string, Key: thumbnailKey }) const existingThumbnailResult = await (app.service('static-resource') as any).Model.findOne({ where: { name: avatar.name, staticResourceType: 'user-thumbnail' } }) if (existingThumbnailResult != null) await app.service('static-resource').remove(existingThumbnailResult.id) await app.service('static-resource').create({ name: avatar.name, url: `https://${storageProvider.cacheDomain}/${thumbnailKey}`, key: thumbnailKey, staticResourceType: 'user-thumbnail' }) resolve(true) }) return Promise.all([avatarPromise, thumbnailPromise]) } export async function uploadAvatar(avatar: any, thumbnail: any, contentPack: string): Promise<any> { if (avatar.url[0] === '/') { const protocol = config.noSSL === true ? 'http://' : 'https://' const domain = 'localhost:3000' avatar.url = new URL(avatar.url, protocol + domain).href } if (thumbnail.url[0] === '/') { const protocol = config.noSSL === true ? 'http://' : 'https://' const domain = 'localhost:3000' thumbnail.url = new URL(thumbnail.url, protocol + domain).href } const avatarUploadPromise = new Promise(async (resolve, reject) => { try { const avatarResult = await axios.get(avatar.url, getAxiosConfig()) await storageProvider.putObject({ Body: avatarResult.data, ContentType: mimeType.lookup(avatar.url) as string, Key: getAvatarKey(contentPack, avatar.key) }) resolve(true) } catch (err) { console.error(err) reject(err) } }) const avatarThumbnailUploadPromise = new Promise(async (resolve, reject) => { try { const avatarThumbnailResult = await axios.get(thumbnail.url, getAxiosConfig()) await storageProvider.putObject({ Body: avatarThumbnailResult.data, ContentType: mimeType.lookup(thumbnail.url) as string, Key: getAvatarThumbnailKey(contentPack, thumbnail.key) }) resolve(true) } catch (err) { console.error(err) reject(err) } }) return Promise.all([avatarUploadPromise, avatarThumbnailUploadPromise]) } /** * * @param project * @param project.name name of the project * @param project.manifest manifest.json URL * @param app * @param params */ export async function populateProject( project: { name: string; manifest: string }, app: Application, params: Params ): Promise<any> { // const uploadPromises = [] // const existingPackResult = await (app.service('project') as any).Model.findOne({ // where: { // name: project.name // } // }) // if (existingPackResult != null) await app.service('project').remove(existingPackResult.id, params) // const manifestStream = await axios.get(project.manifest, getAxiosConfig()) // const manifestData = JSON.parse(manifestStream.data.toString()) as ProjectInterface // console.log('Installing project from ', project.manifest, 'with manifest.json', manifestData) // const files = manifestData.files // uploadPromises.push( // storageProvider.putObject({ // Body: manifestStream.data, // ContentType: getContentType(project.manifest), // Key: `project/${manifestData.name}/manifest.json` // }) // ) // files.forEach((file) => { // const path = file.replace('./', '') // const subFileLink = project.manifest.replace('manifest.json', path) // uploadPromises.push( // new Promise(async (resolve) => { // const fileResult = await axios.get(subFileLink, getAxiosConfig()) // await storageProvider.putObject({ // Body: fileResult.data, // ContentType: getContentType(path), // Key: `project/${manifestData.name}/${path}` // }) // resolve(true) // }) // ) // }) // await app.service('project').create( // { // storageProviderManifest: `https://${storageProvider.cacheDomain}/project/${manifestData.name}/manifest.json`, // sourceManifest: project.manifest, // localManifest: `/projects/projects/${manifestData.name}/manifest.json`, // global: false, // name: manifestData.name // }, // params // ) // await Promise.all(uploadPromises) if (app.k8DefaultClient) { try { console.log('Attempting to reload k8s clients!') const restartClientsResponse = await app.k8DefaultClient.patch( `deployment/${config.server.releaseName}-builder-xrengine-builder`, { spec: { template: { metadata: { annotations: { 'kubectl.kubernetes.io/restartedAt': new Date().toISOString() } } } } } ) console.log('restartClientsResponse', restartClientsResponse) } catch (e) { console.log(e) } } }
the_stack
import { createTransport } from '@sentry/core'; import { EventEnvelope, EventItem } from '@sentry/types'; import { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, serializeEnvelope } from '@sentry/utils'; import * as http from 'http'; import { TextEncoder } from 'util'; import { createGunzip } from 'zlib'; import { makeNodeTransport } from '../../src/transports'; jest.mock('@sentry/core', () => { const actualCore = jest.requireActual('@sentry/core'); return { ...actualCore, createTransport: jest.fn().mockImplementation(actualCore.createTransport), }; }); // eslint-disable-next-line @typescript-eslint/no-var-requires const httpProxyAgent = require('https-proxy-agent'); jest.mock('https-proxy-agent', () => { return jest.fn().mockImplementation(() => new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 })); }); const SUCCESS = 200; const RATE_LIMIT = 429; const INVALID = 400; const FAILED = 500; interface TestServerOptions { statusCode: number; responseHeaders?: Record<string, string | string[] | undefined>; } let testServer: http.Server | undefined; function setupTestServer( options: TestServerOptions, requestInspector?: (req: http.IncomingMessage, body: string, raw: Uint8Array) => void, ) { testServer = http.createServer((req, res) => { const chunks: Buffer[] = []; const stream = req.headers['content-encoding'] === 'gzip' ? req.pipe(createGunzip({})) : req; stream.on('data', data => { chunks.push(data); }); stream.on('end', () => { requestInspector?.(req, chunks.join(), Buffer.concat(chunks)); }); res.writeHead(options.statusCode, options.responseHeaders); res.end(); // also terminate socket because keepalive hangs connection a bit res.connection.end(); }); testServer.listen(18099); return new Promise(resolve => { testServer?.on('listening', resolve); }); } const TEST_SERVER_URL = 'http://localhost:18099'; const EVENT_ENVELOPE = createEnvelope<EventEnvelope>({ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, [ [{ type: 'event' }, { event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2' }] as EventItem, ]); const SERIALIZED_EVENT_ENVELOPE = serializeEnvelope(EVENT_ENVELOPE, new TextEncoder()); const ATTACHMENT_ITEM = createAttachmentEnvelopeItem( { filename: 'empty-file.bin', data: new Uint8Array(50_000) }, new TextEncoder(), ); const EVENT_ATTACHMENT_ENVELOPE = addItemToEnvelope(EVENT_ENVELOPE, ATTACHMENT_ITEM); const SERIALIZED_EVENT_ATTACHMENT_ENVELOPE = serializeEnvelope( EVENT_ATTACHMENT_ENVELOPE, new TextEncoder(), ) as Uint8Array; const defaultOptions = { url: TEST_SERVER_URL, recordDroppedEvent: () => undefined, textEncoder: new TextEncoder(), }; describe('makeNewHttpTransport()', () => { afterEach(() => { jest.clearAllMocks(); if (testServer) { testServer.close(); } }); describe('.send()', () => { it('should correctly send envelope to server', async () => { await setupTestServer({ statusCode: SUCCESS }, (req, body) => { expect(req.method).toBe('POST'); expect(body).toBe(SERIALIZED_EVENT_ENVELOPE); }); const transport = makeNodeTransport(defaultOptions); await transport.send(EVENT_ENVELOPE); }); it('should correctly send user-provided headers to server', async () => { await setupTestServer({ statusCode: SUCCESS }, req => { expect(req.headers).toEqual( expect.objectContaining({ // node http module lower-cases incoming headers 'x-some-custom-header-1': 'value1', 'x-some-custom-header-2': 'value2', }), ); }); const transport = makeNodeTransport({ ...defaultOptions, headers: { 'X-Some-Custom-Header-1': 'value1', 'X-Some-Custom-Header-2': 'value2', }, }); await transport.send(EVENT_ENVELOPE); }); it.each([RATE_LIMIT, INVALID, FAILED])( 'should resolve on bad server response (status %i)', async serverStatusCode => { await setupTestServer({ statusCode: serverStatusCode }); const transport = makeNodeTransport(defaultOptions); await expect(transport.send(EVENT_ENVELOPE)).resolves.toBeUndefined(); }, ); it('should resolve when server responds with rate limit header and status code 200', async () => { await setupTestServer({ statusCode: SUCCESS, responseHeaders: { 'Retry-After': '2700', 'X-Sentry-Rate-Limits': '60::organization, 2700::organization', }, }); const transport = makeNodeTransport(defaultOptions); await expect(transport.send(EVENT_ENVELOPE)).resolves.toBeUndefined(); }); it('should resolve when server responds with rate limit header and status code 200', async () => { await setupTestServer({ statusCode: SUCCESS, responseHeaders: { 'Retry-After': '2700', 'X-Sentry-Rate-Limits': '60::organization, 2700::organization', }, }); const transport = makeNodeTransport(defaultOptions); await transport.send(EVENT_ENVELOPE); }); }); describe('compression', () => { it('small envelopes should not be compressed', async () => { await setupTestServer( { statusCode: SUCCESS, responseHeaders: {}, }, (req, body) => { expect(req.headers['content-encoding']).toBeUndefined(); expect(body).toBe(SERIALIZED_EVENT_ENVELOPE); }, ); const transport = makeNodeTransport(defaultOptions); await transport.send(EVENT_ENVELOPE); }); it('large envelopes should be compressed', async () => { await setupTestServer( { statusCode: SUCCESS, responseHeaders: {}, }, (req, _, raw) => { expect(req.headers['content-encoding']).toEqual('gzip'); expect(raw.buffer).toStrictEqual(SERIALIZED_EVENT_ATTACHMENT_ENVELOPE.buffer); }, ); const transport = makeNodeTransport(defaultOptions); await transport.send(EVENT_ATTACHMENT_ENVELOPE); }); }); describe('proxy', () => { it('can be configured through option', () => { makeNodeTransport({ ...defaultOptions, url: 'http://9e9fd4523d784609a5fc0ebb1080592f@sentry.io:8989/mysubpath/50622', proxy: 'http://example.com', }); expect(httpProxyAgent).toHaveBeenCalledTimes(1); expect(httpProxyAgent).toHaveBeenCalledWith('http://example.com'); }); it('can be configured through env variables option', () => { process.env.http_proxy = 'http://example.com'; makeNodeTransport({ ...defaultOptions, url: 'http://9e9fd4523d784609a5fc0ebb1080592f@sentry.io:8989/mysubpath/50622', }); expect(httpProxyAgent).toHaveBeenCalledTimes(1); expect(httpProxyAgent).toHaveBeenCalledWith('http://example.com'); delete process.env.http_proxy; }); it('client options have priority over env variables', () => { process.env.http_proxy = 'http://foo.com'; makeNodeTransport({ ...defaultOptions, url: 'http://9e9fd4523d784609a5fc0ebb1080592f@sentry.io:8989/mysubpath/50622', proxy: 'http://bar.com', }); expect(httpProxyAgent).toHaveBeenCalledTimes(1); expect(httpProxyAgent).toHaveBeenCalledWith('http://bar.com'); delete process.env.http_proxy; }); it('no_proxy allows for skipping specific hosts', () => { process.env.no_proxy = 'sentry.io'; makeNodeTransport({ ...defaultOptions, url: 'http://9e9fd4523d784609a5fc0ebb1080592f@sentry.io:8989/mysubpath/50622', proxy: 'http://example.com', }); expect(httpProxyAgent).not.toHaveBeenCalled(); delete process.env.no_proxy; }); it('no_proxy works with a port', () => { process.env.http_proxy = 'http://example.com:8080'; process.env.no_proxy = 'sentry.io:8989'; makeNodeTransport({ ...defaultOptions, url: 'http://9e9fd4523d784609a5fc0ebb1080592f@sentry.io:8989/mysubpath/50622', }); expect(httpProxyAgent).not.toHaveBeenCalled(); delete process.env.no_proxy; delete process.env.http_proxy; }); it('no_proxy works with multiple comma-separated hosts', () => { process.env.http_proxy = 'http://example.com:8080'; process.env.no_proxy = 'example.com,sentry.io,wat.com:1337'; makeNodeTransport({ ...defaultOptions, url: 'http://9e9fd4523d784609a5fc0ebb1080592f@sentry.io:8989/mysubpath/50622', }); expect(httpProxyAgent).not.toHaveBeenCalled(); delete process.env.no_proxy; delete process.env.http_proxy; }); }); describe('should register TransportRequestExecutor that returns the correct object from server response', () => { it('rate limit', async () => { await setupTestServer({ statusCode: RATE_LIMIT, responseHeaders: {}, }); makeNodeTransport(defaultOptions); const registeredRequestExecutor = (createTransport as jest.Mock).mock.calls[0][1]; const executorResult = registeredRequestExecutor({ body: serializeEnvelope(EVENT_ENVELOPE, new TextEncoder()), category: 'error', }); await expect(executorResult).resolves.toEqual( expect.objectContaining({ statusCode: RATE_LIMIT, }), ); }); it('OK', async () => { await setupTestServer({ statusCode: SUCCESS, }); makeNodeTransport(defaultOptions); const registeredRequestExecutor = (createTransport as jest.Mock).mock.calls[0][1]; const executorResult = registeredRequestExecutor({ body: serializeEnvelope(EVENT_ENVELOPE, new TextEncoder()), category: 'error', }); await expect(executorResult).resolves.toEqual( expect.objectContaining({ statusCode: SUCCESS, headers: { 'retry-after': null, 'x-sentry-rate-limits': null, }, }), ); }); it('OK with rate-limit headers', async () => { await setupTestServer({ statusCode: SUCCESS, responseHeaders: { 'Retry-After': '2700', 'X-Sentry-Rate-Limits': '60::organization, 2700::organization', }, }); makeNodeTransport(defaultOptions); const registeredRequestExecutor = (createTransport as jest.Mock).mock.calls[0][1]; const executorResult = registeredRequestExecutor({ body: serializeEnvelope(EVENT_ENVELOPE, new TextEncoder()), category: 'error', }); await expect(executorResult).resolves.toEqual( expect.objectContaining({ statusCode: SUCCESS, headers: { 'retry-after': '2700', 'x-sentry-rate-limits': '60::organization, 2700::organization', }, }), ); }); it('NOK with rate-limit headers', async () => { await setupTestServer({ statusCode: RATE_LIMIT, responseHeaders: { 'Retry-After': '2700', 'X-Sentry-Rate-Limits': '60::organization, 2700::organization', }, }); makeNodeTransport(defaultOptions); const registeredRequestExecutor = (createTransport as jest.Mock).mock.calls[0][1]; const executorResult = registeredRequestExecutor({ body: serializeEnvelope(EVENT_ENVELOPE, new TextEncoder()), category: 'error', }); await expect(executorResult).resolves.toEqual( expect.objectContaining({ statusCode: RATE_LIMIT, headers: { 'retry-after': '2700', 'x-sentry-rate-limits': '60::organization, 2700::organization', }, }), ); }); }); });
the_stack
import { isUndefined, sortBy } from 'lodash'; import { useEffect, useRef, useState } from 'react'; import { FaUser } from 'react-icons/fa'; import { IoMdLogOut } from 'react-icons/io'; import { MdBusiness } from 'react-icons/md'; import { Link } from 'react-router-dom'; import API from '../../../../../../api'; import { ErrorKind, EventKind, OptOutItem, Repository } from '../../../../../../types'; import alertDispatcher from '../../../../../../utils/alertDispatcher'; import { REPOSITORY_SUBSCRIPTIONS_LIST, SubscriptionItem } from '../../../../../../utils/data'; import { prepareQueryString } from '../../../../../../utils/prepareQueryString'; import Loading from '../../../../../common/Loading'; import Pagination from '../../../../../common/Pagination'; import RepositoryIcon from '../../../../../common/RepositoryIcon'; import styles from '../SubscriptionsSection.module.css'; import OptOutModal from './Modal'; import SubscriptionSwitch from './SubscriptionSwitch'; interface Props { onAuthError: () => void; } const DEFAULT_LIMIT = 10; interface ChangeSubsProps { data: { repoId: string; kind: EventKind; repoName: string; optOutId?: string; }; callback: () => void; } interface OptOutByRepo { repository: Repository; optOutItems: OptOutItem[]; } const RepositoriesSection = (props: Props) => { const title = useRef<HTMLDivElement>(null); const [isLoading, setIsLoading] = useState(false); const [optOutList, setOptOutList] = useState<OptOutByRepo[] | undefined>(undefined); const [optOutFullList, setOptOutFullList] = useState<OptOutByRepo[] | undefined>(undefined); const [repoIdsList, setRepoIdsList] = useState<string[]>([]); const [optOutItems, setOptOutItems] = useState<OptOutItem[] | undefined>(undefined); const [modalStatus, setModalStatus] = useState<boolean>(false); const [activePage, setActivePage] = useState<number>(1); const calculateOffset = (pageNumber?: number): number => { return DEFAULT_LIMIT * ((pageNumber || activePage) - 1); }; const [offset, setOffset] = useState<number>(calculateOffset()); const [total, setTotal] = useState<number | undefined>(undefined); const onPageNumberChange = (pageNumber: number): void => { setOffset(calculateOffset(pageNumber)); setActivePage(pageNumber); if (title && title.current) { title.current.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth' }); } }; const getNotificationTitle = (kind: EventKind): string => { let title = ''; const notif = REPOSITORY_SUBSCRIPTIONS_LIST.find((subs: SubscriptionItem) => subs.kind === kind); if (!isUndefined(notif)) { title = notif.title.toLowerCase(); } return title; }; const getVisibleOptOut = (items: OptOutByRepo[]): OptOutByRepo[] => { if (isUndefined(items)) return []; return items.slice(offset, offset + DEFAULT_LIMIT); }; const sortOptOutList = (items: OptOutItem[]): OptOutByRepo[] => { let list: OptOutByRepo[] = []; items.forEach((item: OptOutItem) => { const itemIndex = list.findIndex( (obr: OptOutByRepo) => obr.repository.repositoryId === item.repository.repositoryId ); if (itemIndex >= 0) { list[itemIndex] = { ...list[itemIndex], optOutItems: [...list[itemIndex].optOutItems, item] }; } else { list.push({ repository: item.repository, optOutItems: [item], }); } }); return sortBy(list, 'repository.name'); }; async function getOptOutList(callback?: () => void) { try { setIsLoading(true); const items = await API.getAllOptOut(); const formattedItems = sortOptOutList(items); setOptOutItems(items); setOptOutFullList(formattedItems); setRepoIdsList(formattedItems ? formattedItems.map((item: OptOutByRepo) => item.repository.repositoryId!) : []); setTotal(formattedItems.length); const newVisibleItems = getVisibleOptOut(formattedItems); // When current page is empty after changes if (newVisibleItems.length === 0 && activePage !== 1) { onPageNumberChange(1); } else { setOptOutList(newVisibleItems); } setIsLoading(false); } catch (err: any) { setIsLoading(false); if (err.kind !== ErrorKind.Unauthorized) { alertDispatcher.postAlert({ type: 'danger', message: 'An error occurred getting your opt-out entries list, please try again later.', }); setOptOutFullList([]); setOptOutList([]); } else { props.onAuthError(); } } finally { if (callback) { callback(); } } } async function changeSubscription(changeProps: ChangeSubsProps) { const { data, callback } = { ...changeProps }; try { if (!isUndefined(data.optOutId)) { await API.deleteOptOut(data.optOutId); } else { await API.addOptOut(data.repoId, data.kind); } getOptOutList(callback); } catch (err: any) { callback(); if (err.kind !== ErrorKind.Unauthorized) { alertDispatcher.postAlert({ type: 'danger', message: `An error occurred ${ !isUndefined(data.optOutId) ? 'deleting' : 'adding' } the opt-out entry for ${getNotificationTitle(data.kind)} notifications for repository ${ data.repoName }, please try again later.`, }); getOptOutList(); // Get opt-out if changeSubscription fails } else { props.onAuthError(); } } } useEffect(() => { getOptOutList(); }, []); /* eslint-disable-line react-hooks/exhaustive-deps */ useEffect(() => { setOptOutList(getVisibleOptOut(optOutFullList || [])); }, [activePage]); /* eslint-disable-line react-hooks/exhaustive-deps */ return ( <div className="mt-5 pt-3"> {(isUndefined(optOutList) || isLoading) && <Loading />} <div className="d-flex flex-row align-items-start justify-content-between pb-2"> <div ref={title} className={`h4 pb-0 ${styles.title}`}> Repositories </div> <div> <button className={`btn btn-outline-secondary btn-sm text-uppercase ${styles.btnAction}`} onClick={() => setModalStatus(true)} aria-label="Open opt-out modal" > <div className="d-flex flex-row align-items-center justify-content-center"> <IoMdLogOut /> <span className="d-none d-md-inline ms-2">Opt-out</span> </div> </button> </div> </div> <div className="mt-3 mt-md-3"> <p> Repositories notifications are <span className="fw-bold">enabled by default</span>. However, you can opt-out of notifications for certain kinds of events that happen in any of the repositories you can manage. </p> <p> You will <span className="fw-bold">NOT</span> receive notifications when an event that matches any of the repositories in the list is fired. </p> <div className="mt-4 mt-md-5"> {!isUndefined(optOutList) && optOutList.length > 0 && ( <div className="row"> <div className="col-12 col-xxxl-10"> <table className={`table table-bordered table-hover ${styles.table}`} data-testid="repositoriesList"> <thead> <tr className={styles.tableTitle}> <th scope="col" className={`align-middle text-center d-none d-sm-table-cell ${styles.fitCell}`}> Kind </th> <th scope="col" className="align-middle w-50"> Repository </th> <th scope="col" className="align-middle w-50 d-none d-sm-table-cell"> Publisher </th> {REPOSITORY_SUBSCRIPTIONS_LIST.map((subs: SubscriptionItem) => ( <th scope="col" className={`align-middle text-nowrap ${styles.fitCell}`} key={`title_${subs.kind}`} > <div className="d-flex flex-row align-items-center justify-content-center"> {subs.icon} {subs.shortTitle && <span className="d-inline d-lg-none ms-2">{subs.shortTitle}</span>} <span className="d-none d-lg-inline ms-2">{subs.title}</span> </div> </th> ))} </tr> </thead> <tbody className={styles.body}> {optOutList.map((item: OptOutByRepo) => { const repoInfo: Repository = item.repository; return ( <tr key={`subs_${repoInfo.repositoryId}`} data-testid="optOutRow"> <td className="align-middle text-center d-none d-sm-table-cell"> <RepositoryIcon kind={repoInfo.kind} className={`h-auto ${styles.icon}`} /> </td> <td className="align-middle"> <div className="d-flex flex-row align-items-center"> <Link data-testid="repoLink" className="text-dark text-capitalize" to={{ pathname: '/packages/search', search: prepareQueryString({ pageNumber: 1, filters: { repo: [repoInfo.name], }, }), }} > {repoInfo.name} </Link> </div> </td> <td className="align-middle position-relative d-none d-sm-table-cell"> <span className={`mx-1 mb-1 ${styles.tinyIcon}`}> {repoInfo.userAlias ? <FaUser /> : <MdBusiness />} </span>{' '} {repoInfo.userAlias ? ( <Link data-testid="userLink" className="text-dark" to={{ pathname: '/packages/search', search: prepareQueryString({ pageNumber: 1, filters: { user: [repoInfo.userAlias!], }, }), }} > {repoInfo.userAlias} </Link> ) : ( <Link data-testid="orgLink" className="text-dark" to={{ pathname: '/packages/search', search: prepareQueryString({ pageNumber: 1, filters: { org: [repoInfo.organizationName!], }, }), }} > {repoInfo.organizationDisplayName || repoInfo.organizationName} </Link> )} </td> {REPOSITORY_SUBSCRIPTIONS_LIST.map((subs: SubscriptionItem, index: number) => { const optItem = item.optOutItems.find((opt: OptOutItem) => subs.kind === opt.eventKind); return ( <td className="align-middle text-center" key={`td_${repoInfo.name}_${subs.kind}`}> <div className="text-center position-relative"> <SubscriptionSwitch repoInfo={repoInfo} kind={subs.kind} enabled={subs.enabled} optOutItem={optItem} changeSubscription={changeSubscription} /> </div> </td> ); })} </tr> ); })} {!isUndefined(total) && total > DEFAULT_LIMIT && ( <tr className={styles.paginationCell}> <td className="align-middle text-center" colSpan={5}> <Pagination limit={DEFAULT_LIMIT} offset={offset} total={total} active={activePage} className="my-3" onChange={onPageNumberChange} /> </td> </tr> )} </tbody> </table> </div> </div> )} </div> </div> {modalStatus && ( <OptOutModal disabledList={repoIdsList} optOutList={optOutItems} onSuccess={getOptOutList} onClose={() => setModalStatus(false)} onAuthError={props.onAuthError} getNotificationTitle={getNotificationTitle} open /> )} </div> ); }; export default RepositoriesSection;
the_stack
import type * as perspective from "@finos/perspective"; import { PerspectiveViewerElement, register_plugin, } from "@finos/perspective-viewer/dist/pkg/perspective_viewer.js"; import {WASM_MODULE} from "./init"; export type PerspectiveViewerConfig = perspective.ViewConfig & { plugin?: string; settings?: boolean; plugin_config?: any; }; /** * The Custom Elements implementation for `<perspective-viewer>`, as well at its * API. `PerspectiveViewerElement` should not be constructed directly (like its * parent class `HTMLElement`); instead, use `document.createElement()` or * declare your `<perspective-viewer>` element in HTML. Once instantiated, * `<perspective-viewer>` works just like a standard `HTMLElement`, with a few * extra perspective-specific methods. * * @example * ```javascript * const viewer = document.createElement("perspective-viewer"); * ``` * @example * ```javascript * document.body.innerHTML = ` * <perspective-viewer id="viewer"></perspective-viewer> * `; * const viewer = document.body.querySelector("#viewer"); * ``` * @noInheritDoc */ export class HTMLPerspectiveViewerElement extends HTMLElement { private instance: PerspectiveViewerElement; /** * Should not be called directly (will throw `TypeError: Illegal * constructor`). * @ignore */ constructor() { super(); this.load_wasm(); } private async load_wasm(): Promise<void> { await WASM_MODULE; if (!this.instance) { this.instance = new PerspectiveViewerElement(this); } } /** * Part of the Custom Elements API. This method is called by the browser, * and should not be called directly by applications. * * @ignore */ async connectedCallback(): Promise<void> { await this.load_wasm(); this.instance.connected_callback(); } /** * Register a new plugin via its custom element name. This method is called * automatically as a side effect of importing a plugin module, so this * method should only typically be called by plugin authors. * * @category Plugin * @param name The `name` of the custom element to register, as supplied * to the `customElements.define(name)` method. * @example * ```javascript * customElements.get("perspective-viewer").registerPlugin("my-plugin"); * ``` */ static async registerPlugin(name: string): Promise<void> { await WASM_MODULE; register_plugin(name); } /** * Load a `perspective.Table`. If `load` or `update` have already been * called on this element, its internal `perspective.Table` will _not_ be * deleted, but it will bed de-referenced by this `<perspective-viewer>`. * * @category Data * @param data A `Promise` which resolves to the `perspective.Table` * @returns {Promise<void>} A promise which resolves once the data is * loaded, a `perspective.View` has been created, and the active plugin has * rendered. * @example <caption>Load perspective.table</caption> * ```javascript * const my_viewer = document.getElementById('#my_viewer'); * const tbl = perspective.table("x,y\n1,a\n2,b"); * my_viewer.load(tbl); * ``` * @example <caption>Load Promise<perspective.table></caption> * ```javascript * const my_viewer = document.getElementById('#my_viewer'); * const tbl = perspective.table("x,y\n1,a\n2,b"); * my_viewer.load(tbl); * ``` */ async load( table: Promise<perspective.Table> | perspective.Table ): Promise<void> { await this.load_wasm(); await this.instance.js_load(table); } /** * Redraw this `<perspective-viewer>` and plugin when its dimensions or * visibility has been updated. By default, `<perspective-viewer>` will * auto-size when its own dimensions change, so this method need not be * called; when disabled via `setAutoSize(false)` however, this method * _must_ be called, and will not respond to dimension or style changes to * its parent container otherwise. `notifyResize()` does not recalculate * the current `View`, but all plugins will re-request the data window * (which itself may be smaller or larger due to resize). * * @category Util * @param force Whether to re-render, even if the dimenions have not * changed. When set to `false` and auto-size is enabled (the defaults), * calling this method will automatically disable auto-size. * @returns A `Promise<void>` which resolves when this resize event has * finished rendering. * @example <caption>Bind `notfyResize()` to browser dimensions</caption> * ```javascript * const viewer = document.querySelector("perspective-viewer"); * viewer.setAutoSize(false); * window.addEventListener("resize", () => viewer.notifyResize()); * ``` */ async notifyResize(force = false): Promise<void> { await this.load_wasm(); await this.instance.js_resize(force); } /** * Determines the auto-size behavior. When `true` (the default), this * element will re-render itself whenever its own dimensions change, * utilizing a `ResizeObserver`; when `false`, you must explicitly call * `notifyResize()` when the element's dimensions have changed. * * @category Util * @param autosize Whether to re-render when this element's dimensions * change. * @example <caption>Disable auto-size</caption> * ```javascript * await viewer.setAutoSize(false); * ``` */ async setAutoSize(autosize = true): Promise<void> { await this.load_wasm(); await this.instance.js_set_auto_size(autosize); } /** * Returns the `perspective.Table()` which was supplied to `load()` * @category Data * @param wait_for_table Whether to await `load()` if it has not yet been * invoked, or fail immediately. * @returns A `Promise` which resolves to a `perspective.Table` * @example <caption>Share a `Table`</caption> * ```javascript * const viewers = document.querySelectorAll("perspective-viewer"); * const [viewer1, viewer2] = Array.from(viewers); * const table = await viewer1.getTable(); * await viewer2.load(table); * ``` */ async getTable(wait_for_table?: boolean): Promise<perspective.Table> { await this.load_wasm(); const table = await this.instance.js_get_table(!!wait_for_table); return table; } /** * Returns the underlying `perspective.View` currently configured for this * `<perspective-viewer>`. Because ownership of the `perspective.View` is * mainainted by the `<perspective-viewer>` it was created by, this `View` * may become deleted (invalidated by calling `delete()`) at any time - * specifically, it will be deleted whenever the `PerspectiveViewConfig` * changes. Because of this, when using this API, prefer calling * `getView()` repeatedly over caching the returned `perspective.View`, * especially in `async` contexts. * @category Data * @returns A `Promise` which ressolves to a `perspective.View`. * @example <caption>Collapse grid to root</caption> * ```javascript * const viewer = document.querySelector("perspective-viewer"); * const view = await viewer.getView(); * await view.set_depth(0); * ``` */ async getView(): Promise<perspective.View> { await this.load_wasm(); const view = await this.instance.js_get_view(); return view; } /** * Restore this element to a state as generated by a reciprocal call to * `save`. In `json` (default) format, `PerspectiveViewerConfig`'s fields * have specific semantics: * * - When a key is missing, this field is ignored; `<perspective-viewer>` * will maintain whatever settings for this field is currently applied. * - When the key is supplied, but the value is `undefined`, the field is * reset to its default value for this current `View`, i.e. the state it * would be in after `load()` resolves. * - When the key is defined to a value, the value is applied for this * field. * * This behavior is convenient for explicitly controlling current vs desired * UI state in a single request, but it does make it a bit inconvenient to * use `restore()` to reset a `<perspective-viewer>` to default as you must * do so explicitly for each key; for this case, use `reset()` instead of * restore. * * As noted in `save()`, this configuration state does not include the * `Table` or its `Schema`. In order for `restore()` to work correctly, it * must be called on a `<perspective-viewer>` that has a `Table already * `load()`-ed, with the same (or a type-compatible superset) `Schema`. * It does not need have the same rows, or even be populated. * * @category Persistence * @param config returned by `save()`. This can be any format returned by * `save()`; the specific deserialization is chosen by `typeof config`. * @returns A promise which resolves when the changes have been applied and * rendered. * @example <caption>Restore a viewer from `localStorage`</caption> * ```javascript * const viewer = document.querySelector("perspective-viewer"); * const token = localStorage.getItem("viewer_state"); * await viewer.restore(token); * ``` */ async restore( config: PerspectiveViewerConfig | string | ArrayBuffer ): Promise<void> { await this.load_wasm(); await this.instance.js_restore(config); } /** * Serialize this element's attribute/interaction state, but _not_ the * `perspective.Table` or its `Schema`. `save()` is designed to be used in * conjunction with `restore()` to persist user settings and bookmarks, but * the `PerspectiveViewerConfig` object returned in `json` format can also * be written by hand quite easily, which is useful for authoring * pre-conceived configs. * * @category Persistence * @param format The serialization format - `json` (JavaScript object), * `arraybuffer` or `string`. `restore()` uses the returned config's type * to infer format. * @returns a serialized element in the chosen format. * @example <caption>Save a viewer to `localStorage`</caption> * ```javascript * const viewer = document.querySelector("perspective-viewer"); * const token = await viewer.save("string"); * localStorage.setItem("viewer_state", token); * ``` */ async save(): Promise<PerspectiveViewerConfig>; async save(format: "json"): Promise<PerspectiveViewerConfig>; async save(format: "arraybuffer"): Promise<ArrayBuffer>; async save(format: "string"): Promise<string>; async save( format?: "json" | "arraybuffer" | "string" ): Promise<PerspectiveViewerConfig | string | ArrayBuffer> { await this.load_wasm(); const config = await this.instance.js_save(format); return config; } /** * Flush any pending modifications to this `<perspective-viewer>`. Since * `<perspective-viewer>`'s API is almost entirely `async`, it may take * some milliseconds before any method call such as `restore()` affects * the rendered element. If you want to make sure any invoked method which * affects the rendered has had its results rendered, call and await * `flush()` * * @category Util * @returns {Promise<void>} A promise which resolves when the current * pending state changes have been applied and rendered. * @example <caption>Flush an unawaited `restore()`</caption> * ```javascript * const viewer = document.querySelector("perspective-viewer"); * viewer.restore({group_by: ["State"]}); * await viewer.flush(); * console.log("Viewer has been rendered with a pivot!"); * ``` */ async flush(): Promise<void> { await this.load_wasm(); await this.instance.js_flush(); } /** * Reset's this element's view state and attributes to default. Does not * delete this element's `perspective.table` or otherwise modify the data * state. * * @category Persistence * @param all Should `expressions` param be reset as well, defaults to * @example * ```javascript * const viewer = document.querySelector("perspective-viewer"); * await viewer.reset(); * ``` */ async reset(all = false): Promise<void> { await this.load_wasm(); await this.instance.js_reset(all); } /** * Deletes this element and clears it's internal state (but not its * user state). This (or the underlying `perspective.view`'s equivalent * method) must be called in order for its memory to be reclaimed, as well * as the reciprocal method on the `perspective.table` which this viewer is * bound to. * * @category Util */ async delete(): Promise<void> { await this.load_wasm(); await this.instance.js_delete(); } /** * Download this element's data as a CSV file. * * @category UI Action * @param flat Whether to use the element's current view * config, or to use a default "flat" view. */ async download(flat: boolean): Promise<void> { await this.load_wasm(); await this.instance.js_download(flat); } /** * Copies this element's view data (as a CSV) to the clipboard. This method * must be called from an event handler, subject to the browser's * restrictions on clipboard access. See * {@link https://www.w3.org/TR/clipboard-apis/#allow-read-clipboard}. * * @category UI Action * @param flat Whether to use the element's current view * config, or to use a default "flat" view. * @example * ```javascript * const viewer = document.querySelector("perspective-viewer"); * const button = document.querySelector("button"); * button.addEventListener("click", async () => { * await viewer.copy(); * }); * ``` */ async copy(flat: boolean): Promise<void> { await this.load_wasm(); await this.instance.js_copy(flat); } /** * Restyles the elements and to pick up any style changes. While most of * perspective styling is plain CSS and can be updated at any time, some * CSS rules are read and cached, e.g. the series colors for * `@finos/perspective-viewer-d3fc` which are read from CSS then reapplied * as SVG and Canvas attributes. * * @category Util */ async restyleElement(): Promise<void> { await this.load_wasm(); await this.instance.js_restyle_element(); } /** * Sets the theme names available via the `<perspective-viewer>` status bar * UI. Typically these will be auto-detected simply by including the * theme `.css` in a `<link>` tag; however, auto-detection can fail if * the `<link>` tag is not a same-origin request due to CORS. For servers * configured to allow cross-origin requests, you can use the * [`crossorigin` attribute](https://html.spec.whatwg.org/multipage/semantics.html#attr-link-crossorigin) * to enable detection, e.g. `<link crossorigin="anonymous" .. >`. If for * whatever reason auto-detection still fails, you may set the themes via * this method. Note the theme `.css` must still be loaded in this case - * the `resetThemes()` method only lets the `<perspective-viewer>` know what * theme names are available. * @param Util * @example * ```javascript * const viewer = document.querySelector("perspective-viewer"); * await viewer.resetThemes(["Material Light", "Material Dark"]); * ``` */ async resetThemes(themes: Array<string>): Promise<void> { await this.load_wasm(); await this.instance.js_reset_themes(themes); } /** * Gets the edit port, the port number for which `Table` updates from this * `<perspective-viewer>` are generated. This port number will be present * in the options object for a `View.on_update()` callback for any update * which was originated by the `<perspective-viewer>`/user, which can be * used to distinguish server-originated updates from user edits. * * @category Util * @returns A promise which resolves to the current edit port. * @example * ```javascript * const viewer = document.querySelector("perspective-viewer"); * const editport = await viewer.getEditPort(); * const table = await viewer.getTable(); * const view = await table.view(); * view.on_update(obj => { * if (obj.port_id = editport) { * console.log("User edit detected"); * } * }); * ``` */ async getEditPort(): Promise<number> { await this.load_wasm(); const port = await this.instance.js_get_edit_port(); return port; } /** * Determines the render throttling behavior. Can be an integer, for * millisecond window to throttle render event; or, if `undefined`, * will try to determine the optimal throttle time from this component's * render framerate. * * @category Util * @param value an optional throttle rate in milliseconds (integer). If not * supplied, adaptive throttling is calculated from the average plugin * render time. * @example <caption>Limit FPS to 1 frame per second</caption> * ```javascript * await viewer.setThrottle(1000); * ``` */ async setThrottle(value?: number): Promise<void> { await this.load_wasm(); await this.instance.js_set_throttle(value); } /** * Opens/closes the element's config menu, equivalent to clicking the * settings button in the UI. This method is equivalent to * `viewer.restore({settings: force})` when `force` is present, but * `restore()` cannot toggle as `toggleConfig()` can, you would need to * first read the settings state from `save()` otherwise. * * Calling `toggleConfig()` may be delayed if an async render is currently * in process, and it may only partially render the UI if `load()` has not * yet resolved. * * @category UI Action * @param force If supplied, explicitly set the config state to "open" * (`true`) or "closed" (`false`). * @example * ```javascript * await viewer.toggleConfig(); * ``` */ async toggleConfig(force?: boolean): Promise<void> { await this.load_wasm(); await this.instance.js_toggle_config(force); } /** * Get the currently active plugin custom element instance, or a specific * named instance if requested. `getPlugin(name)` does not activate the * plugin requested, so if this plugin is not active the returned * `HTMLElement` will not have a `parentElement`. * * If no plugins have been registered (via `registerPlugin()`), calling * `getPlugin()` will cause `perspective-viewer-plugin` to be registered as * a side effect. * * @category Plugin * @param name Optionally a specific plugin name, defaulting to the current * active plugin. * @returns The active or requested plugin instance. */ async getPlugin(name?: string): Promise<HTMLElement> { await this.load_wasm(); const plugin = await this.instance.js_get_plugin(name); return plugin; } async unsafe_get_model(): Promise<number> { await this.load_wasm(); return await this.instance.js_unsafe_get_model(); } /** * Get all plugin custom element instances, in order of registration. * * If no plugins have been registered (via `registerPlugin()`), calling * `getAllPlugins()` will cause `perspective-viewer-plugin` to be registered * as a side effect. * * @category Plugin * @returns An `Array` of the plugin instances for this * `<perspective-viewer>`. */ async getAllPlugins(): Promise<Array<HTMLElement>> { await this.load_wasm(); const plugins = await this.instance.js_get_all_plugins(); return plugins; } } if (document.createElement("perspective-viewer").constructor === HTMLElement) { window.customElements.define( "perspective-viewer", HTMLPerspectiveViewerElement ); }
the_stack
import "jest-extended"; import { Contracts } from "@packages/core-kernel"; import { Wallet, WalletRepository, WalletRepositoryCopyOnWrite } from "@packages/core-state/src/wallets"; import { addressesIndexer, ipfsIndexer, locksIndexer, publicKeysIndexer, resignationsIndexer, usernamesIndexer, } from "@packages/core-state/src/wallets/indexers/indexers"; import { Utils } from "@packages/crypto/src"; import { setUp } from "../setup"; let walletRepoCopyOnWrite: WalletRepositoryCopyOnWrite; let walletRepo: WalletRepository; beforeAll(async () => { const initialEnv = await setUp(); walletRepoCopyOnWrite = initialEnv.walletRepoCopyOnWrite; walletRepo = initialEnv.walletRepo; }); beforeEach(() => { walletRepoCopyOnWrite.reset(); walletRepo.reset(); }); describe("Wallet Repository Copy On Write", () => { it("should create a wallet", () => { const wallet = walletRepoCopyOnWrite.createWallet("abcd"); expect(wallet.getAddress()).toEqual("abcd"); expect(wallet).toBeInstanceOf(Wallet); }); it("should be able to look up indexers", () => { const expected = ["addresses", "publicKeys", "usernames", "resignations", "locks", "ipfs"]; expect(walletRepoCopyOnWrite.getIndexNames()).toEqual(expected); expect(walletRepoCopyOnWrite.getIndex("addresses").indexer).toEqual(addressesIndexer); expect(walletRepoCopyOnWrite.getIndex("publicKeys").indexer).toEqual(publicKeysIndexer); expect(walletRepoCopyOnWrite.getIndex("usernames").indexer).toEqual(usernamesIndexer); expect(walletRepoCopyOnWrite.getIndex("resignations").indexer).toEqual(resignationsIndexer); expect(walletRepoCopyOnWrite.getIndex("locks").indexer).toEqual(locksIndexer); expect(walletRepoCopyOnWrite.getIndex("ipfs").indexer).toEqual(ipfsIndexer); }); it("should find wallets by address", () => { const spyFindByAddress = jest.spyOn(walletRepo, "findByAddress"); const clonedWallet = walletRepoCopyOnWrite.findByAddress("notexisting"); expect(spyFindByAddress).toHaveBeenCalledWith("notexisting"); const originalWallet = walletRepo.findByAddress(clonedWallet.getAddress()); expect(originalWallet).not.toBe(clonedWallet); }); it("should get all by username", () => { const wallet1 = walletRepoCopyOnWrite.createWallet("abcd"); const wallet2 = walletRepoCopyOnWrite.createWallet("efg"); const wallet3 = walletRepoCopyOnWrite.createWallet("hij"); wallet1.setAttribute("delegate.username", "username1"); wallet2.setAttribute("delegate.username", "username2"); wallet3.setAttribute("delegate.username", "username3"); const allWallets = [wallet1, wallet2, wallet3]; walletRepo.index(allWallets); expect(walletRepoCopyOnWrite.allByUsername()).toEqual([wallet1, wallet2, wallet3]); const wallet4 = walletRepoCopyOnWrite.createWallet("klm"); wallet4.setAttribute("delegate.username", "username4"); walletRepo.index(wallet4); allWallets.push(wallet4); expect(walletRepoCopyOnWrite.allByUsername()).toEqual(allWallets); }); // TODO: test behaves differently to WalletRepository due to inheritance it.skip("findByPublicKey should index wallet", () => { const address = "ATtEq2tqNumWgR9q9zF6FjGp34Mp5JpKGp"; const wallet = walletRepoCopyOnWrite.createWallet(address); const publicKey = "03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"; wallet.setPublicKey(publicKey); expect(walletRepoCopyOnWrite.findByAddress(address)).not.toEqual(wallet); walletRepoCopyOnWrite.getIndex("publicKeys").set(publicKey, wallet); expect(walletRepoCopyOnWrite.findByPublicKey(publicKey).getPublicKey()).toBeDefined(); expect(walletRepoCopyOnWrite.findByPublicKey(publicKey)).toEqual(wallet); /** * TODO: check this is desired behaviour? * TempWalletRepository calls index inside findByPublicKey (unlike WalletRepository). * This has the effect that these are now defined without needing to index */ expect(walletRepoCopyOnWrite.findByAddress(address).getPublicKey()).toBeDefined(); expect(walletRepoCopyOnWrite.findByAddress(address)).toEqual(wallet); }); // TODO: test behaves differently to WalletRepository due to inheritance it.skip("should not retrieve wallets indexed in original repo, until they are indexed", () => { const address = "abcd"; const wallet = walletRepoCopyOnWrite.createWallet(address); walletRepoCopyOnWrite.index(wallet); /** * TODO: check this is desired behaviour * has, hasByAddress and hasByIndex all behave differently because of the problem of inheritance. * I've added has and hasByIndex to TempWalletRepo to fix this (i.e. these should all return false, not just one of them), but in general this architecture needs revisiting. */ expect(walletRepoCopyOnWrite.has(address)).toBeFalse(); expect(walletRepoCopyOnWrite.hasByAddress(address)).toBeFalse(); expect(walletRepoCopyOnWrite.hasByIndex("addresses", address)).toBeFalse(); /** * For example, because allByAddress is *not* overwritten in TempWalletRepo, this falls back to the WalletRepo base class which returns the wallet, despite hasByAddress being false. * * We can add all these different methods to TempWalletRepository to make the class behave more sensibly. However, if these methods aren't intended to ever really be called on the temporary version of the wallet repository it makes sense to use a shared base interface, rather than using inheritance. * * IMO inheritance should be used very sparingly, as it is often difficult to reason about, and calling methods have side effects the calling code may not expect. */ expect(walletRepoCopyOnWrite.allByAddress()).toEqual([wallet]); walletRepo.index(wallet); expect(walletRepoCopyOnWrite.has(address)).toBeTrue(); expect(walletRepoCopyOnWrite.hasByAddress(address)).toBeTrue(); expect(walletRepoCopyOnWrite.hasByIndex("addresses", address)).toBeTrue(); expect(walletRepoCopyOnWrite.allByAddress()).toEqual([wallet]); // TODO: similarly, this behaviour is odd - as the code hasn't been overwritten in the extended class expect(walletRepoCopyOnWrite.has(address)).toBeTrue(); }); // TODO: test behaves differently to WalletRepository due to i it.skip("should create a wallet if one is not found during address lookup", () => { expect(() => walletRepoCopyOnWrite.findByAddress("hello")).not.toThrow(); expect(walletRepoCopyOnWrite.findByAddress("iDontExist")).toBeInstanceOf(Wallet); expect(walletRepoCopyOnWrite.has("hello")).toBeFalse(); expect(walletRepoCopyOnWrite.hasByAddress("iDontExist")).toBeFalse(); /** * TODO: check this is desired behaviour * WalletRepo throws here, TempWalletRepo does not. */ expect(() => walletRepoCopyOnWrite.findByIndex("addresses", "iAlsoDontExist")).not.toThrow(); }); describe("index", () => { // TODO: test behaves differently to WalletRepository due to inheritance it.skip("should not affect the original", () => { const wallet = walletRepo.createWallet("abcdef"); walletRepo.index(wallet); walletRepoCopyOnWrite.index(wallet); expect(walletRepo.findByAddress(wallet.getAddress())).not.toBe( walletRepoCopyOnWrite.findByAddress(wallet.getAddress()), ); }); }); describe("findByAddress", () => { it("should return a copy", () => { const wallet = walletRepo.createWallet("abcdef"); walletRepo.index(wallet); const tempWallet = walletRepoCopyOnWrite.findByAddress(wallet.getAddress()); tempWallet.setBalance(Utils.BigNumber.ONE); expect(wallet.getBalance()).not.toEqual(tempWallet.getBalance()); }); }); describe("findByPublicKey", () => { it("should return a copy", () => { const wallet = walletRepo.createWallet("ATtEq2tqNumWgR9q9zF6FjGp34Mp5JpKGp"); wallet.setPublicKey("03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"); wallet.setBalance(Utils.BigNumber.SATOSHI); walletRepo.index(wallet); const tempWallet = walletRepoCopyOnWrite.findByPublicKey(wallet.getPublicKey()!); tempWallet.setBalance(Utils.BigNumber.ZERO); expect(wallet.getBalance()).toEqual(Utils.BigNumber.SATOSHI); expect(tempWallet.getBalance()).toEqual(Utils.BigNumber.ZERO); }); }); describe("findByUsername", () => { it("should return a copy", () => { const wallet = walletRepo.createWallet("abcdef"); wallet.setAttribute("delegate", { username: "test" }); walletRepo.index(wallet); const tempWallet = walletRepoCopyOnWrite.findByUsername(wallet.getAttribute("delegate.username")); tempWallet.setBalance(Utils.BigNumber.ONE); expect(wallet.getBalance()).not.toEqual(tempWallet.getBalance()); }); }); describe("hasByAddress", () => { it("should be ok", () => { const wallet = walletRepo.createWallet("abcdef"); walletRepo.index(wallet); expect(walletRepoCopyOnWrite.hasByAddress(wallet.getAddress())).toBeTrue(); }); }); describe("hasByPublicKey", () => { it("should be ok", () => { const wallet = walletRepo.createWallet("ATtEq2tqNumWgR9q9zF6FjGp34Mp5JpKGp"); wallet.setPublicKey("03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"); walletRepo.index(wallet); expect(walletRepoCopyOnWrite.hasByPublicKey(wallet.getPublicKey()!)).toBeTrue(); }); }); describe("hasByUsername", () => { it("should be ok", () => { const wallet = walletRepo.createWallet("abcdef"); wallet.setAttribute("delegate", { username: "test" }); walletRepo.index(wallet); expect(walletRepoCopyOnWrite.hasByUsername(wallet.getAttribute("delegate.username"))).toBeTrue(); }); }); describe("hasByIndex", () => { it("should be ok", () => { const wallet = walletRepo.createWallet("abc"); wallet.setAttribute("delegate", { username: "test" }); walletRepo.index(wallet); expect(walletRepoCopyOnWrite.hasByIndex(Contracts.State.WalletIndexes.Usernames, "test")).toBeTrue(); }); }); describe("findByIndex", () => { it("should be ok", () => { const wallet = walletRepo.createWallet("abc"); wallet.setAttribute("delegate", { username: "test" }); walletRepo.index(wallet); const clone = walletRepoCopyOnWrite.findByIndex(Contracts.State.WalletIndexes.Usernames, "test"); expect(clone).not.toBe(wallet); expect(clone.getAddress()).toEqual(wallet.getAddress()); expect(clone.getAttribute("delegate.username")).toEqual(wallet.getAttribute("delegate.username")); }); }); // TODO: Check index where autoIndex = false });
the_stack
import * as assert from 'assert'; import * as vscode from 'vscode'; import * as extensionFunctions from '../../extensionFunctions'; import { handleExtFilePath, handleProjectFilePath } from '../../commandHandler'; import * as path from 'path'; import { removeFilesAndFolders, getCachedOutputChannel, getCachedOutputChannels, setInsertLFForCLILinkSetting, getLinkTextForCLILinkSetting, setLinkTextForCLILinkSetting, DEFAULT_EXECUTE_LINK_TEXT } from '../../utils'; import { beforeEach, after, afterEach } from 'mocha'; import * as sinon from 'sinon'; import { expect } from 'chai'; suite('Extension Functions Test Suite', () => { const uriToRemoteDidactAdoc = 'https://raw.githubusercontent.com/redhat-developer/vscode-didact/0.4.0/demos/asciidoc/simple-example.didact.adoc'; async function cleanFiles() { const testWorkspace = path.resolve(__dirname, '..', '..', '..', './test Fixture with speci@l chars'); const foldersAndFilesToRemove: string[] = [ 'giphy.gif', 'spongebob-exit.gif', 'expanded', 'expanded2', 'newfolder', 'newfolder2' ]; await removeFilesAndFolders(testWorkspace, foldersAndFilesToRemove); } beforeEach(async () => { await cleanFiles(); getCachedOutputChannels().length = 0; }); afterEach(async () => { await vscode.env.clipboard.writeText(''); }); after(async () => { await cleanFiles(); getCachedOutputChannels().length = 0; }); test('open a named output channel', () => { const channelName = 'testOutputChannel'; let channel: vscode.OutputChannel | undefined = getCachedOutputChannel(channelName); assert.strictEqual(channel, undefined); extensionFunctions.openNamedOutputChannel(channelName); channel = getCachedOutputChannel(channelName); assert.notStrictEqual(channel, undefined); assert.strictEqual(channel?.name, channelName); }); test('open the default didact ouput channel if no channel name is provided', () => { const outputSpy = sinon.spy(extensionFunctions.didactOutputChannel, 'show'); extensionFunctions.openNamedOutputChannel(); assert.strictEqual(outputSpy.calledOnce, true); outputSpy.restore(); }); test('open a named output channel and send some text to it', () => { const channelName = 'testCustomChannel'; const txt = 'this is some test'; let channel: vscode.OutputChannel | undefined = getCachedOutputChannel(channelName); assert.strictEqual(channel, undefined); extensionFunctions.openNamedOutputChannel(channelName); channel = getCachedOutputChannel(channelName); assert.notStrictEqual(channel, undefined); assert.strictEqual(channel?.name, channelName); const outputSpy = sinon.spy(channel, 'append'); extensionFunctions.sendTextToOutputChannel(txt, channel); assert.strictEqual(outputSpy.calledOnceWithExactly(`${txt} \n`), true); outputSpy.restore(); }); test('open the default output channel and send some text to it', () => { const txt = 'this is some test'; const outputSpyShow = sinon.spy(extensionFunctions.didactOutputChannel, 'show'); extensionFunctions.openNamedOutputChannel(); assert.strictEqual(outputSpyShow.calledOnce, true); const outputSpyAppend = sinon.spy(extensionFunctions.didactOutputChannel, 'append'); extensionFunctions.sendTextToOutputChannel(txt); assert.strictEqual(outputSpyAppend.calledOnceWithExactly(`${txt} \n`), true); outputSpyShow.restore(); outputSpyAppend.restore(); }); test('send text to terminal', async function() { const testTerminalName = 'testTerminal'; let terminal : vscode.Terminal | undefined = extensionFunctions.findTerminal(testTerminalName); assert.strictEqual(terminal, undefined); await extensionFunctions.sendTerminalText(testTerminalName, "testText"); terminal = extensionFunctions.findTerminal(testTerminalName); assert.notStrictEqual(terminal, undefined); // open to ideas on how to check to see that a message was actually committed to the terminal // but at least we can check to see if the terminal was created as part of the sendTerminalText call }); test('send ctrl+c to terminal', async function() { const testTerminalName = 'testTerminalCtrlC'; let terminalC : vscode.Terminal | undefined = extensionFunctions.findTerminal(testTerminalName); assert.strictEqual(terminalC, undefined); // if it can't find the terminal, it will error out await extensionFunctions.sendTerminalCtrlC(testTerminalName).catch( (error) => { assert.notStrictEqual(error, undefined); }); // terminal should not have been created as part of the method call terminalC = extensionFunctions.findTerminal(testTerminalName); assert.strictEqual(terminalC, undefined); await extensionFunctions.startTerminal(testTerminalName); // terminal should have been created as part of the method call terminalC = extensionFunctions.findTerminal(testTerminalName); assert.notStrictEqual(terminalC, undefined); // again, open to ideas on how to check to see if the terminal text was sent to the active terminal await extensionFunctions.sendTerminalCtrlC(testTerminalName); // we can test to see if the terminal still exists at least assert.notStrictEqual(terminalC, undefined); }); test('open new terminal and then close it', async function() { const terminalNameToClose = 'terminalToKill'; let terminal : vscode.Terminal | undefined = extensionFunctions.findTerminal(terminalNameToClose); assert.strictEqual(terminal, undefined); // if it can't find the terminal, it will error out await extensionFunctions.closeTerminal(terminalNameToClose).catch( (error) => { assert.notStrictEqual(error, undefined); }); await extensionFunctions.startTerminal(terminalNameToClose); terminal = extensionFunctions.findTerminal(terminalNameToClose); assert.notStrictEqual(terminal, undefined); await extensionFunctions.closeTerminal(terminalNameToClose).finally( async () => { terminal = extensionFunctions.findTerminal(terminalNameToClose); // the terminal should be disposed at this point, but we can't test for it // looking in the debugger, the _isDisposed property is set to true, so we should be ok }); }); test('try executing a valid command', async function() { await extensionFunctions.cliExecutionCheck('test-echo','echo').then( (returnBool) => { assert.strictEqual(returnBool, true); }); }); test('try executing an invalid command', async function() { await extensionFunctions.cliExecutionCheck('test-bogus','doesnotexist').then( (returnBool) => { assert.strictEqual(returnBool, false); }); }); test('try parsing didact url with extension path - extension id in url', async function() { const pathToCheck = path.join('vscode-didact', 'examples', 'requirements.example.didact.md'); const pathToCheckOnJenkins = path.join('vscode-didact-release', 'examples', 'requirements.example.didact.md'); checkCanParseDidactUriForPath( 'vscode://redhat.vscode-didact?extension=redhat.vscode-didact/examples/requirements.example.didact.md', pathToCheck, pathToCheckOnJenkins); }); test('try parsing didact url with extension path - no extension id in url', async function() { const pathToCheck = path.join('vscode-didact', 'demos', 'markdown', 'didact-demo.didact.md'); const pathToCheckOnJenkins = path.join('vscode-didact-release', 'demos', 'markdown', 'didact-demo.didact.md'); checkCanParseDidactUriForPath( 'vscode://redhat.vscode-didact?extension=demos/markdown/didact-demo.didact.md', pathToCheck, pathToCheckOnJenkins); }); test('try parsing didact url with http link in url', async function() { const pathToCheck = path.join('vscode-didact', '0.4.0', 'demos', 'markdown', 'didact-demo.didact.md'); const pathToCheckOnJenkins = path.join('vscode-didact-release', '0.4.0', 'demos', 'markdown', 'didact-demo.didact.md'); checkCanParseDidactUriForPath( 'vscode://redhat.vscode-didact?https=raw.githubusercontent.com/redhat-developer/vscode-didact/0.4.0/demos/markdown/didact-demo.didact.md', pathToCheck, pathToCheckOnJenkins); }); test('try to copy a file to workspace root with no change to filename', async function() { const urlToTest = 'https://media.giphy.com/media/7DzlajZNY5D0I/giphy.gif'; const filepathUri = handleProjectFilePath(''); // get workspace root if (filepathUri) { await testCopyFileFromURLtoLocalURI(urlToTest, filepathUri.fsPath); } }); test('try to copy a file with a change to location', async function() { const urlToTest = 'https://media.giphy.com/media/7DzlajZNY5D0I/giphy.gif'; const filepathUri = handleProjectFilePath('newfolder'); // add a folder if (filepathUri) { await testCopyFileFromURLtoLocalURI(urlToTest, filepathUri.fsPath); } }); test('try to copy a file to workspace root with a change to filename', async function() { const urlToTest = 'https://media.giphy.com/media/7DzlajZNY5D0I/giphy.gif'; const filepathUri = handleProjectFilePath(''); // get workspace root const newFilename = `spongebob-exit.gif`; if (filepathUri) { await testCopyFileFromURLtoLocalURI(urlToTest, filepathUri.fsPath, newFilename); } }); test('try to copy a file with a change to location and filename change', async function() { const urlToTest = 'https://media.giphy.com/media/7DzlajZNY5D0I/giphy.gif'; const filepathUri = handleProjectFilePath('newfolder2'); // create a new folder const newFilename = `spongebob-exit2.gif`; if (filepathUri) { await testCopyFileFromURLtoLocalURI(urlToTest, filepathUri.fsPath, newFilename); } }); test('try to copy a zip file and not unzip it with a change to location and filename change', async function() { const urlToTest = 'https://github.com/redhat-developer/vscode-didact/raw/0.4.0/test-archive/testarchive.tar.gz'; const filepathUri = handleProjectFilePath('expanded'); // create a folder to unzip into const newFilename = `giphy.tar.gz`; if (filepathUri) { await testCopyFileFromURLtoLocalURI(urlToTest, filepathUri.fsPath, newFilename, false); } }); test('try to copy and unzip a file with a change to location and filename change', async function() { const urlToTest = 'https://github.com/redhat-developer/vscode-didact/raw/0.4.0/test-archive/testarchive.tar.gz'; const filepathUri = handleProjectFilePath('expanded2'); // create a folder to unzip into const newFilename = `testarchive.tar.gz`; const fileToLookFor = `testfile/spongebob-expands.gif`; if (filepathUri) { await testCopyFileFromURLtoLocalURI(urlToTest, filepathUri.fsPath, newFilename, true, fileToLookFor, true); } }); test('test copy text to clipboard command', async function() { const textForClipboard = 'The fox jumped over the lazy dog.'; await extensionFunctions.placeTextOnClipboard(textForClipboard); const clipboardContent = await vscode.env.clipboard.readText(); expect(clipboardContent).to.equal(textForClipboard); }); test('test copy file text to clipboard command', async function() { const filePathForClipboard = vscode.Uri.parse('didact://?commandId=vscode.didact.copyFileTextToClipboardCommand&extFilePath=src/test/data/textForClipboard.txt'); await extensionFunctions.copyFileTextToClipboard(filePathForClipboard); const clipboardContent2 = await vscode.env.clipboard.readText(); expect(clipboardContent2).to.equal("The fox jumped over the lazy dog again."); }); test('test copy to clipboard with %', async() => { const percentTextForClipboard = 'a test with a %24 percentage inside'; await extensionFunctions.placeTextOnClipboard(percentTextForClipboard); const textInClipBoard: string = await vscode.env.clipboard.readText(); expect(textInClipBoard).to.be.equal(percentTextForClipboard); }); test('test copy to clipboard with doubly url encoded text for long didact link', async() => { const doublyEncodedString = '%5BSend%20some%20fantastic%20text%20to%20a%20Terminal%20window%21%5D%28didact%3A%2F%2F%3FcommandId%3Dvscode.didact.sendNamedTerminalAString%26text%3DTerminalName%24%24echo%2BDidact%2Bis%2Bfantastic%2521%29'; await extensionFunctions.placeTextOnClipboard(doublyEncodedString); const textInClipBoard: string = await vscode.env.clipboard.readText(); expect(textInClipBoard).to.be.equal(doublyEncodedString); }); test('open a remote asciidoc file', async () => { const content = await extensionFunctions.getDataFromUrl(uriToRemoteDidactAdoc); expect(content).to.not.equal(null); expect(content).to.include('How do you access this amazing functionality? The Command Palette!'); }); test('paste from clipboard to active editor', async() => { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); await vscode.commands.executeCommand('workbench.action.files.newUntitledFile'); const textToPaste = 'Some text to copy into a new file created by separate command.'; await extensionFunctions.placeTextOnClipboard(textToPaste); await extensionFunctions.pasteClipboardToActiveEditorOrPreviouslyUsedOne(); if(vscode.window.activeTextEditor) { const doc = vscode.window.activeTextEditor.document; const docText = doc.getText(); expect(docText).to.equal(textToPaste); } else { expect.fail("Editor did not open"); } }); test('paste from clipboard to editor for specific file', async() => { const testUriPath = 'vscode://redhat.vscode-didact?extension=src/test/data/fileToOpen.txt'; const testUri = handleExtFilePath(testUriPath); const textToPaste = 'Some text to copy into an existing file we open.'; if (testUri) { await extensionFunctions.placeTextOnClipboard(textToPaste); await extensionFunctions.pasteClipboardToEditorForFile(testUri); if(vscode.window.activeTextEditor) { const doc = vscode.window.activeTextEditor.document; const docText = doc.getText(); expect(docText).to.equal(textToPaste); } else { expect.fail("Editor did not open"); } } }); test('paste from clipboard to editor for new file', async() => { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); const textToPaste = 'Some text to copy into a new file.'; await extensionFunctions.placeTextOnClipboard(textToPaste); await extensionFunctions.pasteClipboardToNewTextFile(); if(vscode.window.activeTextEditor) { const doc = vscode.window.activeTextEditor.document; const docText = doc.getText(); expect(docText).to.equal(textToPaste); } else { expect.fail("Editor did not open"); } }); test('verify inserted link text for markdown CLI and default send terminal command', async() => { const selectedText = `echo The quick brown fox markdown`; await setInsertLFForCLILinkSetting(true); // reset default const linkText = getLinkTextForCLILinkSetting(); const generatedText = extensionFunctions.getDidactLinkForSelectedText(selectedText, false); const encodedText = encodeURI(selectedText); const defaultCommandToUse = extensionFunctions.SEND_TERMINAL_SOME_TEXT_COMMAND; const expectedLink = ` ([${linkText}](didact://?commandId=${defaultCommandToUse}&text=newTerminal$$${encodedText}))`; expect(generatedText.trim()).to.deep.equal(expectedLink.trim()); }); test('verify inserted link text for adoc CLI and LF send terminal command setting set', async() => { const selectedText = `echo The quick brown fox adoc`; await setInsertLFForCLILinkSetting(false); const linkText = getLinkTextForCLILinkSetting(); const generatedText = extensionFunctions.getDidactLinkForSelectedText(selectedText, true); const encodedText = encodeURI(selectedText); const defaultCommandToUse = extensionFunctions.SEND_TERMINAL_SOME_TEXT_COMMAND_NO_LF; const expectedLink = ` link:didact://?commandId=${defaultCommandToUse}&text=newTerminal$$${encodedText}[(${linkText})]`; await setInsertLFForCLILinkSetting(true); // reset default expect(generatedText.trim()).to.deep.equal(expectedLink.trim()); }); test('verify altered link text appears in generated CLI link', async() => { const selectedText = `echo The quick brown fox`; await setInsertLFForCLILinkSetting(true); // reset default const newLinkText = `**link**`; await setLinkTextForCLILinkSetting(newLinkText); const generatedText = extensionFunctions.getDidactLinkForSelectedText(selectedText, false); const encodedText = encodeURI(selectedText); const defaultCommandToUse = extensionFunctions.SEND_TERMINAL_SOME_TEXT_COMMAND; const expectedLink = ` ([${newLinkText}](didact://?commandId=${defaultCommandToUse}&text=newTerminal$$${encodedText}))`; await setLinkTextForCLILinkSetting(DEFAULT_EXECUTE_LINK_TEXT); // reset default expect(generatedText.trim()).to.deep.equal(expectedLink.trim()); }); test('validate that if we clear the link text setting, it resets to default', async() => { await setLinkTextForCLILinkSetting(DEFAULT_EXECUTE_LINK_TEXT); // reset default await setLinkTextForCLILinkSetting(undefined); const linkTextFromSettings = getLinkTextForCLILinkSetting(); await setLinkTextForCLILinkSetting(DEFAULT_EXECUTE_LINK_TEXT); // reset default expect(linkTextFromSettings).to.equal(DEFAULT_EXECUTE_LINK_TEXT); await setLinkTextForCLILinkSetting(''); // blank const linkTextFromSettings2 = getLinkTextForCLILinkSetting(); await setLinkTextForCLILinkSetting(DEFAULT_EXECUTE_LINK_TEXT); // reset default expect(linkTextFromSettings2).to.equal(DEFAULT_EXECUTE_LINK_TEXT); }); test('basic openUriWithLineAndOrColumn call', async() => { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); const openUriLink1 = `redhat.vscode-didact/demos/markdown/didact-demo.didact.md` const testUri = handleExtFilePath(openUriLink1); if (testUri) { await extensionFunctions.openFileAtLineAndColumn(testUri); if(vscode.window.activeTextEditor) { const doc = vscode.window.activeTextEditor.document; const filename = doc.fileName; expect(filename.endsWith(`didact-demo.didact.md`)).to.be.true; } else { expect.fail("Editor did not open"); } } }); test('openUriWithLineAndOrColumn call with line', async() => { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); const openUriLink1 = `redhat.vscode-didact/demos/markdown/didact-demo.didact.md` const testUri = handleExtFilePath(openUriLink1); if (testUri) { const line = 19; await extensionFunctions.openFileAtLineAndColumn(testUri, line); const activeEditor = vscode.window.activeTextEditor; if(activeEditor) { const doc = activeEditor.document; const filename = doc.fileName; expect(filename.endsWith(`didact-demo.didact.md`)).to.be.true; const position = activeEditor.visibleRanges[0].start; expect(position.line).to.equal(line-1); // convert to 0-based } else { expect.fail("Editor did not open"); } } }); test('openUriWithLineAndOrColumn call with line and column', async() => { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); const openUriLink1 = `redhat.vscode-didact/demos/markdown/didact-demo.didact.md` const testUri = handleExtFilePath(openUriLink1); if (testUri) { const line = 19; const col = vscode.ViewColumn.Beside; await extensionFunctions.openFileAtLineAndColumn(testUri, line, col); const activeEditor = vscode.window.activeTextEditor; if(activeEditor) { const doc = activeEditor.document; const filename = doc.fileName; expect(filename.endsWith(`didact-demo.didact.md`)).to.be.true; const position = activeEditor.visibleRanges[0].start; expect(position.line).to.equal(line-1); // convert to 0-based const currentColumn = activeEditor.viewColumn; // since no editors are open, even if we open it in column 8 it will appear in 1 expect(currentColumn).to.equal(vscode.ViewColumn.One); } else { expect.fail("Editor did not open"); } } }); }); function checkCanParseDidactUriForPath(urlValue: string, endToCheck: string, alternateEnd : string) { console.log(`Testing ${urlValue} to ensure that it resolves to ${endToCheck}`); const textUri = vscode.Uri.parse(urlValue); const rtnUri = extensionFunctions.handleVSCodeDidactUriParsingForPath(textUri); assert.notStrictEqual(rtnUri, undefined); if (rtnUri) { console.log(`-- resolved path1 = ${rtnUri.fsPath}`); const checkEnd1 = rtnUri.fsPath.endsWith(endToCheck); console.log(`-- does it resolve? ${checkEnd1}`); const checkEnd2 = rtnUri.fsPath.endsWith(alternateEnd); console.log(`-- does it resolve? ${checkEnd2}`); const checkEnds = checkEnd1 || checkEnd2; assert.strictEqual(checkEnds, true); } } async function checkCanFindCopiedFile(filepath : string) { console.log(`Testing ${filepath} to ensure that it exists after a copyFileFromURLtoLocalURI call`); assert.notStrictEqual(filepath, null); assert.notStrictEqual(filepath, undefined); const pathUri = vscode.Uri.file(filepath); await vscode.workspace.fs.readFile(pathUri).then( (rtnUri) => { assert.notStrictEqual(rtnUri, undefined); }); } async function testCopyFileFromURLtoLocalURI( fileURL : string, workspaceLocation : string, newfilename? : string, unzip? : boolean, testFileInFolder? : string, ignoreOverwrite = false) { await extensionFunctions.downloadAndUnzipFile(fileURL, workspaceLocation, newfilename, unzip, ignoreOverwrite) .then( async (returnedFilePath) => { if (testFileInFolder) { const folder = path.dirname(returnedFilePath); const testFile = path.resolve(folder, testFileInFolder); await checkCanFindCopiedFile(testFile); } else { await checkCanFindCopiedFile(returnedFilePath); } }); }
the_stack
import * as React from "react"; import { localFiles, localFileProtocol } from "./analyzerTools"; import { LoaderComponent } from "./Loader" import Select from 'react-select'; import { Button, Checkbox, CircularProgress, Dialog, DialogContent, DialogTitle, FormControlLabel, FormGroup, FormHelperText, Switch, TextField } from "@material-ui/core"; declare var require; declare var shortenUrl; export interface Option { label: string; value: string; disabled?: boolean; } export function daysSince(date: Date) { var oneSecond = 1000; var oneMinute = 60 * oneSecond; var oneHour = 60 * oneMinute; var oneDay = 24 * oneHour; let diff = new Date().getTime() - date.getTime(); return Math.round(Math.abs(diff / oneDay)); } export function secondsSince(date: Date) { var oneSecond = 1000; let diff = new Date().getTime() - date.getTime(); return Math.round(Math.abs(diff / oneSecond)); } export function minutesSince(date: Date) { var oneSecond = 1000; var oneMinute = 60 * oneSecond; let diff = new Date().getTime() - date.getTime(); return Math.round(Math.abs(diff / oneMinute)); } export function timeSince(date: Date) { var oneSecond = 1000; var oneMinute = 60 * oneSecond; var oneHour = 60 * oneMinute; var oneDay = 24 * oneHour; let diff = new Date().getTime() - date.getTime(); var days = Math.round(Math.abs(diff / oneDay)); var hours = Math.round(Math.abs(diff % oneDay) / oneHour); var minutes = Math.round(Math.abs(diff % oneHour) / oneMinute); let s = []; if (days > 0) { s.push(`${days} day${days === 1 ? "" : "s"}`); } if (hours > 0) { s.push(`${hours} hour${hours === 1 ? "" : "s"}`); } if (minutes > 0) { s.push(`${minutes} minute${minutes === 1 ? "" : "s"}`); } return s.join(", ") + " ago"; } function unique<T>(array: Array<T>): Array<T> { let result = []; for (let i = 0; i < array.length; i++) { if (result.indexOf(array[i]) < 0) { result.push(array[i]); } } return result; } const ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; declare var process; let masterUrl = window.location.origin + '/'; if (window.location.origin.startsWith('file://') || window.location.origin.startsWith('http://localhost')) { masterUrl = 'https://arewecompressedyet.com/'; } export class RunDetails extends React.Component<{ json: any; }, { }> { render() { let json = this.props.json; let info = json.info; return <div className="runDetail"> <div>Commit: {info.commit}</div> <div>Nick: {info.nick}</div> <div>Task: {info.task}</div> <div>Build Options: {info.build_options}</div> <div>Extra Options: {info.extra_options}</div> <div>Date: {new Date(json.date).toString()}: ({timeSince(new Date(json.date))})</div> </div> } } export class LocalAnalyzerComponent extends React.Component<{ }, { listJson: any; setsJson: any; slots: { runId: string, video: string, quality: number }[]; pairs: any; vote: string; votingEnabled: boolean; filtersEnabled: boolean; showVoteResult: boolean; blind: boolean; voteMessage: string; shortURL: string; taskFilter: string; nickFilter: string; configFilter: Option []; statusFilter: Option []; commandLineFilter: Option []; }> { constructor(props) { super(props); this.state = { listJson: null, setsJson: null, slots: [{ runId: "", video: "", quality: 0 }], vote: "", votingEnabled: false, showVoteResult: false, blind: true, voteMessage: "", shortURL: "", taskFilter: undefined, nickFilter: undefined, configFilter: [], statusFilter: [{ label: "completed", value: "completed" }], commandLineFilter: [], filtersEnabled: true } as any; } loadXHR<T>(path: string, type = "json"): Promise<T> { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); let self = this; xhr.open("GET", path, true); xhr.responseType = "text"; xhr.send(); xhr.addEventListener("load", function () { if (xhr.status != 200) { console.error("Failed to load XHR: " + path); reject(); return; } console.info("Loaded XHR: " + path); let response = this.responseText; if (type === "json") { response = response.replace(/NaN/g, "null"); try { response = response ? JSON.parse(response) : null; } catch (x) { reject(); } } resolve(response as any); }); }); } componentDidMount() { // let listJson = [ // {run_id: "ABC", info: { task: "objective-1-fast", nick: "mbx", build_options: "--enable-xyz --enable-aaa", extra_options: "--enable-xyz --enable-aaa" }}, // {run_id: "DEF", info: { task: "objective-2-fast", nick: "jmx", build_options: "--enable-aaa", extra_options: "--enable-xyz --enable-aaa" }}, // {run_id: "GHI", info: { task: "objective-3-fast", nick: "derf", build_options: "--enable-xyz", extra_options: "--enable-xyz --enable-aaa" }}, // {run_id: "JKL", info: { task: "objective-1-fast", nick: "jmx", build_options: "--enable-bbb", extra_options: "--enable-xyz --enable-aaa" }} // ]; // this.setState({ listJson } as any); // return; this.loadXHR(masterUrl + "list.json").then((listJson: any) => { listJson.sort(function (a, b) { return (new Date(b.date) as any) - (new Date(a.date) as any); }); // Don't filter completed jobs. // listJson = listJson.filter(job => { // return job.status === "completed"; // }); listJson = listJson.slice(0, 5000); // Say no to long names. listJson = listJson.filter(job => { return job.run_id.length < 128; }); this.setState({ listJson } as any); }); this.loadXHR(masterUrl + "sets.json").then((setsJson: any) => { this.setState({ setsJson } as any); }); } handleAction(value) { } resetURL() { this.setState({shortURL: ""} as any); } onChangeTaskFilter(option) { let taskFilter = option ? option.value : undefined; this.setState({ taskFilter } as any); } onChangeNickFilter(option) { let nickFilter = option ? option.value : undefined; this.setState({ nickFilter } as any); } onChangeConfigFilter(option) { let configFilter = option || []; this.setState({ configFilter } as any); } onChangeStatusFilter(option) { let statusFilter = option || []; this.setState({ statusFilter } as any); } onChangeCommandLineFilter(option) { let commandLineFilter = option || []; this.setState({ commandLineFilter } as any); } onChangeRun(slot, option) { let slots = this.state.slots; slots[slot].runId = option ? option.value : undefined; this.setState({ slots } as any); this.resetURL(); } onChangeVideo(slot, option) { let slots = this.state.slots; slots[slot].video = option ? option.value : undefined; this.setState({ slots } as any); this.resetURL(); } onChangeQuality(slot, option) { let slots = this.state.slots; slots[slot].quality = option ? option.value : undefined; this.setState({ slots } as any); this.resetURL(); } onChangeVote(option, value: string) { this.setState({vote: value} as any); this.resetURL(); } onDeleteRun(slot) { let slots = this.state.slots; slots.splice(slot, 1); this.setState({ slots } as any); this.resetURL(); } onDuplicateRun(slot) { let slots = this.state.slots; let oldSlot = slots[slot]; let newSlot = { runId: oldSlot.runId, video: oldSlot.video, quality: oldSlot.quality }; slots.splice(slot, 0, newSlot); this.setState({ slots } as any); this.resetURL(); } onMoveRun(slot, offset) { if (slot + offset < 0) return; let slots = this.state.slots; if (slot + offset >= slots.length) return; let tmp = slots[slot + offset]; slots[slot + offset] = slots[slot]; slots[slot] = tmp; this.setState({ slots } as any); this.resetURL(); } onAddRun() { let slots = this.state.slots; slots.push({ runId: "", video: "", quality: 0 }); this.setState({ slots } as any); this.resetURL(); } onVoteMessageChange(event, value: string) { this.setState({voteMessage: value} as any); this.resetURL(); } makePairs(): any { return this.state.slots.map(slot => { let run = this.getRunById(slot.runId); let videoUrl = masterUrl + `runs/${run.run_id}/${run.info.task}/${slot.video}-${slot.quality}.ivf`; let decoderUrl = masterUrl + `runs/${run.run_id}/js/decoder.js`; return {decoderUrl, videoUrl}; }); } findLongestPrefix(pairs: {decoderUrl: string, videoUrl: string} []): string { let list = []; pairs.forEach(pair => { list.push(pair.decoderUrl); list.push(pair.videoUrl); }); if (list.length == 0) { return ""; } let first = list[0]; let prefix = ""; // Find longest prefix. for (let i = 0; i < first.length; i++) { let tmp = first.slice(0, i); let isCommon = list.every(s => s.indexOf(tmp) == 0); if (!isCommon) { break; } prefix = tmp; } // Remove prefix. pairs.forEach(pair => { pair.decoderUrl = pair.decoderUrl.slice(prefix.length); pair.videoUrl = pair.videoUrl.slice(prefix.length); }); return prefix; } onSend() { window.open(this.createURL(), "_blank"); } getRunById(runId) { return this.state.listJson.find(run => run.run_id === runId); } getOptionsForTask(task: string) { if (!this.state.setsJson || !(task in this.state.setsJson)) { return []; } let array = this.state.setsJson[task].sources; if (!array) { return []; } return array.map(video => { return { value: video, label: video }; }); } getOptionsForQuality(quality: string) { let array = [20, 32, 43, 55, 63]; if (quality) { array = quality.split(" ").map(q => parseInt(q)); } return array.map(q => { return { value: q, label: q }; }) } cannotAnalyze() { let slots = this.state.slots; if (slots.length == 0) { return true; } for (let i = 0; i < slots.length; i++) { let slot = slots[i]; if (!slot.quality || !slot.runId || !slot.video) { return true; } } return false; } createURL() { try { let pairs = this.makePairs(); let prefix = this.findLongestPrefix(pairs); let url = window.location.origin + window.location.pathname + "?"; if (this.state.votingEnabled) { let vote = this.state.vote; if (vote) { vote = this.state.vote.split(",").map(x => x.split(":").map((y: any) => y|0).join(":")).join(","); url += `vote=${vote}&`; } if (this.state.voteMessage) { url += `voteDescription=${this.state.voteMessage}&`; } if (this.state.showVoteResult) { url += `showVoteResult=${1}&`; } if (this.state.vote && this.state.blind) { url += `blind=${1}&`; } } if (!this.state.vote) { url += `maxFrames=${4}&`; } if (prefix) { url += `p=${prefix}&`; } return url + pairs.map(pair => `d=${pair.decoderUrl}&f=${pair.videoUrl}`).join("&"); } catch(e) { return ""; } } onShortenURL() { shortenUrl(this.createURL(), (shortURL) => { this.setState({shortURL} as any); }); } getVoteErrorText() { if (!this.state.vote) { return "Required"; } let vote = []; try { vote = this.state.vote.split(",").map(x => { return x.split(":").map((y: any) => { if (y != (y|0)) { throw `Cannot parse ${y}.`; } return parseInt(y) }); }); } catch (e) { return `Syntax Error: ${e}`; } for (let i = 0; i < vote.length; i++) { for (let j = 0; j < vote[i].length; j++) { let run = vote[i][j]; if (!this.state.slots[run]) { return `Run ${run} is missing.`; } } } return undefined; } render() { function logChange(val) { console.log("Selected: " + val); } let listJson = this.state.listJson; if (!listJson) { return <Dialog open={true}> <DialogTitle>Downloading AWCY Runs</DialogTitle> <DialogContent> <CircularProgress size={40} thickness={7} /> </DialogContent> </Dialog>; } else { let filtersEnabled = this.state.filtersEnabled; let runOptions = listJson.filter(run => { if (!this.state.filtersEnabled) { return true; } let pass = true; if (pass && this.state.statusFilter.length) { // Unlike other filters, this is an OR filter. pass = this.state.statusFilter.some(option => { return run.status == option.value; }); } if (pass && this.state.taskFilter && run.info.task !== this.state.taskFilter) { pass = false; } if (pass && this.state.nickFilter && run.info.nick !== this.state.nickFilter) { pass = false; } if (pass && this.state.configFilter.length) { let buildOptions = run.info.build_options.split(" ").filter(x => !!x); pass = this.state.configFilter.every(option => { return buildOptions.indexOf(option.value) >= 0; }); } if (pass && this.state.commandLineFilter.length) { let commandLineOptions = run.info.extra_options.split(" ").filter(x => !!x); pass = this.state.commandLineFilter.every(option => { return commandLineOptions.indexOf(option.value) >= 0; }); } return pass; }).map(run => { return { value: run.run_id, label: run.run_id } }).slice(0, 1000); let taskFilterOptions = !filtersEnabled ? [] : unique(listJson.map(run => run.info.task)).map(task => { return { value: task, label: task } }); let nickFilterOptions = !filtersEnabled ? [] : unique(listJson.map(run => run.info.nick)).map(nick => { return { value: nick, label: nick } }); let configFilterOptions = !filtersEnabled ? [] : unique(listJson.map(run => run.info.build_options.split(" ").filter(x => !!x)).reduce((a, b) => a.concat(b))).map(option => { return {value: option, label: option} }); let commandLineFilterOptions = !filtersEnabled ? [] : unique(listJson.map(run => run.info.extra_options.split(" ").filter(x => !!x)).reduce((a, b) => a.concat(b))).map(option => { return {value: option, label: option} }); let statusFilterOptions = !filtersEnabled ? [] : unique(listJson.map(run => run.status)).map(status => { return { value: status, label: status } }); return <div> <div className="builderSection"> <FormGroup row> <FormControlLabel control={<Switch style={{width: "300px"}} checked={this.state.filtersEnabled} onChange={(event) => { this.setState({ filtersEnabled: event.target.checked }); this.resetURL(); }} />} label="Filter Runs" /> </FormGroup> </div> { this.state.filtersEnabled && <div> <div className="builderContainer"> <div style={{width: "200px"}}> <Select placeholder="Task Filter" value={this.state.taskFilter} options={taskFilterOptions} onChange={this.onChangeTaskFilter.bind(this)} /> </div> <div style={{width: "200px"}}> <Select placeholder="Nick Filter" value={this.state.nickFilter} options={nickFilterOptions} onChange={this.onChangeNickFilter.bind(this)} /> </div> <div style={{width: "300px"}}> <Select multi placeholder="State Filter" value={this.state.statusFilter} options={statusFilterOptions} onChange={this.onChangeStatusFilter.bind(this)} /> </div> </div> <div className="builderContainer"> <div style={{width: "50%"}}> <Select multi placeholder="Config Filter" value={this.state.configFilter} options={configFilterOptions} onChange={this.onChangeConfigFilter.bind(this)} /> </div> <div style={{width: "50%"}}> <Select multi placeholder="Command Line Filter" value={this.state.commandLineFilter} options={commandLineFilterOptions} onChange={this.onChangeCommandLineFilter.bind(this)} /> </div> </div> </div> } <div className="builderSection"> Runs ({runOptions.length}) </div> {this.state.slots.map((_, i) => { let slot = this.state.slots[i]; let run = this.getRunById(slot.runId); return <div key={i} className="builderVideoContainer"> <div className="builderContainer"> <div style={{width: "32px"}} className="videoSelectionLabel"> {i} </div> <div style={{width: "360px"}}> <Select placeholder="Run" value={slot.runId} options={runOptions} onChange={this.onChangeRun.bind(this, i)} /> </div> <div style={{width: "360px"}}> <Select disabled={!run} placeholder="Video" value={slot.video} options={run ? this.getOptionsForTask(run.info.task) : []} onChange={this.onChangeVideo.bind(this, i)} /> </div> <div style={{width: "60px"}}> <Select disabled={!run} placeholder="QP" value={slot.quality} options={run ? this.getOptionsForQuality(run.info.qualities) : []} onChange={this.onChangeQuality.bind(this, i)} /> </div> <div> <Button variant="contained" disableTouchRipple={true} disableFocusRipple={true} onClick={this.onDeleteRun.bind(this, i)} style={{marginRight: 8}} >Remove</Button> <Button variant="contained" disableTouchRipple={true} disableFocusRipple={true} onClick={this.onDuplicateRun.bind(this, i)} style={{marginRight: 8}} >Duplicate</Button> <Button variant="contained" disabled={i - 1 < 0} disableTouchRipple={true} disableFocusRipple={true} onClick={this.onMoveRun.bind(this, i, -1)} style={{marginRight: 8}} >Up</Button> <Button variant="contained" disabled={i + 1 >= this.state.slots.length} disableTouchRipple={true} disableFocusRipple={true} onClick={this.onMoveRun.bind(this, i, 1)} >Down</Button> </div> </div> <div className="builderContainer" style={{paddingLeft: "40px"}}> {run && <RunDetails json={run} />} </div> </div> }) } <div className="builderSection"> <FormGroup row> <FormControlLabel control={<Switch style={{width: "300px"}} checked={this.state.votingEnabled} onChange={(event) => { this.setState({ votingEnabled: event.target.checked }); this.resetURL(); }} />} label="Enable Voting" /> </FormGroup> </div> {this.state.votingEnabled && <div> <div className="builderContainer"> <div style={{width: "1000px"}}> <TextField error={!!this.getVoteErrorText()} helperText={this.getVoteErrorText()} label="Vote Configuration: 0:1,2:3:4, ..." name="message" value={this.state.vote} style={{width: "1000px"}} onChange={this.onChangeVote.bind(this)}/> </div> </div> <div className="builderContainer"> <FormGroup> <FormControlLabel control={<Checkbox checked={this.state.showVoteResult} onChange={(event) => { this.setState({ showVoteResult: event.target.checked }); this.resetURL(); }} />} label="Show Vote Results" /> <FormHelperText> Show vote results at the end of the voting session. </FormHelperText> </FormGroup> </div> <div className="builderContainer"> <FormGroup> <FormControlLabel control={<Checkbox checked={this.state.blind} onChange={(event) => { this.setState({ blind: event.target.checked }); this.resetURL(); }} />} label="Blind" /> <FormHelperText> Randomize runs when comparing them. </FormHelperText> </FormGroup> </div> <div className="builderContainer"> <TextField label="Vote Intro Message" name="message" value={this.state.voteMessage} style={{width: "1000px"}} onChange={this.onVoteMessageChange.bind(this)}/> </div> </div> } <div className="builderContainer"> <div> <Button variant="contained" disableTouchRipple={true} disableFocusRipple={true} onClick={this.onAddRun.bind(this)} style={{marginRight: 8}} >Add Run</Button> <Button variant="contained" disableTouchRipple={true} disableFocusRipple={true} onClick={this.onShortenURL.bind(this)} style={{marginRight: 8}} >Shorten URL</Button> <Button variant="contained" disabled={this.cannotAnalyze()} disableTouchRipple={true} disableFocusRipple={true} onClick={this.onSend.bind(this)} >Open</Button> </div> </div> <div className="builderSection"> Analyzer Link </div> <div className="builderContainer"> <div className="builderURL"> {this.state.shortURL || this.createURL()} </div> </div> </div> } } }
the_stack
import { AxiosPromise, AxiosRequestConfig, AxiosResponse } from "axios"; import axios from "axios"; import Cookies from "universal-cookie"; import { sessions, users, User, setClerkApiKey } from "@clerk/clerk-sdk-node"; import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult, } from "aws-lambda"; import OAuth from "oauth-1.0a"; import crypto from "crypto"; import AWS from "aws-sdk"; import Mixpanel from "mixpanel"; import randomstring from "randomstring"; export const lambda = new AWS.Lambda({ apiVersion: "2015-03-31" }); export const dynamo = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); export const s3 = new AWS.S3({ apiVersion: "2006-03-01" }); export const ses = new AWS.SES({ apiVersion: "2010-12-01" }); export const mixpanel = process.env.MIXPANEL_TOKEN ? Mixpanel.init(process.env.MIXPANEL_TOKEN) : { track: () => console.log("track") }; const ALLOWED_ORIGINS = ["https://roamjs.com", "https://roamresearch.com"]; type Headers = { [header: string]: boolean | number | string; }; export const headers = ( event: Pick<APIGatewayProxyEvent, "headers"> ): Headers => { const origin = event.headers.origin || event.headers.Origin; return { "Access-Control-Allow-Origin": ALLOWED_ORIGINS.includes(origin) ? origin : "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE", "Access-Control-Allow-Credentials": true, }; }; export const wrapAxios = ( req: AxiosPromise<Record<string, unknown>>, event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => req .then((r) => ({ statusCode: 200, body: JSON.stringify(r.data), headers: headers(event), })) .catch((e) => ({ statusCode: e.response?.status || 500, body: e.response?.data ? JSON.stringify(e.response.data) : e.message, headers: headers(event), })); export const userError = ( body: string, event: APIGatewayProxyEvent ): APIGatewayProxyResult => ({ statusCode: 400, body, headers: headers(event), }); export const serverError = ( body: string, event: Pick<APIGatewayProxyEvent, "headers"> ): APIGatewayProxyResult => ({ statusCode: 500, body, headers: headers(event), }); export const emptyResponse = ( event: APIGatewayProxyEvent ): APIGatewayProxyResult => ({ statusCode: 204, body: JSON.stringify({}), headers: headers(event), }); export const bareSuccessResponse = ( event: Pick<APIGatewayProxyEvent, "headers"> ): APIGatewayProxyResult => ({ statusCode: 200, body: JSON.stringify({ success: true }), headers: headers(event), }); // Github Creds const personalAccessToken = process.env.GITHUB_PERSONAL_ACCESS_TOKEN || ""; export const getGithubOpts = (): AxiosRequestConfig => ({ headers: { Accept: "application/vnd.github.inertia-preview+json", Authorization: `Basic ${Buffer.from( `dvargas92495:${personalAccessToken}` ).toString("base64")}`, }, }); // Twitter Creds const twitterConsumerKey = process.env.TWITTER_CONSUMER_KEY || ""; const twitterConsumerSecret = process.env.TWITTER_CONSUMER_SECRET || ""; export const getTwitterOpts = async ( event: APIGatewayProxyEvent ): Promise<AxiosRequestConfig> => { const twitterBearerTokenResponse = await wrapAxios( axios.post( `https://api.twitter.com/oauth2/token`, {}, { params: { grant_type: "client_credentials", }, auth: { username: twitterConsumerKey, password: twitterConsumerSecret, }, headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", }, } ), event ); const body = JSON.parse(twitterBearerTokenResponse.body); const twitterBearerToken = body.access_token; return { headers: { Authorization: `Bearer ${twitterBearerToken}`, }, }; }; export type Contracts = { link: string; reward: number }[]; export const getFlossActiveContracts = (): Promise<{ projects: Contracts; issues: Contracts; }> => axios .get(`${process.env.FLOSS_API_URL}/contracts`) .then( (r: AxiosResponse<{ projects: Contracts; issues: Contracts }>) => r.data ); export const twitterOAuth = new OAuth({ consumer: { key: process.env.TWITTER_CONSUMER_KEY || "", secret: process.env.TWITTER_CONSUMER_SECRET || "", }, signature_method: "HMAC-SHA1", hash_function(base_string, key) { return crypto.createHmac("sha1", key).update(base_string).digest("base64"); }, }); export const getClerkUser = async ( event: APIGatewayProxyEvent ): Promise<User> => { const cookies = new Cookies(event.headers.Cookie); const sessionToken = cookies.get("__session"); if (!sessionToken) { console.warn("No cookie found", JSON.stringify(event.headers, null, 4)); return undefined; } const sessionId = event.queryStringParameters._clerk_session_id; const session = await sessions.verifySession(sessionId, sessionToken); return await users.getUser(session.userId); }; export const getClerkEmail = async ( event: APIGatewayProxyEvent ): Promise<string> => { const user = await getClerkUser(event); return user ? user.emailAddresses.find((e) => e.id === user.primaryEmailAddressId) ?.emailAddress : ""; }; export const getClerkOpts = ( email: string, headers?: Record<string, string> ): AxiosRequestConfig => ({ headers: { Authorization: `Basic ${Buffer.from(email).toString("base64")}`, ...headers, }, }); export const flossGet = ({ event, path, }: { event: APIGatewayProxyEvent; path: string; }): Promise<APIGatewayProxyResult> => getClerkEmail(event).then((email) => email ? axios .get(`${process.env.FLOSS_API_URL}/${path}`, getClerkOpts(email)) .then((r) => ({ statusCode: 200, body: JSON.stringify(r.data), headers: headers(event), })) : Promise.resolve({ statusCode: 401, body: "No Active Session", headers: headers(event), }) ); export const generateToken = (userId: string): string => Buffer.from( `${userId.replace(/^user_/, "")}:${randomstring.generate({ length: 16 })}` ).toString("base64"); const findUser = async (predicate: (u: User) => boolean): Promise<User> => { let offset = 0; while (offset < 10000) { const us = await users.getUserList({ limit: 100, offset }); const user = us.find(predicate); if (user) { return user; } if (us.length < 100) { return; } offset += us.length; } }; export const getUserFromEvent = ( Authorization: string, service: string, dev?: boolean ): Promise<User> => { if (dev) { setClerkApiKey(process.env.CLERK_DEV_API_KEY); } else { setClerkApiKey(process.env.CLERK_API_KEY); } const [userId, token] = Authorization.length === 32 || Authorization.includes(":") ? // the old ways of generating tokens did not have user id encoded, so we query all users [ null, Authorization.split(":").slice(-1)[0], Authorization.split(":").slice(-1)[0], ] : [ Buffer.from(Authorization, "base64").toString().split(":")[0], Authorization, Buffer.from(Authorization, "base64").toString().split(":")[1], ]; return userId ? users .getUser(`user_${userId}`) .then((user) => (user.publicMetadata as { [s: string]: { token: string } })?.[service] ?.token === token ? user : undefined ) .catch((e) => { return ses .sendEmail({ Destination: { ToAddresses: ["dvargas92495@gmail.com"], }, Message: { Body: { Text: { Charset: "UTF-8", Data: `An error was thrown in a RoamJS lambda: ${e.name}: ${e.message} ${e.stack}`, }, }, Subject: { Charset: "UTF-8", Data: `RoamJS Error: Getting User From Clerk`, }, }, Source: "support@roamjs.com", }) .promise() .then(() => undefined); }) : findUser( (user) => (user.publicMetadata as { [s: string]: { token: string } })?.[service] ?.token === token ); }; export const authenticate = ( handler: APIGatewayProxyHandler, inputService?: "staticSite" | "social" | "developer" ): APIGatewayProxyHandler => (event, ctx, callback) => { const service = inputService || event.queryStringParameters.service; const Authorization = event.headers.Authorization || event.headers.authorization || ""; const dev = !!event.headers["x-roamjs-dev"]; return getUserFromEvent(Authorization, service, dev).then((user) => { if (!user) { console.log( "Failed to authenticate", Authorization.slice(-5), service, dev ); return { statusCode: 401, body: "Invalid token", headers: headers(event), }; } const publicMetadata = user.publicMetadata; const serviceData = ( publicMetadata as { [s: string]: { authenticated: boolean }; } )[service]; if (!serviceData.authenticated) { users.updateUser(user.id, { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore https://github.com/clerkinc/clerk-sdk-node/pull/12#issuecomment-785306137 publicMetadata: JSON.stringify({ ...publicMetadata, [service]: { ...serviceData, authenticated: true, }, }), }); } event.headers.Authorization = user.id; const result = handler(event, ctx, callback); if (!result) { return emptyResponse(event); } return result; }); }; export const emailError = (subject: string, e: Error): Promise<string> => ses .sendEmail({ Destination: { ToAddresses: ["dvargas92495@gmail.com"], }, Message: { Body: { Text: { Charset: "UTF-8", Data: `An error was thrown in a RoamJS lambda: ${e.name}: ${e.message} ${e.stack}`, }, }, Subject: { Charset: "UTF-8", Data: `RoamJS Error: ${subject}`, }, }, Source: "support@roamjs.com", }) .promise() .then((r) => r.MessageId); export const emailCatch = (subject: string, event: APIGatewayProxyEvent) => (e: Error): Promise<APIGatewayProxyResult> => emailError(subject, e).then((id) => ({ statusCode: 500, body: `Unknown error - Message Id ${id}`, headers: headers(event), })); export const listAll = async ( Prefix: string ): Promise<{ objects: AWS.S3.ObjectList; prefixes: AWS.S3.CommonPrefixList; }> => { const objects: AWS.S3.ObjectList = []; const prefixes: AWS.S3.CommonPrefixList = []; let ContinuationToken: string = undefined; let isTruncated = true; while (isTruncated) { const res = await s3 .listObjectsV2({ Bucket: "roamjs.com", Prefix, ContinuationToken, Delimiter: "/", }) .promise(); objects.push(...res.Contents); prefixes.push(...res.CommonPrefixes); ContinuationToken = res.ContinuationToken; isTruncated = res.IsTruncated; } return { objects, prefixes }; }; export const getStripePriceId = (service: string): Promise<string> => axios .get<{ products: { name: string; prices: { id: string }[] }[] }>( `${process.env.FLOSS_API_URL}/stripe-products?project=RoamJS` ) .then( (r) => r.data.products.find( (p) => p.name.toLowerCase() === `roamjs ${service.split("-").slice(-1)}` )?.prices?.[0]?.id );
the_stack
export type SubListener<T = any> = (value: T, prevValue?: T) => void export type Thunk = () => void export type Disposer = Thunk // Exposed, this might be useful for third part reflection based (dev) tools export const $RVal = typeof Symbol === "undefined" ? "$RVal" : Symbol.for('$RVal') export interface Observable<T = unknown> { (): T } export interface Drv<T = unknown, S = T> extends Observable<T> { (newValue: T | S): void } export interface Val<T = unknown, S = T> extends Observable<T> { (updater: (current: T) => T | S): void (newValue: T | S): void } interface RValContext { config: RValConfig isUpdating: boolean pending: Thunk[], currentlyComputingStack: Set<ObservableAdministration>[] currentlyComputing: Set<ObservableAdministration> isRunningReactions: boolean runPendingObservers() } export interface RValConfig { autoFreeze: boolean } interface ObservableAdministration { addListener(observer: Thunk) removeListener(observer: Thunk) get(): any } export type PreProcessor<T = unknown, S = T> = (newValue: T | S, baseValue?: T, api?: RValInstance) => T export interface RValInstance { val<T>(initial: T): Val<T, T> val<T, S=T>(initial: S, preProcessor?: PreProcessor<T, S> | (PreProcessor<T, any>[])): Val<T, S> drv<T, S=T>(derivation: () => T, setter?: (value: S) => void): Drv<T> sub<T>( listener: SubListener<T>, options?: SubscribeOptions ): (src: Observable<T>) => Disposer sub<T>( src: Observable<T>, listener: SubListener<T>, options?: SubscribeOptions ): Disposer effect<T>(fn: () => T, onInvalidate: (onChanged: () => boolean, pull: () => T) => void): Thunk act<T extends Function>(fn: T): T configure(config: Partial<RValConfig>): void } export interface SubscribeOptions { fireImmediately?: boolean } const NOT_TRACKING = 0 const STALE = 1 const UP_TO_DATE = 2 export function rval(base?: Val<any, any>): RValInstance { if (arguments.length) { if (!isVal(base) && !isDrv(base)) throw new Error("Expected val as first argument to rval") return (base[$RVal] as any).api } const context: RValContext = { config: { autoFreeze: true }, isUpdating : false, pending: [], currentlyComputingStack: [], get currentlyComputing() { return this.currentlyComputingStack[this.currentlyComputingStack.length - 1] }, isRunningReactions: false, runPendingObservers } function runAfterBatch(t: Thunk) { context.pending.push(t) } function val(initial, preProcessor: any = defaultPreProcessor): Val<any, any> { return new ObservableValue(context, api, initial, preProcessor).get as any } function drv<T>(derivation: () => T, setter: (value) => void): Drv<T> { return new Computed<T>(context, api, derivation, setter).get as any } function effect<T>(fn: () => T, onInvalidate: (didChange: () => boolean, pull: () => T) => void): Thunk { const computed = isDrv(fn) ? fn[$RVal] : new Computed(context, api, fn) let scheduled = true let disposed = false let lastSeen: any = {} // definitely not pointer equal to something else function didChange() { if (disposed) return false // the right hand of the OR is an easy in case the computed was evaluated early in a batch, but the effect didn't run, // see test 'drv is not re-evaluating if triggered eagerly' const changed = computed.someDependencyHasChanged() || lastSeen !== computed.get() if (!changed) { scheduled = false // no pull is expected } return changed } function pull() { if (disposed) { throw new Error("[rval] pulling from already disposed effect") } scheduled = false return lastSeen = computed.get() } function onDirty () { if (scheduled || disposed) return scheduled = true runAfterBatch(() => onInvalidate(didChange, pull)) } computed.addListener(onDirty) onInvalidate(didChange, pull) return _once(() => { disposed = true computed.removeListener(onDirty) }) } function sub( src, listener?, options? ) { if (arguments.length === 1 || typeof arguments[1] !== "function") { // curried invocation return source => sub(source, src /* the listener actually */, listener /* the options actually */) } let lastSeen: any = undefined let firstRun = true return effect(src, (didChange, pull) => { if (didChange()) { const v = pull() if (firstRun ? (options && options.fireImmediately) : v !== lastSeen) listener(v, lastSeen) lastSeen = v firstRun = false } }) } function act<T extends Function>(fn: T): T { return function act(this: any) { if (context.isUpdating) return fn.apply(this, arguments) try { context.isUpdating = true return fn.apply(this, arguments) } finally { context.isUpdating = false runPendingObservers() } } as any } function runPendingObservers() { if (!context.isUpdating && !context.isRunningReactions) { context.isRunningReactions = true while (context.pending.length) { // N.B. errors here cause other pending subscriptions to be aborted! context.pending.splice(0).forEach(runFn) } context.isRunningReactions = false } } function configure(config: Partial<RValConfig>) { Object.assign(context.config, config) } // prettier-ignore const api = { val, drv, sub, act, effect, configure } return api } const globalProp = "defaultRValInstance" const defaultPreProcessor = value => value export const defaultInstance = global[globalProp] = (() => { const globalInstance = global[globalProp] if (globalInstance) { console.warn("Note: RVal is included in this project twice") // TODO: which is fine, unless this one is used.. return globalInstance } return rval() })() class ObservableValue<T> implements ObservableAdministration { listeners: Thunk[] = [] value: T get: () => T preProcessor: PreProcessor constructor(private context: RValContext, public api: RValInstance, state: T, preProcessor) { this.get = this.getSet.bind(this) as any this.preProcessor = normalizePreProcessor(preProcessor) hiddenProp(this.get, $RVal, this) this.value = this.freeze(this.preProcessor(state, undefined, this.api)) } addListener(listener) { this.listeners.push(listener) } removeListener(listener) { removeCallback(this.listeners, listener) } getSet(newValue?: T) { switch (arguments.length) { case 0: registerRead(this.context, this) return this.value case 1: // prettier-ignore // TODO: re-enable? if (this.context.currentlyComputing) throw new Error('derivations cannot have side effects and update values') if(typeof newValue === "function") newValue = newValue(this.value) newValue = this.preProcessor(newValue, this.value, this.api) as T if (newValue !== this.value) { this.value = this.freeze(newValue!) this.notifyObservers() } break default: throw new Error('val expects 0 or 1 arguments') } } // optimization: could factor out this closure notifyObservers = this.api.act(() => { runAll(this.listeners) }) freeze(v) { if (this.context.config.autoFreeze && (Array.isArray(v) || _isPlainObject(v))) _deepfreeze(v) return v } } class Computed<T = any> implements ObservableAdministration { listeners: Thunk[] = [] inputValues: any[] | undefined = undefined observing: Set<ObservableAdministration> = new Set() state = NOT_TRACKING dirtyCount = 0 value: T = undefined! get: () => T setter?: (value) => void constructor(private context: RValContext, public api: RValInstance, public derivation: () => T, setter?: (value) => void) { this.get = this.getSet.bind(this) as any if (setter) this.setter = api.act(setter) hiddenProp(this.get, $RVal, this) } markDirty = () => { if (++this.dirtyCount === 1) { this.state = STALE runAll(this.listeners) } } addListener(observer) { this.listeners.push(observer) } removeListener(observer) { removeCallback(this.listeners, observer) if (!this.listeners.length) { this.observing.forEach(o => o.removeListener(this.markDirty)) this.observing = new Set() this.value = undefined! this.state = NOT_TRACKING this.inputValues = undefined } } registerDependency(sub: ObservableAdministration) { this.observing.add(sub) } someDependencyHasChanged() { switch(this.state) { case NOT_TRACKING: return true case UP_TO_DATE: return false case STALE: if (!inputSetHasChanged(this.observing, this.inputValues)) { this.dirtyCount = 0 this.state = UP_TO_DATE return false; } } return true; } track() { if (!this.someDependencyHasChanged()) return const oldObserving = this.observing const [newValue, newObserving] = track(this.context, this.derivation) this.value = newValue this.observing = newObserving registerDependencies(this.markDirty, oldObserving, newObserving) this.inputValues = recordInputSet(newObserving) this.dirtyCount = 0 this.state = UP_TO_DATE } getSet(value?) { switch (arguments.length) { case 0: // console.log("GET - "+ this.derivation.toString()) // something being computed? setup tracking registerRead(this.context, this) // yay, we are up to date! if (this.state === UP_TO_DATE) return this.value // nope, we are not, and no one is observing either if (!this.context.currentlyComputing && !this.listeners.length) { // This won't actively remove any listener, but will transition the drv to // untracked, if no other listener arrived // TODO: optimize: have one handler for this! // TODO: should there be an option to disable this optimization to prevent mem leaking? setTimeout(() => this.removeListener(null), 0) } // maybe scheduled, definitely tracking, value is needed, track now! this.track() return this.value case 1: if (this.setter) return void this.setter(value) } throw new Error("[drv] Didn't expect any arguments"); } } type DependencySet = (ObservableAdministration | any)[] function track<R>(context: RValContext, fn: () => R): [R, Set<ObservableAdministration>] { const observing = new Set() context.currentlyComputingStack.push(observing) const res = fn() context.currentlyComputingStack.pop() return [res, observing] } function registerDependencies(listener: Thunk, oldDeps: Set<ObservableAdministration>, newDeps: Set<ObservableAdministration>) { // Optimize: if (!oldDeps) { newDeps.forEach(d => d.addListener(listener)) } else { newDeps.forEach(o => { if (!oldDeps.has(o)) o.addListener(listener) }) oldDeps.forEach(o => { if (!newDeps.has(o)) o.removeListener(listener) }) } } function registerRead(context: RValContext, observable: ObservableAdministration) { // optimize: same last touched by optimization as MobX // Sets are used, and keep insertion order, which is important for optimal performance! // (to make someDependencyHasChanged cheap and not // re-evaluate deps that might not be needed in the future due some branching logic) if (context.currentlyComputing) context.currentlyComputing.add(observable) } function recordInputSet(deps: Set<ObservableAdministration>): any[] { // optimize: write more efficiently return Array.from(deps).map(currentValue) } function inputSetHasChanged(deps: Set<ObservableAdministration>, inputs?: any[]) { return !deps || !inputs || !Array.from(deps.values()).every((o, idx) => o.get() === inputs[idx]) } function currentValue(dep: ObservableAdministration): any { // Returns the current, last known (computed) value of a dep // Regardless whether that is stale or not return (dep as any).value } function runAll(fns: Thunk[]): void { fns.forEach(runFn) } function runFn(fn: Thunk): void { fn() } function removeCallback(fns: Thunk[], fn: Thunk) { const idx = fns.indexOf(fn) if (idx >= 0) fns.splice(idx, 1) } function normalizePreProcessor(preProcessor: undefined | PreProcessor | PreProcessor[]): PreProcessor { if (!preProcessor) return defaultPreProcessor if (typeof preProcessor === "function") return preProcessor if (Array.isArray(preProcessor)) return function(newValue, currentValue, api) { return preProcessor.reduce((acc, current) => current(acc, currentValue, api), newValue) } throw new Error("No valid preprocessor"); } export function isVal(value: any): value is Val { return typeof value === "function" && value[$RVal] instanceof ObservableValue } export function isDrv(value: any): value is Drv { return typeof value === "function" && value[$RVal] instanceof Computed } export function _once<T extends Function>(fn: T): T { // based on 'once' package, but made smaller var f: any = function(this: any) { if (f.called) return f.value f.called = true return (f.value = fn.apply(this, arguments)) } f.called = false return f } export function _deepfreeze(o) { // based on 'deepfreeze' package, but copied here to simplify build setup :-/ if (o === Object(o)) { Object.isFrozen(o) || Object.freeze(o) Object.getOwnPropertyNames(o).forEach(function(prop) { prop === 'constructor' || _deepfreeze(o[prop]) }) } return o } function hiddenProp(target, key, value) { Object.defineProperty(target, key, { configurable: true, enumerable: false, writable: false, value: value }) } export function _isPlainObject(o) { const p = o && typeof o === "object" && Object.getPrototypeOf(o) return p === Object.prototype || p === null } export const val = defaultInstance.val export const drv = defaultInstance.drv export const sub = defaultInstance.sub export const act = defaultInstance.act export const effect = defaultInstance.effect export const configure = defaultInstance.configure
the_stack
import * as $protobuf from "protobufjs"; /** Properties of a Peer. */ export interface IPeer { /** Peer host */ host?: string; /** Peer port */ port?: number; } /** Represents a Peer. */ export class Peer implements IPeer { /** * Constructs a new Peer. * @param [properties] Properties to set */ constructor(properties?: IPeer); /** Peer host. */ public host: string; /** Peer port. */ public port: number; /** * Creates a new Peer instance using the specified properties. * @param [properties] Properties to set * @returns Peer instance */ public static create(properties?: IPeer): Peer; /** * Encodes the specified Peer message. Does not implicitly {@link Peer.verify|verify} messages. * @param message Peer message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPeer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Peer message, length delimited. Does not implicitly {@link Peer.verify|verify} messages. * @param message Peer message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPeer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Peer message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Peer * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Peer; /** * Decodes a Peer message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Peer * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Peer; /** * Verifies a Peer message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Peer message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Peer */ public static fromObject(object: { [k: string]: any }): Peer; /** * Creates a plain object from a Peer message. Also converts values to other types if specified. * @param message Peer * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Peer, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Peer to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Block. */ export interface IBlock { /** Block header */ header?: IBlockHeader; /** Block txs */ txs?: ITx[]; } /** Represents a Block. */ export class Block implements IBlock { /** * Constructs a new Block. * @param [properties] Properties to set */ constructor(properties?: IBlock); /** Block header. */ public header?: IBlockHeader; /** Block txs. */ public txs: ITx[]; /** * Creates a new Block instance using the specified properties. * @param [properties] Properties to set * @returns Block instance */ public static create(properties?: IBlock): Block; /** * Encodes the specified Block message. Does not implicitly {@link Block.verify|verify} messages. * @param message Block message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Block message, length delimited. Does not implicitly {@link Block.verify|verify} messages. * @param message Block message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Block message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Block * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Block; /** * Decodes a Block message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Block * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Block; /** * Verifies a Block message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Block message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Block */ public static fromObject(object: { [k: string]: any }): Block; /** * Creates a plain object from a Block message. Also converts values to other types if specified. * @param message Block * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Block, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Block to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GenesisBlock. */ export interface IGenesisBlock { /** GenesisBlock header */ header?: IGenesisBlockHeader; /** GenesisBlock txs */ txs?: ITx[]; } /** Represents a GenesisBlock. */ export class GenesisBlock implements IGenesisBlock { /** * Constructs a new GenesisBlock. * @param [properties] Properties to set */ constructor(properties?: IGenesisBlock); /** GenesisBlock header. */ public header?: IGenesisBlockHeader; /** GenesisBlock txs. */ public txs: ITx[]; /** * Creates a new GenesisBlock instance using the specified properties. * @param [properties] Properties to set * @returns GenesisBlock instance */ public static create(properties?: IGenesisBlock): GenesisBlock; /** * Encodes the specified GenesisBlock message. Does not implicitly {@link GenesisBlock.verify|verify} messages. * @param message GenesisBlock message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGenesisBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GenesisBlock message, length delimited. Does not implicitly {@link GenesisBlock.verify|verify} messages. * @param message GenesisBlock message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGenesisBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GenesisBlock message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GenesisBlock * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GenesisBlock; /** * Decodes a GenesisBlock message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GenesisBlock * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GenesisBlock; /** * Verifies a GenesisBlock message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GenesisBlock message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GenesisBlock */ public static fromObject(object: { [k: string]: any }): GenesisBlock; /** * Creates a plain object from a GenesisBlock message. Also converts values to other types if specified. * @param message GenesisBlock * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GenesisBlock, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GenesisBlock to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BlockDB. */ export interface IBlockDB { /** BlockDB height */ height?: number; /** BlockDB header */ header?: IBlockHeader; /** BlockDB fileNumber */ fileNumber?: number; /** BlockDB offset */ offset?: number; /** BlockDB length */ length?: number; /** BlockDB tEMA */ tEMA?: number; /** BlockDB pEMA */ pEMA?: number; /** BlockDB nextDifficulty */ nextDifficulty?: number; /** BlockDB totalWork */ totalWork?: number; /** BlockDB uncle */ uncle?: boolean; /** BlockDB nextBlockDifficulty */ nextBlockDifficulty?: number; /** BlockDB blockWorkEMA */ blockWorkEMA?: number; /** BlockDB totalSupply */ totalSupply?: number|Long; } /** Represents a BlockDB. */ export class BlockDB implements IBlockDB { /** * Constructs a new BlockDB. * @param [properties] Properties to set */ constructor(properties?: IBlockDB); /** BlockDB height. */ public height: number; /** BlockDB header. */ public header?: IBlockHeader; /** BlockDB fileNumber. */ public fileNumber: number; /** BlockDB offset. */ public offset: number; /** BlockDB length. */ public length: number; /** BlockDB tEMA. */ public tEMA: number; /** BlockDB pEMA. */ public pEMA: number; /** BlockDB nextDifficulty. */ public nextDifficulty: number; /** BlockDB totalWork. */ public totalWork: number; /** BlockDB uncle. */ public uncle: boolean; /** BlockDB nextBlockDifficulty. */ public nextBlockDifficulty: number; /** BlockDB blockWorkEMA. */ public blockWorkEMA: number; /** BlockDB totalSupply. */ public totalSupply: (number|Long); /** * Creates a new BlockDB instance using the specified properties. * @param [properties] Properties to set * @returns BlockDB instance */ public static create(properties?: IBlockDB): BlockDB; /** * Encodes the specified BlockDB message. Does not implicitly {@link BlockDB.verify|verify} messages. * @param message BlockDB message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IBlockDB, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BlockDB message, length delimited. Does not implicitly {@link BlockDB.verify|verify} messages. * @param message BlockDB message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IBlockDB, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BlockDB message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BlockDB * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): BlockDB; /** * Decodes a BlockDB message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BlockDB * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): BlockDB; /** * Verifies a BlockDB message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BlockDB message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BlockDB */ public static fromObject(object: { [k: string]: any }): BlockDB; /** * Creates a plain object from a BlockDB message. Also converts values to other types if specified. * @param message BlockDB * @param [options] Conversion options * @returns Plain object */ public static toObject(message: BlockDB, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BlockDB to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Network. */ export interface INetwork { /** Network status */ status?: IStatus; /** Network statusReturn */ statusReturn?: IStatusReturn; /** Network ping */ ping?: IPing; /** Network pingReturn */ pingReturn?: IPingReturn; /** Network putTx */ putTx?: IPutTx; /** Network putTxReturn */ putTxReturn?: IPutTxReturn; /** Network getTxs */ getTxs?: IGetTxs; /** Network getTxsReturn */ getTxsReturn?: IGetTxsReturn; /** Network putBlock */ putBlock?: IPutBlock; /** Network putBlockReturn */ putBlockReturn?: IPutBlockReturn; /** Network getBlocksByHash */ getBlocksByHash?: IGetBlocksByHash; /** Network getBlocksByHashReturn */ getBlocksByHashReturn?: IGetBlocksByHashReturn; /** Network getHeadersByHash */ getHeadersByHash?: IGetHeadersByHash; /** Network getHeadersByHashReturn */ getHeadersByHashReturn?: IGetHeadersByHashReturn; /** Network getBlocksByRange */ getBlocksByRange?: IGetBlocksByRange; /** Network getBlocksByRangeReturn */ getBlocksByRangeReturn?: IGetBlocksByRangeReturn; /** Network getHeadersByRange */ getHeadersByRange?: IGetHeadersByRange; /** Network getHeadersByRangeReturn */ getHeadersByRangeReturn?: IGetHeadersByRangeReturn; /** Network getPeers */ getPeers?: IGetPeers; /** Network getPeersReturn */ getPeersReturn?: IGetPeersReturn; /** Network getTip */ getTip?: IGetTip; /** Network getTipReturn */ getTipReturn?: IGetTipReturn; /** Network putHeaders */ putHeaders?: IPutHeaders; /** Network putHeadersReturn */ putHeadersReturn?: IPutHeadersReturn; /** Network getHash */ getHash?: IGetHash; /** Network getHashReturn */ getHashReturn?: IGetHashReturn; /** Network getBlockTxs */ getBlockTxs?: IGetBlockTxs; /** Network getBlockTxsReturn */ getBlockTxsReturn?: IGetBlockTxsReturn; } /** Represents a Network. */ export class Network implements INetwork { /** * Constructs a new Network. * @param [properties] Properties to set */ constructor(properties?: INetwork); /** Network status. */ public status?: IStatus; /** Network statusReturn. */ public statusReturn?: IStatusReturn; /** Network ping. */ public ping?: IPing; /** Network pingReturn. */ public pingReturn?: IPingReturn; /** Network putTx. */ public putTx?: IPutTx; /** Network putTxReturn. */ public putTxReturn?: IPutTxReturn; /** Network getTxs. */ public getTxs?: IGetTxs; /** Network getTxsReturn. */ public getTxsReturn?: IGetTxsReturn; /** Network putBlock. */ public putBlock?: IPutBlock; /** Network putBlockReturn. */ public putBlockReturn?: IPutBlockReturn; /** Network getBlocksByHash. */ public getBlocksByHash?: IGetBlocksByHash; /** Network getBlocksByHashReturn. */ public getBlocksByHashReturn?: IGetBlocksByHashReturn; /** Network getHeadersByHash. */ public getHeadersByHash?: IGetHeadersByHash; /** Network getHeadersByHashReturn. */ public getHeadersByHashReturn?: IGetHeadersByHashReturn; /** Network getBlocksByRange. */ public getBlocksByRange?: IGetBlocksByRange; /** Network getBlocksByRangeReturn. */ public getBlocksByRangeReturn?: IGetBlocksByRangeReturn; /** Network getHeadersByRange. */ public getHeadersByRange?: IGetHeadersByRange; /** Network getHeadersByRangeReturn. */ public getHeadersByRangeReturn?: IGetHeadersByRangeReturn; /** Network getPeers. */ public getPeers?: IGetPeers; /** Network getPeersReturn. */ public getPeersReturn?: IGetPeersReturn; /** Network getTip. */ public getTip?: IGetTip; /** Network getTipReturn. */ public getTipReturn?: IGetTipReturn; /** Network putHeaders. */ public putHeaders?: IPutHeaders; /** Network putHeadersReturn. */ public putHeadersReturn?: IPutHeadersReturn; /** Network getHash. */ public getHash?: IGetHash; /** Network getHashReturn. */ public getHashReturn?: IGetHashReturn; /** Network getBlockTxs. */ public getBlockTxs?: IGetBlockTxs; /** Network getBlockTxsReturn. */ public getBlockTxsReturn?: IGetBlockTxsReturn; /** Network request. */ public request?: ("status"|"statusReturn"|"ping"|"pingReturn"|"putTx"|"putTxReturn"|"getTxs"|"getTxsReturn"|"putBlock"|"putBlockReturn"|"getBlocksByHash"|"getBlocksByHashReturn"|"getHeadersByHash"|"getHeadersByHashReturn"|"getBlocksByRange"|"getBlocksByRangeReturn"|"getHeadersByRange"|"getHeadersByRangeReturn"|"getPeers"|"getPeersReturn"|"getTip"|"getTipReturn"|"putHeaders"|"putHeadersReturn"|"getHash"|"getHashReturn"|"getBlockTxs"|"getBlockTxsReturn"); /** * Creates a new Network instance using the specified properties. * @param [properties] Properties to set * @returns Network instance */ public static create(properties?: INetwork): Network; /** * Encodes the specified Network message. Does not implicitly {@link Network.verify|verify} messages. * @param message Network message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: INetwork, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Network message, length delimited. Does not implicitly {@link Network.verify|verify} messages. * @param message Network message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: INetwork, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Network message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Network * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Network; /** * Decodes a Network message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Network * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Network; /** * Verifies a Network message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Network message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Network */ public static fromObject(object: { [k: string]: any }): Network; /** * Creates a plain object from a Network message. Also converts values to other types if specified. * @param message Network * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Network, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Network to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Status. */ export interface IStatus { /** Status version */ version?: number; /** Status networkid */ networkid?: string; /** Status port */ port?: number; /** Status guid */ guid?: string; /** Status publicPort */ publicPort?: number; } /** Represents a Status. */ export class Status implements IStatus { /** * Constructs a new Status. * @param [properties] Properties to set */ constructor(properties?: IStatus); /** Status version. */ public version: number; /** Status networkid. */ public networkid: string; /** Status port. */ public port: number; /** Status guid. */ public guid: string; /** Status publicPort. */ public publicPort: number; /** * Creates a new Status instance using the specified properties. * @param [properties] Properties to set * @returns Status instance */ public static create(properties?: IStatus): Status; /** * Encodes the specified Status message. Does not implicitly {@link Status.verify|verify} messages. * @param message Status message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IStatus, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Status message, length delimited. Does not implicitly {@link Status.verify|verify} messages. * @param message Status message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IStatus, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Status message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Status * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Status; /** * Decodes a Status message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Status * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Status; /** * Verifies a Status message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Status message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Status */ public static fromObject(object: { [k: string]: any }): Status; /** * Creates a plain object from a Status message. Also converts values to other types if specified. * @param message Status * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Status to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a StatusReturn. */ export interface IStatusReturn { /** StatusReturn success */ success?: boolean; /** StatusReturn status */ status?: IStatus; } /** Represents a StatusReturn. */ export class StatusReturn implements IStatusReturn { /** * Constructs a new StatusReturn. * @param [properties] Properties to set */ constructor(properties?: IStatusReturn); /** StatusReturn success. */ public success: boolean; /** StatusReturn status. */ public status?: IStatus; /** * Creates a new StatusReturn instance using the specified properties. * @param [properties] Properties to set * @returns StatusReturn instance */ public static create(properties?: IStatusReturn): StatusReturn; /** * Encodes the specified StatusReturn message. Does not implicitly {@link StatusReturn.verify|verify} messages. * @param message StatusReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IStatusReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified StatusReturn message, length delimited. Does not implicitly {@link StatusReturn.verify|verify} messages. * @param message StatusReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IStatusReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a StatusReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns StatusReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): StatusReturn; /** * Decodes a StatusReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns StatusReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): StatusReturn; /** * Verifies a StatusReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a StatusReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns StatusReturn */ public static fromObject(object: { [k: string]: any }): StatusReturn; /** * Creates a plain object from a StatusReturn message. Also converts values to other types if specified. * @param message StatusReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: StatusReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this StatusReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Ping. */ export interface IPing { /** Ping nonce */ nonce?: number|Long; } /** Represents a Ping. */ export class Ping implements IPing { /** * Constructs a new Ping. * @param [properties] Properties to set */ constructor(properties?: IPing); /** Ping nonce. */ public nonce: (number|Long); /** * Creates a new Ping instance using the specified properties. * @param [properties] Properties to set * @returns Ping instance */ public static create(properties?: IPing): Ping; /** * Encodes the specified Ping message. Does not implicitly {@link Ping.verify|verify} messages. * @param message Ping message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPing, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Ping message, length delimited. Does not implicitly {@link Ping.verify|verify} messages. * @param message Ping message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPing, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Ping message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Ping * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Ping; /** * Decodes a Ping message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Ping * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Ping; /** * Verifies a Ping message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Ping message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Ping */ public static fromObject(object: { [k: string]: any }): Ping; /** * Creates a plain object from a Ping message. Also converts values to other types if specified. * @param message Ping * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Ping, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Ping to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PingReturn. */ export interface IPingReturn { /** PingReturn nonce */ nonce?: number|Long; } /** Represents a PingReturn. */ export class PingReturn implements IPingReturn { /** * Constructs a new PingReturn. * @param [properties] Properties to set */ constructor(properties?: IPingReturn); /** PingReturn nonce. */ public nonce: (number|Long); /** * Creates a new PingReturn instance using the specified properties. * @param [properties] Properties to set * @returns PingReturn instance */ public static create(properties?: IPingReturn): PingReturn; /** * Encodes the specified PingReturn message. Does not implicitly {@link PingReturn.verify|verify} messages. * @param message PingReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPingReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PingReturn message, length delimited. Does not implicitly {@link PingReturn.verify|verify} messages. * @param message PingReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPingReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PingReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PingReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PingReturn; /** * Decodes a PingReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PingReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PingReturn; /** * Verifies a PingReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PingReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PingReturn */ public static fromObject(object: { [k: string]: any }): PingReturn; /** * Creates a plain object from a PingReturn message. Also converts values to other types if specified. * @param message PingReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PingReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PingReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PutTx. */ export interface IPutTx { /** PutTx txs */ txs?: ITx[]; } /** Represents a PutTx. */ export class PutTx implements IPutTx { /** * Constructs a new PutTx. * @param [properties] Properties to set */ constructor(properties?: IPutTx); /** PutTx txs. */ public txs: ITx[]; /** * Creates a new PutTx instance using the specified properties. * @param [properties] Properties to set * @returns PutTx instance */ public static create(properties?: IPutTx): PutTx; /** * Encodes the specified PutTx message. Does not implicitly {@link PutTx.verify|verify} messages. * @param message PutTx message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPutTx, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PutTx message, length delimited. Does not implicitly {@link PutTx.verify|verify} messages. * @param message PutTx message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPutTx, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PutTx message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PutTx * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PutTx; /** * Decodes a PutTx message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PutTx * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PutTx; /** * Verifies a PutTx message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PutTx message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PutTx */ public static fromObject(object: { [k: string]: any }): PutTx; /** * Creates a plain object from a PutTx message. Also converts values to other types if specified. * @param message PutTx * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PutTx, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PutTx to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PutTxReturn. */ export interface IPutTxReturn { /** PutTxReturn success */ success?: boolean; } /** Represents a PutTxReturn. */ export class PutTxReturn implements IPutTxReturn { /** * Constructs a new PutTxReturn. * @param [properties] Properties to set */ constructor(properties?: IPutTxReturn); /** PutTxReturn success. */ public success: boolean; /** * Creates a new PutTxReturn instance using the specified properties. * @param [properties] Properties to set * @returns PutTxReturn instance */ public static create(properties?: IPutTxReturn): PutTxReturn; /** * Encodes the specified PutTxReturn message. Does not implicitly {@link PutTxReturn.verify|verify} messages. * @param message PutTxReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPutTxReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PutTxReturn message, length delimited. Does not implicitly {@link PutTxReturn.verify|verify} messages. * @param message PutTxReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPutTxReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PutTxReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PutTxReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PutTxReturn; /** * Decodes a PutTxReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PutTxReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PutTxReturn; /** * Verifies a PutTxReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PutTxReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PutTxReturn */ public static fromObject(object: { [k: string]: any }): PutTxReturn; /** * Creates a plain object from a PutTxReturn message. Also converts values to other types if specified. * @param message PutTxReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PutTxReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PutTxReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetBlockTxs. */ export interface IGetBlockTxs { /** GetBlockTxs hashes */ hashes?: Uint8Array[]; } /** Represents a GetBlockTxs. */ export class GetBlockTxs implements IGetBlockTxs { /** * Constructs a new GetBlockTxs. * @param [properties] Properties to set */ constructor(properties?: IGetBlockTxs); /** GetBlockTxs hashes. */ public hashes: Uint8Array[]; /** * Creates a new GetBlockTxs instance using the specified properties. * @param [properties] Properties to set * @returns GetBlockTxs instance */ public static create(properties?: IGetBlockTxs): GetBlockTxs; /** * Encodes the specified GetBlockTxs message. Does not implicitly {@link GetBlockTxs.verify|verify} messages. * @param message GetBlockTxs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetBlockTxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetBlockTxs message, length delimited. Does not implicitly {@link GetBlockTxs.verify|verify} messages. * @param message GetBlockTxs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetBlockTxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetBlockTxs message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetBlockTxs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetBlockTxs; /** * Decodes a GetBlockTxs message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetBlockTxs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetBlockTxs; /** * Verifies a GetBlockTxs message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetBlockTxs message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetBlockTxs */ public static fromObject(object: { [k: string]: any }): GetBlockTxs; /** * Creates a plain object from a GetBlockTxs message. Also converts values to other types if specified. * @param message GetBlockTxs * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetBlockTxs, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetBlockTxs to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BlockTxs. */ export interface IBlockTxs { /** BlockTxs hash */ hash?: Uint8Array; /** BlockTxs txs */ txs?: ITx[]; } /** Represents a BlockTxs. */ export class BlockTxs implements IBlockTxs { /** * Constructs a new BlockTxs. * @param [properties] Properties to set */ constructor(properties?: IBlockTxs); /** BlockTxs hash. */ public hash: Uint8Array; /** BlockTxs txs. */ public txs: ITx[]; /** * Creates a new BlockTxs instance using the specified properties. * @param [properties] Properties to set * @returns BlockTxs instance */ public static create(properties?: IBlockTxs): BlockTxs; /** * Encodes the specified BlockTxs message. Does not implicitly {@link BlockTxs.verify|verify} messages. * @param message BlockTxs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IBlockTxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BlockTxs message, length delimited. Does not implicitly {@link BlockTxs.verify|verify} messages. * @param message BlockTxs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IBlockTxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BlockTxs message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BlockTxs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): BlockTxs; /** * Decodes a BlockTxs message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BlockTxs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): BlockTxs; /** * Verifies a BlockTxs message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BlockTxs message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BlockTxs */ public static fromObject(object: { [k: string]: any }): BlockTxs; /** * Creates a plain object from a BlockTxs message. Also converts values to other types if specified. * @param message BlockTxs * @param [options] Conversion options * @returns Plain object */ public static toObject(message: BlockTxs, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BlockTxs to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetBlockTxsReturn. */ export interface IGetBlockTxsReturn { /** GetBlockTxsReturn txBlocks */ txBlocks?: IBlockTxs[]; } /** Represents a GetBlockTxsReturn. */ export class GetBlockTxsReturn implements IGetBlockTxsReturn { /** * Constructs a new GetBlockTxsReturn. * @param [properties] Properties to set */ constructor(properties?: IGetBlockTxsReturn); /** GetBlockTxsReturn txBlocks. */ public txBlocks: IBlockTxs[]; /** * Creates a new GetBlockTxsReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetBlockTxsReturn instance */ public static create(properties?: IGetBlockTxsReturn): GetBlockTxsReturn; /** * Encodes the specified GetBlockTxsReturn message. Does not implicitly {@link GetBlockTxsReturn.verify|verify} messages. * @param message GetBlockTxsReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetBlockTxsReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetBlockTxsReturn message, length delimited. Does not implicitly {@link GetBlockTxsReturn.verify|verify} messages. * @param message GetBlockTxsReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetBlockTxsReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetBlockTxsReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetBlockTxsReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetBlockTxsReturn; /** * Decodes a GetBlockTxsReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetBlockTxsReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetBlockTxsReturn; /** * Verifies a GetBlockTxsReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetBlockTxsReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetBlockTxsReturn */ public static fromObject(object: { [k: string]: any }): GetBlockTxsReturn; /** * Creates a plain object from a GetBlockTxsReturn message. Also converts values to other types if specified. * @param message GetBlockTxsReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetBlockTxsReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetBlockTxsReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetTxs. */ export interface IGetTxs { /** GetTxs minFee */ minFee?: number|Long; } /** Represents a GetTxs. */ export class GetTxs implements IGetTxs { /** * Constructs a new GetTxs. * @param [properties] Properties to set */ constructor(properties?: IGetTxs); /** GetTxs minFee. */ public minFee: (number|Long); /** * Creates a new GetTxs instance using the specified properties. * @param [properties] Properties to set * @returns GetTxs instance */ public static create(properties?: IGetTxs): GetTxs; /** * Encodes the specified GetTxs message. Does not implicitly {@link GetTxs.verify|verify} messages. * @param message GetTxs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetTxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetTxs message, length delimited. Does not implicitly {@link GetTxs.verify|verify} messages. * @param message GetTxs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetTxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetTxs message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetTxs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetTxs; /** * Decodes a GetTxs message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetTxs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetTxs; /** * Verifies a GetTxs message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetTxs message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetTxs */ public static fromObject(object: { [k: string]: any }): GetTxs; /** * Creates a plain object from a GetTxs message. Also converts values to other types if specified. * @param message GetTxs * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetTxs, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetTxs to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetTxsReturn. */ export interface IGetTxsReturn { /** GetTxsReturn success */ success?: boolean; /** GetTxsReturn txs */ txs?: ITx[]; } /** Represents a GetTxsReturn. */ export class GetTxsReturn implements IGetTxsReturn { /** * Constructs a new GetTxsReturn. * @param [properties] Properties to set */ constructor(properties?: IGetTxsReturn); /** GetTxsReturn success. */ public success: boolean; /** GetTxsReturn txs. */ public txs: ITx[]; /** * Creates a new GetTxsReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetTxsReturn instance */ public static create(properties?: IGetTxsReturn): GetTxsReturn; /** * Encodes the specified GetTxsReturn message. Does not implicitly {@link GetTxsReturn.verify|verify} messages. * @param message GetTxsReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetTxsReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetTxsReturn message, length delimited. Does not implicitly {@link GetTxsReturn.verify|verify} messages. * @param message GetTxsReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetTxsReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetTxsReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetTxsReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetTxsReturn; /** * Decodes a GetTxsReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetTxsReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetTxsReturn; /** * Verifies a GetTxsReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetTxsReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetTxsReturn */ public static fromObject(object: { [k: string]: any }): GetTxsReturn; /** * Creates a plain object from a GetTxsReturn message. Also converts values to other types if specified. * @param message GetTxsReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetTxsReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetTxsReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PutBlock. */ export interface IPutBlock { /** PutBlock blocks */ blocks?: IBlock[]; } /** Represents a PutBlock. */ export class PutBlock implements IPutBlock { /** * Constructs a new PutBlock. * @param [properties] Properties to set */ constructor(properties?: IPutBlock); /** PutBlock blocks. */ public blocks: IBlock[]; /** * Creates a new PutBlock instance using the specified properties. * @param [properties] Properties to set * @returns PutBlock instance */ public static create(properties?: IPutBlock): PutBlock; /** * Encodes the specified PutBlock message. Does not implicitly {@link PutBlock.verify|verify} messages. * @param message PutBlock message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPutBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PutBlock message, length delimited. Does not implicitly {@link PutBlock.verify|verify} messages. * @param message PutBlock message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPutBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PutBlock message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PutBlock * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PutBlock; /** * Decodes a PutBlock message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PutBlock * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PutBlock; /** * Verifies a PutBlock message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PutBlock message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PutBlock */ public static fromObject(object: { [k: string]: any }): PutBlock; /** * Creates a plain object from a PutBlock message. Also converts values to other types if specified. * @param message PutBlock * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PutBlock, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PutBlock to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PutBlockReturn. */ export interface IPutBlockReturn { /** PutBlockReturn statusChanges */ statusChanges?: IStatusChange[]; } /** Represents a PutBlockReturn. */ export class PutBlockReturn implements IPutBlockReturn { /** * Constructs a new PutBlockReturn. * @param [properties] Properties to set */ constructor(properties?: IPutBlockReturn); /** PutBlockReturn statusChanges. */ public statusChanges: IStatusChange[]; /** * Creates a new PutBlockReturn instance using the specified properties. * @param [properties] Properties to set * @returns PutBlockReturn instance */ public static create(properties?: IPutBlockReturn): PutBlockReturn; /** * Encodes the specified PutBlockReturn message. Does not implicitly {@link PutBlockReturn.verify|verify} messages. * @param message PutBlockReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPutBlockReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PutBlockReturn message, length delimited. Does not implicitly {@link PutBlockReturn.verify|verify} messages. * @param message PutBlockReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPutBlockReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PutBlockReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PutBlockReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PutBlockReturn; /** * Decodes a PutBlockReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PutBlockReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PutBlockReturn; /** * Verifies a PutBlockReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PutBlockReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PutBlockReturn */ public static fromObject(object: { [k: string]: any }): PutBlockReturn; /** * Creates a plain object from a PutBlockReturn message. Also converts values to other types if specified. * @param message PutBlockReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PutBlockReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PutBlockReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a NewTx. */ export interface INewTx { /** NewTx txs */ txs?: ITx[]; } /** Represents a NewTx. */ export class NewTx implements INewTx { /** * Constructs a new NewTx. * @param [properties] Properties to set */ constructor(properties?: INewTx); /** NewTx txs. */ public txs: ITx[]; /** * Creates a new NewTx instance using the specified properties. * @param [properties] Properties to set * @returns NewTx instance */ public static create(properties?: INewTx): NewTx; /** * Encodes the specified NewTx message. Does not implicitly {@link NewTx.verify|verify} messages. * @param message NewTx message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: INewTx, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified NewTx message, length delimited. Does not implicitly {@link NewTx.verify|verify} messages. * @param message NewTx message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: INewTx, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a NewTx message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns NewTx * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): NewTx; /** * Decodes a NewTx message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns NewTx * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): NewTx; /** * Verifies a NewTx message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a NewTx message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns NewTx */ public static fromObject(object: { [k: string]: any }): NewTx; /** * Creates a plain object from a NewTx message. Also converts values to other types if specified. * @param message NewTx * @param [options] Conversion options * @returns Plain object */ public static toObject(message: NewTx, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this NewTx to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a NewBlock. */ export interface INewBlock { /** NewBlock blocks */ blocks?: IBlock[]; } /** Represents a NewBlock. */ export class NewBlock implements INewBlock { /** * Constructs a new NewBlock. * @param [properties] Properties to set */ constructor(properties?: INewBlock); /** NewBlock blocks. */ public blocks: IBlock[]; /** * Creates a new NewBlock instance using the specified properties. * @param [properties] Properties to set * @returns NewBlock instance */ public static create(properties?: INewBlock): NewBlock; /** * Encodes the specified NewBlock message. Does not implicitly {@link NewBlock.verify|verify} messages. * @param message NewBlock message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: INewBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified NewBlock message, length delimited. Does not implicitly {@link NewBlock.verify|verify} messages. * @param message NewBlock message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: INewBlock, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a NewBlock message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns NewBlock * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): NewBlock; /** * Decodes a NewBlock message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns NewBlock * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): NewBlock; /** * Verifies a NewBlock message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a NewBlock message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns NewBlock */ public static fromObject(object: { [k: string]: any }): NewBlock; /** * Creates a plain object from a NewBlock message. Also converts values to other types if specified. * @param message NewBlock * @param [options] Conversion options * @returns Plain object */ public static toObject(message: NewBlock, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this NewBlock to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetBlocksByHash. */ export interface IGetBlocksByHash { /** GetBlocksByHash hashes */ hashes?: Uint8Array[]; } /** Represents a GetBlocksByHash. */ export class GetBlocksByHash implements IGetBlocksByHash { /** * Constructs a new GetBlocksByHash. * @param [properties] Properties to set */ constructor(properties?: IGetBlocksByHash); /** GetBlocksByHash hashes. */ public hashes: Uint8Array[]; /** * Creates a new GetBlocksByHash instance using the specified properties. * @param [properties] Properties to set * @returns GetBlocksByHash instance */ public static create(properties?: IGetBlocksByHash): GetBlocksByHash; /** * Encodes the specified GetBlocksByHash message. Does not implicitly {@link GetBlocksByHash.verify|verify} messages. * @param message GetBlocksByHash message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetBlocksByHash, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetBlocksByHash message, length delimited. Does not implicitly {@link GetBlocksByHash.verify|verify} messages. * @param message GetBlocksByHash message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetBlocksByHash, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetBlocksByHash message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetBlocksByHash * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetBlocksByHash; /** * Decodes a GetBlocksByHash message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetBlocksByHash * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetBlocksByHash; /** * Verifies a GetBlocksByHash message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetBlocksByHash message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetBlocksByHash */ public static fromObject(object: { [k: string]: any }): GetBlocksByHash; /** * Creates a plain object from a GetBlocksByHash message. Also converts values to other types if specified. * @param message GetBlocksByHash * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetBlocksByHash, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetBlocksByHash to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetBlocksByHashReturn. */ export interface IGetBlocksByHashReturn { /** GetBlocksByHashReturn success */ success?: boolean; /** GetBlocksByHashReturn blocks */ blocks?: IBlock[]; } /** Represents a GetBlocksByHashReturn. */ export class GetBlocksByHashReturn implements IGetBlocksByHashReturn { /** * Constructs a new GetBlocksByHashReturn. * @param [properties] Properties to set */ constructor(properties?: IGetBlocksByHashReturn); /** GetBlocksByHashReturn success. */ public success: boolean; /** GetBlocksByHashReturn blocks. */ public blocks: IBlock[]; /** * Creates a new GetBlocksByHashReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetBlocksByHashReturn instance */ public static create(properties?: IGetBlocksByHashReturn): GetBlocksByHashReturn; /** * Encodes the specified GetBlocksByHashReturn message. Does not implicitly {@link GetBlocksByHashReturn.verify|verify} messages. * @param message GetBlocksByHashReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetBlocksByHashReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetBlocksByHashReturn message, length delimited. Does not implicitly {@link GetBlocksByHashReturn.verify|verify} messages. * @param message GetBlocksByHashReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetBlocksByHashReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetBlocksByHashReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetBlocksByHashReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetBlocksByHashReturn; /** * Decodes a GetBlocksByHashReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetBlocksByHashReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetBlocksByHashReturn; /** * Verifies a GetBlocksByHashReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetBlocksByHashReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetBlocksByHashReturn */ public static fromObject(object: { [k: string]: any }): GetBlocksByHashReturn; /** * Creates a plain object from a GetBlocksByHashReturn message. Also converts values to other types if specified. * @param message GetBlocksByHashReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetBlocksByHashReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetBlocksByHashReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetHeadersByHash. */ export interface IGetHeadersByHash { /** GetHeadersByHash hashes */ hashes?: Uint8Array[]; } /** Represents a GetHeadersByHash. */ export class GetHeadersByHash implements IGetHeadersByHash { /** * Constructs a new GetHeadersByHash. * @param [properties] Properties to set */ constructor(properties?: IGetHeadersByHash); /** GetHeadersByHash hashes. */ public hashes: Uint8Array[]; /** * Creates a new GetHeadersByHash instance using the specified properties. * @param [properties] Properties to set * @returns GetHeadersByHash instance */ public static create(properties?: IGetHeadersByHash): GetHeadersByHash; /** * Encodes the specified GetHeadersByHash message. Does not implicitly {@link GetHeadersByHash.verify|verify} messages. * @param message GetHeadersByHash message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetHeadersByHash, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetHeadersByHash message, length delimited. Does not implicitly {@link GetHeadersByHash.verify|verify} messages. * @param message GetHeadersByHash message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetHeadersByHash, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetHeadersByHash message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetHeadersByHash * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetHeadersByHash; /** * Decodes a GetHeadersByHash message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetHeadersByHash * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetHeadersByHash; /** * Verifies a GetHeadersByHash message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetHeadersByHash message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetHeadersByHash */ public static fromObject(object: { [k: string]: any }): GetHeadersByHash; /** * Creates a plain object from a GetHeadersByHash message. Also converts values to other types if specified. * @param message GetHeadersByHash * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetHeadersByHash, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetHeadersByHash to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetHeadersByHashReturn. */ export interface IGetHeadersByHashReturn { /** GetHeadersByHashReturn success */ success?: boolean; /** GetHeadersByHashReturn headers */ headers?: IBlockHeader[]; } /** Represents a GetHeadersByHashReturn. */ export class GetHeadersByHashReturn implements IGetHeadersByHashReturn { /** * Constructs a new GetHeadersByHashReturn. * @param [properties] Properties to set */ constructor(properties?: IGetHeadersByHashReturn); /** GetHeadersByHashReturn success. */ public success: boolean; /** GetHeadersByHashReturn headers. */ public headers: IBlockHeader[]; /** * Creates a new GetHeadersByHashReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetHeadersByHashReturn instance */ public static create(properties?: IGetHeadersByHashReturn): GetHeadersByHashReturn; /** * Encodes the specified GetHeadersByHashReturn message. Does not implicitly {@link GetHeadersByHashReturn.verify|verify} messages. * @param message GetHeadersByHashReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetHeadersByHashReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetHeadersByHashReturn message, length delimited. Does not implicitly {@link GetHeadersByHashReturn.verify|verify} messages. * @param message GetHeadersByHashReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetHeadersByHashReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetHeadersByHashReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetHeadersByHashReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetHeadersByHashReturn; /** * Decodes a GetHeadersByHashReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetHeadersByHashReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetHeadersByHashReturn; /** * Verifies a GetHeadersByHashReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetHeadersByHashReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetHeadersByHashReturn */ public static fromObject(object: { [k: string]: any }): GetHeadersByHashReturn; /** * Creates a plain object from a GetHeadersByHashReturn message. Also converts values to other types if specified. * @param message GetHeadersByHashReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetHeadersByHashReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetHeadersByHashReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetBlocksByRange. */ export interface IGetBlocksByRange { /** GetBlocksByRange fromHeight */ fromHeight?: number|Long; /** GetBlocksByRange count */ count?: number|Long; } /** Represents a GetBlocksByRange. */ export class GetBlocksByRange implements IGetBlocksByRange { /** * Constructs a new GetBlocksByRange. * @param [properties] Properties to set */ constructor(properties?: IGetBlocksByRange); /** GetBlocksByRange fromHeight. */ public fromHeight: (number|Long); /** GetBlocksByRange count. */ public count: (number|Long); /** * Creates a new GetBlocksByRange instance using the specified properties. * @param [properties] Properties to set * @returns GetBlocksByRange instance */ public static create(properties?: IGetBlocksByRange): GetBlocksByRange; /** * Encodes the specified GetBlocksByRange message. Does not implicitly {@link GetBlocksByRange.verify|verify} messages. * @param message GetBlocksByRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetBlocksByRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetBlocksByRange message, length delimited. Does not implicitly {@link GetBlocksByRange.verify|verify} messages. * @param message GetBlocksByRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetBlocksByRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetBlocksByRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetBlocksByRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetBlocksByRange; /** * Decodes a GetBlocksByRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetBlocksByRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetBlocksByRange; /** * Verifies a GetBlocksByRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetBlocksByRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetBlocksByRange */ public static fromObject(object: { [k: string]: any }): GetBlocksByRange; /** * Creates a plain object from a GetBlocksByRange message. Also converts values to other types if specified. * @param message GetBlocksByRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetBlocksByRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetBlocksByRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetBlocksByRangeReturn. */ export interface IGetBlocksByRangeReturn { /** GetBlocksByRangeReturn success */ success?: boolean; /** GetBlocksByRangeReturn blocks */ blocks?: IBlock[]; } /** Represents a GetBlocksByRangeReturn. */ export class GetBlocksByRangeReturn implements IGetBlocksByRangeReturn { /** * Constructs a new GetBlocksByRangeReturn. * @param [properties] Properties to set */ constructor(properties?: IGetBlocksByRangeReturn); /** GetBlocksByRangeReturn success. */ public success: boolean; /** GetBlocksByRangeReturn blocks. */ public blocks: IBlock[]; /** * Creates a new GetBlocksByRangeReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetBlocksByRangeReturn instance */ public static create(properties?: IGetBlocksByRangeReturn): GetBlocksByRangeReturn; /** * Encodes the specified GetBlocksByRangeReturn message. Does not implicitly {@link GetBlocksByRangeReturn.verify|verify} messages. * @param message GetBlocksByRangeReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetBlocksByRangeReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetBlocksByRangeReturn message, length delimited. Does not implicitly {@link GetBlocksByRangeReturn.verify|verify} messages. * @param message GetBlocksByRangeReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetBlocksByRangeReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetBlocksByRangeReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetBlocksByRangeReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetBlocksByRangeReturn; /** * Decodes a GetBlocksByRangeReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetBlocksByRangeReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetBlocksByRangeReturn; /** * Verifies a GetBlocksByRangeReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetBlocksByRangeReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetBlocksByRangeReturn */ public static fromObject(object: { [k: string]: any }): GetBlocksByRangeReturn; /** * Creates a plain object from a GetBlocksByRangeReturn message. Also converts values to other types if specified. * @param message GetBlocksByRangeReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetBlocksByRangeReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetBlocksByRangeReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetHeadersByRange. */ export interface IGetHeadersByRange { /** GetHeadersByRange fromHeight */ fromHeight?: number|Long; /** GetHeadersByRange count */ count?: number|Long; } /** Represents a GetHeadersByRange. */ export class GetHeadersByRange implements IGetHeadersByRange { /** * Constructs a new GetHeadersByRange. * @param [properties] Properties to set */ constructor(properties?: IGetHeadersByRange); /** GetHeadersByRange fromHeight. */ public fromHeight: (number|Long); /** GetHeadersByRange count. */ public count: (number|Long); /** * Creates a new GetHeadersByRange instance using the specified properties. * @param [properties] Properties to set * @returns GetHeadersByRange instance */ public static create(properties?: IGetHeadersByRange): GetHeadersByRange; /** * Encodes the specified GetHeadersByRange message. Does not implicitly {@link GetHeadersByRange.verify|verify} messages. * @param message GetHeadersByRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetHeadersByRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetHeadersByRange message, length delimited. Does not implicitly {@link GetHeadersByRange.verify|verify} messages. * @param message GetHeadersByRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetHeadersByRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetHeadersByRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetHeadersByRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetHeadersByRange; /** * Decodes a GetHeadersByRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetHeadersByRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetHeadersByRange; /** * Verifies a GetHeadersByRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetHeadersByRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetHeadersByRange */ public static fromObject(object: { [k: string]: any }): GetHeadersByRange; /** * Creates a plain object from a GetHeadersByRange message. Also converts values to other types if specified. * @param message GetHeadersByRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetHeadersByRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetHeadersByRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetHeadersByRangeReturn. */ export interface IGetHeadersByRangeReturn { /** GetHeadersByRangeReturn success */ success?: boolean; /** GetHeadersByRangeReturn headers */ headers?: IBlockHeader[]; } /** Represents a GetHeadersByRangeReturn. */ export class GetHeadersByRangeReturn implements IGetHeadersByRangeReturn { /** * Constructs a new GetHeadersByRangeReturn. * @param [properties] Properties to set */ constructor(properties?: IGetHeadersByRangeReturn); /** GetHeadersByRangeReturn success. */ public success: boolean; /** GetHeadersByRangeReturn headers. */ public headers: IBlockHeader[]; /** * Creates a new GetHeadersByRangeReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetHeadersByRangeReturn instance */ public static create(properties?: IGetHeadersByRangeReturn): GetHeadersByRangeReturn; /** * Encodes the specified GetHeadersByRangeReturn message. Does not implicitly {@link GetHeadersByRangeReturn.verify|verify} messages. * @param message GetHeadersByRangeReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetHeadersByRangeReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetHeadersByRangeReturn message, length delimited. Does not implicitly {@link GetHeadersByRangeReturn.verify|verify} messages. * @param message GetHeadersByRangeReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetHeadersByRangeReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetHeadersByRangeReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetHeadersByRangeReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetHeadersByRangeReturn; /** * Decodes a GetHeadersByRangeReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetHeadersByRangeReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetHeadersByRangeReturn; /** * Verifies a GetHeadersByRangeReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetHeadersByRangeReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetHeadersByRangeReturn */ public static fromObject(object: { [k: string]: any }): GetHeadersByRangeReturn; /** * Creates a plain object from a GetHeadersByRangeReturn message. Also converts values to other types if specified. * @param message GetHeadersByRangeReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetHeadersByRangeReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetHeadersByRangeReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetPeers. */ export interface IGetPeers { /** GetPeers count */ count?: number; } /** Represents a GetPeers. */ export class GetPeers implements IGetPeers { /** * Constructs a new GetPeers. * @param [properties] Properties to set */ constructor(properties?: IGetPeers); /** GetPeers count. */ public count: number; /** * Creates a new GetPeers instance using the specified properties. * @param [properties] Properties to set * @returns GetPeers instance */ public static create(properties?: IGetPeers): GetPeers; /** * Encodes the specified GetPeers message. Does not implicitly {@link GetPeers.verify|verify} messages. * @param message GetPeers message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetPeers, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetPeers message, length delimited. Does not implicitly {@link GetPeers.verify|verify} messages. * @param message GetPeers message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetPeers, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetPeers message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetPeers * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetPeers; /** * Decodes a GetPeers message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetPeers * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetPeers; /** * Verifies a GetPeers message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetPeers message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetPeers */ public static fromObject(object: { [k: string]: any }): GetPeers; /** * Creates a plain object from a GetPeers message. Also converts values to other types if specified. * @param message GetPeers * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetPeers, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetPeers to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetPeersReturn. */ export interface IGetPeersReturn { /** GetPeersReturn success */ success?: boolean; /** GetPeersReturn peers */ peers?: IPeer[]; } /** Represents a GetPeersReturn. */ export class GetPeersReturn implements IGetPeersReturn { /** * Constructs a new GetPeersReturn. * @param [properties] Properties to set */ constructor(properties?: IGetPeersReturn); /** GetPeersReturn success. */ public success: boolean; /** GetPeersReturn peers. */ public peers: IPeer[]; /** * Creates a new GetPeersReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetPeersReturn instance */ public static create(properties?: IGetPeersReturn): GetPeersReturn; /** * Encodes the specified GetPeersReturn message. Does not implicitly {@link GetPeersReturn.verify|verify} messages. * @param message GetPeersReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetPeersReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetPeersReturn message, length delimited. Does not implicitly {@link GetPeersReturn.verify|verify} messages. * @param message GetPeersReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetPeersReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetPeersReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetPeersReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetPeersReturn; /** * Decodes a GetPeersReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetPeersReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetPeersReturn; /** * Verifies a GetPeersReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetPeersReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetPeersReturn */ public static fromObject(object: { [k: string]: any }): GetPeersReturn; /** * Creates a plain object from a GetPeersReturn message. Also converts values to other types if specified. * @param message GetPeersReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetPeersReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetPeersReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetTip. */ export interface IGetTip { /** GetTip dummy */ dummy?: number|Long; /** GetTip header */ header?: boolean; } /** Represents a GetTip. */ export class GetTip implements IGetTip { /** * Constructs a new GetTip. * @param [properties] Properties to set */ constructor(properties?: IGetTip); /** GetTip dummy. */ public dummy: (number|Long); /** GetTip header. */ public header: boolean; /** * Creates a new GetTip instance using the specified properties. * @param [properties] Properties to set * @returns GetTip instance */ public static create(properties?: IGetTip): GetTip; /** * Encodes the specified GetTip message. Does not implicitly {@link GetTip.verify|verify} messages. * @param message GetTip message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetTip, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetTip message, length delimited. Does not implicitly {@link GetTip.verify|verify} messages. * @param message GetTip message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetTip, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetTip message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetTip * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetTip; /** * Decodes a GetTip message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetTip * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetTip; /** * Verifies a GetTip message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetTip message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetTip */ public static fromObject(object: { [k: string]: any }): GetTip; /** * Creates a plain object from a GetTip message. Also converts values to other types if specified. * @param message GetTip * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetTip, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetTip to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetTipReturn. */ export interface IGetTipReturn { /** GetTipReturn success */ success?: boolean; /** GetTipReturn hash */ hash?: Uint8Array; /** GetTipReturn height */ height?: number|Long; /** GetTipReturn totalwork */ totalwork?: number; } /** Represents a GetTipReturn. */ export class GetTipReturn implements IGetTipReturn { /** * Constructs a new GetTipReturn. * @param [properties] Properties to set */ constructor(properties?: IGetTipReturn); /** GetTipReturn success. */ public success: boolean; /** GetTipReturn hash. */ public hash: Uint8Array; /** GetTipReturn height. */ public height: (number|Long); /** GetTipReturn totalwork. */ public totalwork: number; /** * Creates a new GetTipReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetTipReturn instance */ public static create(properties?: IGetTipReturn): GetTipReturn; /** * Encodes the specified GetTipReturn message. Does not implicitly {@link GetTipReturn.verify|verify} messages. * @param message GetTipReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetTipReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetTipReturn message, length delimited. Does not implicitly {@link GetTipReturn.verify|verify} messages. * @param message GetTipReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetTipReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetTipReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetTipReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetTipReturn; /** * Decodes a GetTipReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetTipReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetTipReturn; /** * Verifies a GetTipReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetTipReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetTipReturn */ public static fromObject(object: { [k: string]: any }): GetTipReturn; /** * Creates a plain object from a GetTipReturn message. Also converts values to other types if specified. * @param message GetTipReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetTipReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetTipReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PutHeaders. */ export interface IPutHeaders { /** PutHeaders headers */ headers?: IBlockHeader[]; } /** Represents a PutHeaders. */ export class PutHeaders implements IPutHeaders { /** * Constructs a new PutHeaders. * @param [properties] Properties to set */ constructor(properties?: IPutHeaders); /** PutHeaders headers. */ public headers: IBlockHeader[]; /** * Creates a new PutHeaders instance using the specified properties. * @param [properties] Properties to set * @returns PutHeaders instance */ public static create(properties?: IPutHeaders): PutHeaders; /** * Encodes the specified PutHeaders message. Does not implicitly {@link PutHeaders.verify|verify} messages. * @param message PutHeaders message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPutHeaders, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PutHeaders message, length delimited. Does not implicitly {@link PutHeaders.verify|verify} messages. * @param message PutHeaders message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPutHeaders, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PutHeaders message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PutHeaders * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PutHeaders; /** * Decodes a PutHeaders message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PutHeaders * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PutHeaders; /** * Verifies a PutHeaders message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PutHeaders message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PutHeaders */ public static fromObject(object: { [k: string]: any }): PutHeaders; /** * Creates a plain object from a PutHeaders message. Also converts values to other types if specified. * @param message PutHeaders * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PutHeaders, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PutHeaders to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PutHeadersReturn. */ export interface IPutHeadersReturn { /** PutHeadersReturn statusChanges */ statusChanges?: IStatusChange[]; } /** Represents a PutHeadersReturn. */ export class PutHeadersReturn implements IPutHeadersReturn { /** * Constructs a new PutHeadersReturn. * @param [properties] Properties to set */ constructor(properties?: IPutHeadersReturn); /** PutHeadersReturn statusChanges. */ public statusChanges: IStatusChange[]; /** * Creates a new PutHeadersReturn instance using the specified properties. * @param [properties] Properties to set * @returns PutHeadersReturn instance */ public static create(properties?: IPutHeadersReturn): PutHeadersReturn; /** * Encodes the specified PutHeadersReturn message. Does not implicitly {@link PutHeadersReturn.verify|verify} messages. * @param message PutHeadersReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPutHeadersReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PutHeadersReturn message, length delimited. Does not implicitly {@link PutHeadersReturn.verify|verify} messages. * @param message PutHeadersReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPutHeadersReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PutHeadersReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PutHeadersReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PutHeadersReturn; /** * Decodes a PutHeadersReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PutHeadersReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PutHeadersReturn; /** * Verifies a PutHeadersReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PutHeadersReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PutHeadersReturn */ public static fromObject(object: { [k: string]: any }): PutHeadersReturn; /** * Creates a plain object from a PutHeadersReturn message. Also converts values to other types if specified. * @param message PutHeadersReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PutHeadersReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PutHeadersReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetHash. */ export interface IGetHash { /** GetHash height */ height?: number|Long; } /** Represents a GetHash. */ export class GetHash implements IGetHash { /** * Constructs a new GetHash. * @param [properties] Properties to set */ constructor(properties?: IGetHash); /** GetHash height. */ public height: (number|Long); /** * Creates a new GetHash instance using the specified properties. * @param [properties] Properties to set * @returns GetHash instance */ public static create(properties?: IGetHash): GetHash; /** * Encodes the specified GetHash message. Does not implicitly {@link GetHash.verify|verify} messages. * @param message GetHash message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetHash, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetHash message, length delimited. Does not implicitly {@link GetHash.verify|verify} messages. * @param message GetHash message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetHash, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetHash message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetHash * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetHash; /** * Decodes a GetHash message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetHash * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetHash; /** * Verifies a GetHash message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetHash message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetHash */ public static fromObject(object: { [k: string]: any }): GetHash; /** * Creates a plain object from a GetHash message. Also converts values to other types if specified. * @param message GetHash * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetHash, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetHash to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetHashReturn. */ export interface IGetHashReturn { /** GetHashReturn success */ success?: boolean; /** GetHashReturn hash */ hash?: Uint8Array; } /** Represents a GetHashReturn. */ export class GetHashReturn implements IGetHashReturn { /** * Constructs a new GetHashReturn. * @param [properties] Properties to set */ constructor(properties?: IGetHashReturn); /** GetHashReturn success. */ public success: boolean; /** GetHashReturn hash. */ public hash: Uint8Array; /** * Creates a new GetHashReturn instance using the specified properties. * @param [properties] Properties to set * @returns GetHashReturn instance */ public static create(properties?: IGetHashReturn): GetHashReturn; /** * Encodes the specified GetHashReturn message. Does not implicitly {@link GetHashReturn.verify|verify} messages. * @param message GetHashReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGetHashReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetHashReturn message, length delimited. Does not implicitly {@link GetHashReturn.verify|verify} messages. * @param message GetHashReturn message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGetHashReturn, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetHashReturn message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetHashReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GetHashReturn; /** * Decodes a GetHashReturn message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetHashReturn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GetHashReturn; /** * Verifies a GetHashReturn message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetHashReturn message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetHashReturn */ public static fromObject(object: { [k: string]: any }): GetHashReturn; /** * Creates a plain object from a GetHashReturn message. Also converts values to other types if specified. * @param message GetHashReturn * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GetHashReturn, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetHashReturn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a StatusChange. */ export interface IStatusChange { /** StatusChange status */ status?: number; /** StatusChange oldStatus */ oldStatus?: number; } /** Represents a StatusChange. */ export class StatusChange implements IStatusChange { /** * Constructs a new StatusChange. * @param [properties] Properties to set */ constructor(properties?: IStatusChange); /** StatusChange status. */ public status: number; /** StatusChange oldStatus. */ public oldStatus: number; /** * Creates a new StatusChange instance using the specified properties. * @param [properties] Properties to set * @returns StatusChange instance */ public static create(properties?: IStatusChange): StatusChange; /** * Encodes the specified StatusChange message. Does not implicitly {@link StatusChange.verify|verify} messages. * @param message StatusChange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IStatusChange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified StatusChange message, length delimited. Does not implicitly {@link StatusChange.verify|verify} messages. * @param message StatusChange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IStatusChange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a StatusChange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns StatusChange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): StatusChange; /** * Decodes a StatusChange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns StatusChange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): StatusChange; /** * Verifies a StatusChange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a StatusChange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns StatusChange */ public static fromObject(object: { [k: string]: any }): StatusChange; /** * Creates a plain object from a StatusChange message. Also converts values to other types if specified. * @param message StatusChange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: StatusChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this StatusChange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GenesisBlockHeader. */ export interface IGenesisBlockHeader { /** GenesisBlockHeader previousHash */ previousHash?: Uint8Array[]; /** GenesisBlockHeader merkleRoot */ merkleRoot?: Uint8Array; /** GenesisBlockHeader stateRoot */ stateRoot?: Uint8Array; /** GenesisBlockHeader difficulty */ difficulty?: number; /** GenesisBlockHeader timeStamp */ timeStamp?: number|Long; /** GenesisBlockHeader nonce */ nonce?: number|Long; /** GenesisBlockHeader miner */ miner?: Uint8Array; } /** Represents a GenesisBlockHeader. */ export class GenesisBlockHeader implements IGenesisBlockHeader { /** * Constructs a new GenesisBlockHeader. * @param [properties] Properties to set */ constructor(properties?: IGenesisBlockHeader); /** GenesisBlockHeader previousHash. */ public previousHash: Uint8Array[]; /** GenesisBlockHeader merkleRoot. */ public merkleRoot: Uint8Array; /** GenesisBlockHeader stateRoot. */ public stateRoot: Uint8Array; /** GenesisBlockHeader difficulty. */ public difficulty: number; /** GenesisBlockHeader timeStamp. */ public timeStamp: (number|Long); /** GenesisBlockHeader nonce. */ public nonce: (number|Long); /** GenesisBlockHeader miner. */ public miner: Uint8Array; /** * Creates a new GenesisBlockHeader instance using the specified properties. * @param [properties] Properties to set * @returns GenesisBlockHeader instance */ public static create(properties?: IGenesisBlockHeader): GenesisBlockHeader; /** * Encodes the specified GenesisBlockHeader message. Does not implicitly {@link GenesisBlockHeader.verify|verify} messages. * @param message GenesisBlockHeader message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IGenesisBlockHeader, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GenesisBlockHeader message, length delimited. Does not implicitly {@link GenesisBlockHeader.verify|verify} messages. * @param message GenesisBlockHeader message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IGenesisBlockHeader, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GenesisBlockHeader message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GenesisBlockHeader * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GenesisBlockHeader; /** * Decodes a GenesisBlockHeader message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GenesisBlockHeader * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GenesisBlockHeader; /** * Verifies a GenesisBlockHeader message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GenesisBlockHeader message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GenesisBlockHeader */ public static fromObject(object: { [k: string]: any }): GenesisBlockHeader; /** * Creates a plain object from a GenesisBlockHeader message. Also converts values to other types if specified. * @param message GenesisBlockHeader * @param [options] Conversion options * @returns Plain object */ public static toObject(message: GenesisBlockHeader, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GenesisBlockHeader to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BlockHeader. */ export interface IBlockHeader { /** BlockHeader previousHash */ previousHash?: Uint8Array[]; /** BlockHeader merkleRoot */ merkleRoot?: Uint8Array; /** BlockHeader stateRoot */ stateRoot?: Uint8Array; /** BlockHeader difficulty */ difficulty?: number; /** BlockHeader timeStamp */ timeStamp?: number|Long; /** BlockHeader nonce */ nonce?: number|Long; /** BlockHeader miner */ miner?: Uint8Array; } /** Represents a BlockHeader. */ export class BlockHeader implements IBlockHeader { /** * Constructs a new BlockHeader. * @param [properties] Properties to set */ constructor(properties?: IBlockHeader); /** BlockHeader previousHash. */ public previousHash: Uint8Array[]; /** BlockHeader merkleRoot. */ public merkleRoot: Uint8Array; /** BlockHeader stateRoot. */ public stateRoot: Uint8Array; /** BlockHeader difficulty. */ public difficulty: number; /** BlockHeader timeStamp. */ public timeStamp: (number|Long); /** BlockHeader nonce. */ public nonce: (number|Long); /** BlockHeader miner. */ public miner: Uint8Array; /** * Creates a new BlockHeader instance using the specified properties. * @param [properties] Properties to set * @returns BlockHeader instance */ public static create(properties?: IBlockHeader): BlockHeader; /** * Encodes the specified BlockHeader message. Does not implicitly {@link BlockHeader.verify|verify} messages. * @param message BlockHeader message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IBlockHeader, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BlockHeader message, length delimited. Does not implicitly {@link BlockHeader.verify|verify} messages. * @param message BlockHeader message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IBlockHeader, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BlockHeader message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BlockHeader * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): BlockHeader; /** * Decodes a BlockHeader message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BlockHeader * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): BlockHeader; /** * Verifies a BlockHeader message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BlockHeader message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BlockHeader */ public static fromObject(object: { [k: string]: any }): BlockHeader; /** * Creates a plain object from a BlockHeader message. Also converts values to other types if specified. * @param message BlockHeader * @param [options] Conversion options * @returns Plain object */ public static toObject(message: BlockHeader, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BlockHeader to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Txs. */ export interface ITxs { /** Txs txs */ txs?: ITx[]; } /** Represents a Txs. */ export class Txs implements ITxs { /** * Constructs a new Txs. * @param [properties] Properties to set */ constructor(properties?: ITxs); /** Txs txs. */ public txs: ITx[]; /** * Creates a new Txs instance using the specified properties. * @param [properties] Properties to set * @returns Txs instance */ public static create(properties?: ITxs): Txs; /** * Encodes the specified Txs message. Does not implicitly {@link Txs.verify|verify} messages. * @param message Txs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: ITxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Txs message, length delimited. Does not implicitly {@link Txs.verify|verify} messages. * @param message Txs message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: ITxs, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Txs message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Txs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Txs; /** * Decodes a Txs message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Txs * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Txs; /** * Verifies a Txs message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Txs message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Txs */ public static fromObject(object: { [k: string]: any }): Txs; /** * Creates a plain object from a Txs message. Also converts values to other types if specified. * @param message Txs * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Txs, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Txs to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Tx. */ export interface ITx { /** Tx from */ from?: Uint8Array; /** Tx to */ to?: Uint8Array; /** Tx amount */ amount?: number|Long; /** Tx fee */ fee?: number|Long; /** Tx nonce */ nonce?: number; /** Tx signature */ signature?: Uint8Array; /** Tx recovery */ recovery?: number; /** Tx transitionSignature */ transitionSignature?: Uint8Array; /** Tx transitionRecovery */ transitionRecovery?: number; /** Tx networkid */ networkid?: string; } /** Represents a Tx. */ export class Tx implements ITx { /** * Constructs a new Tx. * @param [properties] Properties to set */ constructor(properties?: ITx); /** Tx from. */ public from: Uint8Array; /** Tx to. */ public to: Uint8Array; /** Tx amount. */ public amount: (number|Long); /** Tx fee. */ public fee: (number|Long); /** Tx nonce. */ public nonce: number; /** Tx signature. */ public signature: Uint8Array; /** Tx recovery. */ public recovery: number; /** Tx transitionSignature. */ public transitionSignature: Uint8Array; /** Tx transitionRecovery. */ public transitionRecovery: number; /** Tx networkid. */ public networkid: string; /** * Creates a new Tx instance using the specified properties. * @param [properties] Properties to set * @returns Tx instance */ public static create(properties?: ITx): Tx; /** * Encodes the specified Tx message. Does not implicitly {@link Tx.verify|verify} messages. * @param message Tx message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: ITx, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Tx message, length delimited. Does not implicitly {@link Tx.verify|verify} messages. * @param message Tx message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: ITx, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Tx message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Tx * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Tx; /** * Decodes a Tx message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Tx * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Tx; /** * Verifies a Tx message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Tx message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Tx */ public static fromObject(object: { [k: string]: any }): Tx; /** * Creates a plain object from a Tx message. Also converts values to other types if specified. * @param message Tx * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Tx, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Tx to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a TxDB. */ export interface ITxDB { /** TxDB hash */ hash?: Uint8Array; /** TxDB blockHash */ blockHash?: Uint8Array; /** TxDB blockHeight */ blockHeight?: number; /** TxDB txNumber */ txNumber?: number; } /** Represents a TxDB. */ export class TxDB implements ITxDB { /** * Constructs a new TxDB. * @param [properties] Properties to set */ constructor(properties?: ITxDB); /** TxDB hash. */ public hash: Uint8Array; /** TxDB blockHash. */ public blockHash: Uint8Array; /** TxDB blockHeight. */ public blockHeight: number; /** TxDB txNumber. */ public txNumber: number; /** * Creates a new TxDB instance using the specified properties. * @param [properties] Properties to set * @returns TxDB instance */ public static create(properties?: ITxDB): TxDB; /** * Encodes the specified TxDB message. Does not implicitly {@link TxDB.verify|verify} messages. * @param message TxDB message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: ITxDB, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified TxDB message, length delimited. Does not implicitly {@link TxDB.verify|verify} messages. * @param message TxDB message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: ITxDB, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TxDB message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns TxDB * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): TxDB; /** * Decodes a TxDB message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns TxDB * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): TxDB; /** * Verifies a TxDB message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a TxDB message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns TxDB */ public static fromObject(object: { [k: string]: any }): TxDB; /** * Creates a plain object from a TxDB message. Also converts values to other types if specified. * @param message TxDB * @param [options] Conversion options * @returns Plain object */ public static toObject(message: TxDB, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TxDB to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DBState. */ export interface IDBState { /** DBState account */ account?: IAccount; /** DBState node */ node?: IStateNode; /** DBState refCount */ refCount?: number; } /** Represents a DBState. */ export class DBState implements IDBState { /** * Constructs a new DBState. * @param [properties] Properties to set */ constructor(properties?: IDBState); /** DBState account. */ public account?: IAccount; /** DBState node. */ public node?: IStateNode; /** DBState refCount. */ public refCount: number; /** DBState state. */ public state?: ("account"|"node"|"refCount"); /** * Creates a new DBState instance using the specified properties. * @param [properties] Properties to set * @returns DBState instance */ public static create(properties?: IDBState): DBState; /** * Encodes the specified DBState message. Does not implicitly {@link DBState.verify|verify} messages. * @param message DBState message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IDBState, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DBState message, length delimited. Does not implicitly {@link DBState.verify|verify} messages. * @param message DBState message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IDBState, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DBState message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DBState * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): DBState; /** * Decodes a DBState message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DBState * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): DBState; /** * Verifies a DBState message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DBState message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DBState */ public static fromObject(object: { [k: string]: any }): DBState; /** * Creates a plain object from a DBState message. Also converts values to other types if specified. * @param message DBState * @param [options] Conversion options * @returns Plain object */ public static toObject(message: DBState, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DBState to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Account. */ export interface IAccount { /** Account balance */ balance?: number|Long; /** Account nonce */ nonce?: number; } /** Represents an Account. */ export class Account implements IAccount { /** * Constructs a new Account. * @param [properties] Properties to set */ constructor(properties?: IAccount); /** Account balance. */ public balance: (number|Long); /** Account nonce. */ public nonce: number; /** * Creates a new Account instance using the specified properties. * @param [properties] Properties to set * @returns Account instance */ public static create(properties?: IAccount): Account; /** * Encodes the specified Account message. Does not implicitly {@link Account.verify|verify} messages. * @param message Account message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IAccount, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Account message, length delimited. Does not implicitly {@link Account.verify|verify} messages. * @param message Account message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IAccount, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Account message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Account * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Account; /** * Decodes an Account message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Account * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Account; /** * Verifies an Account message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Account message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Account */ public static fromObject(object: { [k: string]: any }): Account; /** * Creates a plain object from an Account message. Also converts values to other types if specified. * @param message Account * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Account, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Account to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a StateNode. */ export interface IStateNode { /** StateNode nodeRefs */ nodeRefs?: INodeRef[]; } /** Represents a StateNode. */ export class StateNode implements IStateNode { /** * Constructs a new StateNode. * @param [properties] Properties to set */ constructor(properties?: IStateNode); /** StateNode nodeRefs. */ public nodeRefs: INodeRef[]; /** * Creates a new StateNode instance using the specified properties. * @param [properties] Properties to set * @returns StateNode instance */ public static create(properties?: IStateNode): StateNode; /** * Encodes the specified StateNode message. Does not implicitly {@link StateNode.verify|verify} messages. * @param message StateNode message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IStateNode, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified StateNode message, length delimited. Does not implicitly {@link StateNode.verify|verify} messages. * @param message StateNode message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IStateNode, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a StateNode message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns StateNode * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): StateNode; /** * Decodes a StateNode message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns StateNode * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): StateNode; /** * Verifies a StateNode message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a StateNode message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns StateNode */ public static fromObject(object: { [k: string]: any }): StateNode; /** * Creates a plain object from a StateNode message. Also converts values to other types if specified. * @param message StateNode * @param [options] Conversion options * @returns Plain object */ public static toObject(message: StateNode, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this StateNode to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a NodeRef. */ export interface INodeRef { /** NodeRef address */ address?: Uint8Array; /** NodeRef child */ child?: Uint8Array; } /** Represents a NodeRef. */ export class NodeRef implements INodeRef { /** * Constructs a new NodeRef. * @param [properties] Properties to set */ constructor(properties?: INodeRef); /** NodeRef address. */ public address: Uint8Array; /** NodeRef child. */ public child: Uint8Array; /** * Creates a new NodeRef instance using the specified properties. * @param [properties] Properties to set * @returns NodeRef instance */ public static create(properties?: INodeRef): NodeRef; /** * Encodes the specified NodeRef message. Does not implicitly {@link NodeRef.verify|verify} messages. * @param message NodeRef message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: INodeRef, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified NodeRef message, length delimited. Does not implicitly {@link NodeRef.verify|verify} messages. * @param message NodeRef message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: INodeRef, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a NodeRef message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns NodeRef * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): NodeRef; /** * Decodes a NodeRef message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns NodeRef * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): NodeRef; /** * Verifies a NodeRef message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a NodeRef message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns NodeRef */ public static fromObject(object: { [k: string]: any }): NodeRef; /** * Creates a plain object from a NodeRef message. Also converts values to other types if specified. * @param message NodeRef * @param [options] Conversion options * @returns Plain object */ public static toObject(message: NodeRef, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this NodeRef to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; }
the_stack
import { KeyCredential, TokenCredential } from "@azure/core-auth"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { CopyAuthorization, GeneratedClient, GetInfoResponse, GetOperationResponse, ModelInfo, ModelSummary, OperationInfo, } from "./generated"; import { accept1 } from "./generated/models/parameters"; import { toTrainingPollOperationState, TrainingOperationDefinition, TrainingPoller, TrainingPollOperationState, } from "./lro/training"; import { lro } from "./lro/util/poller"; import { BuildModelOptions, CopyModelOptions, DeleteModelOptions, DocumentModelAdministrationClientOptions, GetCopyAuthorizationOptions, GetInfoOptions, GetModelOptions, GetOperationOptions, ListModelsOptions, ListOperationsOptions, } from "./options"; import { makeServiceClient, Mappers, SERIALIZER } from "./util"; /** * A client for interacting with the Form Recognizer service's model management features, such as creating, reading, * listing, deleting, and copying models. * * ### Examples: * * #### Azure Active Directory * * ```typescript * import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer"; * import { DefaultAzureCredential } from "@azure/identity"; * * const endpoint = "https://<resource name>.cognitiveservices.azure.com"; * const credential = new DefaultAzureCredential(); * * const client = new DocumentModelAdministrationClient(endpoint, credential); * ``` * * #### API Key (Subscription Key) * * ```typescript * import { DocumentModelAdministrationClient, AzureKeyCredential } from "@azure/ai-form-recognizer"; * * const endpoint = "https://<resource name>.cognitiveservices.azure.com"; * const credential = new AzureKeyCredential("<api key>"); * * const client = new DocumentModelAdministrationClient(endpoint, credential); * ``` */ export class DocumentModelAdministrationClient { private _restClient: GeneratedClient; /** * Create a DocumentModelAdministrationClient instance from a resource endpoint and a an Azure Identity `TokenCredential`. * * See the [`@azure/identity`](https://npmjs.com/package/\@azure/identity) package for more information about * authenticating with Azure Active Directory. * * ### Example: * * ```javascript * import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer"; * import { DefaultAzureCredential } from "@azure/identity"; * * const endpoint = "https://<resource name>.cognitiveservices.azure.com"; * const credential = new DefaultAzureCredential(); * * const client = new DocumentModelAdministrationClient(endpoint, credential); * ``` * * @param endpoint - the endpoint URL of an Azure Cognitive Services instance * @param credential - a TokenCredential instance from the `@azure/identity` package * @param options - optional settings for configuring all methods in the client */ public constructor( endpoint: string, credential: TokenCredential, options?: DocumentModelAdministrationClientOptions ); /** * Create a DocumentModelAdministrationClient instance from a resource endpoint and a static API key * (`KeyCredential`), * * ### Example: * * ```javascript * import { DocumentModelAdministrationClient, AzureKeyCredential } from "@azure/ai-form-recognizer"; * * const endpoint = "https://<resource name>.cognitiveservices.azure.com"; * const credential = new AzureKeyCredential("<api key>"); * * const client = new DocumentModelAdministrationClient(endpoint, credential); * ``` * * @param endpoint - the endpoint URL of an Azure Cognitive Services instance * @param credential - a KeyCredential containing the Cognitive Services instance subscription key * @param options - optional settings for configuring all methods in the client */ public constructor( endpoint: string, credential: KeyCredential, options?: DocumentModelAdministrationClientOptions ); /** * @hidden */ public constructor( endpoint: string, credential: KeyCredential | TokenCredential, options?: DocumentModelAdministrationClientOptions ); public constructor( endpoint: string, credential: KeyCredential | TokenCredential, options: DocumentModelAdministrationClientOptions = {} ) { this._restClient = makeServiceClient(endpoint, credential, options); } // #region Model Creation /** * Build a new model with a given ID from a set of input documents and labeled fields. * * The Model ID can consist of any text, so long as it does not begin with "prebuilt-" (as these models refer to * prebuilt Form Recognizer models that are common to all resources), and so long as it does not already exist within * the resource. * * The Form Recognizer service reads the training data set from an Azure Storage container, given as a URL to the * container with a SAS token that allows the service backend to communicate with the container. At a minimum, the * "read" and "list" permissions are required. In addition, the data in the given container must be organized * according to a particular convention, which is documented in [the service's documentation for building custom * models](https://aka.ms/form-recognizer/custom). * * ### Example * * ```javascript * const modelId = "aNewModel"; * const containerUrl = "<training data container SAS URL>"; * * const poller = await client.beginBuildModel(modelId, containerUrl, { * // Optionally, a text description may be attached to the model * description: "This is an example model!" * }); * * // Model building, like all other model creation operations, returns a poller that eventually produces a ModelInfo * // object * const modelInfo = await poller.pollUntilDone(); * * const { * modelId, // identical to the modelId given when creating the model * description, // identical to the description given when creating the model * createdDateTime, // the Date (timestamp) that the model was created * docTypes // information about the document types in the model and their field schemas * } = modelInfo; * ``` * * @param modelId - the unique ID of the model to create * @param containerUrl - SAS-encoded URL to an Azure Storage container holding the training data set * @param options - optional settings for the model build operation * @returns a long-running operation (poller) that will eventually produce the created model information or an error */ public async beginBuildModel( modelId: string, containerUrl: string, options: BuildModelOptions = {} ): Promise<TrainingPoller> { return this.createTrainingPoller({ options, start: () => this._restClient.buildDocumentModel( { modelId, description: options.description, azureBlobSource: { containerUrl, }, }, options ), }); } /** * Creates a single composed model from several pre-existing submodels. * * The resulting composed model combines the document types of its component models, and inserts a classification step * into the extraction pipeline to determine which of its component submodels is most appropriate for the given input. * * ### Example * * ```javascript * const modelId = "aNewComposedModel"; * const subModelIds = [ * "documentType1Model", * "documentType2Model", * "documentType3Model" * ]; * * // The resulting composed model can classify and extract data from documents * // conforming to any of the above document types * const poller = await client.beginComposeModel(modelId, subModelIds, { * description: "This is a composed model that can handle several document types." * }); * * // Model composition, like all other model creation operations, returns a poller that eventually produces a * // ModelInfo object * const modelInfo = await poller.pollUntilDone(); * * const { * modelId, // identical to the modelId given when creating the model * description, // identical to the description given when creating the model * createdDateTime, // the Date (timestamp) that the model was created * docTypes // information about the document types of the composed submodels * } = modelInfo; * ``` * * @param modelId - the unique ID of the model to create * @param componentModels - an Iterable of strings representing the unique model IDs of the models to compose * @param options - optional settings for model creation * @returns a long-running operation (poller) that will eventually produce the created model information or an error */ public async beginComposeModel( modelId: string, componentModels: Iterable<string>, options: BuildModelOptions = {} ): Promise<TrainingPoller> { return this.createTrainingPoller({ options, start: () => this._restClient.composeDocumentModel( { modelId, componentModels: [...componentModels].map((submodelId) => ({ modelId: submodelId, })), description: options.description, }, options ), }); } /** * Creates an authorization to copy a model into the resource, used with the `beginCopyModel` method. * * The `CopyAuthorization` grants another cognitive service resource the right to create a model in this client's * resource with the model ID and optional description that are encoded into the authorization. * * ### Example * * ```javascript * // The copyAuthorization data structure stored below grants any cognitive services resource the right to copy a * // model into the client's resource with the given destination model ID. * const copyAuthorization = await client.getCopyAuthorization("<destination model ID>"); * ``` * * @param destinationModelId - the unique ID of the destination model (the ID to copy the model into) * @param options - optional settings for creating the copy authorization * @returns a copy authorization that encodes the given modelId and optional description */ public async getCopyAuthorization( destinationModelId: string, options: GetCopyAuthorizationOptions = {} ): Promise<CopyAuthorization> { return this._restClient.authorizeCopyDocumentModel( { modelId: destinationModelId, description: options.description, }, options ); } /** * Copies a model with the given ID into the resource and model ID encoded by a given copy authorization. * * See {@link CopyAuthorization} and {@link getCopyAuthorization}. * * ### Example * * ```javascript * // We need a client for the source model's resource * const sourceEndpoint = "https://<source resource name>.cognitiveservices.azure.com"; * const sourceCredential = new AzureKeyCredential("<source api key>"); * const sourceClient = new DocumentModelAdministrationClient(sourceEndpoint, sourceCredential); * * // We create the copy authorization using a client authenticated with the destination resource. Note that these two * // resources can be the same (you can copy a model to a new ID in the same resource). * const copyAuthorization = await client.getCopyAuthorization("<destination model ID>"); * * // Finally, use the _source_ client to copy the model and await the copy operation * const poller = await sourceClient.beginCopyModel("<source model ID>"); * * // Model copying, like all other model creation operations, returns a poller that eventually produces a ModelInfo * // object * const modelInfo = await poller.pollUntilDone(); * * const { * modelId, // identical to the modelId given when creating the copy authorization * description, // identical to the description given when creating the copy authorization * createdDateTime, // the Date (timestamp) that the model was created * docTypes // information about the document types of the model (identical to the original, source model) * } = modelInfo; * ``` * * @param sourceModelId - the unique ID of the source model that will be copied * @param authorization - an authorization to copy the model, created using the {@link getCopyAuthorization} * @param options - optional settings for * @returns a long-running operation (poller) that will eventually produce the copied model information or an error */ public async beginCopyModel( sourceModelId: string, authorization: CopyAuthorization, options: CopyModelOptions = {} ): Promise<TrainingPoller> { return this.createTrainingPoller({ options, start: () => this._restClient.copyDocumentModelTo(sourceModelId, authorization, options), }); } /** * Create an LRO poller that handles training operations. * * This is the meat of all training polling operations. * * @internal * @param definition - operation definition (start operation method, request options) * @returns a training poller that produces a ModelInfo */ private async createTrainingPoller( definition: TrainingOperationDefinition ): Promise<TrainingPoller> { const { resumeFrom } = definition.options; const toInit = resumeFrom === undefined ? async () => { const { operationLocation } = await definition.start(); if (operationLocation === undefined) { throw new Error( "Unable to start model creation operation: no Operation-Location received." ); } return this._restClient.sendOperationRequest( { options: definition.options, }, { path: operationLocation, httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GetOperationResponse, }, default: { bodyMapper: Mappers.ErrorResponse, }, }, headerParameters: [accept1], serializer: SERIALIZER, } ) as Promise<GetOperationResponse>; } : () => { const { operationId } = JSON.parse(resumeFrom) as { operationId: string }; return this._restClient.getOperation(operationId, definition.options); }; const poller = await lro<ModelInfo, TrainingPollOperationState>( { init: async () => toTrainingPollOperationState(await toInit()), poll: async ({ operationId }) => { const res = await this._restClient.getOperation(operationId, definition.options); return toTrainingPollOperationState(res); }, serialize: ({ operationId }) => JSON.stringify({ operationId }), }, definition.options.updateIntervalInMs ); if (definition.options.onProgress !== undefined) { poller.onProgress(definition.options.onProgress); definition.options.onProgress(poller.getOperationState()); } return poller; } // #endregion // #region Model Management /** * Retrieve basic information about this client's resource. * * ### Example * * ```javascript * const { * // Information about the custom models in the current resource * customDocumentModelInfo: { * // The number of custom models in the current resource * count, * // The maximum number of models that the current resource can support * limit * } * } = await client.getInfo(); * ``` * * @param options - optional settings for the request * @returns basic information about this client's resource */ public getInfo(options?: GetInfoOptions): Promise<GetInfoResponse> { return this._restClient.getInfo(options); } /** * Retrieves information about a model ({@link ModelInfo}) by ID. * * This method can retrieve information about custom as well as prebuilt models. * * ### **Breaking Change** * * In previous versions of the Form Recognizer REST API and SDK, the `getModel` method could return any model, even * one that failed to create due to errors. In the new service versions, `getModel` and `listModels` _only produce * successfully created models_ (i.e. models that are "ready" for use). Failed models are now retrieved through the * "operations" APIs, see {@link getOperation} and {@link listOperations}. * * ### Example * * ```javascript * // The ID of the prebuilt business card model * const modelId = "prebuilt-businessCard"; * * const { * modelId, // identical to the modelId given when calling `getModel` * description, // a textual description of the model, if provided during model creation * createdDateTime, // the Date (timestamp) that the model was created * // information about the document types in the model and their field schemas * docTypes: { * // the document type of the prebuilt business card model * "prebuilt:businesscard": { * // an optional, textual description of this document type * description, * // the schema of the fields in this document type, see the FieldSchema type * fieldSchema, * // the service's confidences in the fields (an object with field names as properties and numeric confidence * // values) * fieldConfidence * } * } * } = await client.getModel(modelId); * ``` * * @param modelId - the unique ID of the model to query * @param options - optional settings for the request * @returns information about the model with the given ID */ public getModel(modelId: string, options?: GetModelOptions): Promise<ModelInfo> { return this._restClient.getModel(modelId, options); } /** * List summaries of models in the resource. Custom as well as prebuilt models will be included. This operation * supports paging. * * The model summary ({@link ModelSummary}) includes only the basic information about the model, and does not include * information about the document types in the model (such as the field schemas and confidence values). * * To access the full information about the model, use {@link getModel}. * * ### **Breaking Change** * * In previous versions of the Form Recognizer REST API and SDK, the `listModels` method would return all models, even * those that failed to create due to errors. In the new service versions, `listModels` and `getModels` _only produce * successfully created models_ (i.e. models that are "ready" for use). Failed models are now retrieved through the * "operations" APIs, see {@link getOperation} and {@link listOperations}. * * ### Examples * * #### Async Iteration * * ```javascript * for await (const summary of client.listModels()) { * const { * modelId, // The model's unique ID * description, // a textual description of the model, if provided during model creation * } = summary; * * // You can get the full model info using `getModel` * const model = await client.getModel(modelId); * } * ``` * * #### By Page * * ```javascript * // The listModels method is paged, and you can iterate by page using the `byPage` method. * const pages = client.listModels().byPage(); * * for await (const page of pages) { * // Each page is an array of models and can be iterated synchronously * for (const model of page) { * const { * modelId, // The model's unique ID * description, // a textual description of the model, if provided during model creation * } = summary; * * // You can get the full model info using `getModel` * const model = await client.getModel(modelId); * } * } * ``` * * @param options - optional settings for the model requests * @returns an async iterable of model summaries that supports paging */ public listModels(options?: ListModelsOptions): PagedAsyncIterableIterator<ModelSummary> { return this._restClient.listModels(options); } /** * Retrieves information about an operation (`OperationInfo`) by its ID. * * Operations represent non-analysis tasks, such as building, composing, or copying a model. * * @param operationId - the ID of the operation to query * @param options - optional settings for the request * @returns information about the operation with the given ID * * ### Example * * ```javascript * // The ID of the operation, which should be a GUID * const operationId = "<operation GUID>"; * * const { * operationId, // identical to the operationId given when calling `getOperation` * kind, // the operation kind, one of "documentModelBuild", "documentModelCompose", or "documentModelCopyTo" * status, // the status of the operation, one of "notStarted", "running", "failed", "succeeded", or "canceled" * percentCompleted, // a number between 0 and 100 representing the progress of the operation * createdDateTime, // a Date object that reflects the time when the operation was started * lastUpdatedDateTime, // a Date object that reflects the time when the operation state was last modified * } = await client.getOperation(operationId); * ``` */ public getOperation(operationId: string, options?: GetOperationOptions): Promise<OperationInfo> { return this._restClient.getOperation(operationId, options); } /** * List model creation operations in the resource. This will produce all operations, including operations that failed * to create models successfully. This operation supports paging. * * ### Examples * * #### Async Iteration * * ```javascript * for await (const operation of client.listOperations()) { * const { * operationId, // the operation's GUID * status, // the operation status, one of "notStarted", "running", "succeeded", "failed", or "canceled" * percentCompleted // the progress of the operation, from 0 to 100 * } = operation; * } * ``` * * #### By Page * * ```javascript * // The listOperations method is paged, and you can iterate by page using the `byPage` method. * const pages = client.listOperations().byPage(); * * for await (const page of pages) { * // Each page is an array of operation info objects and can be iterated synchronously * for (const operation of page) { * const { * operationId, // the operation's GUID * status, // the operation status, one of "notStarted", "running", "succeeded", "failed", or "canceled" * percentCompleted // the progress of the operation, from 0 to 100 * } = operation; * } * } * ``` * * @param options - optional settings for the operation requests * @returns an async iterable of operation information objects that supports paging */ public listOperations( options: ListOperationsOptions = {} ): PagedAsyncIterableIterator<OperationInfo> { return this._restClient.listOperations(options); } /** * Deletes a model with the given ID from the client's resource, if it exists. This operation CANNOT be reverted. * * ### Example * * ```javascript * await client.deleteModel("<model ID to delete>")); * ``` * * @param modelId - the unique ID of the model to delete from the resource * @param options - optional settings for the request */ public deleteModel(modelId: string, options?: DeleteModelOptions): Promise<void> { return this._restClient.deleteModel(modelId, options); } // #endregion }
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { Constant } from './constant'; import { EvaluateExpressionDelegate, EvaluatorLookup, ExpressionEvaluator, ValueWithError, } from './expressionEvaluator'; import { ExpressionType } from './expressionType'; import { Extensions } from './extensions'; import { FunctionTable } from './functionTable'; import { MemoryInterface, SimpleObjectMemory } from './memory'; import { Options } from './options'; import { ExpressionParser } from './parser'; import { ReturnType } from './returnType'; /** * An expression which can be analyzed or evaluated to produce a value. * This provides an open-ended wrapper that supports a number of built-in functions and can also be extended at runtime. * It also supports validation of the correctness of an expression and evaluation that should be exception free. */ export class Expression { /** * Expected result of evaluating the expression. * * @returns The expected result of evaluating the expression. */ get returnType(): ReturnType { return this.evaluator.returnType; } /** * Type of expression. * * @returns The type of the expression. */ get type(): string { return this.evaluator.type; } /** * Children expressions. */ children: Expression[]; /** * Evaluator of expression. */ readonly evaluator: ExpressionEvaluator; /** * Dictionary of function => ExpressionEvaluator. * This is all available functions, you can add custom functions to it, but you cannot * replace builtin functions. If you clear the dictionary, it will be reset to the built in functions. */ static readonly functions: FunctionTable = new FunctionTable(); /** * expression constructor. * * @param type Type of expression from ExpressionType * @param evaluator Information about how to validate and evaluate expression. * @param children Child expressions. */ constructor(type: string, evaluator: ExpressionEvaluator, ...children: Expression[]) { if (evaluator) { this.evaluator = evaluator; this.children = children; } else if (type !== undefined) { if (!Expression.functions.get(type)) { throw Error(`${type} does not have an evaluator, it's not a built-in function or a custom function.`); } this.evaluator = Expression.functions.get(type); this.children = children; } } /** * Do a deep equality between expressions. * * @param other Other expression. * @returns True if expressions are the same. */ deepEquals(other: Expression): boolean { let eq = false; if (other) { eq = this.type === other.type; if (eq) { eq = this.children.length === other.children.length; if (this.type === ExpressionType.And || this.type === ExpressionType.Or) { // And/Or do not depand on order for (let i = 0; eq && i < this.children.length; i++) { const primary = this.children[0]; let found = false; for (let j = 0; j < this.children.length; j++) { if (primary.deepEquals(other.children[j])) { found = true; break; } } eq = found; } } else { for (let i = 0; eq && i < this.children.length; i++) { eq = this.children[i].deepEquals(other.children[i]); } } } } return eq; } /** * Return the static reference paths to memory. * Return all static paths to memory. If there is a computed element index, then the path is terminated there, * but you might get other paths from the computed part as well. * * @returns List of the static reference paths. */ references(): string[] { const { path, refs } = this.referenceWalk(this); if (path !== undefined) { refs.add(path); } return Array.from(refs); } /** * Walking function for identifying static memory references in an expression. * * @param expression Expression to analyze. * @param extension If present, called to override lookup for things like template expansion. * @returns Accessor path of expression. */ referenceWalk( expression: Expression, extension?: (arg0: Expression) => boolean ): { path: string; refs: Set<string> } { let path: string; let refs = new Set<string>(); if (extension === undefined || !extension(expression)) { const children: Expression[] = expression.children; if (expression.type === ExpressionType.Accessor) { const prop: string = (children[0] as Constant).value as string; if (children.length === 1) { path = prop; } if (children.length === 2) { ({ path, refs } = this.referenceWalk(children[1], extension)); if (path !== undefined) { path = path.concat('.', prop); } // if path is null we still keep it null, won't append prop // because for example, first(items).x should not return x as refs } } else if (expression.type === ExpressionType.Element) { ({ path, refs } = this.referenceWalk(children[0], extension)); if (path !== undefined) { if (children[1] instanceof Constant) { const cnst: Constant = children[1] as Constant; if (cnst.returnType === ReturnType.String) { path += `.${cnst.value}`; } else { path += `[${cnst.value}]`; } } else { refs.add(path); } } const result = this.referenceWalk(children[1], extension); const idxPath = result.path; const refs1 = result.refs; refs = new Set([...refs, ...refs1]); if (idxPath !== undefined) { refs.add(idxPath); } } else if ( expression.type === ExpressionType.Foreach || expression.type === ExpressionType.Where || expression.type === ExpressionType.Select ) { let result = this.referenceWalk(children[0], extension); const child0Path = result.path; const refs0 = result.refs; if (child0Path !== undefined) { refs0.add(child0Path); } result = this.referenceWalk(children[2], extension); const child2Path = result.path; const refs2 = result.refs; if (child2Path !== undefined) { refs2.add(child2Path); } const iteratorName = (children[1].children[0] as Constant).value as string; const nonLocalRefs2 = Array.from(refs2).filter( (x): boolean => !(x === iteratorName || x.startsWith(iteratorName + '.') || x.startsWith(iteratorName + '[')) ); refs = new Set([...refs, ...refs0, ...nonLocalRefs2]); } else { for (const child of expression.children) { const result = this.referenceWalk(child, extension); const childPath = result.path; const refs0 = result.refs; refs = new Set([...refs, ...refs0]); if (childPath !== undefined) { refs.add(childPath); } } } } return { path, refs }; } /** * Parse an expression string into an [Expression](xref:adaptive-expressions.Expression) object. * * @param expression Expression string. * @param lookup Optional. [EvaluatorLookup](xref:adaptive-expressions.EvaluatorLookup) function lookup when parsing the expression. Default is [Expression.lookup](xref:adaptive-expressions.Expression.lookup) which uses [Expression.functions](xref:adaptive-expressions.Expression.functions) table. * @returns The expression object. */ static parse(expression: string, lookup?: EvaluatorLookup): Expression { return new ExpressionParser(lookup || Expression.lookup).parse(expression.replace(/^=/, '')); } /** * Lookup an [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) function by name. * * @param functionName Name of function to lookup. * @returns An [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) corresponding to the function name. */ static lookup(functionName: string): ExpressionEvaluator { const exprEvaluator = Expression.functions.get(functionName); if (!exprEvaluator) { return undefined; } return exprEvaluator; } /** * Make an expression and validate it. * * @param type Type of expression from ExpressionType. * @param evaluator Information about how to validate and evaluate expression. * @param children Child expressions. * @returns The new expression. */ static makeExpression(type: string, evaluator: ExpressionEvaluator, ...children: Expression[]): Expression { const expr: Expression = new Expression(type, evaluator, ...children); expr.validate(); return expr; } /** * Construct an expression from a EvaluateExpressionDelegate * * @param func Function to create an expression from. * @returns The new expression. */ static lambaExpression(func: EvaluateExpressionDelegate): Expression { return new Expression(ExpressionType.Lambda, new ExpressionEvaluator(ExpressionType.Lambda, func)); } /** * Construct an expression from a lamba expression over the state. * Exceptions will be caught and surfaced as an error string. * * @param func ambda expression to evaluate. * @returns New expression. */ static lambda(func: (arg0: any) => any): Expression { return new Expression( ExpressionType.Lambda, new ExpressionEvaluator( ExpressionType.Lambda, (_expression: Expression, state: any, _: Options): ValueWithError => { let value: any; let error: string; try { value = func(state); } catch (funcError) { error = funcError; } return { value, error }; } ) ); } /** * Construct and validate an Set a property expression to a value expression. * * @param property property expression. * @param value value expression. * @returns New expression. */ static setPathToValue(property: Expression, value: any): Expression { if (value instanceof Expression) { return Expression.makeExpression(ExpressionType.SetPathToValue, undefined, property, value); } else { return Expression.makeExpression(ExpressionType.SetPathToValue, undefined, property, new Constant(value)); } } /** * Construct and validate an Equals expression. * * @param children Child clauses. * @returns New expression. */ static equalsExpression(...children: Expression[]): Expression { return Expression.makeExpression(ExpressionType.Equal, undefined, ...children); } /** * Construct and validate an And expression. * * @param children Child clauses. * @returns New expression. */ static andExpression(...children: Expression[]): Expression { if (children.length > 1) { return Expression.makeExpression(ExpressionType.And, undefined, ...children); } else { return children[0]; } } /** * Construct and validate an Or expression. * * @param children Child clauses. * @returns New expression. */ static orExpression(...children: Expression[]): Expression { if (children.length > 1) { return Expression.makeExpression(ExpressionType.Or, undefined, ...children); } else { return children[0]; } } /** * Construct and validate an Not expression. * * @param child Child clauses. * @returns New expression. */ static notExpression(child: Expression): Expression { return Expression.makeExpression(ExpressionType.Not, undefined, child); } /** * Validate immediate expression. * * @returns The validated expression. */ validate = (): void => this.evaluator.validateExpression(this); /** * Recursively validate the expression tree. */ validateTree(): void { this.validate(); for (const child of this.children) { child.validateTree(); } } /** * Evaluate the expression. * * @param state Global state to evaluate accessor expressions against. Can be Dictionary, otherwise reflection is used to access property and then indexer. * @param options Options used in the evaluation. * @returns Computed value and an error string. If the string is non-null, then there was an evaluation error. */ tryEvaluate(state: MemoryInterface | any, options: Options = undefined): ValueWithError { if (!Extensions.isMemoryInterface(state)) { state = SimpleObjectMemory.wrap(state); } options = options ? options : new Options(); return this.evaluator.tryEvaluate(this, state, options); } /** * Returns a string that represents the current [Expression](xref:adaptive-expressions.Expression) object. * * @returns A string that represents the current [Expression](xref:adaptive-expressions.Expression) object. */ toString(): string { let builder = ''; let valid = false; // Special support for memory paths if (this.type === ExpressionType.Accessor && this.children.length >= 1) { if (this.children[0] instanceof Constant) { const prop: any = (this.children[0] as Constant).value; if (typeof prop === 'string') { if (this.children.length === 1) { valid = true; builder = builder.concat(prop); } else if (this.children.length === 2) { valid = true; builder = builder.concat(this.children[1].toString(), '.', prop); } } } } else if (this.type === ExpressionType.Element && this.children.length === 2) { valid = true; builder = builder.concat(this.children[0].toString(), '[', this.children[1].toString(), ']'); } if (!valid) { const infix: boolean = this.type.length > 0 && !new RegExp(/[a-z]/i).test(this.type[0]) && this.children.length >= 2; if (!infix) { builder = builder.concat(this.type); } builder = builder.concat('('); let first = true; for (const child of this.children) { if (first) { first = false; } else { if (infix) { builder = builder.concat(' ', this.type, ' '); } else { builder = builder.concat(', '); } } builder = builder.concat(child.toString()); } builder = builder.concat(')'); } return builder; } }
the_stack
import { Component, NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, NavController, NavParams } from '../../../..'; import { DomSanitizer } from '@angular/platform-browser'; let LOG = ''; let SIMPLE_LOG = ''; function log(page: string, message: string, color: string) { console.log(`${page}: ${message}`); SIMPLE_LOG += `${page}:${message}`; SIMPLE_LOG += '\n'; LOG += `${page}:<span style="background:${color};">${message}</span>`; LOG += '\n'; } const TEMPLATE: string = ` <ion-header> <ion-navbar> <ion-title>{{_name}}</ion-title> </ion-navbar> </ion-header> <ion-content text-center> <p>This is the {{_name}}</p> <div f></div> <div f></div> </ion-content> `; const baseCounter: any = {}; export class Base { constructor(public _name: string) { if (baseCounter[_name] === undefined) { baseCounter[_name] = 0; } this._name = `${this._name}-${baseCounter[_name]}`; baseCounter[_name]++; } ionViewWillLoad() { log(this._name, 'willLoad', 'green'); } ionViewDidLoad() { log(this._name, 'didLoad', 'green'); } ionViewWillEnter() { log(this._name, 'willEnter', 'greenyellow'); } ionViewDidEnter() { log(this._name, 'didEnter', 'cyan'); } ionViewWillLeave() { log(this._name, 'willLeave', 'greenyellow'); } ionViewDidLeave() { log(this._name, 'didLeave', 'cyan'); } ionViewWillUnload() { log(this._name, 'willUnload', 'lightgray'); } ionViewCanLeave(): boolean|Promise<any> { log(this._name, 'canLeave', 'deeppink'); return true; } ionViewCanEnter(): boolean|Promise<any> { log(this._name, 'canEnter', '#ff78c1'); return true; } } @Component({ template: TEMPLATE }) export class Page1 extends Base { constructor() { super('Page1'); } } @Component({ template: TEMPLATE }) export class Page2 extends Base { counter = 4; constructor(private nav: NavController) { super('Page2'); } ionViewWillEnter() { super.ionViewWillEnter(); if (this.counter > 0) { this.nav.push(Page3, { animated: (this.counter !== 2)}); } else if (this.counter === 0) { this.nav.push(Page4, {animate: false}); } else { throw new Error('should not be here!'); } this.counter--; } } @Component({ template: TEMPLATE }) export class Page3 extends Base { animated: boolean; constructor(private nav: NavController, params: NavParams) { super('Page3'); this.animated = params.get('animated'); } ionViewDidEnter() { super.ionViewDidEnter(); this.nav.pop({animate: this.animated}); } } @Component({ template: TEMPLATE }) export class Page4 extends Base { constructor(private nav: NavController) { super('Page4'); } doSomethingSync() { // this is a long running synchronous task // (imagine that a huge data must be transformed here recuresively or something similar) console.log('START DOING SOMETHING'); console.time('DO SOMETHING EXPENSIVE SYNCHRONOUSLY'); let e = 0; for (let i = 0; i < 8000000; i++) { e += Math.sqrt(i) / Math.log(i) / Math.cos(i); } console.timeEnd('DO SOMETHING EXPENSIVE SYNCHRONOUSLY'); return e; } ngOnInit() { this.doSomethingSync(); // once it has finished trigger another asynchronously setTimeout(() => { this.doSomethingSync(); setTimeout(() => { this.nav.push(Page5).then((hasCompleted) => { if (!hasCompleted) { this.nav.push(Page6, { continue: false }); setTimeout(() => this.nav.push(Page6, { continue: true }), 510); } }); }, 2000); }, 0); } } @Component({ template: TEMPLATE }) export class Page5 extends Base { constructor() { super('Page5'); } ionViewCanEnter() { super.ionViewCanEnter(); return new Promise((resolve) => { setTimeout(() => resolve(false), 8000); }); } } @Component({ template: TEMPLATE }) export class Page6 extends Base { continue: boolean = false; counter = 3; counterLeave = 3; constructor(private nav: NavController, params: NavParams) { super('Page6'); this.continue = params.get('continue'); console.log(this.continue); } ionViewCanLeave() { super.ionViewCanLeave(); if (this.continue === true) { this.counter--; if (this.counter > 0) { return false; } else if (this.counter === 0) { return true; } else { throw new Error('invalid'); } } return true; } ionViewDidEnter() { if (this.continue === true) { setTimeout(() => this.pop(), 2000 + 3000); } } ionViewWillLeave() { super.ionViewWillLeave(); this.pushPage7(); } ionViewWillUnload() { super.ionViewWillUnload(); this.pushPage7(); } pop() { this.nav.pop().then((hasCompleted) => { if (hasCompleted) { this.pushPage7(); } else { this.pop(); } }); } pushPage7() { if (this.continue) { this.counterLeave--; if (this.counterLeave === 0) { this.nav.push(Page7); } else if (this.counterLeave < 0) { throw new Error('invalid'); } } } } @Component({ template: TEMPLATE }) export class Page7 extends Base { constructor(private nav: NavController) { super('Page7'); } ionViewCanEnter() { super.ionViewCanEnter(); this.nav.setRoot(Page8); this.nav.setRoot(Page8, {animate: false}); this.nav.setRoot(Page8).then(() => { this.nav.setRoot(Results); }); this.nav.push(Page8); this.nav.push(Page8); this.nav.pop(); this.nav.push(Page8); setTimeout(() => { this.nav.pop({ animate: false }); }, Math.random() * 100); setTimeout(() => { this.nav.pop(); }, Math.random() * 100); return true; } } @Component({ template: TEMPLATE }) export class Page8 extends Base { constructor() { super('Page8'); } } @Component({ template: ` <ion-header> <ion-navbar> <ion-title>Results</ion-title> </ion-navbar> </ion-header> <ion-content padding> <pre style="font-size: 0.72em; column-count: 3;" [innerHTML]="result"></pre> </ion-content> ` }) export class Results { result: any; constructor(private sanitizer: DomSanitizer) { } ionViewDidEnter() { setTimeout(() => { if (SIMPLE_LOG !== EXPECTED) { throw 'LOG DOES NOT MATCH'; } this.result = this.sanitizer.bypassSecurityTrustHtml(LOG); }, 100); } } @Component({ template: `<ion-nav [root]="root"></ion-nav>` }) export class AppComponent { root: any = Page1; constructor() { setTimeout(() => this.root = Page2, 100); } } @NgModule({ declarations: [ AppComponent, Page1, Page2, Page3, Page4, Page5, Page6, Page7, Page8, Results ], imports: [ BrowserModule, IonicModule.forRoot(AppComponent) ], bootstrap: [IonicApp], entryComponents: [ AppComponent, Page1, Page2, Page3, Page4, Page5, Page6, Page7, Page8, Results ] }) export class AppModule {} const EXPECTED = `Page1-0:canEnter Page1-0:willLoad Page1-0:didLoad Page1-0:willEnter Page1-0:didEnter Page1-0:canLeave Page2-0:canEnter Page2-0:willLoad Page2-0:didLoad Page1-0:willLeave Page2-0:willEnter Page2-0:didEnter Page1-0:didLeave Page1-0:willUnload Page2-0:canLeave Page3-0:canEnter Page3-0:willLoad Page3-0:didLoad Page2-0:willLeave Page3-0:willEnter Page3-0:didEnter Page2-0:didLeave Page3-0:canLeave Page2-0:canEnter Page3-0:willLeave Page2-0:willEnter Page2-0:didEnter Page3-0:didLeave Page3-0:willUnload Page2-0:canLeave Page3-1:canEnter Page3-1:willLoad Page3-1:didLoad Page2-0:willLeave Page3-1:willEnter Page3-1:didEnter Page2-0:didLeave Page3-1:canLeave Page2-0:canEnter Page3-1:willLeave Page2-0:willEnter Page2-0:didEnter Page3-1:didLeave Page3-1:willUnload Page2-0:canLeave Page3-2:canEnter Page3-2:willLoad Page3-2:didLoad Page2-0:willLeave Page3-2:willEnter Page3-2:didEnter Page2-0:didLeave Page3-2:canLeave Page2-0:canEnter Page3-2:willLeave Page2-0:willEnter Page2-0:didEnter Page3-2:didLeave Page3-2:willUnload Page2-0:canLeave Page3-3:canEnter Page3-3:willLoad Page3-3:didLoad Page2-0:willLeave Page3-3:willEnter Page3-3:didEnter Page2-0:didLeave Page3-3:canLeave Page2-0:canEnter Page3-3:willLeave Page2-0:willEnter Page2-0:didEnter Page3-3:didLeave Page3-3:willUnload Page2-0:canLeave Page4-0:canEnter Page4-0:willLoad Page4-0:didLoad Page2-0:willLeave Page4-0:willEnter Page4-0:didEnter Page2-0:didLeave Page4-0:canLeave Page5-0:canEnter Page4-0:canLeave Page6-0:canEnter Page6-0:willLoad Page6-0:didLoad Page4-0:willLeave Page6-0:willEnter Page4-0:didLeave Page6-0:canLeave Page6-1:canEnter Page6-1:willLoad Page6-1:didLoad Page6-0:willLeave Page6-1:willEnter Page6-0:didLeave Page6-1:canLeave Page6-0:canEnter Page6-1:canLeave Page6-0:canEnter Page6-1:canLeave Page6-0:canEnter Page6-1:willLeave Page6-0:willEnter Page6-1:didLeave Page6-1:willUnload Page6-0:canLeave Page7-0:canEnter Page7-0:willLoad Page7-0:didLoad Page6-0:willLeave Page7-0:willEnter Page7-0:didEnter Page6-0:didLeave Page7-0:canLeave Page8-0:canEnter Page2-0:willLeave Page2-0:didLeave Page2-0:willUnload Page4-0:willLeave Page4-0:didLeave Page4-0:willUnload Page6-0:willLeave Page6-0:didLeave Page6-0:willUnload Page8-0:willLoad Page8-0:didLoad Page7-0:willLeave Page8-0:willEnter Page8-0:didEnter Page7-0:didLeave Page7-0:willUnload Page8-0:canLeave Page8-1:canEnter Page8-1:willLoad Page8-1:didLoad Page8-0:willLeave Page8-1:willEnter Page8-1:didEnter Page8-0:didLeave Page8-0:willUnload Page8-1:canLeave Page8-2:canEnter Page8-2:willLoad Page8-2:didLoad Page8-1:willLeave Page8-2:willEnter Page8-2:didEnter Page8-1:didLeave Page8-1:willUnload Page8-2:canLeave Page8-3:canEnter Page8-3:willLoad Page8-3:didLoad Page8-2:willLeave Page8-3:willEnter Page8-3:didEnter Page8-2:didLeave Page8-3:canLeave Page8-4:canEnter Page8-4:willLoad Page8-4:didLoad Page8-3:willLeave Page8-4:willEnter Page8-4:didEnter Page8-3:didLeave Page8-4:canLeave Page8-3:canEnter Page8-4:willLeave Page8-3:willEnter Page8-3:didEnter Page8-4:didLeave Page8-4:willUnload Page8-3:canLeave Page8-5:canEnter Page8-5:willLoad Page8-5:didLoad Page8-3:willLeave Page8-5:willEnter Page8-5:didEnter Page8-3:didLeave Page8-5:canLeave Page8-3:canEnter Page8-5:willLeave Page8-3:willEnter Page8-3:didEnter Page8-5:didLeave Page8-5:willUnload Page8-3:canLeave Page8-2:canEnter Page8-3:willLeave Page8-2:willEnter Page8-2:didEnter Page8-3:didLeave Page8-3:willUnload Page8-2:canLeave Page8-2:willLeave Page8-2:didLeave Page8-2:willUnload `;
the_stack
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { CreateDefaultAlarmThresholdRequest, DescribeListBGPIPInstancesResponse, DescribeBlackWhiteIpListResponse, ProxyTypeInfo, CreateBoundIPRequest, DescribeListSchedulingDomainRequest, CreateWaterPrintConfigRequest, DDoSGeoIPBlockConfig, CreateBlackWhiteIpListResponse, IPAlarmThresholdRelation, ModifyDDoSGeoIPBlockConfigRequest, DescribeL7RulesBySSLCertIdResponse, DescribeListDDoSSpeedLimitConfigRequest, InstanceRelation, DescribeListProtocolBlockConfigResponse, DescribeListBGPInstancesRequest, KeyValue, DeleteDDoSSpeedLimitConfigRequest, CreatePacketFilterConfigResponse, DescribeListWaterPrintConfigRequest, CreateL7RuleCertsRequest, DeleteDDoSGeoIPBlockConfigRequest, CreateIPAlarmThresholdConfigRequest, DescribeDefaultAlarmThresholdResponse, CreateDDoSAIRequest, DescribeListProtectThresholdConfigRequest, CreateWaterPrintConfigResponse, DescribeListBGPIPInstancesRequest, StaticPackRelation, DescribeL7RulesBySSLCertIdRequest, DescribeListPacketFilterConfigResponse, DeleteBlackWhiteIpListResponse, CreateSchedulingDomainRequest, BoundIpInfo, DisassociateDDoSEipAddressResponse, BGPIPInstance, DeleteBlackWhiteIpListRequest, SourceServer, ModifyDomainUsrNameResponse, DisassociateDDoSEipAddressRequest, BlackWhiteIpRelation, DeleteWaterPrintKeyResponse, EipAddressPackRelation, ProtocolBlockRelation, DescribeListPacketFilterConfigRequest, BGPIPInstanceUsages, ModifyPacketFilterConfigResponse, DescribeListDDoSGeoIPBlockConfigRequest, Layer7Rule, L4RuleSource, CreateDDoSSpeedLimitConfigRequest, CreateDDoSGeoIPBlockConfigRequest, CreateProtocolBlockConfigRequest, DeleteWaterPrintKeyRequest, AssociateDDoSEipAddressResponse, DDoSSpeedLimitConfigRelation, PackInfo, ModifyPacketFilterConfigRequest, DescribeBlackWhiteIpListRequest, ModifyDomainUsrNameRequest, CreateDDoSSpeedLimitConfigResponse, DeletePacketFilterConfigRequest, ModifyL7RulesEdgeRequest, DescribeListDDoSGeoIPBlockConfigResponse, DescribeBasicDeviceStatusResponse, WaterPrintConfig, ProtocolBlockConfig, DescribeListListenerRequest, DeleteWaterPrintConfigResponse, Layer4Rule, DeletePacketFilterConfigResponse, CreateProtocolBlockConfigResponse, BGPIPInstanceSpecification, CreateIPAlarmThresholdConfigResponse, DeleteWaterPrintConfigRequest, DescribeListBlackWhiteIpListResponse, DDoSAIRelation, DescribeListDDoSSpeedLimitConfigResponse, CreateDDoSGeoIPBlockConfigResponse, ListenerCcThreholdConfig, DescribeBasicDeviceStatusRequest, IPLineInfo, EipAddressRelation, DescribeListListenerResponse, ProtectThresholdRelation, ModifyL7RulesEdgeResponse, CreateL7RuleCertsResponse, DDoSSpeedLimitConfig, AssociateDDoSEipLoadBalancerRequest, DescribeListProtectThresholdConfigResponse, CertIdInsL7Rules, CreateDefaultAlarmThresholdResponse, DescribeListIPAlarmConfigResponse, SuccessCode, ProtocolPort, DescribeListBGPInstancesResponse, DescribeListDDoSAIRequest, DescribeListIPAlarmConfigRequest, PortSegment, PacketFilterConfig, DefaultAlarmThreshold, ForwardListener, BGPInstanceSpecification, SwitchWaterPrintConfigResponse, CreateWaterPrintKeyRequest, WaterPrintRelation, InsL7Rules, DescribeListDDoSAIResponse, ModifyDDoSSpeedLimitConfigRequest, AssociateDDoSEipAddressRequest, AssociateDDoSEipLoadBalancerResponse, CreateBlackWhiteIpListRequest, DescribeBizTrendResponse, CreateBoundIPResponse, SpeedValue, SwitchWaterPrintConfigRequest, DescribeListSchedulingDomainResponse, DescribeCCTrendResponse, CreateSchedulingDomainResponse, EipProductInfo, CreateDDoSAIResponse, DDoSGeoIPBlockConfigRelation, DescribeListProtocolBlockConfigRequest, RegionInfo, DescribeDDoSTrendRequest, ModifyDDoSGeoIPBlockConfigResponse, BGPInstance, DescribeBizTrendRequest, DescribeListWaterPrintConfigResponse, BGPInstanceUsages, DeleteDDoSSpeedLimitConfigResponse, L7RuleEntry, CreateWaterPrintKeyResponse, DeleteDDoSGeoIPBlockConfigResponse, DescribeDDoSTrendResponse, DescribeListBlackWhiteIpListRequest, ModifyDDoSSpeedLimitConfigResponse, SchedulingDomainInfo, DescribeDefaultAlarmThresholdRequest, WaterPrintKey, PacketFilterRelation, CreatePacketFilterConfigRequest, DescribeCCTrendRequest, } from "./antiddos_models" /** * antiddos client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("antiddos.tencentcloudapi.com", "2020-03-09", clientConfig) } /** * 本接口 (AssociateDDoSEipAddress) 用于将高防弹性公网IP绑定到实例或弹性网卡的指定内网 IP 上。 */ async AssociateDDoSEipAddress( req: AssociateDDoSEipAddressRequest, cb?: (error: string, rep: AssociateDDoSEipAddressResponse) => void ): Promise<AssociateDDoSEipAddressResponse> { return this.request("AssociateDDoSEipAddress", req, cb) } /** * 修改智能解析域名名称 */ async ModifyDomainUsrName( req: ModifyDomainUsrNameRequest, cb?: (error: string, rep: ModifyDomainUsrNameResponse) => void ): Promise<ModifyDomainUsrNameResponse> { return this.request("ModifyDomainUsrName", req, cb) } /** * 获取DDoS防护的水印防护配置列表 */ async DescribeListWaterPrintConfig( req: DescribeListWaterPrintConfigRequest, cb?: (error: string, rep: DescribeListWaterPrintConfigResponse) => void ): Promise<DescribeListWaterPrintConfigResponse> { return this.request("DescribeListWaterPrintConfig", req, cb) } /** * 删除DDoS防护的访问限速配置 */ async DeleteDDoSSpeedLimitConfig( req: DeleteDDoSSpeedLimitConfigRequest, cb?: (error: string, rep: DeleteDDoSSpeedLimitConfigResponse) => void ): Promise<DeleteDDoSSpeedLimitConfigResponse> { return this.request("DeleteDDoSSpeedLimitConfig", req, cb) } /** * 修改DDoS防护的访问限速配置 */ async ModifyDDoSSpeedLimitConfig( req: ModifyDDoSSpeedLimitConfigRequest, cb?: (error: string, rep: ModifyDDoSSpeedLimitConfigResponse) => void ): Promise<ModifyDDoSSpeedLimitConfigResponse> { return this.request("ModifyDDoSSpeedLimitConfig", req, cb) } /** * 获取业务流量曲线 */ async DescribeBizTrend( req: DescribeBizTrendRequest, cb?: (error: string, rep: DescribeBizTrendResponse) => void ): Promise<DescribeBizTrendResponse> { return this.request("DescribeBizTrend", req, cb) } /** * 删除DDoS防护的区域封禁配置 */ async DeleteDDoSGeoIPBlockConfig( req: DeleteDDoSGeoIPBlockConfigRequest, cb?: (error: string, rep: DeleteDDoSGeoIPBlockConfigResponse) => void ): Promise<DeleteDDoSGeoIPBlockConfigResponse> { return this.request("DeleteDDoSGeoIPBlockConfig", req, cb) } /** * 修改DDoS防护的特征过滤规则 */ async ModifyPacketFilterConfig( req: ModifyPacketFilterConfigRequest, cb?: (error: string, rep: ModifyPacketFilterConfigResponse) => void ): Promise<ModifyPacketFilterConfigResponse> { return this.request("ModifyPacketFilterConfig", req, cb) } /** * 添加DDoS防护的特征过滤规则 */ async CreatePacketFilterConfig( req: CreatePacketFilterConfigRequest, cb?: (error: string, rep: CreatePacketFilterConfigResponse) => void ): Promise<CreatePacketFilterConfigResponse> { return this.request("CreatePacketFilterConfig", req, cb) } /** * 获取单IP告警阈值配置列表 */ async DescribeListIPAlarmConfig( req: DescribeListIPAlarmConfigRequest, cb?: (error: string, rep: DescribeListIPAlarmConfigResponse) => void ): Promise<DescribeListIPAlarmConfigResponse> { return this.request("DescribeListIPAlarmConfig", req, cb) } /** * 获取高防IP资产实例列表 */ async DescribeListBGPIPInstances( req: DescribeListBGPIPInstancesRequest, cb?: (error: string, rep: DescribeListBGPIPInstancesResponse) => void ): Promise<DescribeListBGPIPInstancesResponse> { return this.request("DescribeListBGPIPInstances", req, cb) } /** * 获取单IP默认告警阈值配置 */ async DescribeDefaultAlarmThreshold( req: DescribeDefaultAlarmThresholdRequest, cb?: (error: string, rep: DescribeDefaultAlarmThresholdResponse) => void ): Promise<DescribeDefaultAlarmThresholdResponse> { return this.request("DescribeDefaultAlarmThreshold", req, cb) } /** * 获取DDoS防护的IP黑白名单列表 */ async DescribeListBlackWhiteIpList( req: DescribeListBlackWhiteIpListRequest, cb?: (error: string, rep: DescribeListBlackWhiteIpListResponse) => void ): Promise<DescribeListBlackWhiteIpListResponse> { return this.request("DescribeListBlackWhiteIpList", req, cb) } /** * 获取DDoS防护的区域封禁配置列表 */ async DescribeListDDoSGeoIPBlockConfig( req: DescribeListDDoSGeoIPBlockConfigRequest, cb?: (error: string, rep: DescribeListDDoSGeoIPBlockConfigResponse) => void ): Promise<DescribeListDDoSGeoIPBlockConfigResponse> { return this.request("DescribeListDDoSGeoIPBlockConfig", req, cb) } /** * 本接口 (DisassociateDDoSEipAddress) 用于解绑高防弹性公网IP。 */ async DisassociateDDoSEipAddress( req: DisassociateDDoSEipAddressRequest, cb?: (error: string, rep: DisassociateDDoSEipAddressResponse) => void ): Promise<DisassociateDDoSEipAddressResponse> { return this.request("DisassociateDDoSEipAddress", req, cb) } /** * 绑定IP到高防包实例,支持独享包、共享包;需要注意的是此接口绑定或解绑IP是异步接口,当处于绑定或解绑中时,则不允许再进行绑定或解绑,需要等待当前绑定或解绑完成。 */ async CreateBoundIP( req: CreateBoundIPRequest, cb?: (error: string, rep: CreateBoundIPResponse) => void ): Promise<CreateBoundIPResponse> { return this.request("CreateBoundIP", req, cb) } /** * 获取智能调度域名列表 */ async DescribeListSchedulingDomain( req: DescribeListSchedulingDomainRequest, cb?: (error: string, rep: DescribeListSchedulingDomainResponse) => void ): Promise<DescribeListSchedulingDomainResponse> { return this.request("DescribeListSchedulingDomain", req, cb) } /** * 删除DDoS防护的水印防护密钥 */ async DeleteWaterPrintKey( req: DeleteWaterPrintKeyRequest, cb?: (error: string, rep: DeleteWaterPrintKeyResponse) => void ): Promise<DeleteWaterPrintKeyResponse> { return this.request("DeleteWaterPrintKey", req, cb) } /** * 设置单IP默认告警阈值配置 */ async CreateDefaultAlarmThreshold( req: CreateDefaultAlarmThresholdRequest, cb?: (error: string, rep: CreateDefaultAlarmThresholdResponse) => void ): Promise<CreateDefaultAlarmThresholdResponse> { return this.request("CreateDefaultAlarmThreshold", req, cb) } /** * 添加DDoS防护的水印防护配置 */ async CreateWaterPrintConfig( req: CreateWaterPrintConfigRequest, cb?: (error: string, rep: CreateWaterPrintConfigResponse) => void ): Promise<CreateWaterPrintConfigResponse> { return this.request("CreateWaterPrintConfig", req, cb) } /** * 获取DDoS防护的IP黑白名单 */ async DescribeBlackWhiteIpList( req: DescribeBlackWhiteIpListRequest, cb?: (error: string, rep: DescribeBlackWhiteIpListResponse) => void ): Promise<DescribeBlackWhiteIpListResponse> { return this.request("DescribeBlackWhiteIpList", req, cb) } /** * 获取DDoS防护的AI防护开关列表 */ async DescribeListDDoSAI( req: DescribeListDDoSAIRequest, cb?: (error: string, rep: DescribeListDDoSAIResponse) => void ): Promise<DescribeListDDoSAIResponse> { return this.request("DescribeListDDoSAI", req, cb) } /** * 获取CC攻击指标数据,包括总请求峰值(QPS)和攻击请求(QPS) */ async DescribeCCTrend( req: DescribeCCTrendRequest, cb?: (error: string, rep: DescribeCCTrendResponse) => void ): Promise<DescribeCCTrendResponse> { return this.request("DescribeCCTrend", req, cb) } /** * 设置单IP告警阈值配置 */ async CreateIPAlarmThresholdConfig( req: CreateIPAlarmThresholdConfigRequest, cb?: (error: string, rep: CreateIPAlarmThresholdConfigResponse) => void ): Promise<CreateIPAlarmThresholdConfigResponse> { return this.request("CreateIPAlarmThresholdConfig", req, cb) } /** * 查询与证书ID对于域名匹配的七层规则 */ async DescribeL7RulesBySSLCertId( req: DescribeL7RulesBySSLCertIdRequest, cb?: (error: string, rep: DescribeL7RulesBySSLCertIdResponse) => void ): Promise<DescribeL7RulesBySSLCertIdResponse> { return this.request("DescribeL7RulesBySSLCertId", req, cb) } /** * 获取DDoS防护的特征过滤规则列表 */ async DescribeListPacketFilterConfig( req: DescribeListPacketFilterConfigRequest, cb?: (error: string, rep: DescribeListPacketFilterConfigResponse) => void ): Promise<DescribeListPacketFilterConfigResponse> { return this.request("DescribeListPacketFilterConfig", req, cb) } /** * 获取DDoS防护的访问限速配置列表 */ async DescribeListDDoSSpeedLimitConfig( req: DescribeListDDoSSpeedLimitConfigRequest, cb?: (error: string, rep: DescribeListDDoSSpeedLimitConfigResponse) => void ): Promise<DescribeListDDoSSpeedLimitConfigResponse> { return this.request("DescribeListDDoSSpeedLimitConfig", req, cb) } /** * 获取防护阈值配置列表,包括DDoS的AI、等级、CC阈值开关等 */ async DescribeListProtectThresholdConfig( req: DescribeListProtectThresholdConfigRequest, cb?: (error: string, rep: DescribeListProtectThresholdConfigResponse) => void ): Promise<DescribeListProtectThresholdConfigResponse> { return this.request("DescribeListProtectThresholdConfig", req, cb) } /** * 添加DDoS防护的访问限速配置 */ async CreateDDoSSpeedLimitConfig( req: CreateDDoSSpeedLimitConfigRequest, cb?: (error: string, rep: CreateDDoSSpeedLimitConfigResponse) => void ): Promise<CreateDDoSSpeedLimitConfigResponse> { return this.request("CreateDDoSSpeedLimitConfig", req, cb) } /** * 获取基础防护攻击状态 */ async DescribeBasicDeviceStatus( req: DescribeBasicDeviceStatusRequest, cb?: (error: string, rep: DescribeBasicDeviceStatusResponse) => void ): Promise<DescribeBasicDeviceStatusResponse> { return this.request("DescribeBasicDeviceStatus", req, cb) } /** * 获取高防包资产实例列表 */ async DescribeListBGPInstances( req: DescribeListBGPInstancesRequest, cb?: (error: string, rep: DescribeListBGPInstancesResponse) => void ): Promise<DescribeListBGPInstancesResponse> { return this.request("DescribeListBGPInstances", req, cb) } /** * 本接口 (AssociateDDoSEipLoadBalancer) 用于将高防弹性公网IP绑定到负载均衡指定内网 IP 上。 */ async AssociateDDoSEipLoadBalancer( req: AssociateDDoSEipLoadBalancerRequest, cb?: (error: string, rep: AssociateDDoSEipLoadBalancerResponse) => void ): Promise<AssociateDDoSEipLoadBalancerResponse> { return this.request("AssociateDDoSEipLoadBalancer", req, cb) } /** * 添加DDoS防护的IP黑白名单 */ async CreateBlackWhiteIpList( req: CreateBlackWhiteIpListRequest, cb?: (error: string, rep: CreateBlackWhiteIpListResponse) => void ): Promise<CreateBlackWhiteIpListResponse> { return this.request("CreateBlackWhiteIpList", req, cb) } /** * 修改边界防护L7转发规则 */ async ModifyL7RulesEdge( req: ModifyL7RulesEdgeRequest, cb?: (error: string, rep: ModifyL7RulesEdgeResponse) => void ): Promise<ModifyL7RulesEdgeResponse> { return this.request("ModifyL7RulesEdge", req, cb) } /** * 获取DDoS攻击流量带宽和攻击包速率数据 */ async DescribeDDoSTrend( req: DescribeDDoSTrendRequest, cb?: (error: string, rep: DescribeDDoSTrendResponse) => void ): Promise<DescribeDDoSTrendResponse> { return this.request("DescribeDDoSTrend", req, cb) } /** * 删除DDoS防护的IP黑白名单 */ async DeleteBlackWhiteIpList( req: DeleteBlackWhiteIpListRequest, cb?: (error: string, rep: DeleteBlackWhiteIpListResponse) => void ): Promise<DeleteBlackWhiteIpListResponse> { return this.request("DeleteBlackWhiteIpList", req, cb) } /** * 添加DDoS防护的区域封禁配置 */ async CreateDDoSGeoIPBlockConfig( req: CreateDDoSGeoIPBlockConfigRequest, cb?: (error: string, rep: CreateDDoSGeoIPBlockConfigResponse) => void ): Promise<CreateDDoSGeoIPBlockConfigResponse> { return this.request("CreateDDoSGeoIPBlockConfig", req, cb) } /** * 删除DDoS防护的水印防护配置 */ async DeleteWaterPrintConfig( req: DeleteWaterPrintConfigRequest, cb?: (error: string, rep: DeleteWaterPrintConfigResponse) => void ): Promise<DeleteWaterPrintConfigResponse> { return this.request("DeleteWaterPrintConfig", req, cb) } /** * 设置DDoS防护的AI防护开关 */ async CreateDDoSAI( req: CreateDDoSAIRequest, cb?: (error: string, rep: CreateDDoSAIResponse) => void ): Promise<CreateDDoSAIResponse> { return this.request("CreateDDoSAI", req, cb) } /** * 删除DDoS防护的特征过滤规则 */ async DeletePacketFilterConfig( req: DeletePacketFilterConfigRequest, cb?: (error: string, rep: DeletePacketFilterConfigResponse) => void ): Promise<DeletePacketFilterConfigResponse> { return this.request("DeletePacketFilterConfig", req, cb) } /** * 开启或关闭DDoS防护的水印防护配置 */ async SwitchWaterPrintConfig( req: SwitchWaterPrintConfigRequest, cb?: (error: string, rep: SwitchWaterPrintConfigResponse) => void ): Promise<SwitchWaterPrintConfigResponse> { return this.request("SwitchWaterPrintConfig", req, cb) } /** * 获取DDoS防护的协议封禁配置列表 */ async DescribeListProtocolBlockConfig( req: DescribeListProtocolBlockConfigRequest, cb?: (error: string, rep: DescribeListProtocolBlockConfigResponse) => void ): Promise<DescribeListProtocolBlockConfigResponse> { return this.request("DescribeListProtocolBlockConfig", req, cb) } /** * 创建一个域名,可用于在封堵时调度切换IP */ async CreateSchedulingDomain( req?: CreateSchedulingDomainRequest, cb?: (error: string, rep: CreateSchedulingDomainResponse) => void ): Promise<CreateSchedulingDomainResponse> { return this.request("CreateSchedulingDomain", req, cb) } /** * 添加DDoS防护的水印防护密钥 */ async CreateWaterPrintKey( req: CreateWaterPrintKeyRequest, cb?: (error: string, rep: CreateWaterPrintKeyResponse) => void ): Promise<CreateWaterPrintKeyResponse> { return this.request("CreateWaterPrintKey", req, cb) } /** * 设置DDoS防护的协议封禁配置 */ async CreateProtocolBlockConfig( req: CreateProtocolBlockConfigRequest, cb?: (error: string, rep: CreateProtocolBlockConfigResponse) => void ): Promise<CreateProtocolBlockConfigResponse> { return this.request("CreateProtocolBlockConfig", req, cb) } /** * 批量配置L7转发规则的证书供SSL测调用 */ async CreateL7RuleCerts( req: CreateL7RuleCertsRequest, cb?: (error: string, rep: CreateL7RuleCertsResponse) => void ): Promise<CreateL7RuleCertsResponse> { return this.request("CreateL7RuleCerts", req, cb) } /** * 修改DDoS防护的区域封禁配置 */ async ModifyDDoSGeoIPBlockConfig( req: ModifyDDoSGeoIPBlockConfigRequest, cb?: (error: string, rep: ModifyDDoSGeoIPBlockConfigResponse) => void ): Promise<ModifyDDoSGeoIPBlockConfigResponse> { return this.request("ModifyDDoSGeoIPBlockConfig", req, cb) } /** * 获取转发监听器列表 */ async DescribeListListener( req?: DescribeListListenerRequest, cb?: (error: string, rep: DescribeListListenerResponse) => void ): Promise<DescribeListListenerResponse> { return this.request("DescribeListListener", req, cb) } }
the_stack
import { expect } from 'chai'; import { generate, simulate } from 'simulate-event'; import { each, range } from '@phosphor/algorithm'; import { Message, MessageLoop } from '@phosphor/messaging'; import { TabBar, Title, Widget } from '@phosphor/widgets'; import { VirtualDOM } from '@phosphor/virtualdom'; class LogTabBar extends TabBar<Widget> { events: string[] = []; methods: string[] = []; handleEvent(event: Event): void { super.handleEvent(event); this.events.push(event.type); } protected onBeforeAttach(msg: Message): void { super.onBeforeAttach(msg); this.methods.push('onBeforeAttach'); } protected onAfterDetach(msg: Message): void { super.onAfterDetach(msg); this.methods.push('onAfterDetach'); } protected onUpdateRequest(msg: Message): void { super.onUpdateRequest(msg); this.methods.push('onUpdateRequest'); } } function populateBar(bar: TabBar<Widget>): void { // Add some tabs with labels. each(range(3), i => { let widget = new Widget(); widget.title.label = `Test - ${i}`; widget.title.closable = true; bar.addTab(widget.title); }); // Force the tabs to render MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); // Add the close icon content. each(range(3), i => { let tab = bar.contentNode.children[i]; let icon = tab.querySelector(bar.renderer.closeIconSelector); icon!.textContent = 'X'; }); } type Direction = 'left' | 'right' | 'up' | 'down'; function startDrag(bar: LogTabBar, index = 0, direction: Direction = 'right'): void { bar.tabsMovable = true; let tab = bar.contentNode.children[index] as HTMLElement; bar.currentIndex = index; // Force an update. MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); simulateOnNode(tab, 'mousedown'); let called = true; bar.tabDetachRequested.connect((sender, args) => { called = true; }); let rect = bar.contentNode.getBoundingClientRect(); let args: any; switch (direction) { case 'left': args = { clientX: rect.left - 200, clientY: rect.top }; break; case 'up': args = { clientX: rect.left, clientY: rect.top - 200 }; break; case 'down': args = { clientX: rect.left, clientY: rect.bottom + 200 }; break; default: args = { clientX: rect.right + 200, clientY: rect.top }; break; } simulate(document.body, 'mousemove', args); expect(called).to.equal(true); bar.events = []; } function simulateOnNode(node: Element, eventName: string): void { let rect = node.getBoundingClientRect(); simulate(node, eventName, { clientX: rect.left + 1, clientY: rect.top }); } describe('@phosphor/widgets', () => { describe('TabBar', () => { let bar: LogTabBar; beforeEach(() => { bar = new LogTabBar(); Widget.attach(bar, document.body); }); afterEach(() => { bar.dispose(); }); describe('#constructor()', () => { it('should take no arguments', () => { let newBar = new TabBar<Widget>(); expect(newBar).to.be.an.instanceof(TabBar); }); it('should take an options argument', () => { let renderer = new TabBar.Renderer(); let newBar = new TabBar<Widget>({ orientation: 'horizontal', tabsMovable: true, allowDeselect: true, insertBehavior: 'select-tab', removeBehavior: 'select-previous-tab', renderer }); expect(newBar).to.be.an.instanceof(TabBar); expect(newBar.tabsMovable).to.equal(true); expect(newBar.renderer).to.equal(renderer); }); it('should add the `p-TabBar` class', () => { let newBar = new TabBar<Widget>(); expect(newBar.hasClass('p-TabBar')).to.equal(true); }); }); describe('#dispose()', () => { it('should dispose of the resources held by the widget', () => { bar.dispose(); expect(bar.isDisposed).to.equal(true); bar.dispose(); expect(bar.isDisposed).to.equal(true); }); }); describe('#currentChanged', () => { it('should be emitted when the current tab is changed', () => { populateBar(bar); let called = false; let titles = bar.titles; bar.currentChanged.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.previousIndex).to.equal(0); expect(args.previousTitle).to.equal(titles[0]); expect(args.currentIndex).to.equal(1); expect(args.currentTitle).to.equal(titles[1]); called = true; }); bar.currentTitle = titles[1]; expect(called).to.equal(true); }); it('should not be emitted when another tab is inserted', () => { populateBar(bar); let called = false; bar.currentChanged.connect((sender, args) => { called = true; }); let widget = new Widget(); bar.insertTab(0, widget.title); expect(called).to.equal(false); }); it('should not be emitted when another tab is removed', () => { populateBar(bar); let called = false; bar.currentIndex = 1; bar.currentChanged.connect((sender, args) => { called = true; }); bar.removeTab(bar.titles[0]); expect(called).to.equal(false); }); it('should not be emitted when the current tab is moved', () => { populateBar(bar); let called = false; bar.currentChanged.connect((sender, args) => { called = true; }); bar.insertTab(2, bar.titles[0]); expect(called).to.equal(false); }); }); describe('#tabMoved', () => { it('should be emitted when a tab is moved right by the user', (done) => { populateBar(bar); let titles = bar.titles.slice(); bar.tabMoved.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.fromIndex).to.equal(0); expect(args.toIndex).to.equal(2); expect(args.title).to.equal(titles[0]); done(); }); startDrag(bar); simulate(document.body, 'mouseup'); }); it('should be emitted when a tab is moved left by the user', (done) => { populateBar(bar); let titles = bar.titles.slice(); bar.tabMoved.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.fromIndex).to.equal(2); expect(args.toIndex).to.equal(0); expect(args.title).to.equal(titles[2]); done(); }); startDrag(bar, 2, 'left'); simulate(document.body, 'mouseup'); }); it('should not be emitted when a tab is moved programmatically', () => { populateBar(bar); let called = false; bar.tabMoved.connect((sender, args) => { called = true; }); bar.insertTab(2, bar.titles[0]); expect(called).to.equal(false); }); }); describe('#tabActivateRequested', () => { let tab: HTMLElement; beforeEach(() => { populateBar(bar); bar.tabsMovable = false; tab = bar.contentNode.getElementsByClassName('p-TabBar-tab')[2] as HTMLElement; }); it('should be emitted when a tab is left pressed by the user', () => { let called = false; bar.currentIndex = 0; // Force an update. MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); bar.tabActivateRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(2); expect(args.title).to.equal(bar.titles[2]); called = true; }); simulateOnNode(tab, 'mousedown'); expect(called).to.equal(true); }); it('should make the tab current and emit the `currentChanged` signal', () => { let called = 0; bar.currentIndex = 1; // Force an update. MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); bar.tabActivateRequested.connect(() => { called++; }); bar.currentChanged.connect(() => { called++; }); simulateOnNode(tab, 'mousedown'); expect(bar.currentIndex).to.equal(2); expect(called).to.equal(2); }); it('should emit even if the pressed tab is the current tab', () => { let called = false; bar.currentIndex = 2; // Force an update. MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); bar.tabActivateRequested.connect(() => { called = true; }); simulateOnNode(tab, 'mousedown'); expect(bar.currentIndex).to.equal(2); expect(called).to.equal(true); }); }); describe('#tabCloseRequested', () => { let tab: Element; let closeIcon: Element; beforeEach(() => { populateBar(bar); bar.currentIndex = 0; tab = bar.contentNode.children[0]; closeIcon = tab.querySelector(bar.renderer.closeIconSelector)!; }); it('should be emitted when a tab close icon is left clicked', () => { let called = false; let rect = closeIcon.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(0); expect(args.title).to.equal(bar.titles[0]); called = true; }); simulate(closeIcon, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 0 }); simulate(closeIcon, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 0 }); expect(called).to.equal(true); }); it('should be emitted when a tab is middle clicked', () => { let called = false; let rect = tab.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(0); expect(args.title).to.equal(bar.titles[0]); called = true; }); simulate(tab, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 1 }); simulate(tab, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 1 }); expect(called).to.equal(true); }); it('should not be emitted if the tab title is not `closable`', () => { let called = false; let title = bar.titles[0]; title.closable = false; bar.tabCloseRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(0); expect(args.title).to.equal(bar.titles[0]); called = true; }); let rect1 = closeIcon.getBoundingClientRect(); let rect2 = tab.getBoundingClientRect(); simulate(closeIcon, 'mousedown', { clientX: rect1.left, clientY: rect1.top, button: 0 }); simulate(closeIcon, 'mouseup', { clientX: rect1.left, clientY: rect1.top, button: 0 }); simulate(tab, 'mousedown', { clientX: rect2.left, clientY: rect2.top, button: 1 }); simulate(tab, 'mouseup', { clientX: rect2.left, clientY: rect2.top, button: 1 }); expect(called).to.equal(false); }); }); describe('#tabDetachRequested', () => { let tab: HTMLElement; beforeEach(() => { populateBar(bar); bar.tabsMovable = true; tab = bar.contentNode.children[bar.currentIndex] as HTMLElement; }); it('should be emitted when a tab is dragged beyond the detach threshold', () => { simulateOnNode(tab, 'mousedown'); let called = false; bar.tabDetachRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(0); expect(args.title).to.equal(bar.titles[0]); expect(args.clientX).to.equal(rect.right + 200); expect(args.clientY).to.equal(rect.top); called = true; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(true); }); it('should be handled by calling `releaseMouse` and removing the tab', () => { simulateOnNode(tab, 'mousedown'); let called = false; bar.tabDetachRequested.connect((sender, args) => { bar.releaseMouse(); bar.removeTabAt(args.index); called = true; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(true); }); it('should only be emitted once per drag cycle', () => { simulateOnNode(tab, 'mousedown'); let called = 0; bar.tabDetachRequested.connect((sender, args) => { bar.releaseMouse(); bar.removeTabAt(args.index); called++; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(1); simulate(document.body, 'mousemove', { clientX: rect.right + 201, clientY: rect.top }); expect(called).to.equal(1); }); it('should add the `p-mod-dragging` class to the tab and the bar', () => { simulateOnNode(tab, 'mousedown'); let called = false; bar.tabDetachRequested.connect((sender, args) => { expect(tab.classList.contains('p-mod-dragging')).to.equal(true); expect(bar.hasClass('p-mod-dragging')).to.equal(true); called = true; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(true); }); }); describe('#renderer', () => { it('should be the tab bar renderer', () => { let renderer = Object.create(TabBar.defaultRenderer); let bar = new TabBar<Widget>({ renderer }); expect(bar.renderer).to.equal(renderer); }); it('should default to the default renderer', () => { let bar = new TabBar<Widget>(); expect(bar.renderer).to.equal(TabBar.defaultRenderer); }); }); describe('#tabsMovable', () => { it('should get whether the tabs are movable by the user', () => { let bar = new TabBar<Widget>(); expect(bar.tabsMovable).to.equal(false); }); it('should set whether the tabs are movable by the user', () => { let bar = new TabBar<Widget>(); bar.tabsMovable = true; expect(bar.tabsMovable).to.equal(true); }); it('should still allow programmatic moves', () => { populateBar(bar); let titles = bar.titles.slice(); bar.insertTab(2, titles[0]); expect(bar.titles[2]).to.equal(titles[0]); }); }); describe('#allowDeselect', () => { it('should determine whether a tab can be deselected by the user', () => { populateBar(bar); bar.allowDeselect = false; bar.tabsMovable = false; bar.currentIndex = 2; // Force the tabs to render MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); let tab = bar.contentNode.getElementsByClassName('p-TabBar-tab')[2] as HTMLElement; simulateOnNode(tab, 'mousedown'); expect(bar.currentIndex).to.equal(2); simulateOnNode(tab, 'mouseup'); bar.allowDeselect = true; simulateOnNode(tab, 'mousedown'); expect(bar.currentIndex).to.equal(-1); simulateOnNode(tab, 'mouseup'); }); it('should always allow programmatic deselection', () => { populateBar(bar); bar.allowDeselect = false; bar.currentIndex = -1; expect(bar.currentIndex).to.equal(-1); }); }); describe('#insertBehavior', () => { it('should not change the selection', () => { populateBar(bar); bar.insertBehavior = 'none'; bar.currentIndex = 0; bar.insertTab(2, new Widget().title); expect(bar.currentIndex).to.equal(0); }); it('should select the tab', () => { populateBar(bar); bar.insertBehavior = 'select-tab'; bar.currentIndex = 0; bar.insertTab(2, new Widget().title); expect(bar.currentIndex).to.equal(2); bar.currentIndex = -1; bar.insertTab(1, new Widget().title); expect(bar.currentIndex).to.equal(1); }); it('should select the tab if needed', () => { populateBar(bar); bar.insertBehavior = 'select-tab-if-needed'; bar.currentIndex = 0; bar.insertTab(2, new Widget().title); expect(bar.currentIndex).to.equal(0); bar.currentIndex = -1; bar.insertTab(1, new Widget().title); expect(bar.currentIndex).to.equal(1); }); }); describe('#removeBehavior', () => { it('should select no tab', () => { populateBar(bar); bar.removeBehavior = 'none'; bar.currentIndex = 2; bar.removeTabAt(2); expect(bar.currentIndex).to.equal(-1); }); it('should select the tab after the removed tab if possible', () => { populateBar(bar); bar.removeBehavior = 'select-tab-after'; bar.currentIndex = 0; bar.removeTabAt(0); expect(bar.currentIndex).to.equal(0); bar.currentIndex = 1; bar.removeTabAt(1); expect(bar.currentIndex).to.equal(0); }); it('should select the tab before the removed tab if possible', () => { populateBar(bar); bar.removeBehavior = 'select-tab-before'; bar.currentIndex = 1; bar.removeTabAt(1); expect(bar.currentIndex).to.equal(0); bar.removeTabAt(0); expect(bar.currentIndex).to.equal(0); }); it('should select the previously selected tab if possible', () => { populateBar(bar); bar.removeBehavior = 'select-previous-tab'; bar.currentIndex = 0; bar.currentIndex = 2; bar.removeTabAt(2); expect(bar.currentIndex).to.equal(0); // Reset the bar. bar.removeTabAt(0); bar.removeTabAt(0); populateBar(bar); bar.currentIndex = 1; bar.removeTabAt(1); expect(bar.currentIndex).to.equal(0); }); }); describe('#currentTitle', () => { it('should get the currently selected title', () => { populateBar(bar); bar.currentIndex = 0; expect(bar.currentTitle).to.equal(bar.titles[0]); }); it('should be `null` if no tab is selected', () => { populateBar(bar); bar.currentIndex = -1; expect(bar.currentTitle).to.equal(null); }); it('should set the currently selected title', () => { populateBar(bar); bar.currentTitle = bar.titles[1]; expect(bar.currentTitle).to.equal(bar.titles[1]); }); it('should set the title to `null` if the title does not exist', () => { populateBar(bar); bar.currentTitle = new Widget().title; expect(bar.currentTitle).to.equal(null); }); }); describe('#currentIndex', () => { it('should get index of the currently selected tab', () => { populateBar(bar); expect(bar.currentIndex).to.equal(0); }); it('should be `null` if no tab is selected', () => { expect(bar.currentIndex).to.equal(-1); }); it('should set index of the currently selected tab', () => { populateBar(bar); bar.currentIndex = 1; expect(bar.currentIndex).to.equal(1); }); it('should set the index to `-1` if the value is out of range', () => { populateBar(bar); bar.currentIndex = -1; expect(bar.currentIndex).to.equal(-1); bar.currentIndex = 10; expect(bar.currentIndex).to.equal(-1); }); it('should emit the `currentChanged` signal', () => { populateBar(bar); let titles = bar.titles; let called = false; bar.currentChanged.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.previousIndex).to.equal(0); expect(args.previousTitle).to.equal(titles[0]); expect(args.currentIndex).to.equal(1); expect(args.currentTitle).to.equal(titles[1]); called = true; }); bar.currentIndex = 1; expect(called).to.equal(true); }); it('should schedule an update of the tabs', (done) => { populateBar(bar); requestAnimationFrame(() => { bar.currentIndex = 1; bar.methods = []; requestAnimationFrame(() => { expect(bar.methods.indexOf('onUpdateRequest')).to.not.equal(-1); done(); }); }); }); it('should be a no-op if the index does not change', (done) => { populateBar(bar); requestAnimationFrame(() => { bar.currentIndex = 0; bar.methods = []; requestAnimationFrame(() => { expect(bar.methods.indexOf('onUpdateRequest')).to.equal(-1); done(); }); }); }); }); describe('#orientation', () => { it('should be the orientation of the tab bar', () => { expect(bar.orientation).to.equal('horizontal'); bar.orientation = 'vertical'; expect(bar.orientation).to.equal('vertical'); }); it('should set the orientation attribute of the tab bar', () => { bar.orientation = 'horizontal'; expect(bar.node.getAttribute('data-orientation')).to.equal('horizontal'); bar.orientation = 'vertical'; expect(bar.node.getAttribute('data-orientation')).to.equal('vertical'); }); }); describe('#titles', () => { it('should get the read-only array of titles in the tab bar', () => { let bar = new TabBar<Widget>(); let widgets = [new Widget(), new Widget(), new Widget()]; each(widgets, widget => { bar.addTab(widget.title); }); expect(bar.titles.length).to.equal(3); each(bar.titles, (title, i) => { expect(title.owner).to.equal(widgets[i]); }); }); }); describe('#contentNode', () => { it('should get the tab bar content node', () => { expect(bar.contentNode.classList.contains('p-TabBar-content')).to.equal(true); }); }); describe('#addTab()', () => { it('should add a tab to the end of the tab bar', () => { populateBar(bar); let title = new Widget().title; bar.addTab(title); expect(bar.titles[3]).to.equal(title); }); it('should accept a title options object', () => { let owner = new Widget(); bar.addTab({ owner, label: 'foo' }); expect(bar.titles[0]).to.be.an.instanceof(Title); expect(bar.titles[0].label).to.equal('foo'); }); it('should move an existing title to the end', () => { populateBar(bar); let titles = bar.titles.slice(); bar.addTab(titles[0]); expect(bar.titles[2]).to.equal(titles[0]); }); }); describe('#insertTab()', () => { it('should insert a tab into the tab bar at the specified index', () => { populateBar(bar); let title = new Widget().title; bar.insertTab(1, title); expect(bar.titles[1]).to.equal(title); }); it('should accept a title options object', () => { populateBar(bar); let title = bar.insertTab(1, { owner: new Widget(), label: 'foo' }); expect(title).to.be.an.instanceof(Title); expect(title.label).to.equal('foo'); }); it('should clamp the index to the bounds of the tabs', () => { populateBar(bar); let title = new Widget().title; bar.insertTab(-1, title); expect(bar.titles[0]).to.equal(title); title = new Widget().title; bar.insertTab(10, title); expect(bar.titles[4]).to.equal(title); }); it('should move an existing tab', () => { populateBar(bar); let titles = bar.titles.slice(); bar.insertTab(1, titles[0]); expect(bar.titles[1]).to.equal(titles[0]); }); it('should schedule an update of the tabs', (done) => { let bar = new LogTabBar(); bar.insertTab(0, new Widget().title); requestAnimationFrame(() => { expect(bar.methods.indexOf('onUpdateRequest')).to.not.equal(-1); done(); }); }); it('should schedule an update if the title changes', (done) => { let bar = new LogTabBar(); let title = new Widget().title; bar.insertTab(0, title); requestAnimationFrame(() => { expect(bar.methods.indexOf('onUpdateRequest')).to.not.equal(-1); bar.methods = []; title.label = 'foo'; requestAnimationFrame(() => { expect(bar.methods.indexOf('onUpdateRequest')).to.not.equal(-1); done(); }); }); }); }); describe('#removeTab()', () => { it('should remove a tab from the tab bar by value', () => { populateBar(bar); let titles = bar.titles.slice(); bar.removeTab(titles[0]); expect(bar.titles[0]).to.equal(titles[1]); }); it('should return be a no-op if the title is not in the tab bar', () => { populateBar(bar); bar.removeTab(new Widget().title); }); it('should schedule an update of the tabs', (done) => { let bar = new LogTabBar(); bar.insertTab(0, new Widget().title); requestAnimationFrame(() => { bar.removeTab(bar.titles[0]); bar.methods = []; requestAnimationFrame(() => { expect(bar.methods.indexOf('onUpdateRequest')).to.not.equal(-1); done(); }); }); }); }); describe('#removeTabAt()', () => { it('should remove a tab at a specific index', () => { populateBar(bar); let titles = bar.titles.slice(); bar.removeTabAt(0); expect(bar.titles[0]).to.equal(titles[1]); }); it('should return be a no-op if the index is out of range', () => { populateBar(bar); bar.removeTabAt(9); }); it('should schedule an update of the tabs', (done) => { let bar = new LogTabBar(); bar.insertTab(0, new Widget().title); requestAnimationFrame(() => { bar.removeTabAt(0); bar.methods = []; requestAnimationFrame(() => { expect(bar.methods.indexOf('onUpdateRequest')).to.not.equal(-1); done(); }); }); }); }); describe('#clearTabs()', () => { it('should remove all tabs from the tab bar', () => { populateBar(bar); bar.clearTabs(); expect(bar.titles.length).to.equal(0); }); it('should be a no-op if there are no tabs', () => { let bar = new TabBar<Widget>(); bar.clearTabs(); expect(bar.titles.length).to.equal(0); }); it('should emit the `currentChanged` signal if there was a selected tab', () => { populateBar(bar); let called = false; bar.currentIndex = 0; bar.currentChanged.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.previousIndex).to.equal(0); called = true; }); bar.clearTabs(); expect(called).to.equal(true); }); it('should not emit the `currentChanged` signal if there was no selected tab', () => { populateBar(bar); let called = false; bar.currentIndex = -1; bar.currentChanged.connect((sender, args) => { called = true; }); bar.clearTabs(); expect(called).to.equal(false); }); }); describe('#releaseMouse()', () => { it('should release the mouse and restore the non-dragged tab positions', () => { populateBar(bar); startDrag(bar, 0, 'left'); bar.releaseMouse(); simulate(document.body, 'mousemove'); expect(bar.events.indexOf('mousemove')).to.equal(-1); }); }); describe('#handleEvent()', () => { let tab: Element; let closeIcon: Element; beforeEach(() => { bar.tabsMovable = true; populateBar(bar); bar.currentIndex = 0; tab = bar.contentNode.children[0]; closeIcon = tab.querySelector(bar.renderer.closeIconSelector)!; }); context('left click', () => { it('should emit a tab close requested signal', () => { let called = false; let rect = closeIcon.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(0); expect(args.title).to.equal(bar.titles[0]); called = true; }); simulate(closeIcon, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 0 }); simulate(closeIcon, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 0 }); expect(called).to.equal(true); }); it('should do nothing if a drag is in progress', () => { startDrag(bar, 1, 'up'); let called = false; let rect = closeIcon.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { called = true; }); simulate(closeIcon, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 0 }); simulate(closeIcon, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 0 }); expect(called).to.equal(false); }); it('should do nothing if the click is not on a close icon', () => { let called = false; let rect = closeIcon.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { called = true; }); simulate(closeIcon, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 0 }); simulate(closeIcon, 'mouseup', { clientX: rect.left - 1, clientY: rect.top - 1, button: 0 }); expect(called).to.equal(false); expect(called).to.equal(false); }); it('should do nothing if the tab is not closable', () => { let called = false; bar.titles[0].closable = false; let rect = closeIcon.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { called = true; }); simulate(closeIcon, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 0 }); simulate(closeIcon, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 0 }); expect(called).to.equal(false); }); }); context('middle click', () => { it('should emit a tab close requested signal', () => { let called = false; let rect = tab.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(0); expect(args.title).to.equal(bar.titles[0]); called = true; }); simulate(tab, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 1 }); simulate(tab, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 1 }); expect(called).to.equal(true); }); it('should do nothing if a drag is in progress', () => { startDrag(bar, 1, 'up'); let called = false; let rect = tab.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { called = true; }); simulate(tab, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 1 }); simulate(tab, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 1 }); expect(called).to.equal(false); }); it('should do nothing if the click is not on the tab', () => { let called = false; let rect = tab.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { called = true; }); simulate(tab, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 1 }); simulate(tab, 'mouseup', { clientX: rect.left - 1, clientY: rect.top - 1, button: 1 }); expect(called).to.equal(false); expect(called).to.equal(false); }); it('should do nothing if the tab is not closable', () => { let called = false; bar.titles[0].closable = false; let rect = tab.getBoundingClientRect(); bar.tabCloseRequested.connect((sender, args) => { called = true; }); simulate(tab, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 1 }); simulate(tab, 'mouseup', { clientX: rect.left, clientY: rect.top, button: 1 }); expect(called).to.equal(false); }); }); context('mousedown', () => { it('should add event listeners if the tabs are movable', () => { simulateOnNode(tab, 'mousedown'); simulate(document.body, 'mousemove'); expect(bar.events.indexOf('mousemove')).to.not.equal(-1); }); it('should do nothing if not a left mouse press', () => { let rect = tab.getBoundingClientRect(); simulate(tab, 'mousedown', { clientX: rect.left, clientY: rect.top, button: 1 }); simulate(document.body, 'mousemove'); expect(bar.events.indexOf('mousemove')).to.equal(-1); }); it('should do nothing if the press is not on a tab', () => { let rect = tab.getBoundingClientRect(); simulate(tab, 'mousedown', { clientX: rect.left - 1, clientY: rect.top }); simulate(document.body, 'mousemove'); expect(bar.events.indexOf('mousemove')).to.equal(-1); }); it('should do nothing if the press is on a close icon', () => { simulateOnNode(closeIcon, 'mousedown'); simulate(document.body, 'mousemove'); expect(bar.events.indexOf('mousemove')).to.equal(-1); }); it('should do nothing if the tabs are not movable', () => { bar.tabsMovable = false; simulateOnNode(tab, 'mousedown'); simulate(document.body, 'mousemove'); expect(bar.events.indexOf('mousemove')).to.equal(-1); }); it('should do nothing if there is a drag in progress', () => { startDrag(bar, 2, 'down'); let rect = tab.getBoundingClientRect(); let evt = generate('mousedown', { clientX: rect.left, clientY: rect.top }); let cancelled = !tab.dispatchEvent(evt); expect(cancelled).to.equal(false); }); }); context('mousemove', () => { it('should do nothing if there is a drag in progress', () => { simulateOnNode(tab, 'mousedown'); let called = 0; bar.tabDetachRequested.connect((sender, args) => { called++; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(1); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(1); }); it('should bail if the drag threshold is not exceeded', () => { simulateOnNode(tab, 'mousedown'); let called = false; bar.tabDetachRequested.connect((sender, args) => { bar.releaseMouse(); called = true; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 1, clientY: rect.top }); expect(called).to.equal(false); }); it('should emit the detach requested signal if the threshold is exceeded', () => { simulateOnNode(tab, 'mousedown'); let called = false; bar.tabDetachRequested.connect((sender, args) => { expect(sender).to.equal(bar); expect(args.index).to.equal(0); expect(args.title).to.equal(bar.titles[0]); expect(args.clientX).to.equal(rect.right + 200); expect(args.clientY).to.equal(rect.top); called = true; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(true); }); it('should bail if the signal handler aborted the drag', () => { simulateOnNode(tab, 'mousedown'); let called = false; bar.tabDetachRequested.connect((sender, args) => { bar.releaseMouse(); called = true; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(true); let left = rect.left; rect = tab.getBoundingClientRect(); expect(left).to.equal(rect.left); }); it('should update the positions of the tabs', () => { simulateOnNode(tab, 'mousedown'); let called = false; bar.tabDetachRequested.connect((sender, args) => { called = true; }); let rect = bar.contentNode.getBoundingClientRect(); simulate(document.body, 'mousemove', { clientX: rect.right + 200, clientY: rect.top }); expect(called).to.equal(true); let left = rect.left; rect = tab.getBoundingClientRect(); expect(left).to.not.equal(rect.left); }); }); context('mouseup', () => { it('should emit the `tabMoved` signal', (done) => { startDrag(bar); simulate(document.body, 'mouseup'); bar.tabMoved.connect(() => { done(); }); }); it('should move the tab to its final position', (done) => { startDrag(bar); simulate(document.body, 'mouseup'); let title = bar.titles[0]; bar.tabMoved.connect(() => { expect(bar.titles[2]).to.equal(title); done(); }); }); it('should cancel a middle mouse release', () => { startDrag(bar); let evt = generate('mouseup', { button: 1 }); let cancelled = !document.body.dispatchEvent(evt); expect(cancelled).to.equal(true); }); }); context('keydown', () => { it('should prevent default', () => { startDrag(bar); let evt = generate('keydown'); let cancelled = !document.body.dispatchEvent(evt); expect(cancelled).to.equal(true); }); it('should release the mouse if `Escape` is pressed', () => { startDrag(bar); simulate(document.body, 'keydown', { keyCode: 27 }); simulateOnNode(tab, 'mousedown'); expect(bar.events.indexOf('mousemove')).to.equal(-1); }); }); context('contextmenu', () => { it('should prevent default', () => { startDrag(bar); let evt = generate('contextmenu'); let cancelled = !document.body.dispatchEvent(evt); expect(cancelled).to.equal(true); }); }); }); describe('#onBeforeAttach()', () => { it('should add event listeners to the node', () => { let bar = new LogTabBar(); Widget.attach(bar, document.body); expect(bar.methods).to.contain('onBeforeAttach'); simulate(bar.node, 'mousedown'); expect(bar.events.indexOf('mousedown')).to.not.equal(-1); bar.dispose(); }); }); describe('#onAfterDetach()', () => { it('should remove event listeners', () => { let bar = new LogTabBar(); let owner = new Widget(); bar.addTab(new Title({ owner, label: 'foo' })); MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); Widget.attach(bar, document.body); let tab = bar.contentNode.firstChild as HTMLElement; let rect = tab.getBoundingClientRect(); simulate(tab, 'mousedown', { clientX: rect.left, clientY: rect.top }); Widget.detach(bar); expect(bar.methods).to.contain('onAfterDetach'); simulate(document.body, 'mousemove'); expect(bar.events.indexOf('mousemove')).to.equal(-1); simulate(document.body, 'mouseup'); expect(bar.events.indexOf('mouseup')).to.equal(-1); }); }); describe('#onUpdateRequest()', () => { it('should render tabs and set styles', () => { populateBar(bar); bar.currentIndex = 0; MessageLoop.sendMessage(bar, Widget.Msg.UpdateRequest); expect(bar.methods.indexOf('onUpdateRequest')).to.not.equal(-1); each(bar.titles, (title, i) => { let tab = bar.contentNode.children[i] as HTMLElement; let label = tab.getElementsByClassName('p-TabBar-tabLabel')[0] as HTMLElement; expect(label.textContent).to.equal(title.label); let current = i === 0; expect(tab.classList.contains('p-mod-current')).to.equal(current); }); }); }); describe('.Renderer', () => { let title: Title<Widget>; beforeEach(() => { let owner = new Widget(); title = new Title({ owner, label: 'foo', closable: true, icon: 'bar', className: 'fizz', caption: 'this is a caption' }); }); describe('#closeIconSelector', () => { it('should be `.p-TabBar-tabCloseIcon`', () => { let renderer = new TabBar.Renderer(); expect(renderer.closeIconSelector).to.equal('.p-TabBar-tabCloseIcon'); }); }); describe('#renderTab()', () => { it('should render a virtual node for a tab', () => { let renderer = new TabBar.Renderer(); let vNode = renderer.renderTab({ title, current: true, zIndex: 1 }); let node = VirtualDOM.realize(vNode); expect(node.getElementsByClassName('p-TabBar-tabIcon').length).to.equal(1); expect(node.getElementsByClassName('p-TabBar-tabLabel').length).to.equal(1); expect(node.getElementsByClassName('p-TabBar-tabCloseIcon').length).to.equal(1); expect(node.classList.contains('p-TabBar-tab')).to.equal(true); expect(node.classList.contains(title.className)).to.equal(true); expect(node.classList.contains('p-mod-current')).to.equal(true); expect(node.classList.contains('p-mod-closable')).to.equal(true); expect(node.title).to.equal(title.caption); let icon = node.getElementsByClassName('p-TabBar-tabIcon')[0] as HTMLElement; let label = node.getElementsByClassName('p-TabBar-tabLabel')[0] as HTMLElement; expect(icon.classList.contains(title.icon)).to.equal(true); expect(label.textContent).to.equal(title.label); }); }); describe('#renderIcon()', () => { it('should render the icon element for a tab', () => { let renderer = new TabBar.Renderer(); let vNode = renderer.renderIcon({ title, current: true, zIndex: 1 }); let node = VirtualDOM.realize(vNode); expect(node.className).to.contain('p-TabBar-tabIcon'); expect(node.classList.contains(title.icon)).to.equal(true); }); }); describe('#renderLabel()', () => { it('should render the label element for a tab', () => { let renderer = new TabBar.Renderer(); let vNode = renderer.renderLabel({ title, current: true, zIndex: 1 }); let label = VirtualDOM.realize(vNode); expect(label.className).to.contain('p-TabBar-tabLabel'); expect(label.textContent).to.equal(title.label); }); }); describe('#renderCloseIcon()', () => { it('should render the close icon element for a tab', () => { let renderer = new TabBar.Renderer(); let vNode = renderer.renderCloseIcon({ title, current: true, zIndex: 1 }); let icon = VirtualDOM.realize(vNode); expect(icon.className).to.contain('p-TabBar-tabCloseIcon'); }); }); describe('#createTabKey()', () => { it('should create a unique render key for the tab', () => { let renderer = new TabBar.Renderer(); let key = renderer.createTabKey({ title, current: true, zIndex: 1 }); let newKey = renderer.createTabKey({ title, current: true, zIndex: 1 }); expect(key).to.equal(newKey); }); }); describe('#createTabStyle()', () => { it('should create the inline style object for a tab', () => { let renderer = new TabBar.Renderer(); let style = renderer.createTabStyle({ title, current: true, zIndex: 1 }); expect(style['zIndex']).to.equal('1'); }); }); describe('#createTabClass()', () => { it('should create the class name for the tab', () => { let renderer = new TabBar.Renderer(); let className = renderer.createTabClass({ title, current: true, zIndex: 1 }); expect(className).to.contain('p-TabBar-tab'); expect(className).to.contain('p-mod-closable'); expect(className).to.contain('p-mod-current'); }); }); describe('#createIconClass()', () => { it('should create class name for the tab icon', () => { let renderer = new TabBar.Renderer(); let className = renderer.createIconClass({ title, current: true, zIndex: 1 }); expect(className).to.contain('p-TabBar-tabIcon'); expect(className).to.contain(title.icon); }); }); }); describe('.defaultRenderer', () => { it('should be an instance of `Renderer`', () => { expect(TabBar.defaultRenderer).to.be.an.instanceof(TabBar.Renderer); }); }); }); });
the_stack
import React, { useMemo } from 'react' import { SectionList, Text as TextNative, TouchableHighlight, View } from 'react-native' import { Text } from '@ui-kitten/components' import { CommonActions } from '@react-navigation/native' import { EdgeInsets } from 'react-native-safe-area-context' import { useTranslation } from 'react-i18next' import beapi from '@berty-tech/api' import { Routes, useNavigation } from '@berty-tech/navigation' import { useStyles } from '@berty-tech/styles' import { useConversation, useContact, useConvInteractions, useThemeColor, } from '@berty-tech/store/hooks' import { HintBody } from '@berty-tech/components/shared-components' import { parseInteraction } from '@berty-tech/store/utils' import { ParsedInteraction } from '@berty-tech/store/types.gen' import { pbDateToNum, timeFormat } from '../../helpers' import { ContactAvatar, ConversationAvatar } from '../../avatars' // Styles const _resultAvatarSize = 45 const useStylesSearch = () => { const [{ text, background }] = useStyles() const colors = useThemeColor() return { searchResultHighlightText: [ text.size.small, background.light.yellow, text.bold.medium, { color: colors['secondary-text'], backgroundColor: `${colors['secondary-text']}30` }, ], nameHighlightText: [ text.bold.medium, { color: colors['secondary-text'], backgroundColor: `${colors['secondary-text']}30` }, ], plainMessageText: [text.size.small, { color: colors['secondary-text'] }], } } // SEARCH RESULTS enum SearchResultKind { Contact = 'Contact', Conversation = 'Conversation', Interaction = 'Interaction', } type SearchItemProps = { searchText?: string; data: any; kind: SearchResultKind } const MessageSearchResult: React.FC<{ message: string searchText: string style?: any highlightStyle?: any }> = ({ message, searchText, style, highlightStyle }) => { if (typeof message !== 'string' || typeof searchText !== 'string') { return null } const parts = [] let partsCounter = 0 let lastStart = 0 const firstResultIndex = message.indexOf(searchText) if (firstResultIndex > 20) { message = '...' + message.substr(firstResultIndex - 15) } for (let i = 0; i < message.length; ) { const searchTarget = message.substr(i, searchText.length) if (searchTarget.toLowerCase() === searchText.toLowerCase()) { if (lastStart < i) { const plainPart = message.substr(lastStart, i - lastStart) parts[partsCounter] = ( <Text key={partsCounter} style={style}> {plainPart} </Text> ) partsCounter++ } parts[partsCounter] = ( <Text key={partsCounter} style={highlightStyle}> {searchTarget} </Text> ) partsCounter++ i += searchText.length lastStart = i } else { i++ } } if (lastStart !== message.length) { const plainPart = message.substr(lastStart) parts[partsCounter] = ( <Text key={partsCounter} style={style}> {plainPart} </Text> ) lastStart = message.length partsCounter++ } return <>{parts}</> } const SearchResultItem: React.FC<SearchItemProps> = ({ data, kind, searchText = '' }) => { const [{ color, row, padding, flex, column, text, margin, border }] = useStyles() const { plainMessageText, searchResultHighlightText, nameHighlightText } = useStylesSearch() const { navigate, dispatch } = useNavigation() let convPk: string switch (kind) { case SearchResultKind.Contact: convPk = data.conversationPublicKey || '' break case SearchResultKind.Conversation: convPk = data.publicKey || '' break case SearchResultKind.Interaction: convPk = data.conversationPublicKey || '' break } const conv = useConversation(convPk) let contactPk: string switch (kind) { case SearchResultKind.Contact: contactPk = data.publicKey break case SearchResultKind.Conversation: contactPk = '' break case SearchResultKind.Interaction: contactPk = conv?.contactPublicKey || '' break } const contact = useContact(contactPk) const interactions = useConvInteractions(conv?.publicKey).filter( inte => inte.type === beapi.messenger.AppMessage.Type.TypeUserMessage, ) const lastInteraction = interactions && interactions.length > 0 ? interactions[interactions.length - 1] : null let name: string let inte: beapi.messenger.IInteraction | ParsedInteraction | null let avatar: JSX.Element switch (kind) { case SearchResultKind.Contact: avatar = <ContactAvatar publicKey={contactPk} size={_resultAvatarSize} /> name = data.displayName || '' inte = lastInteraction || null break case SearchResultKind.Conversation: avatar = <ConversationAvatar publicKey={convPk} size={_resultAvatarSize} /> name = data.displayName || '' inte = lastInteraction || null break case SearchResultKind.Interaction: if (conv?.type === beapi.messenger.Conversation.Type.ContactType) { name = contact?.displayName || '' avatar = <ContactAvatar publicKey={contact?.publicKey} size={_resultAvatarSize} /> } else { name = conv?.displayName || '' avatar = <ConversationAvatar publicKey={convPk} size={_resultAvatarSize} /> } inte = data || null if (inte !== null) { try { inte = parseInteraction(inte as beapi.messenger.Interaction) } catch (e) { console.warn(e) } } console.log(data) break default: return null } const date = pbDateToNum(inte?.sentDate) const MessageDisplay = () => { let content switch (kind) { case SearchResultKind.Contact: switch (data.state) { case beapi.messenger.Contact.State.IncomingRequest: content = '📬 Incoming request' break case beapi.messenger.Contact.State.OutgoingRequestEnqueued: content = '📪 Outgoing request enqueued' break case beapi.messenger.Contact.State.OutgoingRequestSent: content = '📫 Outgoing request sent' break default: content = (inte?.payload as any)?.body } break case SearchResultKind.Conversation: content = (inte?.payload as any)?.body break case SearchResultKind.Interaction: content = ( <MessageSearchResult searchText={searchText} message={(inte?.payload as any)?.body} style={plainMessageText} highlightStyle={searchResultHighlightText} /> ) break default: return null } return ( <Text numberOfLines={1} style={plainMessageText}> {content} </Text> ) } const TimeStamp = () => { return ( <Text style={[padding.left.small, text.size.small, text.color.grey]}> {timeFormat.fmtTimestamp1(date)} </Text> ) } return ( <TouchableHighlight underlayColor={!conv ? 'transparent' : color.light.grey} onPress={() => !conv ? data.state === beapi.messenger.Contact.State.IncomingRequest ? navigate.main.contactRequest({ contactId: data.publicKey }) : null : dispatch( CommonActions.navigate({ name: conv.type === beapi.messenger.Conversation.Type.ContactType ? Routes.Chat.OneToOne : Routes.Chat.Group, params: { convId: convPk, scrollToMessage: kind === SearchResultKind.Interaction && inte ? inte.cid : null, }, }), ) } > <View style={[row.center, padding.medium, border.bottom.tiny, border.color.light.grey]}> {avatar} <View style={[flex.medium, column.justify, padding.left.medium]}> <View style={[margin.right.big]}> <Text numberOfLines={1} style={[column.item.fill, text.bold.medium]}> {kind === SearchResultKind.Interaction ? ( name ) : ( <MessageSearchResult message={name} searchText={searchText} style={[text.bold.medium]} highlightStyle={nameHighlightText} /> )} </Text> <MessageDisplay /> </View> </View> <View style={[{ marginLeft: 'auto' }, row.item.center]}> {date > 0 && kind === SearchResultKind.Interaction ? <TimeStamp /> : null} </View> </View> </TouchableHighlight> ) } const createSections = ( conversations: any, contacts: any, interactions: any, searchText: string, ) => { const sections = [ { title: contacts.length ? 'Contacts' : '', data: contacts, renderItem: ({ item }: { item: any }) => ( <SearchResultItem data={item} kind={SearchResultKind.Contact} searchText={searchText} /> ), }, { title: conversations.length ? 'Groups' : '', data: conversations, renderItem: ({ item }: { item: any }) => ( <SearchResultItem data={item} kind={SearchResultKind.Conversation} searchText={searchText} /> ), }, { title: interactions.length ? 'Messages' : '', data: interactions, renderItem: ({ item }: { item: any }) => ( <SearchResultItem data={item} kind={SearchResultKind.Interaction} searchText={searchText} /> ), }, ] return sections } const _approxFooterHeight = 90 export const SearchComponent: React.FC<{ insets: EdgeInsets | null conversations: { [key: string]: beapi.messenger.IConversation | undefined } contacts: { [key: string]: beapi.messenger.IContact | undefined } interactions: beapi.messenger.IInteraction[] hasResults: boolean value: string earliestInteractionCID: string }> = ({ insets, conversations, contacts, interactions, hasResults, value, earliestInteractionCID: _earliestInteractionCID, }) => { const [{ height, width, padding, text, border, margin }] = useStyles() const colors = useThemeColor() const { t } = useTranslation() const validInsets = useMemo(() => insets || { top: 0, bottom: 0, left: 0, right: 0 }, [insets]) const sortedConversations = useMemo(() => { return Object.values(conversations).sort((a, b) => { return pbDateToNum(b?.lastUpdate) - pbDateToNum(a?.lastUpdate) }) }, [conversations]) const sections = useMemo( () => createSections(sortedConversations, Object.values(contacts), interactions, value), [contacts, sortedConversations, interactions, value], ) return hasResults ? ( <SectionList style={{ marginLeft: validInsets.left, marginRight: validInsets.right, }} stickySectionHeadersEnabled={false} bounces={false} keyExtractor={(item: any) => item.cid || item.publicKey} sections={sections} renderSectionHeader={({ section }) => { const { title } = section let isFirst sections?.map((value: any, key: any) => { if (value.data?.length && value.title === section.title) { switch (key) { case 0: isFirst = true break case 1: isFirst = sections[0].data?.length ? false : true break case 2: isFirst = sections[0].data?.length || sections[1].data?.length ? false : true break } } }) return title ? ( <View style={[ !isFirst && border.radius.top.big, { backgroundColor: colors['main-background'] }, !isFirst && { shadowOpacity: 0.1, shadowRadius: 8, shadowColor: colors.shadow, shadowOffset: { width: 0, height: -12 }, }, ]} > <View style={[padding.horizontal.medium]}> <View style={{ flexDirection: 'row', justifyContent: 'center' }}> <View style={[ width(42), height(4), margin.top.medium, { backgroundColor: `${colors['negative-asset']}30` }, ]} /> </View> <TextNative style={[ text.size.scale(25), text.bold.medium, { fontFamily: 'Open Sans', color: colors['main-text'] }, ]} > {title} </TextNative> </View> </View> ) : null }} ListFooterComponent={() => ( // empty div at bottom of list // Workaround to make sure nothing is hidden behind footer; // adding padding/margin to this or a wrapping parent doesn't work <View style={[height(_approxFooterHeight + 20)]} /> )} /> ) : ( <View style={{ position: 'relative' }}> <View style={[margin.top.scale(60)]}> <HintBody /> </View> <TextNative style={[ margin.top.scale(60), text.size.big, text.bold.small, text.align.center, { fontFamily: 'Open Sans', color: colors['main-text'], }, ]} > {t('main.home.search.no-results')} </TextNative> </View> ) }
the_stack
import React from 'react'; import {Box, Flex} from 'theme-ui'; import { notification, Button, Container, Divider, Input, Paragraph, Text, Title, } from '../common'; import Spinner from '../Spinner'; import AccountUsersTable from './AccountUsersTable'; import DisabledUsersTable from './DisabledUsersTable'; import * as API from '../../api'; import {Account, User} from '../../types'; import {FRONTEND_BASE_URL, isUserInvitationEmailEnabled} from '../../config'; import {sleep, hasValidStripeKey} from '../../utils'; import logger from '../../logger'; type Props = {}; type State = { account: Account | null; currentUser: User | null; inviteUrl: string; inviteUserEmail: string; isLoading: boolean; isRefreshing: boolean; showInviteMoreInput: boolean; }; class TeamOverview extends React.Component<Props, State> { input: Input | null = null; state: State = { account: null, currentUser: null, inviteUrl: '', inviteUserEmail: '', isLoading: true, isRefreshing: false, showInviteMoreInput: false, }; async componentDidMount() { await this.fetchLatestAccountInfo(); const currentUser = await API.me(); this.setState({currentUser, isLoading: false}); } fetchLatestAccountInfo = async () => { const account = await API.fetchAccountInfo(); logger.debug('Account info:', account); this.setState({account}); }; hasAdminRole = () => { return this.state.currentUser?.role === 'admin'; }; handleGenerateInviteUrl = async () => { try { const {id: token} = await API.generateUserInvitation(); this.setState( { inviteUrl: `${FRONTEND_BASE_URL}/register/${token}`, }, () => this.focusAndHighlightInput() ); } catch (err) { const hasServerErrorMessage = !!err?.response?.body?.error?.message; const shouldDisplayBillingLink = hasServerErrorMessage && hasValidStripeKey(); const description = err?.response?.body?.error?.message || err?.message || String(err); notification.error({ message: hasServerErrorMessage ? 'Please upgrade to add more users!' : 'Failed to generate user invitation!', description, duration: 10, // 10 seconds btn: ( <a href={ shouldDisplayBillingLink ? '/billing' : 'https://papercups.io/pricing' } > <Button type="primary" size="small"> Upgrade subscription </Button> </a> ), }); } }; handleSendInviteEmail = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); try { const {inviteUserEmail} = this.state; await API.sendUserInvitationEmail(inviteUserEmail); notification.success({ message: `Invitation was successfully sent to ${inviteUserEmail}!`, duration: 10, // 10 seconds }); this.setState({inviteUserEmail: ''}); } catch (err) { // TODO: consolidate error logic with handleGenerateInviteUrl const hasServerErrorMessage = !!err?.response?.body?.error?.message; const shouldDisplayBillingLink = hasServerErrorMessage && hasValidStripeKey(); const description = err?.response?.body?.error?.message || err?.message || String(err); notification.error({ message: hasServerErrorMessage ? 'Please upgrade to add more users!' : 'Failed to generate user invitation!', description, duration: 10, // 10 seconds btn: ( <a href={ shouldDisplayBillingLink ? '/billing' : 'https://papercups.io/pricing' } > <Button type="primary" size="small"> Upgrade subscription </Button> </a> ), }); } }; focusAndHighlightInput = () => { if (!this.input) { return; } this.input.focus(); this.input.select(); if (document.queryCommandSupported('copy')) { document.execCommand('copy'); notification.open({ message: 'Copied to clipboard!', description: 'You can now paste your unique invitation URL to a teammate.', }); } }; handleChangeInviteUserEmail = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({inviteUserEmail: e.target.value}); }; handleDisableUser = async ({id: userId}: User) => { this.setState({isRefreshing: true}); return API.disableAccountUser(userId) .then((user) => { notification.success({ message: 'Successfully disabled user!', description: `If this was a mistake, you can renable ${user.email} below.`, }); }) .then(() => sleep(400)) // Add slight delay so not too jarring .then(() => this.fetchLatestAccountInfo()) .catch((err) => { const description = err?.response?.body?.error?.message || err?.message || 'Something went wrong. Please contact us or try again in a few minutes.'; notification.error({ message: 'Failed to disable user!', description, }); }) .then(() => this.setState({isRefreshing: false})); }; handleUpdateRole = async ({id: userId}: User, role: 'user' | 'admin') => { this.setState({isRefreshing: true}); return API.setAccountUserRole(userId, role) .then((user) => { notification.success({ message: 'Successfully changed role!', description: `${user.email} is now ${ role === 'user' ? 'a team member' : 'an admin' }.`, }); }) .then(() => sleep(400)) // Add slight delay so not too jarring .then(() => this.fetchLatestAccountInfo()) .catch((err) => { const description = err?.response?.body?.error?.message || err?.message || 'Something went wrong. Please contact us or try again in a few minutes.'; notification.error({ message: 'Failed to update role!', description, }); }) .then(() => this.setState({isRefreshing: false})); }; handleEnableUser = async ({id: userId}: User) => { this.setState({isRefreshing: true}); return API.enableAccountUser(userId) .then((user) => { notification.success({ message: 'Successfully re-enabled user!', description: `If this was a mistake, you can disable ${user.email} above.`, }); }) .then(() => sleep(400)) // Add slight delay so not too jarring .then(() => this.fetchLatestAccountInfo()) .catch((err) => { const description = err?.response?.body?.error?.message || err?.message || 'Something went wrong. Please contact us or try again in a few minutes.'; notification.error({ message: 'Failed to enable user!', description, }); }) .then(() => this.setState({isRefreshing: false})); }; handleArchiveUser = async ({id: userId}: User) => { this.setState({isRefreshing: true}); return API.archiveAccountUser(userId) .then((user) => { notification.success({ message: 'Successfully archived user!', description: `If this was a mistake, please notify us and we will reverse the action.`, }); }) .then(() => sleep(400)) // Add slight delay so not too jarring .then(() => this.fetchLatestAccountInfo()) .catch((err) => { const description = err?.response?.body?.error?.message || err?.message || 'Something went wrong. Please contact us or try again in a few minutes.'; notification.error({ message: 'Failed to archive user!', description, }); }) .then(() => this.setState({isRefreshing: false})); }; handleClickOnInviteMoreLink = () => { this.setState({showInviteMoreInput: true}); }; render() { const { account, currentUser, inviteUrl, inviteUserEmail, isLoading, isRefreshing, showInviteMoreInput, } = this.state; if (isLoading) { return ( <Flex sx={{ flex: 1, justifyContent: 'center', alignItems: 'center', height: '100%', }} > <Spinner size={40} /> </Flex> ); } else if (!account || !currentUser) { return null; } const {users = []} = account; const isAdmin = this.hasAdminRole(); return ( <Container sx={{maxWidth: 960}}> <Box mb={4}> <Title level={3}>My Team</Title> </Box> {isAdmin && ( <> <Box mb={4}> <Title level={4}>Invite new teammate</Title> <Paragraph> <Text> Generate a unique invitation URL below and send it to your teammate. </Text> </Paragraph> <Flex sx={{maxWidth: 640}}> <Box mr={1}> <Button type="primary" onClick={this.handleGenerateInviteUrl}> Generate invite URL </Button> </Box> <Box sx={{flex: 1}}> <Input ref={(el) => (this.input = el)} type="text" placeholder="Click the button to generate an invite URL" disabled={!inviteUrl} value={inviteUrl} ></Input> </Box> </Flex> </Box> <Divider /> </> )} <Box mb={4}> <Title level={4}>Team</Title> <AccountUsersTable loading={isRefreshing} users={users.filter((u: User) => !u.disabled_at)} currentUser={currentUser} isAdmin={isAdmin} onDisableUser={this.handleDisableUser} onUpdateRole={this.handleUpdateRole} /> {isAdmin && isUserInvitationEmailEnabled && ( <Box mt={2}> {showInviteMoreInput ? ( <form onSubmit={this.handleSendInviteEmail}> <Flex sx={{maxWidth: 480}}> <Box mr={1} sx={{flex: 1}}> <Input onChange={this.handleChangeInviteUserEmail} placeholder="Email address" required type="email" value={inviteUserEmail} /> </Box> <Button type="primary" htmlType="submit"> Send invite </Button> </Flex> </form> ) : ( <Button type="primary" onClick={this.handleClickOnInviteMoreLink} > Invite teammate </Button> )} </Box> )} </Box> {isAdmin && ( <Box mb={4}> <Title level={4}>Disabled users</Title> <DisabledUsersTable loading={isRefreshing} users={users.filter((u: User) => !!u.disabled_at)} isAdmin={isAdmin} onEnableUser={this.handleEnableUser} onArchiveUser={this.handleArchiveUser} /> </Box> )} </Container> ); } } export default TeamOverview;
the_stack
import * as React from 'react'; import * as networking from '../../utils/networking'; import { SelectDataModelComponent } from './SelectDataModelComponent'; export interface IExternalApiComponentProps { connectionId: any; dataModelElements: any; connection: any; selectedApiDef: any; componentApiResponseMappingsById: any; componentApiResponseMappingsAllIds: any[]; addMapping: () => void; handleMappingChange: (id: any, name: string, e: any) => void; removeMapping: (id: any) => void; handleClientParamsChange: (name: any, value: any) => void; handleMetaParamsChange: (e: any) => void; language: any; } export interface IExternalApiComponentState { apiResponse: any; formDataApiTest: any; } export class ExternalApiComponent extends React.Component<IExternalApiComponentProps, IExternalApiComponentState> { constructor(_props: IExternalApiComponentProps, _state: IExternalApiComponentState) { super(_props, _state); this.state = { apiResponse: null, formDataApiTest: null, }; } public componentDidMount() { const { clientParams, metaParams } = this.props.connection; const formData: any = {}; if (clientParams) { for (const key of Object.keys(clientParams)) { formData[key] = clientParams[key]; } } if (metaParams) { for (const key of Object.keys(metaParams)) { formData[key] = metaParams[key]; } } this.setState((prevState) => { return { ...prevState, formDataApiTest: formData, }; }); } public handleformDataChange = (e: any): void => { const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value; const name = e.target.name; this.setState({ formDataApiTest: { ...this.state.formDataApiTest, [name]: value, }, }); } public handleClientParamsChange = (e: any): void => { const name = e.target.name; const value = e.target.value; this.handleformDataChange(e); this.props.handleClientParamsChange(name, value); } public handleMetaParamsChange = (e: any): void => { this.handleformDataChange(e); this.props.handleMetaParamsChange(e); } public triggerApi = (e: any) => { let uri: string = this.props.selectedApiDef.uri; // Insert client params from form Object.keys(this.state.formDataApiTest).forEach((key) => { uri += `${key}=${this.state.formDataApiTest[key]}&`; }); // Insert meta params from "connection" Object.keys(this.props.connection.metaParams).forEach((key) => { this.props.selectedApiDef.metaParams[key].urlEncode === true ? uri += `${key}=${encodeURI(this.props.connection.metaParams[key])}&` : uri += `${key}=${this.props.connection.metaParams[key]}&`; }); networking.get(uri) .then((response) => { this.setState( { apiResponse: response }, ); }) .catch((error) => { this.setState( { apiResponse: error }, ); }); } public fetchFromApiButton = (): JSX.Element => { let checkForFetch: boolean = false; let readyToFetch: boolean = false; const { clientParams, metaParams } = this.props.selectedApiDef; const mandatoryClientParams: any = Object.keys(clientParams).filter( (key) => clientParams[key].required === true); const mandatoryMetaParams: any = Object.keys(metaParams).filter( (key) => metaParams[key].required === true); const mandatoryParams: any = mandatoryClientParams.concat(mandatoryMetaParams); this.state.formDataApiTest ? checkForFetch = true : checkForFetch = false; if (checkForFetch === true) { const insertedRequiredParams: any = mandatoryParams.filter( (param: any) => this.state.formDataApiTest[param] !== '' && Object.keys(this.state.formDataApiTest).length >= mandatoryParams.length); insertedRequiredParams.length >= mandatoryParams.length ? readyToFetch = true : readyToFetch = false; } return ( <> <div className='mt-2'> {readyToFetch === true ? <button type='button' className='a-btn a-btn-success' onClick={this.triggerApi} > Fetch from API using parameters </button> : <button type='button' className='a-btn disabled' disabled={true} > One or more client params is missing to fetch from API. </button> } </div> </> ); } public renderClientParams = (clientParams: any, clientParamValues: any): JSX.Element => { if (!clientParams || Object.keys(clientParams).length === 0) { return null; } const selectedDataModelElement = !clientParamValues ? '' : clientParamValues; return ( <div> {Object.keys(clientParams).map((key) => { return ( <div className='form-group a-form-group mt-2' key={key}> <h2 className='a-h4'> ClientParam: {clientParams[key].name} </h2> <div className='align-items-center row mt-1'> <div className='col-12 col'> <label className='a-form-label' htmlFor={clientParams[key].name}> Enter for API test: </label> <input id={clientParams[key].name} name={clientParams[key].name} type='text' className='form-control' width={10} placeholder={clientParams[key].example} onChange={this.handleformDataChange} required={true} /> </div> </div> <div className='align-items-center row mt-1'> <div className='col-12 col'> <SelectDataModelComponent onDataModelChange={this.props.handleClientParamsChange.bind(null, clientParams[key].name)} selectedElement={selectedDataModelElement[key]} hideRestrictions={true} language={this.props.language} /> </div> </div> </div> ); })} </div> ); } public renderMetaParams = (metaParams: any, metaParamValues: any): JSX.Element => { return ( <div> {Object.keys(metaParams).map((key) => { return ( <div className='form-group a-form-group mt-2' key={key}> <h2 className='a-h4'> MetaParam: {metaParams[key].name} </h2> <div className='align-items-center row mt-1'> <div className='col-12 col'> <label className='a-form-label' htmlFor={metaParams[key].name}> Enter metaparam: </label> <input id={metaParams[key].name} name={metaParams[key].name} type='text' className='form-control' width={10} placeholder={metaParams[key].example} onChange={this.handleMetaParamsChange} value={!metaParamValues ? '' : metaParamValues[metaParams[key].name]} /> </div> </div> </div> ); })} </div> ); } public renderMappingView = (apiResponse: any, id: any, codelist: boolean = false): JSX.Element => { const resultObject = this.props.componentApiResponseMappingsById[id].resultObject; const valueKey = this.props.componentApiResponseMappingsById[id].valueKey; const labelKey = this.props.componentApiResponseMappingsById[id].labelKey; return ( <div> <div className='row'> <div className='col-6 col'> <label>Object</label> <select name='resultObject' onChange={this.props.handleMappingChange.bind(null, id, 'resultObject')} value={resultObject} className='custom-select a-custom-select' > <option value={''}>Velg objekt:</option> {apiResponse ? Object.keys(apiResponse).map((key) => { return ( <option key={key} value={key} >{key}</option> ); }) : <option value={''}>{'Ingen objekter å presentere...'}</option> } </select> </div> <div className='col-6 form-group a-form-group disabled'> <label>Result</label> <input type='text' placeholder={JSON.stringify(resultObject)} className='form-control' disabled={true} /> </div> </div> {this.props.selectedApiDef && this.props.selectedApiDef.type === 'list' ? <div className='row'> <div className='col-6 col'> <label>Value key</label> <select name='valueKey' onChange={this.props.handleMappingChange.bind(null, id, 'valueKey')} value={valueKey} className='custom-select a-custom-select' > <option value={''}>Choose code key</option> {resultObject && apiResponse[resultObject] && apiResponse[resultObject].length > 0 ? Object.keys(apiResponse[resultObject][0]).map((key: any) => { return ( <option key={key} value={key}>{key}</option> ); }) : <option value={''}>{'Ingen objekter å presentere...'}</option> } </select> </div> <div className='col-6 col'> <label>Label key</label> <select name='labelKey' onChange={this.props.handleMappingChange.bind(null, id, 'labelKey')} value={labelKey} className='custom-select a-custom-select' > <option value={''}>Choose label key</option> {resultObject && apiResponse[resultObject] && apiResponse[resultObject].length > 0 ? Object.keys(apiResponse[resultObject][0]).map((key: any) => { return ( <option key={key} value={key}>{key}</option> ); }) : <option value={''}>{'Ingen objekter å presentere...'}</option> } </select> </div> </div> : null } </div> ); } public renderExternalAPIView = (): JSX.Element => { const { apiResponse } = this.state; const { metaParams, clientParams } = this.props.connection; return ( <div> {/* If API is selected */} {this.props.connection.externalApiId ? <> {/* TEST API SECTION. Mapping through all parameters */} <> {/* Client Parameters */} {this.renderClientParams(this.props.selectedApiDef.clientParams, clientParams)} {/* Meta Parameters */} {this.renderMetaParams(this.props.selectedApiDef.metaParams, metaParams)} {/* Fetch test response from API */} <this.fetchFromApiButton /> <div className='form-group a-form-group mt-2'> <label className='a-form-label' htmlFor='exampleText'>API Response</label> <textarea name='text' id='exampleText' className='form-control a-textarea' value={JSON.stringify(this.state.apiResponse, null, 2)} readOnly={true} rows={10} /> </div> {apiResponse ? ( <div className='form-group a-form-group mt-2'> <div className='row align-items-center'> <div className='col-12'> <label className='a-form-label'> Mappings </label> </div> </div> {this.props.componentApiResponseMappingsAllIds.map((id: any) => { return ( <div className='form-group a-form-group mb-2' key={id}> <div className='align-items-center row a-btn-action'> <div className='col-10'> {this.renderMappingView(apiResponse, id)} <div className='row'> <div className='col-12'> <SelectDataModelComponent onDataModelChange={this.props.handleMappingChange.bind(null, id, 'mappingObject')} selectedElement={this.props.componentApiResponseMappingsById[id].mappingObject} hideRestrictions={true} language={this.props.language} /> </div> </div> </div> <div className='col-2'> <button type='button' className='a-btn a-btn-icon' onClick={this.props.removeMapping.bind(null, id)} > <i className='fa fa-circle-exit a-danger ai-left' /> </button> </div> </div> </div> ); })} <div className='align-items-center row'> <div className='col-6 col'> <button type='button' className='a-btn' onClick={this.props.addMapping} > Add new mapping </button> </div> </div> </div> ) : <div id='alert' className='a-message a-message--arrow-off a-message-info mb-1' role='alert'> Fetch from API to configure API response mapping. </div> } </> </> : // API ikke valgt null } </div> ); } public render(): JSX.Element { return (this.renderExternalAPIView()); } }
the_stack
import {ErrorWithCode} from 'app/common/ErrorWithCode'; import {timeFormat} from 'app/common/timeFormat'; import * as docUtils from 'app/server/lib/docUtils'; import * as log from 'app/server/lib/log'; import {fromCallback} from 'app/server/lib/serverUtils'; import * as sqlite3 from '@gristlabs/sqlite3'; import * as assert from 'assert'; import {each} from 'bluebird'; import * as fse from 'fs-extra'; import fromPairs = require('lodash/fromPairs'); import isEqual = require('lodash/isEqual'); import noop = require('lodash/noop'); import range = require('lodash/range'); // Describes the result of get() and all() database methods. export interface ResultRow { [column: string]: any; } // Describes how to create a new DB or migrate an old one. Any changes to the DB must be reflected // in the 'create' function, and added as new entries in the 'migrations' array. Existing // 'migration' entries may not be modified; they are used to migrate older DBs. export interface SchemaInfo { // Creates a structure for a new DB (i.e. execs CREATE TABLE statements). readonly create: DBFunc; // List of functions that perform DB migrations from one version to the next. This array's // length determines the schema version, which is stored in user_version SQLite property. // // The very first migration should normally be identical to the original version of create(). // I.e. initially SchemaInfo should be { create: X, migrations: [X] }, where the two X's // represent two copies of the same code. Don't go for code reuse here. When the schema is // modified, you will change it to { create: X2, migrations: [X, Y] }. Keeping the unchanged // copy of X is important as a reference to see that X + Y produces the same DB as X2. // // If you may open DBs created without versioning (e.g. predate use of this module), such DBs // will go through all migrations including the very first one. In this case, the first // migration's job is to bring any older DB to the same consistent state. readonly migrations: ReadonlyArray<DBFunc>; } export type DBFunc = (db: SQLiteDB) => Promise<void>; export enum OpenMode { OPEN_CREATE, // Open DB or create if doesn't exist (the default mode for sqlite3 module) OPEN_EXISTING, // Open DB or fail if doesn't exist OPEN_READONLY, // Open DB in read-only mode or fail if doens't exist. CREATE_EXCL, // Create new DB or fail if it already exists. } /** * Callbacks to use if a migration is run, so that backups are made. */ export interface MigrationHooks { beforeMigration?(currentVersion: number, newVersion: number): Promise<void>; afterMigration?(newVersion: number, success: boolean): Promise<void>; } /** * An interface implemented both by SQLiteDB and DocStorage (by forwarding). Methods * documented in SQLiteDB. */ export interface ISQLiteDB { exec(sql: string): Promise<void>; run(sql: string, ...params: any[]): Promise<void>; get(sql: string, ...params: any[]): Promise<ResultRow|undefined>; all(sql: string, ...params: any[]): Promise<ResultRow[]>; prepare(sql: string, ...params: any[]): Promise<sqlite3.Statement>; execTransaction<T>(callback: () => Promise<T>): Promise<T>; runAndGetId(sql: string, ...params: any[]): Promise<number>; requestVacuum(): Promise<boolean>; } /** * Wrapper around sqlite3.Database. This class provides many of the same methods, but promisified. * In addition, it offers: * * SQLiteDB.openDB(): Opens a DB, and initialize or migrate it to correct schema. * db.execTransaction(cb): Runs a callback in the context of a new DB transaction. */ export class SQLiteDB { /** * Opens a database or creates a new one, according to OpenMode enum. The schemaInfo specifies * how to initialize a new database, and how to migrate an existing one from an older version. * If the database was migrated, its "migrationBackupPath" property will be set. * * If a migration was needed but failed, the DB remains unchanged, and gets opened anyway. * We report the migration error, and expose it via .migrationError property. */ public static async openDB(dbPath: string, schemaInfo: SchemaInfo, mode: OpenMode = OpenMode.OPEN_CREATE, hooks: MigrationHooks = {}): Promise<SQLiteDB> { const db = await SQLiteDB.openDBRaw(dbPath, mode); const userVersion: number = await db.getMigrationVersion(); // It's possible that userVersion is 0 for a non-empty DB if it was created without this // module. In that case, we apply migrations starting with the first one. if (userVersion === 0 && (await isEmpty(db))) { await db._initNewDB(schemaInfo); } else if (mode === OpenMode.CREATE_EXCL) { await db.close(); throw new ErrorWithCode('EEXISTS', `EEXISTS: Database already exists: ${dbPath}`); } else { // Don't attempt migrations in OPEN_READONLY mode. if (mode === OpenMode.OPEN_READONLY) { const targetVer: number = schemaInfo.migrations.length; if (userVersion < targetVer) { db._migrationError = new Error(`SQLiteDB[${dbPath}] needs migration but is readonly`); } } else { try { db._migrationBackupPath = await db._migrate(userVersion, schemaInfo, hooks); } catch (err) { db._migrationError = err; } } await db._reportSchemaDiscrepancies(schemaInfo); } return db; } /** * Opens a database or creates a new one according to OpenMode value. Does not check for or do * any migrations. */ public static async openDBRaw(dbPath: string, mode: OpenMode = OpenMode.OPEN_CREATE): Promise<SQLiteDB> { const sqliteMode: number = // tslint:disable-next-line:no-bitwise (mode === OpenMode.OPEN_READONLY ? sqlite3.OPEN_READONLY : sqlite3.OPEN_READWRITE) | (mode === OpenMode.OPEN_CREATE || mode === OpenMode.CREATE_EXCL ? sqlite3.OPEN_CREATE : 0); let _db: sqlite3.Database; await fromCallback(cb => { _db = new sqlite3.Database(dbPath, sqliteMode, cb); }); if (SQLiteDB._addOpens(dbPath, 1) > 1) { log.warn("SQLiteDB[%s] avoid opening same DB more than once", dbPath); } return new SQLiteDB(_db!, dbPath); } /** * Reads the migration version from the database without any attempts to migrate it. */ public static async getMigrationVersion(dbPath: string): Promise<number> { const db = await SQLiteDB.openDBRaw(dbPath, OpenMode.OPEN_READONLY); try { return await db.getMigrationVersion(); } finally { await db.close(); } } // It is a bad idea to open the same database file multiple times, because simultaneous use can // cause SQLITE_BUSY errors, and artificial delays (default of 1 sec) when there is contention. // We keep track of open DB paths, and warn if one is opened multiple times. private static _openPaths: Map<string, number> = new Map(); // Convert the "create" function from schemaInfo into a DBMetadata object that describes the // tables, columns, and types. This is used for checking if an open database matches the // schema we expect, including after a migration, and reporting discrepancies. private static async _getExpectedMetadata(schemaInfo: SchemaInfo): Promise<DBMetadata> { // We cache the result and associate it with the create function, since it's not that cheap to // build. To build the metadata, we open an in-memory DB and apply "create" function to it. // Note that for tiny DBs it takes <10ms. if (!dbMetadataCache.has(schemaInfo.create)) { const db = await SQLiteDB.openDB(':memory:', schemaInfo, OpenMode.CREATE_EXCL); dbMetadataCache.set(schemaInfo.create, await db.collectMetadata()); await db.close(); } return dbMetadataCache.get(schemaInfo.create)!; } // Private helper to keep track of opens for the same path. Returns the number of times this // path is open, after adding the delta. Use delta of +1 for open, -1 for close. private static _addOpens(dbPath: string, delta: number): number { const newCount = (SQLiteDB._openPaths.get(dbPath) || 0) + delta; if (newCount > 0) { SQLiteDB._openPaths.set(dbPath, newCount); } else { SQLiteDB._openPaths.delete(dbPath); } return newCount; } private _prevTransaction: Promise<any> = Promise.resolve(); private _inTransaction: boolean = false; private _migrationBackupPath: string|null = null; private _migrationError: Error|null = null; private _needVacuum: boolean = false; private constructor(private _db: sqlite3.Database, private _dbPath: string) { // Default database to serialized execution. See https://github.com/mapbox/node-sqlite3/wiki/Control-Flow // This isn't enough for transactions, which we serialize explicitly. this._db.serialize(); } /** * If a DB was migrated on open, this will be set to the path of the pre-migration backup copy. * If migration failed, open throws with unchanged DB and no backup file. */ public get migrationBackupPath(): string|null { return this._migrationBackupPath; } /** * If a needed migration failed, the DB will be opened anyway, with this property set to the * error. E.g. you may use it like so: * sdb = await SQLiteDB.openDB(...) * if (sdb.migrationError) { throw sdb.migrationError; } */ public get migrationError(): Error|null { return this._migrationError; } // The following methods mirror https://github.com/mapbox/node-sqlite3/wiki/API, but return // Promises. We use fromCallback() rather than use promisify, to get better type-checking. public exec(sql: string): Promise<void> { return fromCallback(cb => this._db.exec(sql, cb)); } public run(sql: string, ...params: any[]): Promise<void> { return fromCallback(cb => this._db.run(sql, ...params, cb)); } public get(sql: string, ...params: any[]): Promise<ResultRow|undefined> { return fromCallback(cb => this._db.get(sql, ...params, cb)); } public all(sql: string, ...params: any[]): Promise<ResultRow[]> { return fromCallback(cb => this._db.all(sql, ...params, cb)); } public allMarshal(sql: string, ...params: any[]): Promise<Buffer> { // allMarshal isn't in the typings, because it is our addition to our fork of sqlite3 JS lib. return fromCallback(cb => (this._db as any).allMarshal(sql, ...params, cb)); } public prepare(sql: string, ...params: any[]): Promise<sqlite3.Statement> { let stmt: sqlite3.Statement; // The original interface is a little strange; we resolve to Statement if prepare() succeeded. return fromCallback(cb => { stmt = this._db.prepare(sql, ...params, cb); }).then(() => stmt); } /** * VACUUM the DB either immediately or, if in a transaction, after that transaction. */ public async requestVacuum(): Promise<boolean> { if (this._inTransaction) { this._needVacuum = true; return false; } await this.exec("VACUUM"); log.info("SQLiteDB[%s]: DB VACUUMed", this._dbPath); this._needVacuum = false; return true; } /** * Run each of the statements in turn. Each statement is either a string, or an array of arguments * to db.run, e.g. [sqlString, [params...]]. */ public runEach(...statements: Array<string | [string, any[]]>): Promise<void> { return each(statements, (stmt: any) => { return (Array.isArray(stmt) ? this.run(stmt[0], ...stmt[1]) : this.exec(stmt)) .catch(err => { log.warn(`SQLiteDB: Failed to run ${stmt}`); throw err; }); }); } public close(): Promise<void> { return fromCallback(cb => this._db.close(cb)) .then(() => { SQLiteDB._addOpens(this._dbPath, -1); }); } /** * As for run(), but captures the last_insert_rowid after the statement executes. This * is sqlite's rowid for the last insert made on this database connection. This method * is only useful if the sql is actually an INSERT operation, but we don't check this. */ public runAndGetId(sql: string, ...params: any[]): Promise<number> { return new Promise<number>((resolve, reject) => { this._db.run(sql, ...params, function(this: any, err: any) { if (err) { reject(err); } else { resolve(this.lastID); } }); }); } /** * Runs callback() in the context of a new DB transaction, committing on success and rolling * back on error in the callback. The callback may return a promise, which will be waited for. * The callback is called with no arguments. * * This method can be nested. The result is one big merged transaction that will succeed or * roll back as a single unit. */ public async execTransaction<T>(callback: () => Promise<T>): Promise<T> { if (this._inTransaction) { return callback(); } let outerResult; try { outerResult = await (this._prevTransaction = this._execTransactionImpl(async () => { this._inTransaction = true; let innerResult; try { innerResult = await callback(); } finally { this._inTransaction = false; } return innerResult; })); } finally { if (this._needVacuum) { await this.requestVacuum(); } } return outerResult; } /** * Returns the 'user_version' saved in the database that reflects the current DB schema. It is 0 * initially, and we update it to 1 or higher when initializing or migrating the database. */ public async getMigrationVersion(): Promise<number> { const row = await this.get("PRAGMA user_version"); return (row && row.user_version) || 0; } /** * Creates a DBMetadata object mapping DB's table names to column names to column types. Used * for reporting discrepancies in DB schema, and exposed for tests. * * Optionally, a list of table names can be supplied, and metadata will be omitted for any * tables not named in that list. */ public async collectMetadata(names?: string[]): Promise<DBMetadata> { const tables = await this.all("SELECT name FROM sqlite_master WHERE type='table'"); const metadata: DBMetadata = {}; for (const t of tables) { if (names && !names.includes(t.name)) { continue; } const infoRows = await this.all(`PRAGMA table_info(${quoteIdent(t.name)})`); const columns = fromPairs(infoRows.map(r => [r.name, r.type])); metadata[t.name] = columns; } return metadata; } // Implementation of execTransction. private async _execTransactionImpl<T>(callback: () => Promise<T>): Promise<T> { // We need to swallow errors, so that one failed transaction doesn't cause the next one to fail. await this._prevTransaction.catch(noop); await this.exec("BEGIN"); try { const value = await callback(); await this.exec("COMMIT"); return value; } catch (err) { try { await this.exec("ROLLBACK"); } catch (rollbackErr) { log.error("SQLiteDB[%s]: Rollback failed: %s", this._dbPath, rollbackErr); } throw err; // Throw the original error from the transaction. } } /** * Applies schemaInfo.create function to initialize a new DB. */ private async _initNewDB(schemaInfo: SchemaInfo): Promise<void> { await this.execTransaction(async () => { const targetVer: number = schemaInfo.migrations.length; await schemaInfo.create(this); await this.exec(`PRAGMA user_version = ${targetVer}`); }); } /** * Applies migrations to this database according to MigrationInfo. In all cases, checks the * database schema against MigrationInfo.currentSchema, and warns of discrepancies. * * If migration succeeded, it leaves a backup file and returns its path. If no migration was * needed, returns null. If migration failed, leaves DB unchanged and throws Error. */ private async _migrate(actualVer: number, schemaInfo: SchemaInfo, hooks: MigrationHooks): Promise<string|null> { const targetVer: number = schemaInfo.migrations.length; let backupPath: string|null = null; let success: boolean = false; if (actualVer > targetVer) { log.warn("SQLiteDB[%s]: DB is at version %s ahead of target version %s", this._dbPath, actualVer, targetVer); } else if (actualVer < targetVer) { log.info("SQLiteDB[%s]: DB needs migration from version %s to %s", this._dbPath, actualVer, targetVer); const versions = range(actualVer, targetVer); backupPath = await createBackupFile(this._dbPath, actualVer); await hooks.beforeMigration?.(actualVer, targetVer); try { await this.execTransaction(async () => { for (const versionNum of versions) { await schemaInfo.migrations[versionNum](this); } await this.exec(`PRAGMA user_version = ${targetVer}`); }); success = true; // After a migration, reduce the sqlite file size. This must be run outside a transaction. await this.run("VACUUM"); log.info("SQLiteDB[%s]: DB backed up to %s, migrated to %s", this._dbPath, backupPath, targetVer); } catch (err) { // If the transaction failed, we trust SQLite to have left the DB in unmodified state, so // we remove the pointless backup. await fse.remove(backupPath); backupPath = null; log.warn("SQLiteDB[%s]: DB migration from %s to %s failed: %s", this._dbPath, actualVer, targetVer, err); err.message = `SQLiteDB[${this._dbPath}] migration to ${targetVer} failed: ${err.message}`; throw err; } finally { await hooks.afterMigration?.(targetVer, success); } } return backupPath; } private async _reportSchemaDiscrepancies(schemaInfo: SchemaInfo): Promise<void> { // Regardless of where we started, warn if DB doesn't match expected schema. const expected = await SQLiteDB._getExpectedMetadata(schemaInfo); const metadata = await this.collectMetadata(Object.keys(expected)); for (const tname in expected) { if (expected.hasOwnProperty(tname) && !isEqual(metadata[tname], expected[tname])) { log.warn("SQLiteDB[%s]: table %s does not match schema: %s != %s", this._dbPath, tname, JSON.stringify(metadata[tname]), JSON.stringify(expected[tname])); } } } } // Every SchemaInfo.create function determines a DB structure. We can get it by initializing a // dummy DB, and we use it to do sanity checking, in particular after migrations. To avoid // creating dummy DBs multiple times, the result is cached, keyed by the "create" function itself. const dbMetadataCache: Map<DBFunc, DBMetadata> = new Map(); interface DBMetadata { [tableName: string]: { [colName: string]: string; // Maps column name to SQLite type, e.g. "TEXT". }; } // Helper to see if a database is empty. async function isEmpty(db: SQLiteDB): Promise<boolean> { return (await db.get("SELECT count(*) as count FROM sqlite_master"))!.count === 0; } /** * Copies filePath to "filePath.YYYY-MM-DD.V0[-N].bak", adding "-N" suffix (starting at "-2") if * needed to ensure the path is new. Returns the backup path. */ async function createBackupFile(filePath: string, versionNum: number): Promise<string> { const backupPath = await docUtils.createNumberedTemplate( `${filePath}.${timeFormat('D', new Date())}.V${versionNum}{NUM}.bak`, docUtils.createExclusive); await docUtils.copyFile(filePath, backupPath); return backupPath; } /** * Validate and quote SQL identifiers such as table and column names. */ export function quoteIdent(ident: string): string { assert(/^[\w.]+$/.test(ident), `SQL identifier is not valid: ${ident}`); return `"${ident}"`; }
the_stack
import { applyPatches, getSnapshot, idProp, model, Model, modelAction, modelIdKey, onPatches, Patch, prop, registerRootStore, runUnprotected, unregisterRootStore, } from "../../src" import "../commonSetup" import { createP } from "../testbed" import { autoDispose } from "../utils" describe("onPatches and applyPatches", () => { function setup(withArray = false) { const p = createP(withArray) const sn = getSnapshot(p) const pPatches: Patch[][] = [] const pInvPatches: Patch[][] = [] autoDispose( onPatches(p, (ptchs, iptchs) => { pPatches.push(ptchs) pInvPatches.push(iptchs) }) ) const p2Patches: Patch[][] = [] const p2InvPatches: Patch[][] = [] autoDispose( onPatches(p.p2!, (ptchs, iptchs) => { p2Patches.push(ptchs) p2InvPatches.push(iptchs) }) ) function expectSameSnapshotOnceReverted() { runUnprotected(() => { pInvPatches .slice() .reverse() .forEach((invpatches) => applyPatches(p, invpatches, true)) }) expect(getSnapshot(p)).toStrictEqual(sn) } return { p, sn, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted, } } test("no changes should result in no patches", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches } = setup(true) runUnprotected(() => { p.x = p.x // eslint-disable-line no-self-assign p.arr[0] = p.arr[0] // eslint-disable-line no-self-assign p.p2!.y = p.p2!.y }) expect(pPatches).toMatchInlineSnapshot(`Array []`) expect(pInvPatches).toMatchInlineSnapshot(`Array []`) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) }) test("increment numbers", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup() runUnprotected(() => { p.x++ p.p2!.y++ }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "x", ], "value": 6, }, ], Array [ Object { "op": "replace", "path": Array [ "p2", "y", ], "value": 13, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "x", ], "value": 5, }, ], Array [ Object { "op": "replace", "path": Array [ "p2", "y", ], "value": 12, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "y", ], "value": 13, }, ], ] `) expect(p2InvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "y", ], "value": 12, }, ], ] `) expectSameSnapshotOnceReverted() }) test("remove subobj", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup() runUnprotected(() => { p.p2 = undefined }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "p2", ], "value": undefined, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "p2", ], "value": Object { "$modelId": "id-1", "$modelType": "P2", "y": 12, }, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("swap items around", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr = [3, 2, 1] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", ], "value": Array [ 3, 2, 1, ], }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", ], "value": Array [ 1, 2, 3, ], }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("splice items (less items)", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.splice(1, 2, 5) // [1, 5] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 1, }, Object { "op": "add", "path": Array [ "arr", 1, ], "value": 5, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 2, ], "value": 3, }, Object { "op": "add", "path": Array [ "arr", 1, ], "value": 2, }, Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 1, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("splice items (more items)", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.splice(1, 2, 5, 6, 7) // [1, 5, 6, 7] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 1, }, Object { "op": "add", "path": Array [ "arr", 1, ], "value": 5, }, Object { "op": "add", "path": Array [ "arr", 2, ], "value": 6, }, Object { "op": "add", "path": Array [ "arr", 3, ], "value": 7, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 2, ], "value": 3, }, Object { "op": "add", "path": Array [ "arr", 1, ], "value": 2, }, Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 1, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("splice items (same items)", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.splice(1, 2, 5, 3) // [1, 5, 3] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", 1, ], "value": 5, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", 1, ], "value": 2, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("splice one in the middle", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.splice(1, 1) // [1, 3] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "remove", "path": Array [ "arr", 1, ], }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 1, ], "value": 2, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("splice items at the end that do not exist", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.splice(3, 2, 5) // [1, 2, 3, 5] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 3, ], "value": 5, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 3, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("splice items over the end that do not exist", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.splice(8, 2, 5) // [1, 2, 3, 5] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 3, ], "value": 5, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 3, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("unshift items", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.unshift(10, 11) // [10, 11, 1, 2, 3] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 0, ], "value": 10, }, Object { "op": "add", "path": Array [ "arr", 1, ], "value": 11, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "remove", "path": Array [ "arr", 0, ], }, Object { "op": "remove", "path": Array [ "arr", 1, ], }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("unshift items (empty array)", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(false) runUnprotected(() => { p.arr.unshift(10, 11) // [10, 11] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 0, ], "value": 10, }, Object { "op": "add", "path": Array [ "arr", 1, ], "value": 11, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 0, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("push items", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(true) runUnprotected(() => { p.arr.push(10, 11) // [1, 2, 3, 10, 11] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 3, ], "value": 10, }, Object { "op": "add", "path": Array [ "arr", 4, ], "value": 11, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 3, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) test("push items (empty array)", () => { const { p, pPatches, pInvPatches, p2Patches, p2InvPatches, expectSameSnapshotOnceReverted } = setup(false) runUnprotected(() => { p.arr.push(10, 11) // [10, 11] }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "arr", 0, ], "value": 10, }, Object { "op": "add", "path": Array [ "arr", 1, ], "value": 11, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "arr", "length", ], "value": 0, }, ], ] `) expect(p2Patches).toMatchInlineSnapshot(`Array []`) expect(p2InvPatches).toMatchInlineSnapshot(`Array []`) expectSameSnapshotOnceReverted() }) }) test("patches with reserved prop names", () => { @model("test/patchesWithReservedPropNames") class M extends Model({ [modelIdKey]: idProp, onInit: prop(4), }) { @modelAction setOnInit(n: number) { this.$.onInit = n } } const p = new M({}) const sn = getSnapshot(p) const pPatches: Patch[][] = [] const pInvPatches: Patch[][] = [] autoDispose( onPatches(p, (ptchs, iptchs) => { pPatches.push(ptchs) pInvPatches.push(iptchs) }) ) function reset() { pPatches.length = 0 pInvPatches.length = 0 } function expectSameSnapshotOnceReverted() { runUnprotected(() => { pInvPatches .slice() .reverse() .forEach((invpatches) => applyPatches(p, invpatches, true)) }) expect(getSnapshot(p)).toStrictEqual(sn) } // no changes should result in no patches reset() runUnprotected(() => { p.$.onInit = p.$.onInit + 0 }) expect(pPatches).toMatchInlineSnapshot(`Array []`) expect(pInvPatches).toMatchInlineSnapshot(`Array []`) reset() runUnprotected(() => { p.$.onInit++ }) expect(pPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "onInit", ], "value": 5, }, ], ] `) expect(pInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "onInit", ], "value": 4, }, ], ] `) expectSameSnapshotOnceReverted() }) test("patches with action in onAttachedToRootStore", () => { @model("test/patchesWithActionInOnAttachedToRootStore/M") class M extends Model({ [modelIdKey]: idProp, value: prop<number>(0), }) { onAttachedToRootStore() { this.setValue(1) } @modelAction setValue(value: number) { this.value = value } } @model("test/patchesWithActionInOnAttachedToRootStore/R") class R extends Model({ [modelIdKey]: idProp, ms: prop<M[]>(() => []), }) { @modelAction addM(m: M) { this.ms.push(m) } } const r = new R({}) autoDispose(() => unregisterRootStore(r)) registerRootStore(r) const sn = getSnapshot(r) const rPatches: Patch[][] = [] const rInvPatches: Patch[][] = [] autoDispose( onPatches(r, (ptchs, iptchs) => { rPatches.push(ptchs) rInvPatches.push(iptchs) }) ) expect(rPatches).toMatchInlineSnapshot(`Array []`) expect(rInvPatches).toMatchInlineSnapshot(`Array []`) r.addM(new M({})) expect(rPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "add", "path": Array [ "ms", 0, ], "value": Object { "$modelId": "id-2", "$modelType": "test/patchesWithActionInOnAttachedToRootStore/M", "value": 0, }, }, ], Array [ Object { "op": "replace", "path": Array [ "ms", 0, "value", ], "value": 1, }, ], ] `) expect(rInvPatches).toMatchInlineSnapshot(` Array [ Array [ Object { "op": "replace", "path": Array [ "ms", "length", ], "value": 0, }, ], Array [ Object { "op": "replace", "path": Array [ "ms", 0, "value", ], "value": 0, }, ], ] `) runUnprotected(() => { rInvPatches .slice() .reverse() .forEach((invpatches) => applyPatches(r, invpatches, true)) }) expect(getSnapshot(r)).toStrictEqual(sn) })
the_stack
import fs from 'fs-extra'; import R from 'ramda'; import AbstractConfig from './abstract-config'; import { Compilers, Testers } from './abstract-config'; import { BitConfigNotFound, InvalidBitJson, InvalidPackageJson } from './exceptions'; import { DEFAULT_COMPONENTS_DIR_PATH, DEFAULT_DEPENDENCIES_DIR_PATH, DEFAULT_PACKAGE_MANAGER, DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS } from '../../constants'; import filterObject from '../../utils/filter-object'; import { PathOsBasedAbsolute, PathOsBased } from '../../utils/path'; import logger from '../../logger/logger'; import { isValidPath } from '../../utils'; import InvalidConfigPropPath from './exceptions/invalid-config-prop-path'; import ConsumerOverrides from './consumer-overrides'; import InvalidPackageManager from './exceptions/invalid-package-manager'; import { ExtensionDataList } from './extension-data'; import { ResolveModulesConfig } from '../component/dependencies/files-dependency-builder/types/dependency-tree-type'; import { ILegacyWorkspaceConfig, PackageManagerClients } from './legacy-workspace-config-interface'; const DEFAULT_USE_WORKSPACES = false; const DEFAULT_MANAGE_WORKSPACES = true; export type WorkspaceConfigIsExistFunction = (dirPath: string | PathOsBased) => Promise<boolean | undefined>; export type WorkspaceConfigLoadFunction = ( dirPath: string | PathOsBased ) => Promise<ILegacyWorkspaceConfig | undefined>; export type WorkspaceConfigEnsureFunction = ( dirPath: PathOsBasedAbsolute, standAlone: boolean, workspaceConfigProps: WorkspaceConfigProps ) => Promise<ILegacyWorkspaceConfig>; export type WorkspaceConfigProps = { compiler?: string | Compilers; tester?: string | Testers; saveDependenciesAsComponents?: boolean; lang?: string; distTarget?: string | undefined; distEntry?: string | undefined; componentsDefaultDirectory?: string; dependenciesDirectory?: string; bindingPrefix?: string; extensions?: ExtensionDataList; packageManager?: PackageManagerClients; packageManagerArgs?: string[]; packageManagerProcessOptions?: Record<string, any>; useWorkspaces?: boolean; manageWorkspaces?: boolean; resolveModules?: ResolveModulesConfig; defaultScope?: string; overrides?: ConsumerOverrides; }; export default class WorkspaceConfig extends AbstractConfig { distTarget: string | undefined; // path where to store build artifacts // path to remove while storing build artifacts. If, for example the code is in 'src' directory, and the component // is-string is in src/components/is-string, the dists files will be in dists/component/is-string (without the 'src') distEntry: string | undefined; componentsDefaultDirectory: string; dependenciesDirectory: string; saveDependenciesAsComponents: boolean; // save hub dependencies as bit components rather than npm packages packageManager: PackageManagerClients; packageManagerArgs: string[] | undefined; // package manager client to use packageManagerProcessOptions: Record<string, any> | undefined; // package manager process options useWorkspaces: boolean; // Enables integration with Yarn Workspaces manageWorkspaces: boolean; // manage workspaces with yarn resolveModules: ResolveModulesConfig | undefined; overrides: ConsumerOverrides; packageJsonObject: Record<string, any> | null | undefined; // workspace package.json if exists (parsed) defaultScope: string | undefined; // default remote scope to export to static workspaceConfigIsExistRegistry: WorkspaceConfigIsExistFunction; static registerOnWorkspaceConfigIsExist(func: WorkspaceConfigIsExistFunction) { this.workspaceConfigIsExistRegistry = func; } static workspaceConfigLoadingRegistry: WorkspaceConfigLoadFunction; static registerOnWorkspaceConfigLoading(func: WorkspaceConfigLoadFunction) { this.workspaceConfigLoadingRegistry = func; } static workspaceConfigEnsuringRegistry: WorkspaceConfigEnsureFunction; static registerOnWorkspaceConfigEnsuring(func: WorkspaceConfigEnsureFunction) { this.workspaceConfigEnsuringRegistry = func; } constructor({ compiler, tester, saveDependenciesAsComponents = DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS, lang, distTarget, distEntry, componentsDefaultDirectory = DEFAULT_COMPONENTS_DIR_PATH, dependenciesDirectory = DEFAULT_DEPENDENCIES_DIR_PATH, bindingPrefix, extensions, packageManager = DEFAULT_PACKAGE_MANAGER, packageManagerArgs, packageManagerProcessOptions, useWorkspaces = DEFAULT_USE_WORKSPACES, manageWorkspaces = DEFAULT_MANAGE_WORKSPACES, resolveModules, defaultScope, overrides = ConsumerOverrides.load() }: WorkspaceConfigProps) { super({ compiler, tester, lang, bindingPrefix, extensions }); if (packageManager !== 'npm' && packageManager !== 'yarn') { throw new InvalidPackageManager(packageManager); } this.distTarget = distTarget; this.distEntry = distEntry; this.componentsDefaultDirectory = componentsDefaultDirectory; // Make sure we have the component name in the path. otherwise components will be imported to the same dir. if (!componentsDefaultDirectory.includes('{name}')) { this.componentsDefaultDirectory = `${this.componentsDefaultDirectory}/{name}`; } this.dependenciesDirectory = dependenciesDirectory; this.saveDependenciesAsComponents = saveDependenciesAsComponents; this.packageManager = packageManager; this.packageManagerArgs = packageManagerArgs; this.packageManagerProcessOptions = packageManagerProcessOptions; this.useWorkspaces = useWorkspaces; this.manageWorkspaces = manageWorkspaces; this.resolveModules = resolveModules; this.defaultScope = defaultScope; this.overrides = overrides; } toPlainObject() { const superObject = super.toPlainObject(); let consumerObject = R.merge(superObject, { componentsDefaultDirectory: this.componentsDefaultDirectory, dependenciesDirectory: this.dependenciesDirectory, saveDependenciesAsComponents: this.saveDependenciesAsComponents, packageManager: this.packageManager, packageManagerArgs: this.packageManagerArgs, packageManagerProcessOptions: this.packageManagerProcessOptions, useWorkspaces: this.useWorkspaces, manageWorkspaces: this.manageWorkspaces, resolveModules: this.resolveModules, defaultScope: this.defaultScope, overrides: this.overrides.overrides }); if (this.distEntry || this.distTarget) { const dist = {}; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (this.distEntry) dist.entry = this.distEntry; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (this.distTarget) dist.target = this.distTarget; consumerObject = R.merge(consumerObject, { dist }); } const isPropDefault = (val, key) => { if (key === 'dependenciesDirectory') return val !== DEFAULT_DEPENDENCIES_DIR_PATH; if (key === 'useWorkspaces') return val !== DEFAULT_USE_WORKSPACES; if (key === 'manageWorkspaces') return val !== DEFAULT_MANAGE_WORKSPACES; if (key === 'saveDependenciesAsComponents') return val !== DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS; if (key === 'resolveModules') return !R.isEmpty(val); if (key === 'defaultScope') return Boolean(val); if (key === 'overrides') return !R.isEmpty(val); return true; }; return filterObject(consumerObject, isPropDefault); } static create(workspaceConfigProps: WorkspaceConfigProps): WorkspaceConfig { return new WorkspaceConfig(workspaceConfigProps); } static async ensure( dirPath: PathOsBasedAbsolute, standAlone = false, workspaceConfigProps: WorkspaceConfigProps = {} as any ): Promise<ILegacyWorkspaceConfig> { const ensureFunc = this.workspaceConfigEnsuringRegistry; return ensureFunc(dirPath, standAlone, workspaceConfigProps); } static async _ensure( dirPath: PathOsBasedAbsolute, standAlone: boolean, workspaceConfigProps: WorkspaceConfigProps = {} as any ): Promise<WorkspaceConfig> { try { const workspaceConfig = await this.load(dirPath); return workspaceConfig; } catch (err) { if (err instanceof BitConfigNotFound || err instanceof InvalidBitJson) { const consumerBitJson = this.create(workspaceConfigProps); const packageJsonExists = await AbstractConfig.pathHasPackageJson(dirPath); if (packageJsonExists && !standAlone) { consumerBitJson.writeToPackageJson = true; } else { consumerBitJson.writeToBitJson = true; } return consumerBitJson; } throw err; } } static async reset(dirPath: PathOsBasedAbsolute, resetHard: boolean): Promise<void> { const deleteBitJsonFile = async () => { const bitJsonPath = AbstractConfig.composeBitJsonPath(dirPath); logger.info(`deleting the workspace configuration file at ${bitJsonPath}`); await fs.remove(bitJsonPath); }; if (resetHard) { await deleteBitJsonFile(); } await WorkspaceConfig.ensure(dirPath); } static fromPlainObject(object: Record<string, any>) { this.validate(object); const { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! env, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! lang, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! componentsDefaultDirectory, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! dependenciesDirectory, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! dist, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! bindingPrefix, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! extensions, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! saveDependenciesAsComponents, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! packageManager, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! packageManagerArgs, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! packageManagerProcessOptions, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! useWorkspaces, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! manageWorkspaces, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! resolveModules, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! defaultScope, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! overrides } = object; return new WorkspaceConfig({ compiler: R.propOr(undefined, 'compiler', env), tester: R.propOr(undefined, 'tester', env), lang, bindingPrefix, extensions, saveDependenciesAsComponents, componentsDefaultDirectory, dependenciesDirectory, packageManager, packageManagerArgs, packageManagerProcessOptions, useWorkspaces, manageWorkspaces, resolveModules, distTarget: R.propOr(undefined, 'target', dist), distEntry: R.propOr(undefined, 'entry', dist), defaultScope, overrides: ConsumerOverrides.load(overrides) }); } static async load(dirPath: string): Promise<WorkspaceConfig> { const res = await this._loadIfExist(dirPath); if (!res) { throw new BitConfigNotFound(); } return res; } static async loadIfExist(dirPath: string | PathOsBased): Promise<ILegacyWorkspaceConfig | undefined> { const loadFunc = this.workspaceConfigLoadingRegistry; if (loadFunc && typeof loadFunc === 'function') { return loadFunc(dirPath); } return undefined; } static async isExist(dirPath: string): Promise<boolean | undefined> { const isExistFunc = this.workspaceConfigIsExistRegistry; if (isExistFunc && typeof isExistFunc === 'function') { return isExistFunc(dirPath); } return undefined; } static async _isExist(dirPath: string): Promise<boolean> { const bitJsonPath = AbstractConfig.composeBitJsonPath(dirPath); const packageJsonPath = AbstractConfig.composePackageJsonPath(dirPath); const bitJsonExist = await fs.pathExists(bitJsonPath); if (bitJsonExist) { return true; } const packageJson = await this.loadPackageJson(packageJsonPath); if (packageJson && packageJson.bit) { return true; } return false; } static async _loadIfExist(dirPath: string): Promise<WorkspaceConfig | undefined> { const bitJsonPath = AbstractConfig.composeBitJsonPath(dirPath); const packageJsonPath = AbstractConfig.composePackageJsonPath(dirPath); const [bitJsonFile, packageJsonFile] = await Promise.all([ this.loadBitJson(bitJsonPath), // $FlowFixMe this.loadPackageJson(packageJsonPath) ]); const bitJsonConfig = bitJsonFile || {}; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const packageJsonHasConfig = packageJsonFile && packageJsonFile.bit; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const packageJsonConfig = packageJsonHasConfig ? packageJsonFile.bit : {}; if (R.isEmpty(bitJsonConfig) && R.isEmpty(packageJsonConfig)) return undefined; // in case of conflicts, bit.json wins package.json const config = Object.assign(packageJsonConfig, bitJsonConfig); const workspaceConfig = this.fromPlainObject(config); workspaceConfig.path = bitJsonPath; workspaceConfig.writeToBitJson = Boolean(bitJsonFile); workspaceConfig.writeToPackageJson = packageJsonHasConfig; workspaceConfig.packageJsonObject = packageJsonFile; return workspaceConfig; } static async loadBitJson(bitJsonPath: string): Promise<Record<string, any> | null | undefined> { try { const file = await AbstractConfig.loadJsonFileIfExist(bitJsonPath); return file; } catch (e) { throw new InvalidBitJson(bitJsonPath); } } static async loadPackageJson(packageJsonPath: string): Promise<Record<string, any> | null | undefined> { try { const file = await AbstractConfig.loadJsonFileIfExist(packageJsonPath); return file; } catch (e) { throw new InvalidPackageJson(packageJsonPath); } } static validate(object: Record<string, any>) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const { componentsDefaultDirectory, dependenciesDirectory } = object; const pathsToValidate = { componentsDefaultDirectory, dependenciesDirectory }; Object.keys(pathsToValidate).forEach(field => throwForInvalidPath(field, pathsToValidate[field])); function throwForInvalidPath(fieldName, pathToValidate): void { if (pathToValidate && !isValidPath(pathToValidate)) { throw new InvalidConfigPropPath(fieldName, pathToValidate); } } // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! ConsumerOverrides.validate(object.overrides); } }
the_stack
import { Storage, File } from '@google-cloud/storage' import { BadPathError, InvalidInputError, DoesNotExist } from '../errors' import { ListFilesResult, PerformWriteArgs, WriteResult, PerformDeleteArgs, PerformRenameArgs, StatResult, PerformStatArgs, PerformReadArgs, ReadResult, PerformListFilesArgs, ListFilesStatResult, ListFileStatResult, DriverStatics, DriverModel, DriverModelTestMethods } from '../driverModel' import { pipelineAsync, logger, dateToUnixTimeSeconds } from '../utils' export interface GC_CONFIG_TYPE { gcCredentials?: { email?: string, projectId?: string, keyFilename?: string, credentials?: { client_email?: string, private_key?: string } }, cacheControl?: string, pageSize?: number, bucket: string, resumable?: boolean } class GcDriver implements DriverModel, DriverModelTestMethods { bucket: string storage: Storage pageSize: number cacheControl?: string initPromise: Promise<void> resumable: boolean supportsETagMatching = false; static getConfigInformation() { const envVars: any = {} const gcCredentials: any = {} if (process.env['GAIA_GCP_EMAIL']) { gcCredentials['email'] = process.env['GAIA_GCP_EMAIL'] envVars['gcCredentials'] = gcCredentials } if (process.env['GAIA_GCP_PROJECT_ID']) { gcCredentials['projectId'] = process.env['GAIA_GCP_PROJECT_ID'] envVars['gcCredentials'] = gcCredentials } if (process.env['GAIA_GCP_KEY_FILENAME']) { gcCredentials['keyFilename'] = process.env['GAIA_GCP_KEY_FILENAME'] envVars['gcCredentials'] = gcCredentials } if (process.env['GAIA_GCP_CLIENT_EMAIL']) { gcCredentials['credentials'] = {} gcCredentials['credentials']['client_email'] = process.env['GAIA_GCP_CLIENT_EMAIL'] if (process.env['GAIA_GCP_CLIENT_PRIVATE_KEY']) { gcCredentials['credentials']['private_key'] = process.env['GAIA_GCP_CLIENT_PRIVATE_KEY'] } envVars['gcCredentials'] = gcCredentials } return { defaults: { gcCredentials: {} }, envVars } } constructor (config: GC_CONFIG_TYPE) { this.storage = new Storage(config.gcCredentials) this.bucket = config.bucket this.pageSize = config.pageSize ? config.pageSize : 100 this.cacheControl = config.cacheControl this.initPromise = this.createIfNeeded() this.resumable = config.resumable || false } ensureInitialized() { return this.initPromise } dispose() { return Promise.resolve() } static isPathValid(path: string){ // for now, only disallow double dots. return !path.includes('..') } getReadURLPrefix () { return `https://storage.googleapis.com/${this.bucket}/` } async createIfNeeded() { try { const bucket = this.storage.bucket(this.bucket) const [ exists ] = await bucket.exists() if (!exists) { try { await this.storage.createBucket(this.bucket) logger.info(`initialized google cloud storage bucket: ${this.bucket}`) } catch (err) { logger.error(`failed to initialize google cloud storage bucket: ${err}`) throw err } } } catch (err) { logger.error(`failed to connect to google cloud storage bucket: ${err}`) throw err } } async deleteEmptyBucket() { const files = await this.listFiles({pathPrefix: ''}) if (files.entries.length > 0) { /* istanbul ignore next */ throw new Error('Tried deleting non-empty bucket') } await this.storage.bucket(this.bucket).delete() } async listAllObjects(prefix: string, page?: string, pageSize?: number) { // returns {'entries': [...], 'page': next_page} const opts: { prefix: string, maxResults: number, pageToken?: string } = { prefix: prefix, maxResults: pageSize || this.pageSize, pageToken: page || undefined } const getFilesResult = await new Promise<{files: File[], nextQuery: any}>((resolve, reject) => { this.storage .bucket(this.bucket) .getFiles(opts, (err, files, nextQuery) => { if (err) { reject(err) } else { resolve({files, nextQuery}) } }) }) const fileEntries = getFilesResult.files.map(file => { return { name: file.name.slice(prefix.length + 1), file: file } }) const result = { entries: fileEntries, page: (getFilesResult.nextQuery && getFilesResult.nextQuery.pageToken) || null } return result } async listFiles(args: PerformListFilesArgs): Promise<ListFilesResult> { // returns {'entries': [...], 'page': next_page} const listResult = await this.listAllObjects(args.pathPrefix, args.page) const result: ListFilesResult = { page: listResult.page, entries: listResult.entries.map(file => file.name) } return result } async listFilesStat(args: PerformListFilesArgs): Promise<ListFilesStatResult> { const listResult = await this.listAllObjects(args.pathPrefix, args.page, args.pageSize) const result: ListFilesStatResult = { page: listResult.page, entries: listResult.entries.map(entry => { const statResult = GcDriver.parseFileMetadataStat(entry.file.metadata) const entryResult: ListFileStatResult = { ...statResult, name: entry.name, exists: true } return entryResult }) } return result } async performWrite(args: PerformWriteArgs): Promise<WriteResult> { if (!GcDriver.isPathValid(args.path)) { throw new BadPathError('Invalid Path') } if (args.contentType && args.contentType.length > 1024) { throw new InvalidInputError('Invalid content-type') } const filename = `${args.storageTopLevel}/${args.path}` const publicURL = `${this.getReadURLPrefix()}${filename}` const metadata: any = {} metadata.contentType = args.contentType if (this.cacheControl) { metadata.cacheControl = this.cacheControl } const fileDestination = this.storage .bucket(this.bucket) .file(filename) /* > There is some overhead when using a resumable upload that can cause > noticeable performance degradation while uploading a series of small > files. When uploading files less than 10MB, it is recommended that > the resumable feature is disabled." For details see https://github.com/googleapis/nodejs-storage/issues/312 */ const fileWriteStream = fileDestination.createWriteStream({ public: true, resumable: this.resumable, metadata }) try { await pipelineAsync(args.stream, fileWriteStream) logger.debug(`storing ${filename} in bucket ${this.bucket}`) const etag = GcDriver.formatETagFromMD5(fileDestination.metadata.md5Hash) return { publicURL, etag } } catch (error) { logger.error(`failed to store ${filename} in bucket ${this.bucket}`) throw new Error('Google cloud storage failure: failed to store' + ` ${filename} in bucket ${this.bucket}: ${error}`) } } async performDelete(args: PerformDeleteArgs): Promise<void> { if (!GcDriver.isPathValid(args.path)) { throw new BadPathError('Invalid Path') } const filename = `${args.storageTopLevel}/${args.path}` const bucketFile = this.storage .bucket(this.bucket) .file(filename) try { await bucketFile.delete() } catch (error) { if (error.code === 404) { throw new DoesNotExist('File does not exist') } /* istanbul ignore next */ logger.error(`failed to delete ${filename} in bucket ${this.bucket}`) /* istanbul ignore next */ throw new Error('Google cloud storage failure: failed to delete' + ` ${filename} in bucket ${this.bucket}: ${error}`) } } static formatETagFromMD5(md5Hash: string): string { const hex = Buffer.from(md5Hash, 'base64').toString('hex') const formatted = `"${hex}"` return formatted } static parseFileMetadataStat(metadata: any): StatResult { const lastModified = dateToUnixTimeSeconds(new Date(metadata.updated)) const result: StatResult = { exists: true, etag: this.formatETagFromMD5(metadata.md5Hash), contentType: metadata.contentType, contentLength: parseInt(metadata.size), lastModifiedDate: lastModified } return result } async performRead(args: PerformReadArgs): Promise<ReadResult> { if (!GcDriver.isPathValid(args.path)) { throw new BadPathError('Invalid Path') } const filename = `${args.storageTopLevel}/${args.path}` const bucketFile = this.storage .bucket(this.bucket) .file(filename) try { const [getResult] = await bucketFile.get({autoCreate: false}) const statResult = GcDriver.parseFileMetadataStat(getResult.metadata) const dataStream = getResult.createReadStream() const result: ReadResult = { ...statResult, exists: true, data: dataStream } return result } catch (error) { if (error.code === 404) { throw new DoesNotExist('File does not exist') } /* istanbul ignore next */ logger.error(`failed to read ${filename} in bucket ${this.bucket}`) /* istanbul ignore next */ throw new Error('Google cloud storage failure: failed to read' + ` ${filename} in bucket ${this.bucket}: ${error}`) } } async performStat(args: PerformStatArgs): Promise<StatResult> { if (!GcDriver.isPathValid(args.path)) { throw new BadPathError('Invalid Path') } const filename = `${args.storageTopLevel}/${args.path}` const bucketFile = this.storage .bucket(this.bucket) .file(filename) try { const [metadataResult] = await bucketFile.getMetadata() const result = GcDriver.parseFileMetadataStat(metadataResult) return result } catch (error) { if (error.code === 404) { const result = { exists: false } as StatResult return result } /* istanbul ignore next */ logger.error(`failed to stat ${filename} in bucket ${this.bucket}`) /* istanbul ignore next */ throw new Error('Google cloud storage failure: failed to stat ' + ` ${filename} in bucket ${this.bucket}: ${error}`) } } async performRename(args: PerformRenameArgs): Promise<void> { if (!GcDriver.isPathValid(args.path)) { throw new BadPathError('Invalid original path') } if (!GcDriver.isPathValid(args.newPath)) { throw new BadPathError('Invalid new path') } const filename = `${args.storageTopLevel}/${args.path}` const bucketFile = this.storage .bucket(this.bucket) .file(filename) const newFilename = `${args.storageTopLevel}/${args.newPath}` const newBucketFile = this.storage .bucket(this.bucket) .file(newFilename) try { await bucketFile.move(newBucketFile) } catch (error) { if (error.code === 404) { throw new DoesNotExist('File does not exist') } /* istanbul ignore next */ logger.error(`failed to rename ${filename} to ${newFilename} in bucket ${this.bucket}`) /* istanbul ignore next */ throw new Error('Google cloud storage failure: failed to rename' + ` ${filename} to ${newFilename} in bucket ${this.bucket}: ${error}`) } } } const driver: typeof GcDriver & DriverStatics = GcDriver export default driver
the_stack
import AMM from './AMM' import Base, { ChainProviders } from './Base' import Chain from './models/Chain' import Token from './Token' import TokenModel from './models/Token' import fetch from 'isomorphic-fetch' import l1Erc20BridgeAbi from '@hop-protocol/core/abi/generated/L1_ERC20_Bridge.json' import l1HomeAmbNativeToErc20 from '@hop-protocol/core/abi/static/L1_HomeAMBNativeToErc20.json' import l2AmmWrapperAbi from '@hop-protocol/core/abi/generated/L2_AmmWrapper.json' import l2BridgeAbi from '@hop-protocol/core/abi/generated/L2_Bridge.json' import { BigNumber, BigNumberish, Signer, ethers } from 'ethers' import { BondTransferGasLimit, CanonicalToken, Errors, HToken, LpFeeBps, PendingAmountBuffer, SettlementGasLimitPerTx, TokenIndex, TokenSymbol } from './constants' import { PriceFeed } from './priceFeed' import { TAmount, TChain, TProvider, TTime, TTimeSlot, TToken } from './types' import { bondableChains, metadata } from './config' import { getAddress as checksumAddress, parseUnits } from 'ethers/lib/utils' type SendL1ToL2Input = { destinationChain: Chain sourceChain: Chain relayer?: string relayerFee?: TAmount amount: TAmount amountOutMin?: TAmount deadline?: BigNumberish recipient?: string checkAllowance?: boolean } type SendL2ToL1Input = { destinationChain: Chain sourceChain: Chain amount: TAmount amountOutMin: TAmount destinationAmountOutMin?: TAmount deadline?: BigNumberish destinationDeadline?: BigNumberish bonderFee?: TAmount recipient?: string checkAllowance?: boolean } type SendL2ToL2Input = { destinationChain: Chain sourceChain: Chain amount: TAmount amountOutMin: TAmount destinationAmountOutMin?: TAmount bonderFee?: TAmount deadline?: BigNumberish destinationDeadline?: BigNumberish recipient?: string checkAllowance?: boolean } type SendOptions = { deadline: BigNumberish relayer: string relayerFee: TAmount recipient: string amountOutMin: TAmount bonderFee: TAmount destinationAmountOutMin: TAmount destinationDeadline: BigNumberish checkAllowance?: boolean } type AddLiquidityOptions = { minToMint: TAmount deadline: BigNumberish } type RemoveLiquidityOptions = { amount0Min: TAmount amount1Min: TAmount deadline: BigNumberish } type RemoveLiquidityOneTokenOptions = { amountMin: TAmount deadline: BigNumberish } type RemoveLiquidityImbalanceOptions = { maxBurnAmount: TAmount deadline: BigNumberish } /** * Class representing Hop bridge. * @namespace HopBridge */ class HopBridge extends Base { private tokenSymbol: TokenSymbol /** Source Chain model */ public sourceChain: Chain /** Destination Chain model */ public destinationChain: Chain /** Default deadline for transfers */ public defaultDeadlineMinutes = 7 * 24 * 60 // 1 week public readonly priceFeed: PriceFeed /** * @desc Instantiates Hop Bridge. * Returns a new Hop Bridge instance. * @param {String} network - L1 network name (e.g. 'mainnet', 'kovan', 'goerli') * @param {Object} signer - Ethers `Signer` for signing transactions. * @param {Object} token - Token symbol or model * @param {Object} sourceChain - Source chain model * @param {Object} destinationChain - Destination chain model * @returns {Object} HopBridge SDK instance. * @example *```js *import { HopBridge, Chain, Token } from '@hop-protocol/sdk' *import { Wallet } from 'ethers' * *const signer = new Wallet(privateKey) *const bridge = new HopBridge('kovan', signer, Token.USDC, Chain.Optimism, Chain.Gnosis) *``` */ constructor ( network: string, signer: TProvider, token: TToken, chainProviders?: ChainProviders ) { super(network, signer, chainProviders) if (token instanceof Token || token instanceof TokenModel) { this.tokenSymbol = token.symbol } else if (typeof token === 'string') { this.tokenSymbol = token } if (!token) { throw new Error('token is required') } this.priceFeed = new PriceFeed() } /** * @desc Returns hop bridge instance with signer connected. Used for adding or changing signer. * @param {Object} signer - Ethers `Signer` for signing transactions. * @returns {Object} New HopBridge SDK instance with connected signer. * @example *```js *import { Hop, Token } from '@hop-protocol/sdk' *import { Wallet } from 'ethers' * *const signer = new Wallet(privateKey) *let hop = new Hop() * // ... *const bridge = hop.bridge(Token.USDC).connect(signer) *``` */ public connect (signer: Signer) { return new HopBridge( this.network, signer, this.tokenSymbol, this.chainProviders ) } public getL1Token () { return this.toCanonicalToken(this.tokenSymbol, this.network, Chain.Ethereum) } public getCanonicalToken (chain: TChain) { return this.toCanonicalToken(this.tokenSymbol, this.network, chain) } public getL2HopToken (chain: TChain) { return this.toHopToken(this.tokenSymbol, this.network, chain) } public toCanonicalToken ( token: TToken, network: string, chain: TChain ): Token | undefined { token = this.toTokenModel(token) chain = this.toChainModel(chain) let { name, symbol, decimals, image } = metadata.tokens[network][ token.canonicalSymbol ] if (chain.equals(Chain.Gnosis) && token.symbol === CanonicalToken.DAI) { symbol = CanonicalToken.XDAI } let address if (chain.isL1) { address = this.getL1CanonicalTokenAddress(token.symbol, chain) } else { address = this.getL2CanonicalTokenAddress(token.symbol, chain) } return new Token( network, chain, address, decimals, symbol as never, name, image, this.signer, this.chainProviders ) } public toHopToken ( token: TToken, network: string, chain: TChain ): Token | undefined { chain = this.toChainModel(chain) token = this.toTokenModel(token) if (chain.isL1) { throw new Error('Hop tokens do not exist on layer 1') } const { name, symbol, decimals, image } = metadata.tokens[network][ token.canonicalSymbol ] const address = this.getL2HopBridgeTokenAddress(token.symbol, chain) return new Token( network, chain, address, decimals, `h${token.canonicalSymbol}` as HToken, `Hop ${name}`, image, this.signer, this.chainProviders ) } /** * @desc Send tokens to another chain. * @param {String} tokenAmount - Token amount to send denominated in smallest unit. * @param {Object} sourceChain - Source chain model. * @param {Object} destinationChain - Destination chain model. * @returns {Object} Ethers Transaction object. * @example *```js *import { Hop, Chain, Token } from '@hop-protocol/sdk' * *const hop = new Hop() *const bridge = hop.connect(signer).bridge(Token.USDC) *\// send 1 USDC token from Optimism -> Gnosis *const tx = await bridge.send('1000000000000000000', Chain.Optimism, Chain.Gnosis) *console.log(tx.hash) *``` */ public async send ( tokenAmount: TAmount, sourceChain?: TChain, destinationChain?: TChain, options: Partial<SendOptions> = {} ) { sourceChain = this.toChainModel(sourceChain) const populatedTx = await this.populateSendTx( tokenAmount, sourceChain, destinationChain, { ...options, checkAllowance: true } ) let balance: BigNumber const canonicalToken = this.getCanonicalToken(sourceChain) if (this.isNativeToken(sourceChain)) { balance = await canonicalToken.getNativeTokenBalance() } else { balance = await canonicalToken.balanceOf() } if (balance.lt(tokenAmount)) { throw new Error(Errors.NotEnoughAllowance) } const availableLiquidity = await this.getFrontendAvailableLiquidity( sourceChain, destinationChain ) const requiredLiquidity = await this.getRequiredLiquidity(tokenAmount, sourceChain) const isAvailable = availableLiquidity.gte(requiredLiquidity) if (!isAvailable) { throw new Error('Insufficient liquidity available by bonder. Try again in a few minutes') } this.checkConnectedChain(this.signer, sourceChain) return this.signer.sendTransaction(populatedTx) } public async populateSendTx ( tokenAmount: TAmount, sourceChain?: TChain, destinationChain?: TChain, options: Partial<SendOptions> = {} ):Promise<any> { tokenAmount = BigNumber.from(tokenAmount.toString()) if (!sourceChain) { sourceChain = this.sourceChain } if (!destinationChain) { destinationChain = this.destinationChain } if (!sourceChain) { throw new Error('source chain is required') } if (!destinationChain) { throw new Error('destination chain is required') } sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) tokenAmount = BigNumber.from(tokenAmount.toString()) // L1 -> L1 or L2 if (sourceChain.isL1) { // L1 -> L1 if (destinationChain.isL1) { throw new Error('Cannot send from layer 1 to layer 1') } // L1 -> L2 return this.populateSendL1ToL2Tx({ destinationChain: destinationChain, sourceChain, relayer: options?.relayer ?? ethers.constants.AddressZero, relayerFee: options?.relayerFee ?? 0, amount: tokenAmount, amountOutMin: options?.amountOutMin ?? 0, deadline: options?.deadline, recipient: options?.recipient, checkAllowance: options?.checkAllowance }) } // else: // L2 -> L1 or L2 let bonderFee = options?.bonderFee if (!bonderFee) { bonderFee = await this.getTotalFee( tokenAmount, sourceChain, destinationChain ) } // L2 -> L1 if (destinationChain.isL1) { return this.populateSendL2ToL1Tx({ destinationChain: destinationChain, sourceChain, amount: tokenAmount, bonderFee, recipient: options?.recipient, amountOutMin: options?.amountOutMin, deadline: options?.deadline, destinationAmountOutMin: options?.destinationAmountOutMin, destinationDeadline: options?.destinationDeadline, checkAllowance: options?.checkAllowance }) } // L2 -> L2 return this.populateSendL2ToL2Tx({ destinationChain: destinationChain, sourceChain, amount: tokenAmount, bonderFee, recipient: options?.recipient, amountOutMin: options?.amountOutMin, deadline: options?.deadline, destinationAmountOutMin: options?.destinationAmountOutMin, destinationDeadline: options?.destinationDeadline, checkAllowance: options?.checkAllowance }) } public async estimateSendGasLimit ( tokenAmount: TAmount, sourceChain: TChain, destinationChain: TChain, options: Partial<SendOptions> = {} ) { const populatedTx = await this.populateSendTx(tokenAmount, sourceChain, destinationChain, options) return this.getEstimatedGasLimit(sourceChain, destinationChain, populatedTx) } private async getEstimatedGasLimit ( sourceChain: TChain, destinationChain: TChain, populatedTx: any ) { sourceChain = this.toChainModel(sourceChain) if (!populatedTx.from) { // a `from` address is required if using only provider (not signer) populatedTx.from = await this.getGasEstimateFromAddress(sourceChain, destinationChain) } return sourceChain.provider.estimateGas({ ...populatedTx, gasLimit: 500000 }) } public async getSendEstimatedGasCost ( tokenAmount: TAmount, sourceChain: TChain, destinationChain: TChain, options: Partial<SendOptions> = {} ) { sourceChain = this.toChainModel(sourceChain) const populatedTx = await this.populateSendTx(tokenAmount, sourceChain, destinationChain, options) const estimatedGasLimit = await this.getEstimatedGasLimit(sourceChain, destinationChain, populatedTx) const gasPrice = await sourceChain.provider.getGasPrice() return gasPrice.mul(estimatedGasLimit) } // ToDo: Docs public getSendApprovalAddress ( sourceChain: TChain, isHTokenTransfer: boolean = false ) { sourceChain = this.toChainModel(sourceChain) if (sourceChain.equals(Chain.Ethereum)) { return this.getL1BridgeAddress(this.tokenSymbol, sourceChain) } const ammWrapperAddress = this.getL2AmmWrapperAddress( this.tokenSymbol, sourceChain ) const l2BridgeAddress = this.getL2BridgeAddress( this.tokenSymbol, sourceChain ) return isHTokenTransfer ? l2BridgeAddress : ammWrapperAddress } public async populateSendApprovalTx ( tokenAmount: TAmount, sourceChain: TChain, isHTokenTransfer: boolean = false ):Promise<any> { sourceChain = this.toChainModel(sourceChain) const spender = await this.getSendApprovalAddress(sourceChain, isHTokenTransfer) const isNativeToken = this.isNativeToken(sourceChain) if (isNativeToken) { return null } let token if (sourceChain.isL1) { token = this.getL1Token() } else if (isHTokenTransfer) { token = this.getL2HopToken(sourceChain) } else { token = this.getCanonicalToken(sourceChain) } const populatedTx = await token.populateApproveTx(spender, tokenAmount) return populatedTx } public async sendApproval ( tokenAmount: TAmount, sourceChain: TChain, destinationChain: TChain, isHTokenTransfer: boolean = false ) { sourceChain = this.toChainModel(sourceChain) const populatedTx = await this.populateSendApprovalTx(tokenAmount, sourceChain, isHTokenTransfer) if (populatedTx) { this.checkConnectedChain(this.signer, sourceChain) return this.signer.sendTransaction(populatedTx) } } // ToDo: Docs public async sendHToken ( tokenAmount: TAmount, sourceChain: TChain, destinationChain: TChain, options: Partial<SendOptions> = {} ) { sourceChain = this.toChainModel(sourceChain) const populatedTx = await this.populateSendHTokensTx(tokenAmount, sourceChain, destinationChain, options) this.checkConnectedChain(this.signer, sourceChain) return this.signer.sendTransaction(populatedTx) } public async estimateSendHTokensGasLimit ( tokenAmount: TAmount, sourceChain: TChain, destinationChain: TChain, options: Partial<SendOptions> = {} ) { const populatedTx = await this.sendHToken(tokenAmount, sourceChain, destinationChain, options) return this.getEstimatedGasLimit(sourceChain, destinationChain, populatedTx) } public async populateSendHTokensTx ( tokenAmount: TAmount, sourceChain: TChain, destinationChain: TChain, options: Partial<SendOptions> = {} ):Promise<any> { if (!sourceChain) { throw new Error('source chain is required') } if (!destinationChain) { throw new Error('destination chain is required') } sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) if (sourceChain.isL1 && destinationChain.isL1) { throw new Error('sourceChain and destinationChain cannot both be L1') } else if (!sourceChain.isL1 && !destinationChain.isL1) { throw new Error('Sending hToken L2 to L2 is not currently supported') } if ( options?.deadline || options?.amountOutMin || options?.destinationDeadline || options?.destinationAmountOutMin ) { throw new Error('Invalid sendHToken option') } let defaultBonderFee = BigNumber.from(0) if (!sourceChain.isL1) { defaultBonderFee = await this.getTotalFee( tokenAmount, sourceChain, destinationChain ) } let recipient = options?.recipient ?? await this.getSignerAddress() if (!recipient) { throw new Error('recipient is required') } recipient = checksumAddress(recipient) const bonderFee = options?.bonderFee ? BigNumber.from(options?.bonderFee) : defaultBonderFee const amountOutMin = BigNumber.from(0) const deadline = BigNumber.from(0) const relayer = ethers.constants.AddressZero if (sourceChain.isL1) { if (bonderFee.gt(0)) { throw new Error('Bonder fee should be 0 when sending hToken to L2') } const isNativeToken = this.isNativeToken(sourceChain) const txOptions = [ destinationChain.chainId, recipient, tokenAmount, amountOutMin, deadline, relayer, bonderFee, { ...(await this.txOverrides(Chain.Ethereum)), value: isNativeToken ? tokenAmount : undefined } ] const l1Bridge = await this.getL1Bridge(sourceChain.provider) return l1Bridge.populateTransaction.sendToL2(...txOptions) } else { if (bonderFee.eq(0)) { throw new Error('Send at least the minimum Bonder fee') } const txOptions = [ destinationChain.chainId, recipient, tokenAmount, bonderFee, amountOutMin, deadline, await this.txOverrides(sourceChain) ] const l2Bridge = await this.getL2Bridge(sourceChain, sourceChain.provider) return l2Bridge.populateTransaction.send(...txOptions) } } // ToDo: Docs public getTokenSymbol () { return this.tokenSymbol } // ToDo: Docs public getTokenImage () { return this.getL1Token()?.image } // ToDo: Docs public async getSendData ( amountIn: BigNumberish, sourceChain: TChain, destinationChain: TChain, isHTokenSend: boolean = false ) { amountIn = BigNumber.from(amountIn) sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) const hTokenAmount = await this.calcToHTokenAmount(amountIn, sourceChain) const amountOutWithoutFeePromise = this.calcFromHTokenAmount( hTokenAmount, destinationChain ) const amountInNoSlippage = BigNumber.from(1000) const amountOutNoSlippagePromise = this.getAmountOut( amountInNoSlippage, sourceChain, destinationChain ) const bonderFeeRelativePromise = this.getBonderFeeRelative( amountIn, sourceChain, destinationChain ) const destinationTxFeePromise = this.getDestinationTransactionFee( sourceChain, destinationChain ) const [ amountOutWithoutFee, amountOutNoSlippage, bonderFeeRelative, destinationTxFee ] = await Promise.all([ amountOutWithoutFeePromise, amountOutNoSlippagePromise, bonderFeeRelativePromise, destinationTxFeePromise ]) const amountOut = await this.calcFromHTokenAmount( hTokenAmount, destinationChain ) let adjustedBonderFee let adjustedDestinationTxFee let totalFee if (sourceChain.isL1) { // there are no Hop fees when the source is L1 adjustedBonderFee = BigNumber.from(0) adjustedDestinationTxFee = BigNumber.from(0) totalFee = BigNumber.from(0) } else { if (isHTokenSend) { // fees do not need to be adjusted for AMM slippage when sending hTokens adjustedBonderFee = bonderFeeRelative adjustedDestinationTxFee = destinationTxFee } else { // adjusted fee is the fee in the canonical token after adjusting for the hToken price adjustedBonderFee = await this.calcFromHTokenAmount( bonderFeeRelative, destinationChain ) adjustedDestinationTxFee = await this.calcFromHTokenAmount( destinationTxFee, destinationChain ) } // enforce bonderFeeAbsolute after adjustment const bonderFeeAbsolute = await this.getBonderFeeAbsolute() adjustedBonderFee = adjustedBonderFee.gt(bonderFeeAbsolute) ? adjustedBonderFee : bonderFeeAbsolute totalFee = adjustedBonderFee.add(adjustedDestinationTxFee) } const sourceToken = this.getCanonicalToken(sourceChain) const destToken = this.getCanonicalToken(destinationChain) const rate = this.getRate( amountIn, amountOutWithoutFee, sourceToken, destToken ) const marketRate = this.getRate( amountInNoSlippage, amountOutNoSlippage, sourceToken, destToken ) const priceImpact = this.getPriceImpact(rate, marketRate) const lpFees = await this.getLpFees(amountIn, sourceChain, destinationChain) let estimatedReceived = amountOut if (totalFee.gt(0)) { estimatedReceived = estimatedReceived.sub(totalFee) } if (estimatedReceived.lt(0)) { estimatedReceived = BigNumber.from(0) } return { amountOut, rate, priceImpact, requiredLiquidity: hTokenAmount, lpFees, adjustedBonderFee, adjustedDestinationTxFee, totalFee, estimatedReceived } } // ToDo: Docs public async getAmmData ( chain: TChain, amountIn: BigNumberish, isToHToken: boolean, slippageTolerance: number ) { chain = this.toChainModel(chain) amountIn = BigNumber.from(amountIn) const canonicalToken = this.getCanonicalToken(chain) const hToken = this.getL2HopToken(chain) const sourceToken = isToHToken ? canonicalToken : hToken const destToken = isToHToken ? hToken : canonicalToken const amountInNoSlippage = BigNumber.from(1000) let amountOut let amountOutNoSlippage if (isToHToken) { amountOut = await this.calcToHTokenAmount(amountIn, chain) amountOutNoSlippage = await this.calcToHTokenAmount( amountInNoSlippage, chain ) } else { amountOut = await this.calcFromHTokenAmount(amountIn, chain) amountOutNoSlippage = await this.calcFromHTokenAmount( amountInNoSlippage, chain ) } const rate = this.getRate(amountIn, amountOut, sourceToken, destToken) const marketRate = this.getRate( amountInNoSlippage, amountOutNoSlippage, sourceToken, destToken ) const priceImpact = this.getPriceImpact(rate, marketRate) const oneDestBN = ethers.utils.parseUnits('1', sourceToken.decimals) const slippageToleranceBps = slippageTolerance * 100 const minBps = Math.ceil(10000 - slippageToleranceBps) const amountOutMin = amountOut.mul(minBps).div(10000) // Divide by 10000 at the end so that the amount isn't floored at 0 const lpFee = BigNumber.from(LpFeeBps) const lpFeeBN = parseUnits(lpFee.toString(), destToken.decimals) const lpFeeAmount = amountIn .mul(lpFeeBN) .div(oneDestBN) .div(10000) return { rate, priceImpact, amountOutMin, lpFeeAmount } } public async getTotalFee ( amountIn: BigNumberish, sourceChain: TChain, destinationChain: TChain ): Promise<BigNumber> { const { totalFee } = await this.getSendData( amountIn, sourceChain, destinationChain ) return totalFee } public async getLpFees ( amountIn: BigNumberish, sourceChain: TChain, destinationChain: TChain ): Promise<BigNumber> { sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) let lpFeeBpsBn = BigNumber.from(0) if (!sourceChain.isL1) { lpFeeBpsBn = lpFeeBpsBn.add(LpFeeBps) } if (!destinationChain.isL1) { lpFeeBpsBn = lpFeeBpsBn.add(LpFeeBps) } amountIn = BigNumber.from(amountIn) const lpFees = amountIn.mul(lpFeeBpsBn).div(10000) return lpFees } public async getDestinationTransactionFee ( sourceChain: TChain, destinationChain: TChain ): Promise<BigNumber> { sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) if (sourceChain?.equals(Chain.Ethereum)) { return BigNumber.from(0) } const canonicalToken = this.getCanonicalToken(sourceChain) const chainNativeToken = this.getChainNativeToken(destinationChain) const chainNativeTokenPrice = await this.priceFeed.getPriceByTokenSymbol( chainNativeToken.symbol ) const tokenPrice = await this.priceFeed.getPriceByTokenSymbol( canonicalToken.symbol ) const rate = chainNativeTokenPrice / tokenPrice let gasPrice = await destinationChain.provider.getGasPrice() let bondTransferGasLimit = await this.estimateBondWithdrawalGasLimit( sourceChain, destinationChain ) // Arbitrum returns a gasLimit & gasPriceBid of 2x what is generally paid if (destinationChain.equals(Chain.Arbitrum)) { gasPrice = gasPrice.div(2) bondTransferGasLimit = bondTransferGasLimit.div(2) } // Include the cost to settle an individual transfer const settlementGasLimitPerTx: number = SettlementGasLimitPerTx[destinationChain.slug] const bondTransferGasLimitWithSettlement = bondTransferGasLimit.add(settlementGasLimitPerTx) let txFeeEth = gasPrice.mul(bondTransferGasLimitWithSettlement) const oneEth = ethers.utils.parseEther('1') const rateBN = ethers.utils.parseUnits( rate.toFixed(canonicalToken.decimals), canonicalToken.decimals ) if (destinationChain.equals(Chain.Optimism)) { const l1FeeInWei = await this.getOptimismL1Fee(sourceChain, destinationChain) txFeeEth = txFeeEth.add(l1FeeInWei) } let fee = txFeeEth.mul(rateBN).div(oneEth) if ( destinationChain.equals(Chain.Ethereum) || destinationChain.equals(Chain.Optimism) || destinationChain.equals(Chain.Arbitrum) ) { const multiplier = ethers.utils.parseEther(this.destinationFeeGasPriceMultiplier.toString()) if (multiplier.gt(0)) { fee = fee.mul(multiplier).div(oneEth) } } return fee } async getOptimismL1Fee ( sourceChain: TChain, destinationChain: TChain ) { try { const [gasLimit, { data, to }] = await Promise.all([ this.estimateBondWithdrawalGasLimit(sourceChain, destinationChain), this.populateBondWithdrawalTx(sourceChain, destinationChain) ]) const l1FeeInWei = await this.estimateOptimismL1FeeFromData(gasLimit, data, to) return l1FeeInWei } catch (err) { console.error(err) return BigNumber.from(0) } } async estimateBondWithdrawalGasLimit ( sourceChain: TChain, destinationChain: TChain ): Promise<any> { destinationChain = this.toChainModel(destinationChain) try { const populatedTx = await this.populateBondWithdrawalTx(sourceChain, destinationChain) const estimatedGas = await destinationChain.provider.estimateGas(populatedTx) return estimatedGas } catch (err) { console.error(err, { destinationChain }) let bondTransferGasLimit: string = BondTransferGasLimit.Ethereum if (destinationChain.equals(Chain.Optimism)) { bondTransferGasLimit = BondTransferGasLimit.Optimism } else if (destinationChain.equals(Chain.Arbitrum)) { bondTransferGasLimit = BondTransferGasLimit.Arbitrum } return BigNumber.from(bondTransferGasLimit) } } async populateBondWithdrawalTx ( sourceChain: TChain, destinationChain: TChain ): Promise<any> { destinationChain = this.toChainModel(destinationChain) let destinationBridge if (destinationChain.isL1) { destinationBridge = await this.getL1Bridge() } else { destinationBridge = await this.getL2Bridge(destinationChain) } destinationBridge = destinationBridge.connect(destinationChain.provider) const bonder = this.getBonderAddress(sourceChain, destinationChain) const amount = BigNumber.from(10) const amountOutMin = BigNumber.from(0) const bonderFee = BigNumber.from(1) const deadline = this.defaultDeadlineSeconds const transferNonce = `0x${'0'.repeat(64)}` const recipient = `0x${'1'.repeat(40)}` const attemptSwap = this.shouldAttemptSwap(amountOutMin, deadline) if (attemptSwap && !destinationChain.isL1) { const payload = [ recipient, amount, transferNonce, bonderFee, amountOutMin, deadline, { from: bonder } ] return destinationBridge.populateTransaction.bondWithdrawalAndDistribute( ...payload ) } else { const payload = [ recipient, amount, transferNonce, bonderFee, { from: bonder } ] return destinationBridge.populateTransaction.bondWithdrawal( ...payload ) } } /** * @desc Estimate token amount out. * @param {String} tokenAmountIn - Token amount input. * @param {Object} sourceChain - Source chain model. * @param {Object} destinationChain - Destination chain model. * @returns {Object} Amount as BigNumber. * @example *```js *import { Hop, Chain Token } from '@hop-protocol/sdk' * *const hop = new Hop() *const bridge = hop.connect(signer).bridge(Token.USDC) *const amountOut = await bridge.getAmountOut('1000000000000000000', Chain.Optimism, Chain.Gnosis) *console.log(amountOut) *``` */ public async getAmountOut ( tokenAmountIn: TAmount, sourceChain?: TChain, destinationChain?: TChain ) { tokenAmountIn = BigNumber.from(tokenAmountIn.toString()) sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) const hTokenAmount = await this.calcToHTokenAmount( tokenAmountIn, sourceChain ) const amountOut = await this.calcFromHTokenAmount( hTokenAmount, destinationChain ) return amountOut } /** * @desc Estimate the bonder liquidity needed at the destination. * @param {String} tokenAmountIn - Token amount input. * @param {Object} sourceChain - Source chain model. * @param {Object} destinationChain - Destination chain model. * @returns {Object} Amount as BigNumber. * @example *```js *import { Hop, Chain Token } from '@hop-protocol/sdk' * *const hop = new Hop() *const bridge = hop.connect(signer).bridge(Token.USDC) *const requiredLiquidity = await bridge.getRequiredLiquidity('1000000000000000000', Chain.Optimism, Chain.Gnosis) *console.log(requiredLiquidity) *``` */ public async getRequiredLiquidity ( tokenAmountIn: TAmount, sourceChain: TChain ): Promise<BigNumber> { tokenAmountIn = BigNumber.from(tokenAmountIn.toString()) sourceChain = this.toChainModel(sourceChain) if (sourceChain.equals(Chain.Ethereum)) { return BigNumber.from(0) } const hTokenAmount = await this.calcToHTokenAmount( tokenAmountIn, sourceChain ) return hTokenAmount } public async getAvailableLiquidity ( destinationChain: TChain, bonder: string ): Promise<BigNumber> { const [credit, debit] = await Promise.all([ this.getCredit(destinationChain, bonder), this.getTotalDebit(destinationChain, bonder) ]) const availableLiquidity = credit.sub(debit) return availableLiquidity } /** * @desc Returns available liquidity for Hop bridge at specified chain. * @param {Object} sourceChain - Source chain model. * @param {Object} destinationChain - Destination chain model. * @returns {Object} Available liquidity as BigNumber. */ public async getFrontendAvailableLiquidity ( sourceChain: TChain, destinationChain: TChain ): Promise<BigNumber> { sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) const token = this.toTokenModel(this.tokenSymbol) const bonder = this.getBonderAddress(sourceChain, destinationChain) let availableLiquidity = await this.getAvailableLiquidity( destinationChain, bonder ) const unbondedTransferRootAmount = await this.getUnbondedTransferRootAmount( sourceChain, destinationChain ) if ( this.isOruToL1(sourceChain, destinationChain) || this.isNonOruToL1(sourceChain, destinationChain) ) { const bridgeContract = await this.getBridgeContract(sourceChain) let pendingAmounts = BigNumber.from(0) for (const chain of bondableChains) { const exists = this.getL2BridgeAddress(this.tokenSymbol, chain) if (!exists) { continue } const bridge = await this.getBridgeContract(chain) const pendingAmount = await bridge.pendingAmountForChainId( Chain.Ethereum.chainId ) pendingAmounts = pendingAmounts.add(pendingAmount) } const tokenPrice = await this.priceFeed.getPriceByTokenSymbol( token.canonicalSymbol ) const tokenPriceBn = parseUnits(tokenPrice.toString(), token.decimals) const bufferAmountBn = parseUnits(PendingAmountBuffer, token.decimals) const precision = parseUnits('1', token.decimals) const bufferAmountTokensBn = bufferAmountBn .div(tokenPriceBn) .mul(precision) availableLiquidity = availableLiquidity .sub(pendingAmounts) .sub(unbondedTransferRootAmount) .sub(bufferAmountTokensBn) if (this.isOruToL1(sourceChain, destinationChain)) { availableLiquidity = availableLiquidity.div(2) } } if (availableLiquidity.lt(0)) { return BigNumber.from(0) } return availableLiquidity } isOruToL1 (sourceChain: Chain, destinationChain: Chain) { return ( destinationChain.equals(Chain.Ethereum) && bondableChains.includes(sourceChain.slug) ) } isNonOruToL1 (sourceChain: Chain, destinationChain: Chain) { return ( destinationChain.equals(Chain.Ethereum) && !bondableChains.includes(sourceChain.slug) ) } async getBonderAvailableLiquidityData () { const url = `https://assets.hop.exchange/${this.network}/v1-available-liquidity.json` const res = await fetch(url) const json = await res.json() if (!json) { throw new Error('expected json object') } const { timestamp, data } = json const tenMinutes = 10 * 60 * 1000 const isOutdated = Date.now() - timestamp > tenMinutes if (isOutdated) { return } return data } async getUnbondedTransferRootAmount ( sourceChain: Chain, destinationChain: Chain ) { try { const data = await this.getBonderAvailableLiquidityData() if (data) { const _unbondedTransferRootAmount = data?.[this.tokenSymbol]?.unbondedTransferRootAmounts?.[ sourceChain.slug ]?.[destinationChain.slug] if (_unbondedTransferRootAmount) { return BigNumber.from(_unbondedTransferRootAmount) } } } catch (err) { console.error(err) } return BigNumber.from(0) } /** * @desc Returns bridge contract instance for specified chain. * @param {Object} chain - chain model. * @returns {Object} Ethers contract instance. */ public async getBridgeContract (chain: TChain) { chain = this.toChainModel(chain) let bridge: ethers.Contract if (chain.isL1) { bridge = await this.getL1Bridge() } else { bridge = await this.getL2Bridge(chain) } return bridge } /** * @desc Returns total credit that bonder holds on Hop bridge at specified chain. * @param {Object} chain - Chain model. * @returns {Object} Total credit as BigNumber. */ public async getCredit ( sourceChain: TChain, bonder: string ): Promise<BigNumber> { const bridge = await this.getBridgeContract(sourceChain) return bridge.getCredit(bonder) } /** * @desc Returns total debit, including sliding window debit, that bonder holds on Hop bridge at specified chain. * @param {Object} chain - Chain model. * @returns {Object} Total debit as BigNumber. */ public async getTotalDebit ( sourceChain: TChain, bonder: string ): Promise<BigNumber> { const bridge = await this.getBridgeContract(sourceChain) return bridge.getDebitAndAdditionalDebit(bonder) } /** * @desc Returns total debit that bonder holds on Hop bridge at specified chain. * @param {Object} chain - Chain model. * @returns {Object} Total debit as BigNumber. */ public async getDebit ( sourceChain: TChain, bonder: string ): Promise<BigNumber> { const bridge = await this.getBridgeContract(sourceChain) return bridge.getRawDebit(bonder) } /** * @desc Sends transaction to execute swap on Saddle contract. * @param {Object} sourceChain - Source chain model. * @param {Boolean} toHop - Converts to Hop token only if set to true. * @param {Object} amount - Amount of token to swap. * @param {Object} minAmountOut - Minimum amount of tokens to receive in order * for transaction to be successful. * @param {Number} deadline - Transaction deadline in seconds. * @returns {Object} Ethers transaction object. */ public async execSaddleSwap ( sourceChain: TChain, toHop: boolean, amount: TAmount, minAmountOut: TAmount, deadline: BigNumberish ) { sourceChain = this.toChainModel(sourceChain) let tokenIndexFrom: number let tokenIndexTo: number const l2CanonicalTokenAddress = this.getL2CanonicalTokenAddress( this.tokenSymbol, sourceChain ) if (!l2CanonicalTokenAddress) { throw new Error(`source chain "${sourceChain.slug}" is unsupported`) } const l2HopBridgeTokenAddress = this.getL2HopBridgeTokenAddress( this.tokenSymbol, sourceChain ) if (!l2HopBridgeTokenAddress) { throw new Error(`source chain "${sourceChain.slug}" is unsupported`) } const amm = await this.getAmm(sourceChain) const saddleSwap = await amm.getSaddleSwap() const canonicalTokenIndex = Number( (await saddleSwap.getTokenIndex(l2CanonicalTokenAddress)).toString() ) const hopTokenIndex = Number( (await saddleSwap.getTokenIndex(l2HopBridgeTokenAddress)).toString() ) if (toHop) { tokenIndexFrom = canonicalTokenIndex tokenIndexTo = hopTokenIndex } else { tokenIndexFrom = hopTokenIndex tokenIndexTo = canonicalTokenIndex } return saddleSwap.swap( tokenIndexFrom, tokenIndexTo, amount, minAmountOut, deadline ) } /** * @desc Returns Hop L1 Bridge Ethers contract instance. * @param {Object} signer - Ethers signer * @returns {Object} Ethers contract instance. */ public async getL1Bridge (signer: TProvider = this.signer) { const bridgeAddress = this.getL1BridgeAddress( this.tokenSymbol, Chain.Ethereum ) if (!bridgeAddress) { throw new Error(`token "${this.tokenSymbol}" is unsupported`) } const provider = await this.getSignerOrProvider(Chain.Ethereum, signer) return this.getContract(bridgeAddress, l1Erc20BridgeAbi, provider) } /** * @desc Returns Hop L2 Bridge Ethers contract instance. * @param {Object} chain - Chain model. * @param {Object} signer - Ethers signer * @returns {Object} Ethers contract instance. */ public async getL2Bridge (chain: TChain, signer: TProvider = this.signer) { chain = this.toChainModel(chain) const bridgeAddress = this.getL2BridgeAddress(this.tokenSymbol, chain) if (!bridgeAddress) { throw new Error( `token "${this.tokenSymbol}" on chain "${chain.slug}" is unsupported` ) } const provider = await this.getSignerOrProvider(chain, signer) return this.getContract(bridgeAddress, l2BridgeAbi, provider) } // ToDo: Docs public getAmm (chain: TChain) { chain = this.toChainModel(chain) if (chain.isL1) { throw new Error('No AMM exists on L1') } return new AMM(this.network, this.tokenSymbol, chain, this.signer) } /** * @desc Returns Hop Bridge AMM wrapper Ethers contract instance. * @param {Object} chain - Chain model. * @param {Object} signer - Ethers signer * @returns {Object} Ethers contract instance. */ public async getAmmWrapper (chain: TChain, signer: TProvider = this.signer) { chain = this.toChainModel(chain) const ammWrapperAddress = this.getL2AmmWrapperAddress( this.tokenSymbol, chain ) if (!ammWrapperAddress) { throw new Error( `token "${this.tokenSymbol}" on chain "${chain.slug}" is unsupported` ) } const provider = await this.getSignerOrProvider(chain, signer) return this.getContract(ammWrapperAddress, l2AmmWrapperAbi, provider) } /** * @desc Returns Hop Bridge Saddle reserve amounts. * @param {Object} chain - Chain model. * @returns {Array} Array containing reserve amounts for canonical token * and hTokens. */ public async getSaddleSwapReserves (chain: TChain = this.sourceChain) { const amm = this.getAmm(chain) const saddleSwap = await amm.getSaddleSwap() return Promise.all([ saddleSwap.getTokenBalance(0), saddleSwap.getTokenBalance(1) ]) } public async getReservesTotal (chain: TChain = this.sourceChain) { const [reserve0, reserve1] = await this.getSaddleSwapReserves(chain) return reserve0.add(reserve1) } /** * @desc Returns Hop Bridge Saddle Swap LP Token Ethers contract instance. * @param {Object} chain - Chain model. * @param {Object} signer - Ethers signer * @returns {Object} Ethers contract instance. */ public async getSaddleLpToken ( chain: TChain, signer: TProvider = this.signer ) { // ToDo: Remove ability to pass in signer like other token getters chain = this.toChainModel(chain) const saddleLpTokenAddress = this.getL2SaddleLpTokenAddress( this.tokenSymbol, chain ) if (!saddleLpTokenAddress) { throw new Error( `token "${this.tokenSymbol}" on chain "${chain.slug}" is unsupported` ) } // ToDo: Get actual saddle LP token symbol and name return new Token( this.network, chain, saddleLpTokenAddress, 18, `${this.tokenSymbol} LP` as TokenSymbol, `${this.tokenSymbol} LP`, '', signer, this.chainProviders ) } /** * @desc Sends transaction to add liquidity to AMM. * @param {Object} amount0Desired - Amount of token #0 in smallest unit * @param {Object} amount1Desired - Amount of token #1 in smallest unit * @param {Object} chain - Chain model of desired chain to add liquidity to. * @param {Object} options - Method options. * @returns {Object} Ethers transaction object. */ public async addLiquidity ( amount0Desired: TAmount, amount1Desired: TAmount, chain?: TChain, options: Partial<AddLiquidityOptions> = {} ) { if (!chain) { chain = this.sourceChain } amount0Desired = BigNumber.from(amount0Desired.toString()) chain = this.toChainModel(chain) const amm = new AMM( this.network, this.tokenSymbol, chain, this.signer, this.chainProviders ) return amm.addLiquidity( amount0Desired, amount1Desired, options.minToMint, options.deadline ) } /** * @desc Sends transaction to remove liquidity from AMM. * @param {Object} liquidityTokenAmount - Amount of LP tokens to burn. * @param {Object} chain - Chain model of desired chain to add liquidity to. * @param {Object} options - Method options. * @returns {Object} Ethers transaction object. */ public async removeLiquidity ( liquidityTokenAmount: TAmount, chain?: TChain, options: Partial<RemoveLiquidityOptions> = {} ) { if (!chain) { chain = this.sourceChain } chain = this.toChainModel(chain) const amm = new AMM( this.network, this.tokenSymbol, chain, this.signer, this.chainProviders ) return amm.removeLiquidity( liquidityTokenAmount, options.amount0Min, options.amount1Min, options.deadline ) } public async removeLiquidityOneToken ( lpTokenAmount: TAmount, tokenIndex: number, chain?: TChain, options: Partial<RemoveLiquidityOneTokenOptions> = {} ) { if (!chain) { chain = this.sourceChain } chain = this.toChainModel(chain) const amm = new AMM( this.network, this.tokenSymbol, chain, this.signer, this.chainProviders ) return amm.removeLiquidityOneToken( lpTokenAmount, tokenIndex, options?.amountMin, options?.deadline ) } public async removeLiquidityImbalance ( token0Amount: TAmount, token1Amount: TAmount, chain?: TChain, options: Partial<RemoveLiquidityImbalanceOptions> = {} ) { if (!chain) { chain = this.sourceChain } chain = this.toChainModel(chain) const amm = new AMM( this.network, this.tokenSymbol, chain, this.signer, this.chainProviders ) return amm.removeLiquidityImbalance( token0Amount, token1Amount, options?.maxBurnAmount, options?.deadline ) } public async calculateWithdrawOneToken ( tokenAmount: TAmount, tokenIndex: number, chain?: TChain ) { if (!chain) { chain = this.sourceChain } chain = this.toChainModel(chain) const amm = new AMM( this.network, this.tokenSymbol, chain, this.signer, this.chainProviders ) return amm.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ) } /** * @readonly * @desc The default deadline to use in seconds. * @returns {Number} Deadline in seconds */ public get defaultDeadlineSeconds () { return (Date.now() / 1000 + this.defaultDeadlineMinutes * 60) | 0 } /** * @readonly * @desc The time slot for the current time. * @param {Object} time - Unix timestamp (in seconds) to get the time slot. * @returns {Object} Time slot for the given time as BigNumber. */ public async getTimeSlot (time: TTime): Promise<BigNumber> { const bridge = await this.getL1Bridge() time = BigNumber.from(time.toString()) return bridge.getTimeSlot(time) } /** * @readonly * @desc The challenge period. * @returns {Object} The challenge period for the bridge as BigNumber. */ public async challengePeriod (): Promise<BigNumber> { const bridge = await this.getL1Bridge() return bridge.challengePeriod() } /** * @readonly * @desc The size of the time slots. * @returns {Object} The size of the time slots for the bridge as BigNumber. */ public async timeSlotSize (): Promise<BigNumber> { const bridge = await this.getL1Bridge() return bridge.TIME_SLOT_SIZE() } /** * @readonly * @desc The amount bonded for a time slot for a bonder. * @param {Object} chain - Chain model. * @param {Number} timeSlot - Time slot to get. * @param {String} bonder - Address of the bonder to check. * @returns {Object} Amount bonded for the bonder for the given time slot as BigNumber. */ public async timeSlotToAmountBonded ( timeSlot: TTimeSlot, bonder: string ): Promise<BigNumber> { const bridge = await this.getL1Bridge() timeSlot = BigNumber.from(timeSlot.toString()) return bridge.timeSlotToAmountBonded(timeSlot, bonder) } private async getTokenIndexes (path: string[], chain: TChain) { const amm = this.getAmm(chain) const saddleSwap = await amm.getSaddleSwap() const tokenIndexFrom = Number( (await saddleSwap.getTokenIndex(path[0])).toString() ) const tokenIndexTo = Number( (await saddleSwap.getTokenIndex(path[1])).toString() ) return [tokenIndexFrom, tokenIndexTo] } private async populateSendL1ToL2Tx (input: SendL1ToL2Input) { let { destinationChain, sourceChain, relayer, relayerFee, amount, amountOutMin, deadline, recipient, checkAllowance } = input if (!sourceChain.isL1) { // ToDo: Don't pass in sourceChain since it will always be L1 throw new Error('sourceChain must be L1') } const destinationChainId = destinationChain.chainId deadline = deadline === undefined ? this.defaultDeadlineSeconds : deadline amountOutMin = BigNumber.from((amountOutMin || 0).toString()) recipient = recipient || await this.getSignerAddress() if (!recipient) { throw new Error('recipient is required') } recipient = checksumAddress(recipient) const isNativeToken = this.isNativeToken(sourceChain) let l1Bridge = await this.getL1Bridge(sourceChain.provider) if (checkAllowance) { this.checkConnectedChain(this.signer, sourceChain) l1Bridge = await this.getL1Bridge(this.signer) if (!isNativeToken) { const l1Token = this.getL1Token() const allowance = await l1Token.allowance(l1Bridge.address) if (allowance.lt(BigNumber.from(amount))) { throw new Error(Errors.NotEnoughAllowance) } } } if (amountOutMin.lt(0)) { amountOutMin = BigNumber.from(0) } const txOptions = [ destinationChainId, recipient, amount || 0, amountOutMin, deadline, relayer, relayerFee || 0, { ...(await this.txOverrides(Chain.Ethereum)), value: isNativeToken ? amount : undefined } ] return l1Bridge.populateTransaction.sendToL2( ...txOptions ) } private async populateSendL2ToL1Tx (input: SendL2ToL1Input) { let { destinationChain, sourceChain, amount, destinationAmountOutMin, bonderFee, recipient, amountOutMin, deadline, destinationDeadline, checkAllowance } = input const destinationChainId = destinationChain.chainId deadline = deadline === undefined ? this.defaultDeadlineSeconds : deadline amountOutMin = BigNumber.from((amountOutMin || 0).toString()) destinationDeadline = destinationDeadline || 0 destinationAmountOutMin = BigNumber.from( (destinationAmountOutMin || 0).toString() ) if (destinationChain.isL1) { const attemptSwap = this.shouldAttemptSwap(destinationAmountOutMin, destinationDeadline) if (attemptSwap) { throw new Error('"destinationAmountOutMin" and "destinationDeadline" must be 0 when sending to an L1') } } recipient = recipient || await this.getSignerAddress() if (!recipient) { throw new Error('recipient is required') } recipient = checksumAddress(recipient) let ammWrapper = await this.getAmmWrapper(sourceChain, sourceChain.provider) let l2Bridge = await this.getL2Bridge(sourceChain, sourceChain.provider) const attemptSwapAtSource = this.shouldAttemptSwap(amountOutMin, deadline) const spender = attemptSwapAtSource ? ammWrapper.address : l2Bridge.address if (BigNumber.from(bonderFee).gt(amount)) { throw new Error(`amount must be greater than bonder fee. amount: ${amount.toString()}, bonderFee: ${bonderFee.toString()}`) } const isNativeToken = this.isNativeToken(sourceChain) if (checkAllowance) { this.checkConnectedChain(this.signer, sourceChain) ammWrapper = await this.getAmmWrapper(sourceChain, this.signer) l2Bridge = await this.getL2Bridge(sourceChain, this.signer) if (!isNativeToken) { const l2CanonicalToken = this.getCanonicalToken(sourceChain) const allowance = await l2CanonicalToken.allowance(spender) if (allowance.lt(BigNumber.from(amount))) { throw new Error(Errors.NotEnoughAllowance) } } } if (amountOutMin.lt(0)) { amountOutMin = BigNumber.from(0) } if (destinationAmountOutMin.lt(0)) { destinationAmountOutMin = BigNumber.from(0) } const txOptions = [ destinationChainId, recipient, amount, bonderFee, amountOutMin, deadline ] if (attemptSwapAtSource) { const additionalOptions = [ destinationAmountOutMin, destinationDeadline, { ...(await this.txOverrides(sourceChain)), value: isNativeToken ? amount : undefined } ] return ammWrapper.populateTransaction.swapAndSend( ...txOptions, ...additionalOptions ) } return l2Bridge.populateTransaction.send( ...txOptions, { ...(await this.txOverrides(sourceChain)), value: isNativeToken ? amount : undefined } ) } private async populateSendL2ToL2Tx (input: SendL2ToL2Input) { let { destinationChain, sourceChain, amount, destinationAmountOutMin, bonderFee, deadline, destinationDeadline, amountOutMin, recipient, checkAllowance } = input const destinationChainId = destinationChain.chainId deadline = deadline || this.defaultDeadlineSeconds destinationDeadline = destinationDeadline || this.defaultDeadlineSeconds amountOutMin = BigNumber.from((amountOutMin || 0).toString()) destinationAmountOutMin = BigNumber.from( (destinationAmountOutMin || 0).toString() ) if (BigNumber.from(bonderFee).gt(amount)) { throw new Error('Amount must be greater than bonder fee') } recipient = recipient || await this.getSignerAddress() if (!recipient) { throw new Error('recipient is required') } recipient = checksumAddress(recipient) let ammWrapper = await this.getAmmWrapper(sourceChain, sourceChain.provider) const isNativeToken = this.isNativeToken(sourceChain) if (checkAllowance) { this.checkConnectedChain(this.signer, sourceChain) ammWrapper = await this.getAmmWrapper(sourceChain, this.signer) if (!isNativeToken) { const l2CanonicalToken = this.getCanonicalToken(sourceChain) const allowance = await l2CanonicalToken.allowance(ammWrapper.address) if (allowance.lt(BigNumber.from(amount))) { throw new Error(Errors.NotEnoughAllowance) } } } if (amountOutMin.lt(0)) { amountOutMin = BigNumber.from(0) } if (destinationAmountOutMin.lt(0)) { destinationAmountOutMin = BigNumber.from(0) } const txOptions = [ destinationChainId, recipient, amount, bonderFee, amountOutMin, deadline, destinationAmountOutMin, destinationDeadline, { ...(await this.txOverrides(sourceChain)), value: isNativeToken ? amount : undefined } ] return ammWrapper.populateTransaction.swapAndSend(...txOptions) } private async calcToHTokenAmount ( amount: TAmount, chain: Chain ): Promise<BigNumber> { amount = BigNumber.from(amount.toString()) if (chain.isL1) { return amount } const amm = this.getAmm(chain) const saddleSwap = await amm.getSaddleSwap() if (amount.eq(0)) { return BigNumber.from(0) } const amountOut = await saddleSwap.calculateSwap( TokenIndex.CanonicalToken, TokenIndex.HopBridgeToken, amount ) return amountOut } private async calcFromHTokenAmount ( amount: TAmount, chain: Chain ): Promise<BigNumber> { amount = BigNumber.from(amount.toString()) if (chain.isL1) { return BigNumber.from(amount) } const amm = this.getAmm(chain) const saddleSwap = await amm.getSaddleSwap() if (amount.eq(0)) { return BigNumber.from(0) } const amountOut = await saddleSwap.calculateSwap( TokenIndex.HopBridgeToken, TokenIndex.CanonicalToken, amount ) return amountOut } private async getBonderFeeRelative ( amountIn: TAmount, sourceChain: TChain, destinationChain: TChain ) { sourceChain = this.toChainModel(sourceChain) destinationChain = this.toChainModel(destinationChain) if (sourceChain.isL1) { return BigNumber.from(0) } const hTokenAmount = await this.calcToHTokenAmount( amountIn.toString(), sourceChain ) const feeBps = this.getFeeBps(this.tokenSymbol, destinationChain) const bonderFeeRelative = hTokenAmount.mul(feeBps).div(10000) return bonderFeeRelative } private async getBonderFeeAbsolute (): Promise<BigNumber> { const token = this.toTokenModel(this.tokenSymbol) const tokenPrice = await this.priceFeed.getPriceByTokenSymbol(token.symbol) const minBonderFeeUsd = 0.25 const bonderFeeAbsolute = parseUnits( (minBonderFeeUsd / tokenPrice).toFixed(token.decimals), token.decimals ) return bonderFeeAbsolute } private getRate ( amountIn: BigNumber, amountOut: BigNumber, sourceToken: Token, destToken: Token ) { let rateBN if (amountIn.eq(0)) { rateBN = BigNumber.from(0) } else { const oneSourceBN = ethers.utils.parseUnits('1', sourceToken.decimals) rateBN = amountOut.mul(oneSourceBN).div(amountIn) } const rate = Number(ethers.utils.formatUnits(rateBN, destToken.decimals)) return rate } private getPriceImpact (rate: number, marketRate: number) { return ((marketRate - rate) / marketRate) * 100 } private async checkConnectedChain (signer: TProvider, chain: Chain) { const connectedChainId = await (signer as Signer)?.getChainId() if (connectedChainId !== chain.chainId) { throw new Error('invalid connected chain ID. Make sure signer provider is connected to source chain network') } } // Gnosis AMB bridge async getAmbBridge (chain: TChain) { chain = this.toChainModel(chain) if (chain.equals(Chain.Ethereum)) { const address = this.getL1AmbBridgeAddress(this.tokenSymbol, Chain.Gnosis) const provider = await this.getSignerOrProvider(Chain.Ethereum) return this.getContract(address, l1HomeAmbNativeToErc20, provider) } const address = this.getL2AmbBridgeAddress(this.tokenSymbol, Chain.Gnosis) const provider = await this.getSignerOrProvider(Chain.Gnosis) return this.getContract(address, l1HomeAmbNativeToErc20, provider) } getChainNativeToken (chain: TChain) { chain = this.toChainModel(chain) if (chain?.equals(Chain.Polygon)) { return this.toTokenModel(CanonicalToken.MATIC) } else if (chain?.equals(Chain.Gnosis)) { return this.toTokenModel(CanonicalToken.DAI) } return this.toTokenModel(CanonicalToken.ETH) } isNativeToken (chain?: TChain) { const token = this.getCanonicalToken(chain || this.sourceChain) return token.isNativeToken } async getEthBalance (chain: TChain = this.sourceChain, address?: string) { chain = this.toChainModel(chain) address = address ?? await this.getSignerAddress() if (!address) { throw new Error('address is required') } return chain.provider.getBalance(address) } isSupportedAsset (chain: TChain) { chain = this.toChainModel(chain) const supported = this.getSupportedAssets() return !!supported[chain.slug]?.[this.tokenSymbol] } getBonderAddress (sourceChain: TChain, destinationChain: TChain): string { return this._getBonderAddress(this.tokenSymbol, sourceChain, destinationChain) } shouldAttemptSwap (amountOutMin: BigNumber, deadline: BigNumberish): boolean { deadline = BigNumber.from(deadline?.toString() || 0) return amountOutMin?.gt(0) || deadline?.gt(0) } private async getGasEstimateFromAddress (sourceChain: TChain, destinationChain: TChain) { let address = await this.getSignerAddress() if (!address) { address = await this.getBonderAddress(sourceChain, destinationChain) } return address } } export default HopBridge
the_stack
import * as path from 'path'; import {Command, CLIError, flags} from '@microsoft/bf-cli-command'; import {Orchestrator, Utility} from '@microsoft/bf-orchestrator'; export default class OrchestratorTest extends Command { static description: string = `The "test" command can operate in three modes: test, evaluation, assessment. 1) Test mode: test a collection of utterance/label samples loaded from a test file against a previously generated Orchestrator .blu snapshot/train file, and create a detailed train/test evaluation report. 2) Evaluation mode: create an leave-one-out cross validation (LOOCV) evaluation report on a previously generated Orchestrator .blu snapshot/train file. 3) Assessment mode: assess a collection of utterance/label predictions against their ground-truth labels and create an evaluation report. This mode can evaluate predictions produced by other NLP or machine learning systems. There is no need for an Orchestrator base model. Notice that, this mode is generic and can apply to evaluate any ML systems, learners, models, and scenarios if a user can carefully construct the prediction and grounf-truth files by the specification detailed below. Essentially the key to a NLP data instance is a text (utterance, sentence, query, document, etc.), which is the basis of all the features feeding to a ML model. For other ML systems, the key to a data instance can be built directly from the features and put in place of text in a prediction and ground-truth file. The 'test' mode is activated if there is a '--test' argument set for a test file. The 'assessment' mode is activated if there is a '--prediction' argument set for a prediction file. If there is no '--test' or '--prediction' arguments, then "test" command runs on the 'evaluation' mode.`; static examples: Array<string> = [` $ bf orchestrator:test --in=./path/to/snapshot/file --test=./path/to/test/file/ --out=./path/to/output/ --model=./path/to/model/directory $ bf orchestrator:test --in=./path/to/ground-truth/file --prediction=./path/to/prediction/file --out=./path/to/output/folder/ $ bf orchestrator:test --in=./path/to/snapshot/file --out=./path/to/output/folder/ [--model=./path/to/model/directory]`] static flags: flags.Input<any> = { in: flags.string({char: 'i', description: '(required) Path to a previously created Orchestrator .blu file.'}), out: flags.string({char: 'o', description: '(required) Directory where analysis and output files will be placed.'}), model: flags.string({char: 'm', description: 'Optional directory for hosting Orchestrator config and base model files, not needed for the "assessment" mode.'}), entityModel: flags.string({char: 'e', description: 'Path to Orchestrator entity base model directory.'}), test: flags.string({char: 't', description: 'Optional path to a test file. This option enable the "test" mode.'}), prediction: flags.string({char: 'p', description: 'Optional path to a prediction label file, or comma-separated paths to a collection of (e.g., crosss-valiaton) files.'}), debug: flags.boolean({char: 'd'}), help: flags.help({char: 'h'}), } // ---- NOTE ---- advanced parameters removed from command line, but still can be set through environment variables. // // --fullEmbeddings Optional flag to run on full embeddings instead // of compact embeddings. // --obfuscate Optional flag to obfuscate labels and utterances // in evaluation reports or not. // -a, --ambiguousClosenessThreshold=threshold Optional ambiguous analysis threshold. Default to 0.2. // -l, --lowConfidenceScoreThreshold=threshold Optional low confidence analysis threshold. Default to 0.5. // -p, --multiLabelPredictionThreshold=threshold Optional numeral/plural/multi-label prediction threshold, // default to 1. For the default, only labels shared the same max scores are adopted as prediction. If // the threshold is lower than 1, the any labels with a prediction score higher will be adoopted as prediction. // -u, --unknownLabelPredictionThreshold=threshold Optional unknown label threshold, default to 0.3. // eslint-disable-next-line complexity async run(): Promise<void> { const {flags}: flags.Output = this.parse(OrchestratorTest); const flagsKeys: string[] = Object.keys(flags); if (Utility.isEmptyStringArray(flagsKeys)) { this._help(); } const inputPathConfiguration: string = flags.in; const outputPathConfiguration: string = flags.out; let baseModelPath: string = flags.model; if (baseModelPath) { baseModelPath = path.resolve(baseModelPath); } let entityBaseModelPath: string = flags.entityModel; if (entityBaseModelPath) { entityBaseModelPath = path.resolve(entityBaseModelPath); } let testPath: string = flags.test; if (testPath) { testPath = path.resolve(testPath); } let predictionPathConfiguration: string = flags.prediction; if (predictionPathConfiguration) { predictionPathConfiguration = path.resolve(predictionPathConfiguration); } try { let fullEmbeddings: boolean = false; if (process.env.fullEmbeddings) { fullEmbeddings = true; } let obfuscate: boolean = false; if (process.env.obfuscate) { obfuscate = true; } let ambiguousClosenessThresholdParameter: number = Utility.DefaultAmbiguousClosenessThresholdParameter; let lowConfidenceScoreThresholdParameter: number = Utility.DefaultLowConfidenceScoreThresholdParameter; let multiLabelPredictionThresholdParameter: number = Utility.DefaultMultiLabelPredictionThresholdParameter; let unknownLabelPredictionThresholdParameter: number = Utility.DefaultUnknownLabelPredictionThresholdParameter; if (process.env.ambiguousClosenessThreshold) { ambiguousClosenessThresholdParameter = Number(process.env.ambiguousClosenessThreshold); if (Number.isNaN(ambiguousClosenessThresholdParameter)) { Utility.writeStringLineToConsoleStderr(`ambiguous parameter "${process.env.ambiguousClosenessThreshold}" is not a number`); Utility.debuggingThrow(`ambiguous parameter "${process.env.ambiguousClosenessThreshold}" is not a number`); } } if (process.env.lowConfidenceScoreThreshold) { lowConfidenceScoreThresholdParameter = Number(process.env.lowConfidenceScoreThreshold); if (Number.isNaN(lowConfidenceScoreThresholdParameter)) { Utility.writeStringLineToConsoleStderr(`low-confidence parameter "${process.env.lowConfidenceScoreThreshold}" is not a number`); Utility.debuggingThrow(`low-confidence parameter "${process.env.lowConfidenceScoreThreshold}" is not a number`); } } if (process.env.multiLabelPredictionThreshold) { multiLabelPredictionThresholdParameter = Number(process.env.multiLabelPredictionThreshold); if (Number.isNaN(multiLabelPredictionThresholdParameter)) { Utility.writeStringLineToConsoleStderr(`multi-label threshold parameter "${process.env.multiLabelPredictionThreshold}" is not a number`); Utility.debuggingThrow(`multi-label threshold parameter "${process.env.multiLabelPredictionThreshold}" is not a number`); } } if (process.env.unknownLabelPredictionThreshold) { unknownLabelPredictionThresholdParameter = Number(process.env.unknownLabelPredictionThreshold); if (Number.isNaN(unknownLabelPredictionThresholdParameter)) { Utility.writeStringLineToConsoleStderr(`unknown threshold parameter "${process.env.unknownLabelPredictionThreshold}" is not a number`); Utility.debuggingThrow(`unknown threshold parameter "${process.env.unknownLabelPredictionThreshold}" is not a number`); } } Utility.resetFlagToPrintDebuggingLogToConsole(flags.debug); Utility.debuggingLog(`OrchestratorTest.run(): this.id=${this.id}`); Utility.debuggingLog(`OrchestratorTest.run(): inputPathConfiguration=${inputPathConfiguration}`); Utility.debuggingLog(`OrchestratorTest.run(): outputPathConfiguration=${outputPathConfiguration}`); Utility.debuggingLog(`OrchestratorTest.run(): baseModelPath=${baseModelPath}`); Utility.debuggingLog(`OrchestratorTest.run(): entityBaseModelPath=${entityBaseModelPath}`); Utility.debuggingLog(`OrchestratorTest.run(): testPath=${testPath}`); Utility.debuggingLog(`OrchestratorTest.run(): predictionPathConfiguration=${predictionPathConfiguration}`); Utility.debuggingLog(`OrchestratorTest.run(): ambiguousClosenessThresholdParameter=${ambiguousClosenessThresholdParameter}`); Utility.debuggingLog(`OrchestratorTest.run(): lowConfidenceScoreThresholdParameter=${lowConfidenceScoreThresholdParameter}`); Utility.debuggingLog(`OrchestratorTest.run(): multiLabelPredictionThresholdParameter=${multiLabelPredictionThresholdParameter}`); Utility.debuggingLog(`OrchestratorTest.run(): unknownLabelPredictionThresholdParameter=${unknownLabelPredictionThresholdParameter}`); Utility.debuggingLog(`OrchestratorTest.run(): fullEmbeddings=${fullEmbeddings}`); Utility.debuggingLog(`OrchestratorTest.run(): obfuscate=${obfuscate}`); if (testPath) { try { this.trackEvent(`${this.id}:test`, {callee: 'test'}); } catch (error) { } await Orchestrator.testAsync( baseModelPath, inputPathConfiguration, testPath, outputPathConfiguration, entityBaseModelPath, ambiguousClosenessThresholdParameter, lowConfidenceScoreThresholdParameter, multiLabelPredictionThresholdParameter, unknownLabelPredictionThresholdParameter, fullEmbeddings, obfuscate); } else if (predictionPathConfiguration) { try { this.trackEvent(`${this.id}:assess`, {callee: 'assess'}); } catch (error) { } await Orchestrator.assessAsync( inputPathConfiguration, predictionPathConfiguration, outputPathConfiguration, obfuscate); } else { try { this.trackEvent(`${this.id}:evaluate`, {callee: 'evaluate'}); } catch (error) { } await Orchestrator.evaluateAsync( inputPathConfiguration, outputPathConfiguration, baseModelPath, entityBaseModelPath, ambiguousClosenessThresholdParameter, lowConfidenceScoreThresholdParameter, multiLabelPredictionThresholdParameter, unknownLabelPredictionThresholdParameter, fullEmbeddings, obfuscate); } } catch (error) { throw (new CLIError(error)); } } }
the_stack
declare module evothings { export module ble { /** Information extracted from a scanRecord. Some or all of the fields may be undefined. This varies between BLE devices. * Depending on OS version and BLE device, additional fields, not documented here, may be present. * @typedef {Object} AdvertisementData * @property {string} kCBAdvDataLocalName - The device's name. Equal to DeviceInfo.name. * @property {number} kCBAdvDataChannel - A positive integer, the BLE channel on which the device listens for connections. Ignore this number. * @property {boolean} kCBAdvDataIsConnectable - True if the device accepts connections. False if it doesn't. * @property {array} kCBAdvDataServiceUUIDs - Array of strings, the UUIDs of services advertised by the device. Formatted according to RFC 4122, all lowercase. * @property {string} kCBAdvDataManufacturerData - Base-64-encoded binary data. This field is used by BLE devices to advertise custom data that don't fit into any of the other fields. */ interface AdvertisementData { kCBAdvDataLocalName : string; kCBAdvDataChannel : number; kCBAdvDataIsConnectable : boolean; kCBAdvDataServiceUUIDs : string[]; kCBAdvDataManufacturerData : string; } interface TranslationList {[index: number] : string } /** Info about a BLE device. * @typedef {Object} DeviceInfo //* @property {string} address - Has the form xx:xx:xx:xx:xx:xx, where x are hexadecimal characters. * @property {string} address - Uniquely identifies the device. Pass this to connect(). * The form of the address depends on the host platform. * @property {number} rssi - A negative integer, the signal strength in decibels. * @property {string} name - The device's name, or nil. * @property {string} scanRecord - Base64-encoded binary data. Its meaning is device-specific. Not available on iOS. * @property {AdvertisementData} advertisementData - Object containing some of the data from the scanRecord. Available natively on iOS. Available on Android by parsing the scanRecord, which is implemented in the library {@link https://github.com/evothings/evothings-examples/tree/master/resources/libs/evothings/easyble|easyble.js}. */ interface DeviceInfo { address : string; rssi : number; name : string; scanRecord : string; advertisementData : AdvertisementData; } interface FailCallback { (errorString:string) :void; } interface EmptyCallback { () :void; } enum ConnectionState { STATE_DISCONNECTED, STATE_CONNECTING, STATE_CONNECTED, STATE_DISCONNECTING, } /** Info about connection events and state. * @typedef {Object} ConnectInfo * @property {number} deviceHandle - Handle to the device. Save it for other function calls. * @property {number} state - One of the {@link connectionState} keys. */ interface ConnectInfo { deviceHandle : number; state : ConnectionState; } enum ServiceType { SERVICE_TYPE_PRIMARY, SERVICE_TYPE_SECONDARY } enum WriteType { WRITE_TYPE_NO_RESPONSE = 1, WRITE_TYPE_DEFAULT = 2, WRITE_TYPE_SIGNED = 4, } enum Permission { PERMISSION_READ = 1, PERMISSION_READ_ENCRYPTED = 2, PERMISSION_READ_ENCRYPTED_MITM = 4, PERMISSION_WRITE = 16, PERMISSION_WRITE_ENCRYPTED = 32, PERMISSION_WRITE_ENCRYPTED_MITM = 64, PERMISSION_WRITE_SIGNED = 128, PERMISSION_WRITE_SIGNED_MITM = 256, } /** Describes a GATT service. * @typedef {Object} Service * @property {number} handle * @property {string} uuid - Formatted according to RFC 4122, all lowercase. * @property {serviceType} type */ interface Service { handle : number; uuid : string; type : ServiceType; } /** Describes a GATT descriptor. * @typedef {Object} Descriptor * @property {number} handle * @property {string} uuid - Formatted according to RFC 4122, all lowercase. * @property {permission} permissions - Bitmask of zero or more permission flags. * */ interface Descriptor { handle : number; uuid : string; permission : number; } /** Describes a GATT characteristic. * @typedef {Object} Characteristic * @property {number} handle * @property {string} uuid - Formatted according to RFC 4122, all lowercase. * @property {permission} permissions - Bitmask of zero or more permission flags. * @property {property} properties - Bitmask of zero or more property flags. * @property {writeType} writeType */ interface Characteristic { handle : number; uuid : string; permission : number; properties : number; writeType : WriteType; } interface CharacteristicExtended extends Characteristic { descriptors : Descriptor[]; } interface ServiceExtended extends Service { characteristics : CharacteristicExtended[]; } /** * @callback serviceCallback * @param {Array} services - Array of {@link Service} objects. */ interface ServiceCallback { (services:Service[]) : void } /** @module com.evothings.ble */ /** Starts scanning for devices. * <p>Found devices and errors will be reported to the supplied callbacks.</p> * <p>Will keep scanning indefinitely until you call stopScan().</p> * To conserve energy, call stopScan() as soon as you've found the device you're looking for. * <p>Calling this function while scanning is in progress has no effect?</p> * * @param {scanCallback} win * @param {failCallback} fail * * @example evothings.ble.startScan( function(device) { console.log('BLE startScan found device named: ' + device.name); }, function(errorCode) { console.log('BLE startScan error: ' + errorCode); } ); */ export function startScan(win:(device:DeviceInfo) => void, fail:FailCallback); /** This function is a parameter to startScan() and is called when a new device is discovered. * @callback scanCallback * @param {DeviceInfo} device */ /** This function is called when an operation fails. * @callback failCallback * @param {string} errorString - A human-readable string that describes the error that occurred. */ /** Stops scanning for devices. * * @example evothings.ble.stopScan(); */ export function stopScan(); /** Connect to a remote device. * @param {string} address - From scanCallback. * @param {connectCallback} win * @param {failCallback} fail * @example evothings.ble.connect( address, function(info) { console.log('BLE connect status for device: ' + info.deviceHandle + ' state: ' + info.state); }, function(errorCode) { console.log('BLE connect error: ' + errorCode); } ); */ export function connect(address:string, win:(info:ConnectInfo) =>void, fail:FailCallback); /** Will be called whenever the device's connection state changes. * @callback connectCallback * @param {ConnectInfo} info */ /** Info about connection events and state. * @typedef {Object} ConnectInfo * @property {number} deviceHandle - Handle to the device. Save it for other function calls. * @property {number} state - One of the {@link connectionState} keys. */ /** A number-string map describing possible connection states. * @global * @readonly * @enum {string} */ /* interface ConnectionState { 0: 'STATE_DISCONNECTED'; 1: 'STATE_CONNECTING'; 2: 'STATE_CONNECTED'; 3: 'STATE_DISCONNECTING'; }; */ export var connectionState:TranslationList; /** Close the connection to a remote device. * <p>Frees any native resources associated with the device. * <p>Does not cause any callbacks to the function passed to connect(). * @param {number} deviceHandle - A handle from {@link connectCallback}. * @example evothings.ble.close(deviceHandle); */ export function close(deviceHandle); /** Fetch the remote device's RSSI (signal strength). * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {rssiCallback} win * @param {failCallback} fail * @example evothings.ble.rssi( deviceHandle, function(rssi) { console.log('BLE rssi: ' + rssi); }, function(errorCode) { console.log('BLE rssi error: ' + errorCode); } ); */ export function rssi(deviceHandle:number, win, fail:FailCallback); /** This function is called with an RSSI value. * @callback rssiCallback * @param {number} rssi - A negative integer, the signal strength in decibels. */ /** Fetch information about a remote device's services. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {serviceCallback} win - Called with array of {@link Service} objects. * @param {failCallback} fail * @example evothings.ble.services( deviceHandle, function(services) { for (var i = 0; i < services.length; i++) { var service = services[i]; console.log('BLE service: '); console.log(' ' + service.handle); console.log(' ' + service.uuid); console.log(' ' + service.serviceType); } }, function(errorCode) { console.log('BLE services error: ' + errorCode); }); */ export function services(deviceHandle:number, win:ServiceCallback, fail:FailCallback) ; /** A number-string map describing possible service types. * @global * @readonly * @enum {string} */ /* serviceType = { 0: 'SERVICE_TYPE_PRIMARY', 1: 'SERVICE_TYPE_SECONDARY', }; */ export var serviceType:TranslationList; /** Fetch information about a service's characteristics. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} serviceHandle - A handle from {@link serviceCallback}. * @param {characteristicCallback} win - Called with array of {@link Characteristic} objects. * @param {failCallback} fail * @example evothings.ble.characteristics( deviceHandle, service.handle, function(characteristics) { for (var i = 0; i < characteristics.length; i++) { var characteristic = characteristics[i]; console.log('BLE characteristic: ' + characteristic.uuid); } }, function(errorCode) { console.log('BLE characteristics error: ' + errorCode); }); */ export function characteristics(deviceHandle:number, serviceHandle : number, win, fail:FailCallback); /** * @callback characteristicCallback * @param {Array} characteristics - Array of {@link Characteristic} objects. */ /** Describes a GATT characteristic. * @typedef {Object} Characteristic * @property {number} handle * @property {string} uuid - Formatted according to RFC 4122, all lowercase. * @property {permission} permissions - Bitmask of zero or more permission flags. * @property {property} properties - Bitmask of zero or more property flags. * @property {writeType} writeType */ /** A number-string map describing possible permission flags. * @global * @readonly * @enum {string} */ /* permission = { 1: 'PERMISSION_READ', 2: 'PERMISSION_READ_ENCRYPTED', 4: 'PERMISSION_READ_ENCRYPTED_MITM', 16: 'PERMISSION_WRITE', 32: 'PERMISSION_WRITE_ENCRYPTED', 64: 'PERMISSION_WRITE_ENCRYPTED_MITM', 128: 'PERMISSION_WRITE_SIGNED', 256: 'PERMISSION_WRITE_SIGNED_MITM', } */ export var permission:TranslationList; /** A number-string map describing possible property flags. * @global * @readonly * @enum {string} */ /* interface Property = { 1: 'PROPERTY_BROADCAST', 2: 'PROPERTY_READ', 4: 'PROPERTY_WRITE_NO_RESPONSE', 8: 'PROPERTY_WRITE', 16: 'PROPERTY_NOTIFY', 32: 'PROPERTY_INDICATE', 64: 'PROPERTY_SIGNED_WRITE', 128: 'PROPERTY_EXTENDED_PROPS', }; */ export var property:TranslationList; /** A number-string map describing possible write types. * @global * @readonly * @enum {string} */ export var writeType:TranslationList; /** Fetch information about a characteristic's descriptors. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} characteristicHandle - A handle from {@link characteristicCallback}. * @param {descriptorCallback} win - Called with array of {@link Descriptor} objects. * @param {failCallback} fail * @example evothings.ble.descriptors( deviceHandle, characteristic.handle, function(descriptors) { for (var i = 0; i < descriptors.length; i++) { var descriptor = descriptors[i]; console.log('BLE descriptor: ' + descriptor.uuid); } }, function(errorCode) { console.log('BLE descriptors error: ' + errorCode); }); */ export function descriptors(deviceHandle:number, characteristicHandle:number, win, fail:FailCallback); /** * @callback descriptorCallback * @param {Array} descriptors - Array of {@link Descriptor} objects. */ // TODO: What is read* ? // read*: fetch and return value in one op. // values should be cached on the JS side, if at all. /** * @callback dataCallback * @param {ArrayBuffer} data */ /** Reads a characteristic's value from a remote device. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} characteristicHandle - A handle from {@link characteristicCallback}. * @param {dataCallback} win * @param {failCallback} fail * @example evothings.ble.readCharacteristic( deviceHandle, characteristic.handle, function(data) { console.log('BLE characteristic data: ' + evothings.ble.fromUtf8(data)); }, function(errorCode) { console.log('BLE readCharacteristic error: ' + errorCode); }); */ export function readCharacteristic(deviceHandle:number, characteristicHandle:number, win:(data:ArrayBuffer) =>void, fail:FailCallback); /** Reads a descriptor's value from a remote device. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} descriptorHandle - A handle from {@link descriptorCallback}. * @param {dataCallback} win * @param {failCallback} fail * @example evothings.ble.readDescriptor( deviceHandle, descriptor.handle, function(data) { console.log('BLE descriptor data: ' + evothings.ble.fromUtf8(data)); }, function(errorCode) { console.log('BLE readDescriptor error: ' + errorCode); }); */ export function readDescriptor(deviceHandle:number, descriptorHandle:number, win:(data:ArrayBuffer) =>void, fail:FailCallback); /** * @callback emptyCallback - Callback that takes no parameters. This callback indicates that an operation was successful, without specifying and additional information. */ /** Write a characteristic's value to the remote device. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} characteristicHandle - A handle from {@link characteristicCallback}. * @param {ArrayBufferView} data - The value to be written. * @param {emptyCallback} win * @param {failCallback} fail * @example TODO: Add example. */ export function writeCharacteristic(deviceHandle:number, characteristicHandle:number, data:ArrayBufferView, win:EmptyCallback, fail:FailCallback) ; /** Write a descriptor's value to a remote device. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} descriptorHandle - A handle from {@link descriptorCallback}. * @param {ArrayBufferView} data - The value to be written. * @param {emptyCallback} win * @param {failCallback} fail * @example TODO: Add example. */ export function writeDescriptor(deviceHandle:number, descriptorHandle:number, data:ArrayBufferView, win:EmptyCallback, fail:FailCallback) /** Request notification on changes to a characteristic's value. * This is more efficient than polling the value using readCharacteristic(). * * <p>To activate notifications, * some (all?) devices require you to write a special value to a separate configuration characteristic, * in addition to calling this function. * Refer to your device's documentation. * * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} characteristicHandle - A handle from {@link characteristicCallback}. * @param {dataCallback} win - Called every time the value changes. * @param {failCallback} fail * @example evothings.ble.enableNotification( deviceHandle, characteristic.handle, function(data) { console.log('BLE characteristic data: ' + evothings.ble.fromUtf8(data)); }, function(errorCode) { console.log('BLE enableNotification error: ' + errorCode); }); */ export function enableNotification(deviceHandle:number, characteristicHandle:number, win:(data:ArrayBuffer) =>void, fail:FailCallback); /** Disable notification of changes to a characteristic's value. * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {number} characteristicHandle - A handle from {@link characteristicCallback}. * @param {emptyCallback} win * @param {failCallback} fail * @example evothings.ble.disableNotification( deviceHandle, characteristic.handle, function() { console.log('BLE characteristic notification disabled'); }, function(errorCode) { console.log('BLE disableNotification error: ' + errorCode); }); */ export function disableNotification(deviceHandle:number, characteristicHandle:number, win:EmptyCallback, fail); /** i is an integer. It is converted to byte and put in an array[1]. * The array is returned. * <p>assert(string.charCodeAt(0) == i). * * @param {number} i * @param {dataCallback} win - Called every time the value changes. */ export function testCharConversion(i:number, win:(data:ArrayBuffer) =>void); /** Resets the device's Bluetooth system. * This is useful on some buggy devices where BLE functions stops responding until reset. * Available on Android 4.3+. This function takes 3-5 seconds to reset BLE. * On iOS this function stops any ongoing scan operation and disconnects * all connected devices. * * @param {emptyCallback} win * @param {failCallback} fail */ export function reset(win:EmptyCallback, fail:FailCallback); /** Converts an ArrayBuffer containing UTF-8 data to a JavaScript String. * @param {ArrayBuffer} a * @returns string */ export function fromUtf8(a:ArrayBuffer):string; /** Converts a JavaScript String to an Uint8Array containing UTF-8 data. * @param {string} s * @returns Uint8Array */ export function toUtf8(s:string):Uint8Array; /** Fetch information about a remote device's services, * as well as its associated characteristics and descriptors. * * This function is an easy-to-use wrapper of the low-level functions * ble.services(), ble.characteristics() and ble.descriptors(). * * @param {number} deviceHandle - A handle from {@link connectCallback}. * @param {serviceCallback} win - Called with array of {@link Service} objects. * Those Service objects each have an additional field "characteristics", which is an array of {@link Characteristic} objects. * Those Characteristic objects each have an additional field "descriptors", which is an array of {@link Descriptor} objects. * @param {failCallback} fail */ export function readAllServiceData(deviceHandle:number, win:(services:ServiceExtended[])=>void, fail:FailCallback); } }
the_stack
type Size = { width: number, height: number }; /** * Wraps the native Canvas element and overrides its CanvasRenderingContext2D to * provide resolution independent rendering based on `window.devicePixelRatio`. */ export class HdpiCanvas { readonly document: Document; readonly element: HTMLCanvasElement; readonly context: CanvasRenderingContext2D; // The width/height attributes of the Canvas element default to // 300/150 according to w3.org. constructor(document = window.document, width = 600, height = 300) { this.document = document; this.element = document.createElement('canvas'); this.context = this.element.getContext('2d')!; this.element.style.userSelect = 'none'; this.element.style.display = 'block'; this.setPixelRatio(); this.resize(width, height); } private _container: HTMLElement | undefined = undefined; set container(value: HTMLElement | undefined) { if (this._container !== value) { this.remove(); if (value) { value.appendChild(this.element); } this._container = value; } } get container(): HTMLElement | undefined { return this._container; } private remove() { const { parentNode } = this.element; if (parentNode != null) { parentNode.removeChild(this.element); } } destroy() { this.element.remove(); (this as any)._canvas = undefined; Object.freeze(this); } toImage(): HTMLImageElement { const img = this.document.createElement('img'); img.src = this.getDataURL(); return img; } getDataURL(type?: string): string { return this.element.toDataURL(type); } /** * @param fileName The name of the file upon save. The `.png` extension is going to be added automatically. */ download(fileName?: string) { fileName = ((fileName || '').trim() || 'image') + '.png'; // Chart images saved as JPEG are a few times larger at 50% quality than PNG images, // so we don't support saving to JPEG. const type = 'image/png'; const dataUrl = this.getDataURL(type); const document = this.document; if (navigator.msSaveOrOpenBlob) { // IE11 const binary = atob(dataUrl.split(',')[1]); // strip the `data:image/png;base64,` part const array = []; for (let i = 0, n = binary.length; i < n; i++) { array.push(binary.charCodeAt(i)); } const blob = new Blob([new Uint8Array(array)], { type }); navigator.msSaveOrOpenBlob(blob, fileName); } else { const a = document.createElement('a'); a.href = dataUrl; a.download = fileName; a.style.display = 'none'; document.body.appendChild(a); // required for the `click` to work in Firefox a.click(); document.body.removeChild(a); } } // `NaN` is deliberate here, so that overrides are always applied // and the `resetTransform` inside the `resize` method works in IE11. _pixelRatio: number = NaN; get pixelRatio(): number { return this._pixelRatio; } /** * Changes the pixel ratio of the Canvas element to the given value, * or uses the window.devicePixelRatio (default), then resizes the Canvas * element accordingly (default). */ setPixelRatio(ratio?: number) { const pixelRatio = ratio || window.devicePixelRatio; if (pixelRatio === this.pixelRatio) { return; } HdpiCanvas.overrideScale(this.context, pixelRatio); this._pixelRatio = pixelRatio; this.resize(this.width, this.height); } set pixelated(value: boolean) { this.element.style.imageRendering = value ? 'pixelated' : 'auto'; } get pixelated(): boolean { return this.element.style.imageRendering === 'pixelated'; } private _width: number = 100; get width(): number { return this._width; } private _height: number = 100; get height(): number { return this._height; } resize(width: number, height: number) { if (!(width > 0 && height > 0)) { return; } const { element, context, pixelRatio } = this; element.width = Math.round(width * pixelRatio); element.height = Math.round(height * pixelRatio); element.style.width = width + 'px'; element.style.height = height + 'px'; context.resetTransform(); this._width = width; this._height = height; } // 2D canvas context used for measuring text. private static _textMeasuringContext?: CanvasRenderingContext2D; private static get textMeasuringContext(): CanvasRenderingContext2D { if (this._textMeasuringContext) { return this._textMeasuringContext; } const canvas = document.createElement('canvas'); return this._textMeasuringContext = canvas.getContext('2d')!; } // Offscreen SVGTextElement for measuring text. This fallback method // is at least 25 times slower than `CanvasRenderingContext2D.measureText`. // Using a <span> and its `getBoundingClientRect` for text measurement // is also slow and often results in a grossly incorrect measured height. private static _svgText?: SVGTextElement; private static get svgText(): SVGTextElement { if (this._svgText) { return this._svgText; } const xmlns = 'http://www.w3.org/2000/svg'; const svg = document.createElementNS(xmlns, 'svg'); svg.setAttribute('width', '100'); svg.setAttribute('height', '100'); // Add a descriptive class name in case someone sees this SVG element // in devtools and wonders about its purpose: if (svg.classList) { svg.classList.add('text-measuring-svg'); } else { svg.setAttribute('class', 'text-measuring-svg'); } svg.style.position = 'absolute'; svg.style.top = '-1000px'; svg.style.visibility = 'hidden'; const svgText = document.createElementNS(xmlns, 'text'); svgText.setAttribute('x', '0'); svgText.setAttribute('y', '30'); svgText.setAttribute('text', 'black'); svg.appendChild(svgText); document.body.appendChild(svg); this._svgText = svgText; return svgText; } private static _has?: { textMetrics: boolean, getTransform: boolean }; static get has() { if (this._has) { return this._has; } const isChrome = navigator.userAgent.indexOf('Chrome') > -1; const isFirefox = navigator.userAgent.indexOf('Firefox') > -1; const isSafari = !isChrome && navigator.userAgent.indexOf('Safari') > -1; return this._has = Object.freeze({ textMetrics: this.textMeasuringContext.measureText('test').actualBoundingBoxDescent !== undefined // Firefox implemented advanced TextMetrics object in v74: // https://bugzilla.mozilla.org/show_bug.cgi?id=1102584 // but it's buggy, so we'll keed using the SVG for text measurement in Firefox for now. && !isFirefox && !isSafari, getTransform: this.textMeasuringContext.getTransform !== undefined }); } static measureText(text: string, font: string, textBaseline: CanvasTextBaseline, textAlign: CanvasTextAlign): TextMetrics { const ctx = this.textMeasuringContext; ctx.font = font; ctx.textBaseline = textBaseline; ctx.textAlign = textAlign; return ctx.measureText(text); } /** * Returns the width and height of the measured text. * @param text The single-line text to measure. * @param font The font shorthand string. */ static getTextSize(text: string, font: string): Size { if (this.has.textMetrics) { const ctx = this.textMeasuringContext; ctx.font = font; const metrics = ctx.measureText(text); return { width: metrics.width, height: metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent }; } else { return this.measureSvgText(text, font); } } private static textSizeCache: { [font: string]: { [text: string]: Size } } = {}; private static measureSvgText(text: string, font: string): Size { const cache = this.textSizeCache; const fontCache = cache[font]; // Note: consider not caching the size of numeric strings. // For example: if (isNaN(+text)) { // skip if (fontCache) { const size = fontCache[text]; if (size) { return size; } } else { cache[font] = {}; } const svgText = this.svgText; svgText.style.font = font; svgText.textContent = text; // `getBBox` returns an instance of `SVGRect` with the same `width` and `height` // measurements as `DOMRect` instance returned by the `getBoundingClientRect`. // But the `SVGRect` instance has half the properties of the `DOMRect`, // so we use the `getBBox` method. const bbox = svgText.getBBox(); const size: Size = { width: bbox.width, height: bbox.height }; cache[font][text] = size; return size; } static overrideScale(ctx: CanvasRenderingContext2D, scale: number) { let depth = 0; const overrides = { save() { this.$save(); depth++; }, restore() { if (depth > 0) { this.$restore(); depth--; } }, setTransform(a: number, b: number, c: number, d: number, e: number, f: number) { this.$setTransform( a * scale, b * scale, c * scale, d * scale, e * scale, f * scale ); }, resetTransform() { // As of Jan 8, 2019, `resetTransform` is still an "experimental technology", // and doesn't work in IE11 and Edge 44. this.$setTransform(scale, 0, 0, scale, 0, 0); this.save(); depth = 0; // The scale above will be impossible to restore, // because we override the `ctx.restore` above and // check `depth` there. } } as any; for (const name in overrides) { if (overrides.hasOwnProperty(name)) { // Save native methods under prefixed names, // if this hasn't been done by the previous overrides already. if (!(ctx as any)['$' + name]) { (ctx as any)['$' + name] = (ctx as any)[name]; } // Replace native methods with overrides, // or previous overrides with the new ones. (ctx as any)[name] = overrides[name]; } } } }
the_stack
import { FillQuoteTransformerOrderType } from '@0x/protocol-utils'; import { BigNumber } from '@0x/utils'; import { constants } from '../constants'; import { MarketOperation } from '../types'; import { FeeSchedule, NativeLimitOrderFillData, OptimizedMarketOrder } from './market_operation_utils/types'; import { getNativeAdjustedTakerFeeAmount } from './utils'; const { PROTOCOL_FEE_MULTIPLIER, ZERO_AMOUNT } = constants; const { ROUND_DOWN, ROUND_UP } = BigNumber; // tslint:disable completed-docs export interface QuoteFillResult { // Maker asset bought. makerAssetAmount: BigNumber; // Taker asset sold. takerAssetAmount: BigNumber; // Taker fees that can be paid with the maker asset. takerFeeMakerAssetAmount: BigNumber; // Taker fees that can be paid with the taker asset. takerFeeTakerAssetAmount: BigNumber; // Total maker asset amount bought (including fees). totalMakerAssetAmount: BigNumber; // Total taker asset amount sold (including fees). totalTakerAssetAmount: BigNumber; // Protocol fees paid. protocolFeeAmount: BigNumber; // (Estimated) gas used. gas: number; // Fill amounts by source. // For sells, this is the taker assets sold. // For buys, this is the maker assets bought. fillAmountBySource: { [source: string]: BigNumber }; } interface IntermediateQuoteFillResult { // Input tokens filled. Taker asset for sells, maker asset for buys. input: BigNumber; // Output tokens filled. Maker asset for sells, taker asset for buys. output: BigNumber; // Taker fees that can be paid with the input token. // Positive for sells, negative for buys. inputFee: BigNumber; // Taker fees that can be paid with the output token. // Negative for sells, positive for buys. outputFee: BigNumber; // Protocol fees paid. protocolFee: BigNumber; // (Estimated) gas used. gas: number; // Input amounts filled by sources. inputBySource: { [source: string]: BigNumber }; } const EMPTY_QUOTE_INTERMEDIATE_FILL_RESULT = { input: ZERO_AMOUNT, output: ZERO_AMOUNT, outputFee: ZERO_AMOUNT, inputFee: ZERO_AMOUNT, protocolFee: ZERO_AMOUNT, gas: 0, }; export interface QuoteFillInfo { orders: OptimizedMarketOrder[]; fillAmount: BigNumber; gasPrice: BigNumber; side: MarketOperation; opts: Partial<QuoteFillInfoOpts>; } export interface QuoteFillInfoOpts { gasSchedule: FeeSchedule; protocolFeeMultiplier: BigNumber; slippage: number; } const DEFAULT_SIMULATED_FILL_QUOTE_INFO_OPTS: QuoteFillInfoOpts = { gasSchedule: {}, protocolFeeMultiplier: PROTOCOL_FEE_MULTIPLIER, slippage: 0, }; export interface QuoteFillOrderCall { order: OptimizedMarketOrder; // Total input amount defined in the order. totalOrderInput: BigNumber; // Total output amount defined in the order. totalOrderOutput: BigNumber; // Total fees payable with input token, defined in the order. // Positive for sells, negative for buys. totalOrderInputFee: BigNumber; // Total fees payable with output token, defined in the order. // Negative for sells, positive for buys. totalOrderOutputFee: BigNumber; } // Simulates filling a quote in the best case. export function simulateBestCaseFill(quoteInfo: QuoteFillInfo): QuoteFillResult { const opts = { ...DEFAULT_SIMULATED_FILL_QUOTE_INFO_OPTS, ...quoteInfo.opts, }; const protocolFeePerFillOrder = quoteInfo.gasPrice.times(opts.protocolFeeMultiplier); const result = fillQuoteOrders( createBestCaseFillOrderCalls(quoteInfo), quoteInfo.fillAmount, protocolFeePerFillOrder, opts.gasSchedule, ); return fromIntermediateQuoteFillResult(result, quoteInfo); } // Simulates filling a quote in the worst case. export function simulateWorstCaseFill(quoteInfo: QuoteFillInfo): QuoteFillResult { const opts = { ...DEFAULT_SIMULATED_FILL_QUOTE_INFO_OPTS, ...quoteInfo.opts, }; const protocolFeePerFillOrder = quoteInfo.gasPrice.times(opts.protocolFeeMultiplier); const bestCase = createBestCaseFillOrderCalls(quoteInfo); const result = { ...fillQuoteOrders(bestCase, quoteInfo.fillAmount, protocolFeePerFillOrder, opts.gasSchedule), // Worst case gas and protocol fee is hitting all orders. gas: getTotalGasUsedByFills(quoteInfo.orders, opts.gasSchedule), protocolFee: protocolFeePerFillOrder.times(quoteInfo.orders.filter(o => hasProtocolFee(o)).length), }; // Adjust the output by 1-slippage for the worst case if it is a sell // Adjust the output by 1+slippage for the worst case if it is a buy result.output = quoteInfo.side === MarketOperation.Sell ? result.output.times(1 - opts.slippage).integerValue(BigNumber.ROUND_DOWN) : result.output.times(1 + opts.slippage).integerValue(BigNumber.ROUND_UP); return fromIntermediateQuoteFillResult(result, quoteInfo); } export function fillQuoteOrders( fillOrders: QuoteFillOrderCall[], inputAmount: BigNumber, protocolFeePerFillOrder: BigNumber, gasSchedule: FeeSchedule, ): IntermediateQuoteFillResult { const result: IntermediateQuoteFillResult = { ...EMPTY_QUOTE_INTERMEDIATE_FILL_RESULT, inputBySource: {}, }; let remainingInput = inputAmount; for (const fo of fillOrders) { if (remainingInput.lte(0)) { break; } for (const fill of fo.order.fills) { if (remainingInput.lte(0)) { break; } const { source, fillData } = fill; const gas = gasSchedule[source] === undefined ? 0 : gasSchedule[source]!(fillData); result.gas += new BigNumber(gas).toNumber(); result.inputBySource[source] = result.inputBySource[source] || ZERO_AMOUNT; // Actual rates are rarely linear, so fill subfills individually to // get a better approximation of fill size. for (const subFill of fill.subFills) { if (remainingInput.lte(0)) { break; } const filledInput = solveForInputFillAmount( remainingInput, subFill.input, fo.totalOrderInput, fo.totalOrderInputFee, ); const filledOutput = subFill.output.times(filledInput.div(subFill.input)); const filledInputFee = filledInput.div(fo.totalOrderInput).times(fo.totalOrderInputFee); const filledOutputFee = filledOutput.div(fo.totalOrderOutput).times(fo.totalOrderOutputFee); result.inputBySource[source] = result.inputBySource[source].plus(filledInput); result.input = result.input.plus(filledInput); result.output = result.output.plus(filledOutput); result.inputFee = result.inputFee.plus(filledInputFee); result.outputFee = result.outputFee.plus(filledOutputFee); remainingInput = remainingInput.minus(filledInput.plus(filledInputFee)); } } // NOTE: V4 Limit orders have Protocol fees const protocolFee = hasProtocolFee(fo.order) ? protocolFeePerFillOrder : ZERO_AMOUNT; result.protocolFee = result.protocolFee.plus(protocolFee); } return result; } function hasProtocolFee(o: OptimizedMarketOrder): boolean { return o.type === FillQuoteTransformerOrderType.Limit; } function solveForInputFillAmount( remainingInput: BigNumber, fillableInput: BigNumber, totalOrderInput: BigNumber, totalOrderInputFee: BigNumber, ): BigNumber { // When accounting for input token taker fees, the effective input amount is // given by: // i' = i + f * i / o // where: // i' - The effective input amount, including fees // i - An input amount // f - totalOrderInputFee // o - totalOrderInput // Solving for i we get: // i = (i' * o) / (f + o) const denom = totalOrderInput.plus(totalOrderInputFee); if (denom.eq(0)) { // A zero denominator would imply an order whose fees are >= the input // token amount. // For sells, takerFeeAmount >= takerAssetAmount (technically OK but really undesirable). // For buys, takerFeeAmount >= makerAssetAmount (losing all your returns to fees). return fillableInput; } return BigNumber.min( fillableInput, // let i' = remainingInput remainingInput.times(totalOrderInput).div(denom), ); } function createBestCaseFillOrderCalls(quoteInfo: QuoteFillInfo): QuoteFillOrderCall[] { const { orders, side } = quoteInfo; return orders.map(o => ({ order: o, ...(side === MarketOperation.Sell ? { totalOrderInput: o.takerAmount, totalOrderOutput: o.makerAmount, totalOrderInputFee: o.type === FillQuoteTransformerOrderType.Limit ? getNativeAdjustedTakerFeeAmount( (o.fillData as NativeLimitOrderFillData).order, o.takerAmount, ) : ZERO_AMOUNT, totalOrderOutputFee: ZERO_AMOUNT, // makerToken fees are not supported in v4 (sell output) } : // Buy { totalOrderInput: o.makerAmount, totalOrderOutput: o.takerAmount, totalOrderInputFee: ZERO_AMOUNT, // makerToken fees are not supported in v4 (buy input) totalOrderOutputFee: o.type === FillQuoteTransformerOrderType.Limit ? getNativeAdjustedTakerFeeAmount( (o.fillData as NativeLimitOrderFillData).order, o.takerAmount, ) : ZERO_AMOUNT, }), })); } function roundInputAmount(amount: BigNumber, side: MarketOperation): BigNumber { return amount.integerValue(side === MarketOperation.Sell ? ROUND_UP : ROUND_DOWN); } function roundOutputAmount(amount: BigNumber, side: MarketOperation): BigNumber { return amount.integerValue(side === MarketOperation.Sell ? ROUND_DOWN : ROUND_UP); } function roundIntermediateFillResult( ir: IntermediateQuoteFillResult, side: MarketOperation, ): IntermediateQuoteFillResult { return { input: roundInputAmount(ir.input, side), output: roundOutputAmount(ir.output, side), inputFee: roundInputAmount(ir.inputFee, side), outputFee: roundOutputAmount(ir.outputFee, side), protocolFee: ir.protocolFee.integerValue(ROUND_UP), gas: Math.ceil(ir.gas), inputBySource: Object.assign( {}, ...Object.entries(ir.inputBySource).map(([k, v]) => ({ [k]: roundInputAmount(v, side) })), ), }; } function fromIntermediateQuoteFillResult(ir: IntermediateQuoteFillResult, quoteInfo: QuoteFillInfo): QuoteFillResult { const { side } = quoteInfo; const _ir = roundIntermediateFillResult(ir, side); return { ...(side === MarketOperation.Sell ? // Sell { makerAssetAmount: _ir.output, takerAssetAmount: _ir.input, takerFeeMakerAssetAmount: _ir.outputFee, takerFeeTakerAssetAmount: _ir.inputFee, totalMakerAssetAmount: _ir.output.plus(_ir.outputFee), totalTakerAssetAmount: _ir.input.plus(_ir.inputFee), } : // Buy { makerAssetAmount: _ir.input, takerAssetAmount: _ir.output, takerFeeMakerAssetAmount: _ir.inputFee, takerFeeTakerAssetAmount: _ir.outputFee, totalMakerAssetAmount: _ir.input.plus(_ir.inputFee), totalTakerAssetAmount: _ir.output.plus(_ir.outputFee), }), protocolFeeAmount: _ir.protocolFee, gas: _ir.gas, fillAmountBySource: _ir.inputBySource, }; } function getTotalGasUsedByFills(fills: OptimizedMarketOrder[], gasSchedule: FeeSchedule): number { let gasUsed = 0; for (const f of fills) { const fee = gasSchedule[f.source] === undefined ? 0 : gasSchedule[f.source]!(f.fillData); gasUsed += new BigNumber(fee).toNumber(); } return gasUsed; }
the_stack
import 'es6-promise/auto'; // polyfill Promise on IE import { expect } from 'chai'; import { generate } from 'simulate-event'; import { CommandRegistry } from '@phosphor/commands'; import { JSONObject } from '@phosphor/coreutils'; import { Platform } from '@phosphor/domutils'; const NULL_COMMAND = { execute: (args: JSONObject) => { return args; } }; describe('@phosphor/commands', () => { describe('CommandRegistry', () => { let registry: CommandRegistry = null!; beforeEach(() => { registry = new CommandRegistry(); }); describe('#constructor()', () => { it('should take no arguments', () => { expect(registry).to.be.an.instanceof(CommandRegistry); }); }); describe('#commandChanged', () => { it('should be emitted when a command is added', () => { let called = false; registry.commandChanged.connect((reg, args) => { expect(reg).to.equal(registry); expect(args.id).to.equal('test'); expect(args.type).to.equal('added'); called = true; }); registry.addCommand('test', NULL_COMMAND); expect(called).to.equal(true); }); it('should be emitted when a command is changed', () => { let called = false; registry.addCommand('test', NULL_COMMAND); registry.commandChanged.connect((reg, args) => { expect(reg).to.equal(registry); expect(args.id).to.equal('test'); expect(args.type).to.equal('changed'); called = true; }); registry.notifyCommandChanged('test'); expect(called).to.equal(true); }); it('should be emitted when a command is removed', () => { let called = false; let disposable = registry.addCommand('test', NULL_COMMAND); registry.commandChanged.connect((reg, args) => { expect(reg).to.equal(registry); expect(args.id).to.equal('test'); expect(args.type).to.equal('removed'); called = true; }); disposable.dispose(); expect(called).to.equal(true); }); }); describe('#commandExecuted', () => { it('should be emitted when a command is executed', () => { let called = false; registry.addCommand('test', NULL_COMMAND); registry.commandExecuted.connect((reg, args) => { expect(reg).to.equal(registry); expect(args.id).to.equal('test'); expect(args.args).to.deep.equal({}); expect(args.result).to.be.an.instanceof(Promise); called = true; }); registry.execute('test'); expect(called).to.equal(true); }); }); describe('#keyBindings', () => { it('should be the keybindings in the palette', () => { registry.addCommand('test', { execute: () => { } }); registry.addKeyBinding({ keys: ['Ctrl ;'], selector: `body`, command: 'test' }); expect(registry.keyBindings.length).to.equal(1); expect(registry.keyBindings[0].command).to.equal('test'); }); }); describe('#listCommands()', () => { it('should list the ids of the registered commands', () => { registry.addCommand('test0', NULL_COMMAND); registry.addCommand('test1', NULL_COMMAND); expect(registry.listCommands()).to.deep.equal(['test0', 'test1']); }); it('should be a new array', () => { registry.addCommand('test0', NULL_COMMAND); registry.addCommand('test1', NULL_COMMAND); let cmds = registry.listCommands(); cmds.push('test2'); expect(registry.listCommands()).to.deep.equal(['test0', 'test1']); }); }); describe('#hasCommand()', () => { it('should test whether a specific command is registerd', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.hasCommand('test')).to.equal(true); expect(registry.hasCommand('foo')).to.equal(false); }); }); describe('#addCommand()', () => { it('should add a command to the registry', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.hasCommand('test')).to.equal(true); }); it('should return a disposable which will unregister the command', () => { let disposable = registry.addCommand('test', NULL_COMMAND); disposable.dispose(); expect(registry.hasCommand('test')).to.equal(false); }); it('should throw an error if the given `id` is already registered', () => { registry.addCommand('test', NULL_COMMAND); expect(() => { registry.addCommand('test', NULL_COMMAND); }).to.throw(Error); }); it('should clone the `cmd` before adding it to the registry', () => { let cmd = { execute: (args: JSONObject) => { return args; }, label: 'foo' }; registry.addCommand('test', cmd); cmd.label = 'bar'; expect(registry.label('test')).to.equal('foo'); }); }); describe('#notifyCommandChanged()', () => { it('should emit the `commandChanged` signal for the command', () => { let called = false; registry.addCommand('test', NULL_COMMAND); registry.commandChanged.connect((reg, args) => { expect(reg).to.equal(registry); expect(args.id).to.equal('test'); expect(args.type).to.equal('changed'); called = true; }); registry.notifyCommandChanged('test'); expect(called).to.equal(true); }); it('should throw an error if the command is not registered', () => { expect(() => { registry.notifyCommandChanged('foo'); }).to.throw(Error); }); }); describe('#label()', () => { it('should get the display label for a specific command', () => { let cmd = { execute: (args: JSONObject) => { return args; }, label: 'foo' }; registry.addCommand('test', cmd); expect(registry.label('test')).to.equal('foo'); }); it('should give the appropriate label given arguments', () => { let cmd = { execute: (args: JSONObject) => { return args; }, label: (args: JSONObject) => { return JSON.stringify(args); } }; registry.addCommand('test', cmd); expect(registry.label('test', {})).to.equal('{}'); }); it('should return an empty string if the command is not registered', () => { expect(registry.label('foo')).to.equal(''); }); it('should default to an empty string for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.label('test')).to.equal(''); }); }); describe('#mnemonic()', () => { it('should get the mnemonic index for a specific command', () => { let cmd = { execute: (args: JSONObject) => { return args; }, mnemonic: 1 }; registry.addCommand('test', cmd); expect(registry.mnemonic('test')).to.equal(1); }); it('should give the appropriate mnemonic given arguments', () => { let cmd = { execute: (args: JSONObject) => { return args; }, mnemonic: (args: JSONObject) => { return JSON.stringify(args).length; } }; registry.addCommand('test', cmd); expect(registry.mnemonic('test', {})).to.equal(2); }); it('should return a `-1` if the command is not registered', () => { expect(registry.mnemonic('foo')).to.equal(-1); }); it('should default to `-1` for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.mnemonic('test')).to.equal(-1); }); }); describe('#icon()', () => { it('should get the icon for a specific command', () => { let cmd = { execute: (args: JSONObject) => { return args; }, icon: 'foo' }; registry.addCommand('test', cmd); expect(registry.icon('test')).to.equal('foo'); }); it('should give the appropriate icon given arguments', () => { let cmd = { execute: (args: JSONObject) => { return args; }, icon: (args: JSONObject) => { return JSON.stringify(args); } }; registry.addCommand('test', cmd); expect(registry.icon('test', {})).to.equal('{}'); }); it('should return an empty string if the command is not registered', () => { expect(registry.icon('foo')).to.equal(''); }); it('should default to an empty string for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.icon('test')).to.equal(''); }); }); describe('#caption()', () => { it('should get the caption for a specific command', () => { let cmd = { execute: (args: JSONObject) => { return args; }, caption: 'foo' }; registry.addCommand('test', cmd); expect(registry.caption('test')).to.equal('foo'); }); it('should give the appropriate caption given arguments', () => { let cmd = { execute: (args: JSONObject) => { return args; }, caption: (args: JSONObject) => { return JSON.stringify(args); } }; registry.addCommand('test', cmd); expect(registry.caption('test', {})).to.equal('{}'); }); it('should return an empty string if the command is not registered', () => { expect(registry.caption('foo')).to.equal(''); }); it('should default to an empty string for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.caption('test')).to.equal(''); }); }); describe('#usage()', () => { it('should get the usage text for a specific command', () => { let cmd = { execute: (args: JSONObject) => { return args; }, usage: 'foo' }; registry.addCommand('test', cmd); expect(registry.usage('test')).to.equal('foo'); }); it('should give the appropriate usage text given arguments', () => { let cmd = { execute: (args: JSONObject) => { return args; }, usage: (args: JSONObject) => { return JSON.stringify(args); } }; registry.addCommand('test', cmd); expect(registry.usage('test', {})).to.equal('{}'); }); it('should return an empty string if the command is not registered', () => { expect(registry.usage('foo')).to.equal(''); }); it('should default to an empty string for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.usage('test')).to.equal(''); }); }); describe('#className()', () => { it('should get the extra class name for a specific command', () => { let cmd = { execute: (args: JSONObject) => { return args; }, className: 'foo' }; registry.addCommand('test', cmd); expect(registry.className('test')).to.equal('foo'); }); it('should give the appropriate class name given arguments', () => { let cmd = { execute: (args: JSONObject) => { return args; }, className: (args: JSONObject) => { return JSON.stringify(args); } }; registry.addCommand('test', cmd); expect(registry.className('test', {})).to.equal('{}'); }); it('should return an empty string if the command is not registered', () => { expect(registry.className('foo')).to.equal(''); }); it('should default to an empty string for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.className('test')).to.equal(''); }); }); describe('#isEnabled()', () => { it('should test whether a specific command is enabled', () => { let cmd = { execute: (args: JSONObject) => { return args; }, isEnabled: (args: JSONObject) => { return args.enabled as boolean; } }; registry.addCommand('test', cmd); expect(registry.isEnabled('test', { enabled: true })).to.equal(true); expect(registry.isEnabled('test', { enabled: false })).to.equal(false); }); it('should return `false` if the command is not registered', () => { expect(registry.isEnabled('foo')).to.equal(false); }); it('should default to `true` for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.isEnabled('test')).to.equal(true); }); }); describe('#isToggled()', () => { it('should test whether a specific command is toggled', () => { let cmd = { execute: (args: JSONObject) => { return args; }, isToggled: (args: JSONObject) => { return args.toggled as boolean; } }; registry.addCommand('test', cmd); expect(registry.isToggled('test', { toggled: true })).to.equal(true); expect(registry.isToggled('test', { toggled: false })).to.equal(false); }); it('should return `false` if the command is not registered', () => { expect(registry.isToggled('foo')).to.equal(false); }); it('should default to `false` for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.isToggled('test')).to.equal(false); }); }); describe('#isVisible()', () => { it('should test whether a specific command is visible', () => { let cmd = { execute: (args: JSONObject) => { return args; }, isVisible: (args: JSONObject) => { return args.visible as boolean; } }; registry.addCommand('test', cmd); expect(registry.isVisible('test', { visible: true })).to.equal(true); expect(registry.isVisible('test', { visible: false })).to.equal(false); }); it('should return `false` if the command is not registered', () => { expect(registry.isVisible('foo')).to.equal(false); }); it('should default to `true` for a command', () => { registry.addCommand('test', NULL_COMMAND); expect(registry.isVisible('test')).to.equal(true); }); }); describe('#execute()', () => { it('should execute a specific command', () => { let called = false; let cmd = { execute: (args: JSONObject) => { called = true; }, }; registry.addCommand('test', cmd); registry.execute('test'); expect(called).to.equal(true); }); it('should resolve with the result of the command', (done) => { let cmd = { execute: (args: JSONObject) => { return args; }, }; registry.addCommand('test', cmd); registry.execute('test', { foo: 12 }).then(result => { expect(result).to.deep.equal({ foo: 12 }); done(); }); }); it('should reject if the command throws an error', (done) => { let cmd = { execute: (args: JSONObject) => { throw new Error(''); }, }; registry.addCommand('test', cmd); registry.execute('test').catch(() => { done(); }); }); it('should reject if the command is not registered', (done) => { registry.execute('foo').catch(() => { done(); }); }); }); let elemID = 0; let elem: HTMLElement = null!; beforeEach(() => { elem = document.createElement('div') as HTMLElement; elem.id = `test${elemID++}`; elem.addEventListener('keydown', event => { registry.processKeydownEvent(event); }); document.body.appendChild(elem); }); afterEach(() => { document.body.removeChild(elem); }); describe('#addKeyBinding()', () => { it('should add key bindings to the registry', () => { let called = false; registry.addCommand('test', { execute: () => { called = true; } }); registry.addKeyBinding({ keys: ['Ctrl ;'], selector: `#${elem.id}`, command: 'test' }); let event = generate('keydown', { keyCode: 59, ctrlKey: true }); elem.dispatchEvent(event); expect(called).to.equal(true); }); it('should remove a binding when disposed', () => { let called = false; registry.addCommand('test', { execute: () => { called = true; } }); let binding = registry.addKeyBinding({ keys: ['Ctrl ;'], selector: `#${elem.id}`, command: 'test' }); binding.dispose(); let event = generate('keydown', { keyCode: 59, ctrlKey: true }); elem.dispatchEvent(event); expect(called).to.equal(false); }); it('should emit a key binding changed signal when added and removed', () => { let added = false; registry.addCommand('test', { execute: () => { } }); registry.keyBindingChanged.connect((sender, args) => { added = args.type === 'added'; }); let binding = registry.addKeyBinding({ keys: ['Ctrl ;'], selector: `#${elem.id}`, command: 'test' }); expect(added).to.equal(true); binding.dispose(); expect(added).to.equal(false); }); it('should throw an error if binding has an invalid selector', () => { let options = { keys: ['Ctrl ;'], selector: '..', command: 'test' }; expect(() => { registry.addKeyBinding(options); }).to.throw(Error); }); }); describe('#processKeydownEvent()', () => { it('should dispatch on a correct keyboard event', () => { let called = false; registry.addCommand('test', { execute: () => { called = true; } }); registry.addKeyBinding({ keys: ['Ctrl ;'], selector: `#${elem.id}`, command: 'test' }); let event = generate('keydown', { keyCode: 59, ctrlKey: true }); elem.dispatchEvent(event); expect(called).to.equal(true); }); it('should not dispatch on a non-matching keyboard event', () => { let called = false; registry.addCommand('test', { execute: () => { called = true; } }); registry.addKeyBinding({ keys: ['Ctrl ;'], selector: `#${elem.id}`, command: 'test' }); let event = generate('keydown', { keyCode: 45, ctrlKey: true }); elem.dispatchEvent(event); expect(called).to.equal(false); }); it('should not dispatch with non-matching modifiers', () => { let count = 0; registry.addCommand('test', { execute: () => { count++; } }); registry.addKeyBinding({ keys: ['Ctrl S'], selector: `#${elem.id}`, command: 'test' }); let eventAlt = generate('keydown', { keyCode: 83, altKey: true }); let eventShift = generate('keydown', { keyCode: 83, shiftKey: true }); elem.dispatchEvent(eventAlt); expect(count).to.equal(0); elem.dispatchEvent(eventShift); expect(count).to.equal(0); }); it('should dispatch with multiple chords in a key sequence', () => { let count = 0; registry.addCommand('test', { execute: () => { count++; } }); registry.addKeyBinding({ keys: ['Ctrl K', 'Ctrl L'], selector: `#${elem.id}`, command: 'test' }); let eventK = generate('keydown', { keyCode: 75, ctrlKey: true }); let eventL = generate('keydown', { keyCode: 76, ctrlKey: true }); elem.dispatchEvent(eventK); expect(count).to.equal(0); elem.dispatchEvent(eventL); expect(count).to.equal(1); elem.dispatchEvent(generate('keydown', eventL)); // Don't reuse; clone. expect(count).to.equal(1); elem.dispatchEvent(generate('keydown', eventK)); // Don't reuse; clone. expect(count).to.equal(1); elem.dispatchEvent(generate('keydown', eventL)); // Don't reuse; clone. expect(count).to.equal(2); }); it('should not execute handler without matching selector', () => { let count = 0; registry.addCommand('test', { execute: () => { count++; } }); registry.addKeyBinding({ keys: ['Shift P'], selector: '.inaccessible-scope', command: 'test' }); let event = generate('keydown', { keyCode: 80, shiftKey: true }); expect(count).to.equal(0); elem.dispatchEvent(event); expect(count).to.equal(0); }); it('should not execute a handler when missing a modifier', () => { let count = 0; registry.addCommand('test', { execute: () => { count++; } }); registry.addKeyBinding({ keys: ['Ctrl P'], selector: `#${elem.id}`, command: 'test' }); let event = generate('keydown', { keyCode: 17 }); expect(count).to.equal(0); elem.dispatchEvent(event); expect(count).to.equal(0); }); it('should register partial and exact matches', () => { let count1 = 0; let count2 = 0; registry.addCommand('test1', { execute: () => { count1++; } }); registry.addCommand('test2', { execute: () => { count2++; } }); registry.addKeyBinding({ keys: ['Ctrl S'], selector: `#${elem.id}`, command: 'test1' }); registry.addKeyBinding({ keys: ['Ctrl S', 'Ctrl D'], selector: `#${elem.id}`, command: 'test2' }); let event1 = generate('keydown', { keyCode: 83, ctrlKey: true }); let event2 = generate('keydown', { keyCode: 68, ctrlKey: true }); expect(count1).to.equal(0); expect(count2).to.equal(0); elem.dispatchEvent(event1); expect(count1).to.equal(0); expect(count2).to.equal(0); elem.dispatchEvent(event2); expect(count1).to.equal(0); expect(count2).to.equal(1); }); it('should recognize permutations of modifiers', () => { let count1 = 0; let count2 = 0; registry.addCommand('test1', { execute: () => { count1++; } }); registry.addCommand('test2', { execute: () => { count2++; } }); registry.addKeyBinding({ keys: ['Shift Alt Ctrl T'], selector: `#${elem.id}`, command: 'test1' }); registry.addKeyBinding({ keys: ['Alt Shift Ctrl Q'], selector: `#${elem.id}`, command: 'test2' }); let event1 = generate('keydown', { keyCode: 84, ctrlKey: true, altKey: true, shiftKey: true }); let event2 = generate('keydown', { keyCode: 81, ctrlKey: true, altKey: true, shiftKey: true }); expect(count1).to.equal(0); elem.dispatchEvent(event1); expect(count1).to.equal(1); expect(count2).to.equal(0); elem.dispatchEvent(event2); expect(count2).to.equal(1); }); it('should play back a partial match that was not completed', () => { let codes: number[] = []; let keydown = (event: KeyboardEvent) => { codes.push(event.keyCode); }; document.body.addEventListener('keydown', keydown); let called = false; registry.addCommand('test', { execute: () => { called = true; } }); registry.addKeyBinding({ keys: ['D', 'D'], selector: `#${elem.id}`, command: 'test' }); let event1 = generate('keydown', { keyCode: 68 }); let event2 = generate('keydown', { keyCode: 69 }); elem.dispatchEvent(event1); expect(codes.length).to.equal(0); elem.dispatchEvent(event2); expect(called).to.equal(false); expect(codes).to.deep.equal([68, 69]); document.body.removeEventListener('keydown', keydown); }); it('should play back a partial match that times out', (done) => { let codes: number[] = []; let keydown = (event: KeyboardEvent) => { codes.push(event.keyCode); }; document.body.addEventListener('keydown', keydown); let called = false; registry.addCommand('test', { execute: () => { called = true; } }); registry.addKeyBinding({ keys: ['D', 'D'], selector: `#${elem.id}`, command: 'test' }); let event = generate('keydown', { keyCode: 68 }); elem.dispatchEvent(event); expect(codes.length).to.equal(0); setTimeout(() => { expect(codes).to.deep.equal([68]); expect(called).to.equal(false); document.body.removeEventListener('keydown', keydown); done(); }, 1300); }); it('should resolve an exact match of partial match time out', (done) => { let called1 = false; let called2 = false; registry.addCommand('test1', { execute: () => { called1 = true; } }); registry.addCommand('test2', { execute: () => { called2 = true; } }); registry.addKeyBinding({ keys: ['D', 'D'], selector: `#${elem.id}`, command: 'test1' }); registry.addKeyBinding({ keys: ['D'], selector: `#${elem.id}`, command: 'test2' }); let event = generate('keydown', { keyCode: 68 }); elem.dispatchEvent(event); expect(called1).to.equal(false); expect(called2).to.equal(false); setTimeout(() => { expect(called1).to.equal(false); expect(called2).to.equal(true); done(); }, 1300); }); it('should pick the selector with greater specificity', () => { elem.classList.add('test'); let called1 = false; let called2 = false; registry.addCommand('test1', { execute: () => { called1 = true; } }); registry.addCommand('test2', { execute: () => { called2 = true; } }); registry.addKeyBinding({ keys: ['Ctrl ;'], selector: '.test', command: 'test1' }); registry.addKeyBinding({ keys: ['Ctrl ;'], selector: `#${elem.id}`, command: 'test2' }); let event = generate('keydown', { keyCode: 59, ctrlKey: true }); elem.dispatchEvent(event); expect(called1).to.equal(false); expect(called2).to.equal(true); }); it('should propagate if partial binding selector does not match', () => { let codes: number[] = []; let keydown = (event: KeyboardEvent) => { codes.push(event.keyCode); }; document.body.addEventListener('keydown', keydown); let called = false; registry.addCommand('test', { execute: () => { called = true; } }); registry.addKeyBinding({ keys: ['D', 'D'], selector: '#baz', command: 'test' }); let event = generate('keydown', { keyCode: 68 }); elem.dispatchEvent(event); expect(codes).to.deep.equal([68]); expect(called).to.equal(false); document.body.removeEventListener('keydown', keydown); }); it('should propagate if exact binding selector does not match', () => { let codes: number[] = []; let keydown = (event: KeyboardEvent) => { codes.push(event.keyCode); }; document.body.addEventListener('keydown', keydown); let called = false; registry.addCommand('test', { execute: () => { called = true; } }); registry.addKeyBinding({ keys: ['D'], selector: '#baz', command: 'test' }); let event = generate('keydown', { keyCode: 68 }); elem.dispatchEvent(event); expect(codes).to.deep.equal([68]); expect(called).to.equal(false); document.body.removeEventListener('keydown', keydown); }); }); describe('.parseKeystroke()', () => { it('should parse a keystroke into its parts', () => { let parts = CommandRegistry.parseKeystroke('Ctrl Shift Alt S'); expect(parts.cmd).to.equal(false); expect(parts.ctrl).to.equal(true); expect(parts.alt).to.equal(true); expect(parts.shift).to.equal(true); expect(parts.key).to.equal('S'); }); it('should be a tolerant parse', () => { let parts = CommandRegistry.parseKeystroke('G Ctrl Shift S Shift K'); expect(parts.cmd).to.equal(false); expect(parts.ctrl).to.equal(true); expect(parts.alt).to.equal(false); expect(parts.shift).to.equal(true); expect(parts.key).to.equal('K'); }); }); describe('.normalizeKeystroke()', () => { it('should normalize and validate a keystroke', () => { let stroke = CommandRegistry.normalizeKeystroke('Ctrl S'); expect(stroke).to.equal('Ctrl S'); }); it('should handle multiple modifiers', () => { let stroke = CommandRegistry.normalizeKeystroke('Ctrl Shift Alt S'); expect(stroke).to.equal('Ctrl Alt Shift S'); }); it('should handle platform specific modifiers', () => { let stroke = ''; if (Platform.IS_MAC) { stroke = CommandRegistry.normalizeKeystroke('Cmd S'); expect(stroke).to.equal('Cmd S'); stroke = CommandRegistry.normalizeKeystroke('Accel S'); expect(stroke).to.equal('Cmd S'); } else { stroke = CommandRegistry.normalizeKeystroke('Cmd S'); expect(stroke).to.equal('S'); stroke = CommandRegistry.normalizeKeystroke('Accel S'); expect(stroke).to.equal('Ctrl S'); } }); }); describe('.keystrokeForKeydownEvent()', () => { it('should create a normalized keystroke', () => { let event = generate('keydown', { ctrlKey: true, keyCode: 83 }); let keystroke = CommandRegistry.keystrokeForKeydownEvent(event as KeyboardEvent); expect(keystroke).to.equal('Ctrl S'); }); it('should handle multiple modifiers', () => { let event = generate('keydown', { ctrlKey: true, altKey: true, shiftKey: true, keyCode: 83 }); let keystroke = CommandRegistry.keystrokeForKeydownEvent(event as KeyboardEvent); expect(keystroke).to.equal('Ctrl Alt Shift S'); }); it('should fail on an invalid shortcut', () => { let event = generate('keydown', { keyCode: -1 }); let keystroke = CommandRegistry.keystrokeForKeydownEvent(event as KeyboardEvent); expect(keystroke).to.equal(''); }); }); }); });
the_stack
import { PermissionStatus, PermissionExpiration, PermissionHookOptions, createPermissionHook, UnavailabilityError, CodedError, } from 'expo-modules-core'; import ExponentImagePicker from './ExponentImagePicker'; import { CameraPermissionResponse, CameraRollPermissionResponse, MediaLibraryPermissionResponse, ImagePickerResult, ImagePickerErrorResult, MediaTypeOptions, ImagePickerOptions, VideoExportPreset, ExpandImagePickerResult, ImageInfo, ImagePickerMultipleResult, ImagePickerCancelledResult, OpenFileBrowserOptions, UIImagePickerControllerQualityType, UIImagePickerPresentationStyle, } from './ImagePicker.types'; function validateOptions(options: ImagePickerOptions) { const { aspect, quality, videoMaxDuration } = options; if (aspect != null) { const [x, y] = aspect; if (x <= 0 || y <= 0) { throw new CodedError( 'ERR_INVALID_ARGUMENT', `Invalid aspect ratio values ${x}:${y}. Provide positive numbers.` ); } } if (quality && (quality < 0 || quality > 1)) { throw new CodedError( 'ERR_INVALID_ARGUMENT', `Invalid 'quality' value ${quality}. Provide a value between 0 and 1.` ); } if (videoMaxDuration && videoMaxDuration < 0) { throw new CodedError( 'ERR_INVALID_ARGUMENT', `Invalid 'videoMaxDuration' value ${videoMaxDuration}. Provide a non-negative number.` ); } return options; } // @needsAudit /** * Checks user's permissions for accessing camera. * @return A promise that fulfills with an object of type [CameraPermissionResponse](#imagepickercamerapermissionresponse). */ export async function getCameraPermissionsAsync(): Promise<CameraPermissionResponse> { return ExponentImagePicker.getCameraPermissionsAsync(); } /** * @deprecated Use `getMediaLibraryPermissionsAsync()` instead. */ export async function getCameraRollPermissionsAsync(): Promise<MediaLibraryPermissionResponse> { console.warn( 'ImagePicker.getCameraRollPermissionsAsync() is deprecated in favour of ImagePicker.getMediaLibraryPermissionsAsync()' ); return getMediaLibraryPermissionsAsync(); } // @needsAudit /** * Checks user's permissions for accessing photos. * @param writeOnly Whether to request write or read and write permissions. Defaults to `false` * @return A promise that fulfills with an object of type [MediaLibraryPermissionResponse](#imagepickercamerarollpermissionresponse). */ export async function getMediaLibraryPermissionsAsync( writeOnly: boolean = false ): Promise<MediaLibraryPermissionResponse> { const imagePickerMethod = ExponentImagePicker.getMediaLibraryPermissionsAsync; return imagePickerMethod(writeOnly); } // @needsAudit /** * Asks the user to grant permissions for accessing camera. This does nothing on web because the * browser camera is not used. * @return A promise that fulfills with an object of type [CameraPermissionResponse](#imagepickercamerapermissionresponse). */ export async function requestCameraPermissionsAsync(): Promise<CameraPermissionResponse> { return ExponentImagePicker.requestCameraPermissionsAsync(); } /** * @deprecated Use `requestMediaLibraryPermissionsAsync()` instead. */ export async function requestCameraRollPermissionsAsync(): Promise<MediaLibraryPermissionResponse> { console.warn( 'ImagePicker.requestCameraRollPermissionsAsync() is deprecated in favour of ImagePicker.requestMediaLibraryPermissionsAsync()' ); return requestMediaLibraryPermissionsAsync(); } // @needsAudit /** * Asks the user to grant permissions for accessing user's photo. This method does nothing on web. * @param writeOnly Whether to request write or read and write permissions. Defaults to `false` * @return A promise that fulfills with an object of type [MediaLibraryPermissionResponse](#imagepickercamerarollpermissionresponse). */ export async function requestMediaLibraryPermissionsAsync( writeOnly: boolean = false ): Promise<MediaLibraryPermissionResponse> { const imagePickerMethod = ExponentImagePicker.requestMediaLibraryPermissionsAsync; return imagePickerMethod(writeOnly); } // @needsAudit /** * Check or request permissions to access the media library. * This uses both `requestMediaLibraryPermissionsAsync` and `getMediaLibraryPermissionsAsync` to interact with the permissions. * * @example * ```ts * const [status, requestPermission] = ImagePicker.useMediaLibraryPermissions(); * ``` */ export const useMediaLibraryPermissions = createPermissionHook< MediaLibraryPermissionResponse, { writeOnly?: boolean } >({ // TODO(cedric): permission requesters should have an options param or a different requester getMethod: (options) => getMediaLibraryPermissionsAsync(options?.writeOnly), requestMethod: (options) => requestMediaLibraryPermissionsAsync(options?.writeOnly), }); // @needsAudit /** * Check or request permissions to access the camera. * This uses both `requestCameraPermissionsAsync` and `getCameraPermissionsAsync` to interact with the permissions. * * @example * ```ts * const [status, requestPermission] = ImagePicker.useCameraPermissions(); * ``` */ export const useCameraPermissions = createPermissionHook({ getMethod: getCameraPermissionsAsync, requestMethod: requestCameraPermissionsAsync, }); // @needsAudit /** * Android system sometimes kills the `MainActivity` after the `ImagePicker` finishes. When this * happens, we lost the data selected from the `ImagePicker`. However, you can retrieve the lost * data by calling `getPendingResultAsync`. You can test this functionality by turning on * `Don't keep activities` in the developer options. * @return * - **On Android:** a promise that resolves to an array of objects of exactly same type as in * `ImagePicker.launchImageLibraryAsync` or `ImagePicker.launchCameraAsync` if the `ImagePicker` * finished successfully. Otherwise, to the array of [`ImagePickerErrorResult`](#imagepickerimagepickererrorresult). * - **On other platforms:** an empty array. */ export async function getPendingResultAsync(): Promise< (ImagePickerResult | ImagePickerErrorResult)[] > { if (ExponentImagePicker.getPendingResultAsync) { return ExponentImagePicker.getPendingResultAsync(); } return []; } // @needsAudit /** * Display the system UI for taking a photo with the camera. Requires `Permissions.CAMERA`. * On Android and iOS 10 `Permissions.CAMERA_ROLL` is also required. On mobile web, this must be * called immediately in a user interaction like a button press, otherwise the browser will bloc * the request without a warning. * > **Note:** Make sure that you handle `MainActivity` destruction on **Android**. See [ImagePicker.getPendingResultAsync](#imagepickergetpendingresultasync). * > **Notes for Web:** The system UI can only be shown after user activation (e.g. a `Button` press). * Therefore, calling `launchCameraAsync` in `componentDidMount`, for example, will **not** work as * intended. The `cancelled` event will not be returned in the browser due to platform restrictions * and inconsistencies across browsers. * @param options An `ImagePickerOptions` object. * @return If the user cancelled the action, the method returns `{ cancelled: true }`. Otherwise, * this method returns information about the selected media item. When the chosen item is an image, * this method returns `{ cancelled: false, type: 'image', uri, width, height, exif, base64 }`; * when the item is a video, this method returns `{ cancelled: false, type: 'video', uri, width, height, duration }`. */ export async function launchCameraAsync( options: ImagePickerOptions = {} ): Promise<ImagePickerResult> { if (!ExponentImagePicker.launchCameraAsync) { throw new UnavailabilityError('ImagePicker', 'launchCameraAsync'); } return await ExponentImagePicker.launchCameraAsync(validateOptions(options)); } // @needsAudit /** * Display the system UI for choosing an image or a video from the phone's library. * Requires `Permissions.MEDIA_LIBRARY` on iOS 10 only. On mobile web, this must be called * immediately in a user interaction like a button press, otherwise the browser will block the * request without a warning. * **Animated GIFs support** If the selected image is an animated GIF, the result image will be an * animated GIF too if and only if `quality` is set to `undefined` and `allowsEditing` is set to `false`. * Otherwise compression and/or cropper will pick the first frame of the GIF and return it as the * result (on Android the result will be a PNG, on iOS — GIF). * > **Notes for Web:** The system UI can only be shown after user activation (e.g. a `Button` press). * Therefore, calling `launchImageLibraryAsync` in `componentDidMount`, for example, will **not** * work as intended. The `cancelled` event will not be returned in the browser due to platform * restrictions and inconsistencies across browsers. * @param options An object extended by [`ImagePickerOptions`](#imagepickeroptions). * @return If the user cancelled the action, the method returns `{ cancelled: true }`. Otherwise, * this method returns information about the selected media item. When the chosen item is an image, * this method returns `{ cancelled: false, type: 'image', uri, width, height, exif, base64 }`; * when the item is a video, this method returns `{ cancelled: false, type: 'video', uri, width, height, duration }`. */ export async function launchImageLibraryAsync<T extends ImagePickerOptions>( options?: T ): Promise<ExpandImagePickerResult<T>> { if (!ExponentImagePicker.launchImageLibraryAsync) { throw new UnavailabilityError('ImagePicker', 'launchImageLibraryAsync'); } return await ExponentImagePicker.launchImageLibraryAsync(options ?? {}); } export { MediaTypeOptions, ImagePickerOptions, ImagePickerResult, ImagePickerErrorResult, VideoExportPreset, CameraPermissionResponse, CameraRollPermissionResponse, MediaLibraryPermissionResponse, PermissionStatus, PermissionExpiration, PermissionHookOptions, ImageInfo, ImagePickerMultipleResult, ImagePickerCancelledResult, OpenFileBrowserOptions, ExpandImagePickerResult, UIImagePickerControllerQualityType, UIImagePickerPresentationStyle, };
the_stack
import { columnTypes, ILinkFieldValue, ILookupFieldValue, IPersonFieldValue } from './State'; export const getRandomInteger = (minValue:number, maxValue:number): number => { minValue = Math.ceil(minValue); maxValue = Math.floor(maxValue); return Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue; }; export const getRandomDate = (start:Date, end:Date): Date => { let randomDate:Date = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); return randomDate; }; const nouns: Array<string> = [ 'Dog','Cat','Mouse','Moose','Squirrel','Chair','Table','Computer','Apple','Pizza','Kitchen','Rabbit','Tractor','Statue', 'Old Lady','Skeleton','Flag','Pile of Rocks','Pork','Potato','Candle','Rope','Wrench','Tub','Lard','Toe','Burrito','King', 'Butter','Cheese','Tooth','Foot','Tuxedo','Car','Plane','Hamster','Lizard','Brother','Sister','Pumpkin','Sweater','Newt', 'Wizard','Building','Mall','Canyon','Treasure','Telescope','Island','Zombies','Grandma','Grandpa','Email','Puppies','Bug', 'Phone','Construction Set','Bag of Billy Goats','Turtle','Diaper','Tree','Candy','Pillow','Alien','Baby','Cookie','Cup', 'Book','Blouse','Pants','Socks','Troll','Fan','Dice','Cards','Box','Package','Sheep','Clown','Snot','Nose','Ear','Belly', 'Widget','Gadget','Thing','Ice','Snow','Water','Leg','Hammer','Whale','Kangaroo','Dolphin','Elephant','Ornament','Reindeer', 'Watch','Coin','Canada','Hat','Sombrero','Pony','Horse','Lips','Wheel','Gear','Knife','Refridgerator','Oven','Movie','Song', 'Yeti','Polar Bear','Heart','Waffle','Steak','Slide','Shoe','Roller Blades','Cucumber','Popsicle','Toad','Tiger','Monkey', 'Badger','Gremlin','Mummy','Vampire','Finger Tip','Bed','Sofa','Couch','Tent','Sleeping Bag','Iron','Bowl of Soup','Flute', 'Trumpet','Piano','Hair','Plug','Notebook','Pencil','Pen','Sewing Machine','Tape','Toolbox','Cone','Watermelon','Sea Creature', 'Vase','Donkey','Scarf','Monster','Printer','Dog Food','Food','Scar','Bandage','Truck','Motorcycle','Coffee Cup','Fog','Frog', 'Pirate','Snake','Battleship','Scab','Buddy','Peanut','Jelly','Bean','Human','Robot','Planet','Spaceship','Boat','Goat', 'Survivor','Samurai','Plant','President','Lima Beans','Seahorse','Egg','Adventure','Cactus','Pizza','Blanket','Lamp','Chicken' ]; const adjectives: Array<string> = [ 'Old','Blue','Red','Orange','Smelly','Squishy','Pretty','Tiny','Small','Huge','Ugly','Brown','Soft','Memorable','Dead','Sad','Cool', 'Proud','Angry','Foamy','Weird','Nasty','Shiny','Sparkly','Glittery','Pink','Purple','Massive','Unreliable','Ancient','Hot','Bumpy', 'Crunchy','Salty','Delicious','Smart','Funny','Hillarious','Generous','Kind','Evil','Yellow','Stinky','Fragrant','Golden','Sour', 'Illegal','Flammable','Wet','Dirty','Crazy','Slimy','New','Ridiculous','Silly','Dumb','Great','Spooky','Scary','Calm','Hidden', 'Misunderstood','Serious','Tall','Short','Spicy','Clammy','Furry','Wide','Melted','Slick','Cold','Damp','Musky','Saucy','Fuzzy', 'Jelly Filled','Cheesy','Scrumptious','Undead','Moldy','Sweet','Sweaty','Chocolate Covered','Wise','Unwise','Troublesome','Freaky', 'Unhinged','Maroon','Turquoise','Lovely','Friendly','Nice','Pirate','Green','Jealous','Hungry','Good Looking','Tasty','Questionable', 'Hard Boiled','Apathetic','Sassy','Clever','Frustrated','Terrific','Awesome','Holy','Lumpy','Horrific','Scrawny','Vengeful','Round' ]; const firstNames: Array<string> = [ 'Fred','Betty','Louis','Chris','Noah','Eleanor','Geneva','Charlie','Jordan','Vince','Steve','Vesa','Marilyn','Abraham','John', 'Martin','Nelson','Bill','Billy','Charles','Muhammad','Mahatma','Margaret','Maggie','Chelsie','Amy','Sarah','Matilda','Joan', 'Peter','Pete','Donny','Vinnie','Christopher','George','Elvis','Albert','Paul','Elizabeth','Liz','Beth','Mikhail','Jawaharlal', 'Leonardo','Raphael','Leo','Pablo','Frank','Thomas','Tom','Tommy','Ludwig','Oprah','Indira','Eva','Benazir','Desmond','Walter', 'Neil','Barack','Malcom','Richard','Rick','Casey','Pat','Patrick','Russ','Russel','Mike','Michael','Georgie','Vladimir','Ingrid', 'Amelia','Mary','Marty','Monty','Eric','William','Will','Gloria','Glenda','Alan','Mary Ellen','Sabrina','Keri','Kyle','Robert', 'Bob','Bobbie','Rob','Steven','Stephen','Ronald','Ronnie','Ron','Christie','Crystal','Lionel','Roger','Sigmund','Katherine', 'Katie','Kate','Jenny','Jennifer','David','Dave','Davey','Usain','Mao','Woodrow','Woody','Carl','Jack','Jackie','Anne','Simon', 'Florence','Frances','Francis','Emile','Cristiano','Marie','Tim','Timmy','Timo','Timothy','Jon','Sara','Abe','Johnny','Rupert', 'Jim','James','Jimmy','Kylie','Malala','Liam','Mason','Benjamin','Ben','Jacob','Elijah','Ethan','Emma','Emily','Olivia','Ava', 'Sophia','Isabella','Mia','Charlotte','Abigail','Abby','Harper','Henry','Dorothy','Teddy','Theodore','Finn','Owen','Caleb','Elliot', 'Grayson','Aria','Violet','Norah','Hazel','Aurora','Isla','Scarlett','Audrey','Luna','Alex','Alexander','Sebastian','Silas', 'Jasper','Gabriel','Lucas','Jackson','Grace','Adelaide','Penelope','Vivienne','Evangeline','Eloise','Ivy','Lily','Landon','Aiden', 'Archer','Felix','Wyatt','Milo','Atticus','Luke','Ezra','Lincoln','Arthur','Cora','Lydia','Mark','Lucy','Clara','Freya','Naomi', 'Nate','Daniel','Dan','Dayne','Tyson','Bruce','Wayne','Clark','Lindsay','Mindy','Sawyer','Ruby','Maeve','Kaia','Chloe','Autumn', 'August','Miles','Quinn','Rowan','Logan','Rose','Simon','Willow','Lucia','Milagros','Santiago','Lautaro','Franco','Joshua','Josh', 'Ella','Sienna','Cooper','Riley','Lachlan','Lukas','Tobias','Maximilian','Lena','Leonie','Hannah','Lina','Yasmine','Aya','Adam', 'Rayan','Nathan','Anas','Hugo','Manon','Lotte','Stan','Camille','Lucie','Lousie','Matheus','Thiago','Larissa','Beatriz','Madison', 'Owen','Diego','Martina','Antonia','Isidora','Jose','Petra','Jan','Filip','Philip','Kirsten','Susanne','Inge','Jens','Lars', 'Henrik','Soren','Hans','Jorgen','Niels','Alfie','Mikael','Amanda','Johannes','Juhani','Oskari','Aleksi','Enzo','Jade','Kilian', 'Bence','Laura','Conor','Sean','Ryan','Bryan','Brian','Kate','Lewis','Sam','Samuel','Holly','Lillie','Francesco','Matteo','Luca', 'Giulia','Francesca','Andrea','Mantas','Goda','Karina','Katrina','Dragan','Igor','Elena','Suzana','Elisa','Julian','Nicholas', 'Nick','Nicole','Isaac','Miguel','Diego','Luis','Eduardo','Camila','Maria Fernanda','Daniela','Mariana','Maria Guadalupe','Ray', 'Angel','Ruben','Jesse','Lisa','Fleur','Dylan','Jonas','Magnus','Emil','Emilie','Thea','Piotr','Barbara','Pawel','Ivan','Dmitry', 'Alexei','Polina','Mariya','Viktoria','Yelizaveta','Stefan','Denisa','Georgiana','Seo-yeon','Min-jun','Ji-hun','Javier','Sergio', 'Marta','Claudia','Anastasia','Olexandr','Natalia','Zhang Wei','Wang Fang','Li Wei','Li Xiu Ying','Li Na','Zhang Min','Wang Li', 'Li Qiang','Li Jun','Zhang Yong','Li Yan','Li Yong','Wang Ping','Liu Fang','Li Li','Aiko','Chikako','Atsuko','Daisuke','Fumiko', 'Haruko','Hideyoshi','Ichiro','Itsuki','Kazuhito','Kasumi','Mitsu','Shinobu','Tomoko','Yoshi','Wataru','Ado','Kyla','Harry','Anthony', 'Tony','Brandon','Cameron','Christian','Briana','Alyssa','Alexis','Aliyah','Aaliyah','Destiny','Diamond','Hailey','Imani','Jasmine', 'Josiah','Justin','Isaiah','Jayden','Jada','Kayla','Kennedy','Kevin','Tyler','Xavier','Zion','Trinity','Sydney','Makayla','Madison', 'Laila','Kiara','Malik','Terrell','Toby','Terrance','Andre','Tyrone','Derek','Wes','Wesley','Lamar','Alonzo','Omar','Youssef', 'Ahmed','Hussein','Abdallah','Manuel','Junior','Mehdi','Fatima','Fatma','Suha','Precious','Irene','Juan','Carlos','Cesar','Agustin', 'Alysha','Alice','Mariana','Widelene','Lovelie','Esther','Angeline','Angilee','Luciana','Patricia','Linda','Abril','Hamza','Wei', 'Reza','Noam','Amit','Nor','Ashley','Janine','Nadia','Marc','Ian','Tobias','Ali','Noel','Dmitrios','Georgios','Ellen','Ivaana' ]; const lastNames: Array<string> = [ 'Smith','Jones','Brown','Johnson','Williams','Miller','Gump','Taylor','Wilson','Davis','White','Clark','Hall','Thompson','Moore', 'Anderson','Walker','Hill','Wood','Robinson','Lewis','Jackson','Tryniski','Green','Evans','King','Baker','Harris','Campbell','Lee', 'Stewart','Turner','Parker','Cook','Edwards','Kent','Ward','Watson','Morgan','Davies','Cooper','Phillips','Gray','Hughes','Harrison', 'Carter','Hamilton','Shaw','Bennett','Reed','Murphey','Hawn','McGown','Gove','Jimison','Healy','Willman','Shepherd','Fisher','Cox', 'Washington','Palmer','Church','Stone','Marshall','Chapman','Holmes','Fox','Cole','Hart','Wells','Sullivan','Johnston','West', 'Kennedy','Wallace','Porter','Webster','Long','Grant','Webb','Richards','Day','Ford','Barnes','Brooks','Gibson','Lincoln','Lane', 'Black','Gardner','Street','Gordon','Lawrence','Rice','Jenkins','Armstrong','Knight','Burns','Dunn','Reid','Barker','Montgomery', 'Roosevelt','Weaver','Lamb','Owens','Sutton','Kerr','Stanley','Watts','Fleming','Buchanan','Saunders','Peters','Connor','Mann', 'Barton','Barber','Simmons','Harper','Stephens','Atkinson','Fowler','Howe','Bates','Snyder','Hawkins','Newman','Barrett','Sharp', 'Hudson','Matthews','Coleman','Stevenson','Parsons','Warner','Pratt','Berry','Sherman','Morton','Williamson','Baldwin','Bishop', 'French','Pearson','Payne','Potter','Hopkins','Dixon','Tucker','Fellows','Freeman','Myers','Park','Ferguson','Davidson','Peterson', 'Morrison','Carpenter','Fuller','Fletcher','Crawford','Patterson','Rose','Hayes','Musayev','Hasanov','Huseynov','Mammadov','Ahmed', 'Dewan','Gazi','Hasan','Rohoman','Wong','Wang','Zhou','Sun','Guo','Bairamov','Shengelia','Kumar','Ram','Sharma','Patel','Singh', 'Mandal','Khatun','Cohen','Levi','Peretz','Friedman','Katz','Amar','Suzuki','Tanaka','Sato','Nakamura','Yoshida','Matsumoto','Ito', 'Kobayashi','Watanabe','Takahashi','Hasegawa','Fujii','Kim','Jeong','Han','Cho','Kang','Shrestha','Tan','dela Cruz','Bautista', 'Cortez','Rosales','Kaya','Demir','Arslan','Dogan','Nguyen','Pham','Phan','Duong','Gruber','Wagner','Steiner','Moser','Winkler', 'Muller','Hofer','Peeters','Janssens','Jacobs','Dupont','De Smet','Horvat','Kovacevic','Novak','Nielsen','Anderson','Andersen', 'Tamm','Ivanov','Vassiljev','Petrov','Pavlov','Kuznetsov','Korhonen','Virtanen','Laine','Lehtonen','Koskinen','Juvonen','Lindholm', 'Martin','Bernard','Dubois','Petit','Durand','Schmidt','Schneider','Fischer','Schulz','Becker','Hoffmann','Horvath','Szabo', 'Murphey','Walsh','Sullivan','Kelly','Doyle','McCarthy','Quinn','Rossi','Russo','Ferrari','Esposito','Romano','De Luca','Mancini', 'Fontana','Lombardi','Greco','Kastrati','Jansons','Butkus','Borg','Farrugia','Davidov','Ivanovski','Petrovski','Janev','De Vries', 'Van den Berg','De Boer','Dekker','Ven der Meer','Olsen','Larsen','Dahl','Pedersen','Nowak','Kowalski','Wozniak','Silva','Santos', 'Cruz','Dumitru','Smirnov','Kozlov','Garcia','Fernandez','Rodriquez','Diaz','Ruiz','Perez','Giovanni','Kovalchuk','Bondar','Taylor', 'Hall','MacDonald','Ross','Driscoll','Price','Gonzalez','Lopez','Alvarez','Romero','Torres','Ramirez','Hernandez','Flores','Gomez', 'Tremblay','Gagnon','Sanchez','King','Collins','Bell','Kelly' ]; const domainSuffixes: Array<string> = [ 'com','org','net','gov','edu' ]; interface IPictureColor { color:string; lightText:boolean; } const pictureColors: Array<IPictureColor> = [ {color:'5c005c',lightText:true},{color:'b4009e',lightText:true},{color:'e3008c',lightText:true},{color:'32145a',lightText:true}, {color:'5c2d91',lightText:true},{color:'b4a0ff',lightText:false},{color:'002050',lightText:true},{color:'00188f',lightText:true}, {color:'0078d7',lightText:true},{color:'00bcf2',lightText:false},{color:'004b50',lightText:true},{color:'008272',lightText:true}, {color:'00b294',lightText:false},{color:'004b1c',lightText:true},{color:'107c10',lightText:true},{color:'bad80a',lightText:false}, {color:'ffb900',lightText:false},{color:'fff100',lightText:false},{color:'d83b01',lightText:true},{color:'ea4300',lightText:true}, {color:'ff8c00',lightText:false},{color:'a80000',lightText:true},{color:'e81123',lightText:true} ]; export const generateTextValue = (): string => { return adjectives[getRandomInteger(0,adjectives.length-1)] + ' ' + nouns[getRandomInteger(0,nouns.length-1)]; }; export const generateDomainName = (): string => { return generateTextValue().replace(/\s/g,'') + '.' + domainSuffixes[getRandomInteger(0,domainSuffixes.length-1)]; }; export const generatePerson = (): IPersonFieldValue => { let fName:string = firstNames[getRandomInteger(0,firstNames.length-1)]; let lName:string = lastNames[getRandomInteger(0,lastNames.length-1)]; let emailAddress:string = fName.substring(0,1) + lName.replace(/\s/g,'.') + '@' + generateDomainName(); return { title: fName + ' ' + lName, id: getRandomInteger(1,999), email: emailAddress, sip: emailAddress, picture: '' }; }; export const generateLink = (): ILinkFieldValue => { return { URL: 'http://www.' + generateDomainName(), desc: generateTextValue() }; }; export const generatePictureLink = (width:number, height:number): ILinkFieldValue => { let text:string = nouns[getRandomInteger(0,nouns.length-1)]; //let color:string = getRandomInteger(0,200).toString(16) + getRandomInteger(0,200).toString(16) + getRandomInteger(0,200).toString(16); let color:IPictureColor = pictureColors[getRandomInteger(0,pictureColors.length-1)]; return { URL: `https://dummyimage.com/${width}x${height}/${color.color}/${color.lightText ? 'ffffff' : '000000'}&text=${text}`, desc: text }; }; export const generateLookup = (): ILookupFieldValue => { return { lookupId: getRandomInteger(1,999), lookupValue: generateTextValue() }; }; export const generateDate = (): Date => { let today:Date = new Date(); //Random date between 90 days ago and 90 days in the future return getRandomDate(new Date(today.setTime(today.getTime() - 90 * 86400000)), new Date(today.setTime(today.getTime() + 90 * 86400000))); }; export const generateRowValue = (type:columnTypes): any => { switch (type) { case columnTypes.person: return generatePerson(); case columnTypes.boolean: return getRandomInteger(0,1) == 0; case columnTypes.number: return getRandomInteger(-10,100); case columnTypes.link: return generateLink(); case columnTypes.picture: return generatePictureLink(150,100); case columnTypes.datetime: return generateDate(); case columnTypes.lookup: return generateLookup(); default: return generateTextValue(); } };
the_stack
import Backburner from 'backburner'; QUnit.module('tests/throttle'); QUnit.test('throttle', function(assert) { assert.expect(18); let bb = new Backburner(['zomg']); let step = 0; let done = assert.async(); let wasCalled = false; function throttler() { assert.ok(!wasCalled); wasCalled = true; } // let's throttle the function `throttler` for 40ms // it will be executed in 40ms bb.throttle(null, throttler, 40, false); assert.equal(step++, 0); // let's schedule `throttler` to run in 10ms setTimeout(() => { assert.equal(step++, 1); assert.ok(!wasCalled); bb.throttle(null, throttler, false); }, 10); // let's schedule `throttler` to run again in 20ms setTimeout(() => { assert.equal(step++, 2); assert.ok(!wasCalled); bb.throttle(null, throttler, false); }, 20); // let's schedule `throttler` to run yet again in 30ms setTimeout(() => { assert.equal(step++, 3); assert.ok(!wasCalled); bb.throttle(null, throttler, false); }, 30); // at 40ms, `throttler` will get called once // now, let's schedule an assertion to occur at 50ms, // 10ms after `throttler` has been called setTimeout(() => { assert.equal(step++, 4); assert.ok(wasCalled); }, 50); // great, we've made it this far, there's one more thing // we need to test. we want to make sure we can call `throttle` // again with the same target/method after it has executed // at the 60ms mark, let's schedule another call to `throttle` setTimeout(() => { wasCalled = false; // reset the flag // assert call order assert.equal(step++, 5); // call throttle for the second time bb.throttle(null, throttler, 100, false); // assert that it is called in the future and not blackholed setTimeout(() => { assert.equal(step++, 6); assert.ok(wasCalled, 'Another throttle call with the same function can be executed later'); }, 110); }, 60); setTimeout(() => { wasCalled = false; // reset the flag // assert call order assert.equal(step++, 7); // call throttle again that time using a string number like time interval bb.throttle(null, throttler, '100', false); // assert that it is called in the future and not blackholed setTimeout(() => { assert.equal(step++, 8); assert.ok(wasCalled, 'Throttle accept a string number like time interval'); done(); }, 110); }, 180); }); QUnit.test('throttle with cancelTimers', function(assert) { assert.expect(1); let count = 0; let bb = new Backburner(['zomg']); // Throttle a no-op 10ms bb.throttle(null, () => { /* no-op */ }, 10, false); try { bb.cancelTimers(); } catch (e) { count++; } assert.equal(count, 0, 'calling cancelTimers while something is being throttled does not throw an error'); }); QUnit.test('throttled function is called with final argument', function(assert) { assert.expect(1); let done = assert.async(); let count = 0; let bb = new Backburner(['zomg']); function throttled(arg) { assert.equal(arg, 'bus'); done(); } bb.throttle(null, throttled, 'car' , 10, false); bb.throttle(null, throttled, 'bicycle' , 10, false); bb.throttle(null, throttled, 'bus' , 10, false); }); QUnit.test('throttle returns same timer', function(assert) { assert.expect(2); let bb = new Backburner(['joker']); function throttled1() {} function throttled2() {} let timer1 = bb.throttle(null, throttled1, 10); let timer2 = bb.throttle(null, throttled2, 10); let timer3 = bb.throttle(null, throttled1, 10); let timer4 = bb.throttle(null, throttled2, 10); assert.equal(timer1, timer3); assert.equal(timer2, timer4); }); QUnit.test('throttle leading edge', function(assert) { assert.expect(10); let bb = new Backburner(['zerg']); let throttle; let throttle2; let wasCalled = false; let done = assert.async(); function throttler() { assert.ok(!wasCalled, 'throttler hasn\'t been called yet'); wasCalled = true; } // let's throttle the function `throttler` for 40ms // it will be executed immediately, but throttled for the future hits throttle = bb.throttle(null, throttler, 40); assert.ok(wasCalled, 'function was executed immediately'); wasCalled = false; // let's schedule `throttler` to run again, it shouldn't be allowed to queue for another 40 msec throttle2 = bb.throttle(null, throttler, 40); assert.equal(throttle, throttle2, 'No new throttle was inserted, returns old throttle'); setTimeout(() => { assert.ok(!wasCalled, 'attempt to call throttle again didn\'t happen'); throttle = bb.throttle(null, throttler, 40); assert.ok(wasCalled, 'newly inserted throttle after timeout functioned'); assert.ok(bb.cancel(throttle), 'wait time of throttle was cancelled'); wasCalled = false; throttle2 = bb.throttle(null, throttler, 40); assert.notEqual(throttle, throttle2, 'the throttle is different'); assert.ok(wasCalled, 'throttle was inserted and run immediately after cancel'); done(); }, 60); }); QUnit.test('throttle returns timer information usable for cancelling', function(assert) { assert.expect(3); let done = assert.async(); let bb = new Backburner(['batman']); let wasCalled = false; function throttler() { assert.ok(false, 'this method shouldn\'t be called'); wasCalled = true; } let timer = bb.throttle(null, throttler, 1, false); assert.ok(bb.cancel(timer), 'the timer is cancelled'); // should return false second time around assert.ok(!bb.cancel(timer), 'the timer no longer exists in the list'); setTimeout(() => { assert.ok(!wasCalled, 'the timer wasn\'t called after waiting'); done(); }, 60); }); QUnit.test('throttler cancel after it\'s executed returns false', function(assert) { assert.expect(3); let bb = new Backburner(['darkknight']); let done = assert.async(); let wasCalled = false; function throttler() { assert.ok(true, 'the throttled method was called'); wasCalled = true; } let timer = bb.throttle(null, throttler, 1); setTimeout(() => { assert.ok(!bb.cancel(timer), 'no timer existed to cancel'); assert.ok(wasCalled, 'the timer was actually called'); done(); }, 10); }); QUnit.test('throttler returns the appropriate timer to cancel if the old item still exists', function(assert) { assert.expect(5); let bb = new Backburner(['robin']); let wasCalled = false; let done = assert.async(); function throttler() { assert.ok(true, 'the throttled method was called'); wasCalled = true; } let timer = bb.throttle(null, throttler, 1); let timer2 = bb.throttle(null, throttler, 1); assert.deepEqual(timer, timer2, 'the same timer was returned'); setTimeout(() => { bb.throttle(null, throttler, 1); assert.ok(!bb.cancel(timer), 'the second timer isn\'t removed, despite appearing to be the same item'); assert.ok(wasCalled, 'the timer was actually called'); done(); }, 10); }); QUnit.test('throttle without a target, without args', function(assert) { let done = assert.async(); let bb = new Backburner(['batman']); let calledCount = 0; let calledWith = new Array(); function throttled(...args) { calledCount++; calledWith.push(args); } bb.throttle(throttled, 10); bb.throttle(throttled, 10); bb.throttle(throttled, 10); assert.equal(calledCount, 1, 'throttle method was called immediately'); assert.deepEqual(calledWith, [ [] ], 'throttle method was called with the correct arguments'); setTimeout(() => { bb.throttle(throttled, 10); assert.equal(calledCount, 1, 'throttle method was not called again within the time window'); }, 0); setTimeout(() => { assert.equal(calledCount, 1, 'throttle method was was only called once'); done(); }, 20); }); QUnit.test('throttle without a target, without args - can be canceled', function(assert) { let bb = new Backburner(['batman']); let fooCalledCount = 0; let barCalledCount = 0; function foo() { fooCalledCount++; } function bar() { barCalledCount++; } bb.throttle(foo, 10); bb.throttle(foo, 10); assert.equal(fooCalledCount, 1, 'foo was called immediately, then throttle'); bb.throttle(bar, 10); let timer = bb.throttle(bar, 10); assert.equal(barCalledCount, 1, 'bar was called immediately, then throttle'); bb.cancel(timer); bb.throttle(bar, 10); assert.equal(barCalledCount, 2, 'after canceling the prior throttle, bar was called again'); }); QUnit.test('throttle without a target, without args, not immediate', function(assert) { let done = assert.async(); let bb = new Backburner(['batman']); let calledCount = 0; let calledWith = new Array(); function throttled(...args) { calledCount++; calledWith.push(args); } bb.throttle(throttled, 10, false); bb.throttle(throttled, 10, false); bb.throttle(throttled, 10, false); assert.equal(calledCount, 0, 'throttle method was not called immediately'); setTimeout(() => { assert.equal(calledCount, 0, 'throttle method was not called in next tick'); bb.throttle(throttled, 10, false); }, 0); setTimeout(() => { assert.equal(calledCount, 1, 'throttle method was was only called once'); assert.deepEqual(calledWith, [ [] ], 'throttle method was called with the correct arguments'); done(); }, 20); }); QUnit.test('throttle without a target, without args, not immediate - can be canceled', function(assert) { let done = assert.async(); let bb = new Backburner(['batman']); let fooCalledCount = 0; let barCalledCount = 0; function foo() { fooCalledCount++; } function bar() { barCalledCount++; } bb.throttle(foo, 10, false); bb.throttle(foo, 10, false); assert.equal(fooCalledCount, 0, 'foo was not called immediately'); bb.throttle(bar, 10, false); let timer = bb.throttle(bar, 10, false); assert.equal(barCalledCount, 0, 'bar was not called immediately'); setTimeout(() => { assert.equal(fooCalledCount, 0, 'foo was not called within the time window'); assert.equal(barCalledCount, 0, 'bar was not called within the time window'); bb.cancel(timer); }, 0); setTimeout(() => { assert.equal(fooCalledCount, 1, 'foo ran'); assert.equal(barCalledCount, 0, 'bar was properly canceled'); bb.throttle(bar, 10, false); setTimeout(() => { assert.equal(barCalledCount, 1, 'bar was able to run after being canceled'); done(); }, 20); }, 20); }); QUnit.test('throttle without a target, with args', function(assert) { let bb = new Backburner(['batman']); let calledWith: object[] = []; function throttled(first) { calledWith.push(first); } let foo = { isFoo: true }; let bar = { isBar: true }; let baz = { isBaz: true }; bb.throttle(throttled, foo, 10); bb.throttle(throttled, bar, 10); bb.throttle(throttled, baz, 10); assert.deepEqual(calledWith, [{ isFoo: true }], 'throttle method was only called once, with correct argument'); }); QUnit.test('throttle without a target, with args - can be canceled', function(assert) { let done = assert.async(); let bb = new Backburner(['batman']); let calledCount = 0; let calledWith: object[] = []; function throttled(first) { calledCount++; calledWith.push(first); } let foo = { isFoo: true }; let bar = { isBar: true }; let baz = { isBaz: true }; let qux = { isQux: true }; bb.throttle(throttled, foo, 10); bb.throttle(throttled, bar, 10); let timer = bb.throttle(throttled, baz, 10); assert.deepEqual(calledWith, [{ isFoo: true }], 'throttle method was only called once, with correct argument'); setTimeout(() => { bb.cancel(timer); bb.throttle(throttled, qux, 10, true); assert.deepEqual(calledWith, [{ isFoo: true }, { isQux: true }], 'throttle method was called again after canceling prior timer'); }, 0); setTimeout(() => { assert.deepEqual(calledWith, [{ isFoo: true }, { isQux: true }], 'throttle method was not called again'); done(); }, 20); }); QUnit.test('throttle without a target, with args, not immediate', function(assert) { let done = assert.async(); let bb = new Backburner(['batman']); let calledWith: object[] = []; function throttler(first) { calledWith.push(first); } let foo = { isFoo: true }; let bar = { isBar: true }; let baz = { isBaz: true }; bb.throttle(throttler, foo, 10, false); bb.throttle(throttler, bar, 10, false); bb.throttle(throttler, baz, 10, false); assert.deepEqual(calledWith, [], 'throttler was not called immediately'); setTimeout(() => { assert.deepEqual(calledWith, [{ isBaz: true }], 'debounce method was only called once, with correct argument'); done(); }, 20); }); QUnit.test('throttle without a target, with args, not immediate - can be canceled', function(assert) { let done = assert.async(); let bb = new Backburner(['batman']); let calledCount = 0; let calledWith: object[] = []; function throttled(first) { calledCount++; calledWith.push(first); } let foo = { isFoo: true }; let bar = { isBar: true }; let baz = { isBaz: true }; bb.throttle(throttled, foo, 10, false); bb.throttle(throttled, bar, 10, false); let timer = bb.throttle(throttled, baz, 10, false); assert.equal(calledCount, 0, 'throttle method was not called immediately'); setTimeout(() => { assert.deepEqual(calledWith, [], 'throttle method has not been called on next tick'); bb.cancel(timer); }, 0); setTimeout(() => { assert.deepEqual(calledWith, [], 'throttle method is not called when canceled'); done(); }, 20); }); QUnit.test('onError', function(assert) { assert.expect(1); function onError(error) { assert.equal('test error', error.message); } let bb = new Backburner(['errors'], { onError: onError }); bb.throttle(null, () => { throw new Error('test error'); }, 20); }); QUnit.test('throttle + immediate joins existing run loop instances', function(assert) { assert.expect(1); function onError(error) { assert.equal('test error', error.message); } let bb = new Backburner(['errors'], { onError: onError }); bb.run(() => { let parentInstance = bb.currentInstance; bb.throttle(null, () => { assert.equal(bb.currentInstance, parentInstance); }, 20, true); }); }); QUnit.test('when [callback, string] args passed', function(assert) { assert.expect(2); let bb = new Backburner(['one']); let functionWasCalled = false; bb.run(() => { bb.throttle(function(name) { assert.equal(name, 'batman'); functionWasCalled = true; }, 'batman', 200); }); assert.ok(functionWasCalled, 'function was called'); });
the_stack
import * as vscode from 'vscode'; import * as path from 'path'; import * as parse from './parsing'; import SourceSymbol from './SourceSymbol'; import CSymbol from './CSymbol'; import SubSymbol from './SubSymbol'; import { ProposedPosition } from './ProposedPosition'; import { activeLanguageServer, LanguageServer } from './extension'; import { showSingleQuickPick } from './QuickPick'; /** * Returns the file extension without the dot. */ export function fileExtension(fsPath: string): string { const extension = path.extname(fsPath); if (extension.length > 0) { return extension.substring(1); } return extension; } /** * Strips the directory and extension from a file name. */ export function fileNameBase(fsPath: string): string { return path.basename(fsPath, path.extname(fsPath)); } /** * Returns a coefficient of how similar the paths are to each other. * Lower numbers mean more similar. Equivalent paths will return 0. */ export function compareDirectoryPaths(directoryPath_a: string, directoryPath_b: string): number { const a_segments = directoryPath_a.split(path.sep).filter(segment => segment.length > 0); const b_segments = directoryPath_b.split(path.sep).filter(segment => segment.length > 0); const minSegments = Math.min(a_segments.length, b_segments.length); let commonLeadingDirectories = 0; for (let i = 0; i < minSegments; ++i) { if (a_segments[i] !== b_segments[i]) { break; } ++commonLeadingDirectories; } let commonTrailingDirectories = 0; for (let i = 1; i < minSegments - commonLeadingDirectories; ++i) { if (a_segments[a_segments.length - i] !== b_segments[b_segments.length - i]) { break; } ++commonTrailingDirectories; } const commonDirectories = commonLeadingDirectories + commonTrailingDirectories; const coefficient = Math.max((a_segments.length - commonDirectories), (b_segments.length - commonDirectories)); return a_segments.length !== b_segments.length ? coefficient + 1 : coefficient; } export function arraysAreEqual<T>( array_a: ReadonlyArray<T>, array_b: ReadonlyArray<T>, equalityFn: (a: T, b: T) => boolean = (a: T, b: T) => a === b ): boolean { if (array_a.length !== array_b.length) { return false; } for (let i = 0; i < array_a.length; ++i) { if (!equalityFn(array_a[i], array_b[i])) { return false; } } return true; } /** * Returns true if the arrays are equal, or if either array is a sub-array of * the other, starting from the beginning of the arrays. * For example, `[1,2,3]` and `[1,2]` intersect while `[1,2,3]` and `[2,3]` do not. */ export function arraysIntersect<T>( array_a: ReadonlyArray<T>, array_b: ReadonlyArray<T>, equalityFn: (a: T, b: T) => boolean = (a: T, b: T) => a === b ): boolean { const minLength = Math.min(array_a.length, array_b.length); for (let i = 0; i < minLength; ++i) { if (!equalityFn(array_a[i], array_b[i])) { return false; } } return true; } export function arraysShareAnyElement<T>(array_a: ReadonlyArray<T>, array_b: ReadonlyArray<T>): boolean { for (const element of array_a) { if (array_b.includes(element)) { return true; } } return false; } export async function uriExists(uri: vscode.Uri): Promise<boolean> { try { await vscode.workspace.fs.stat(uri); } catch (e) { return false; } return true; } export function containedInWorkspace(locationOrUri: vscode.Location | vscode.Uri): boolean { if (locationOrUri instanceof vscode.Location) { return vscode.workspace.asRelativePath(locationOrUri.uri) !== locationOrUri.uri.fsPath; } return vscode.workspace.asRelativePath(locationOrUri) !== locationOrUri.fsPath; } export function revealRange(editor: vscode.TextEditor, range: vscode.Range): void { editor.revealRange(editor.document.validateRange(range), vscode.TextEditorRevealType.InCenter); // revealRange() sometimes doesn't work for large files, this appears to be a bug in vscode. // Waiting a bit and re-executing seems to work around this issue. (BigBahss/vscode-cmantic#2) setTimeout(() => { for (const visibleRange of editor.visibleRanges) { if (visibleRange.contains(range)) { return; } } editor.revealRange(range, vscode.TextEditorRevealType.InCenter); }, 500); } export function indentation(options?: vscode.TextEditorOptions): string { if (!options) { const editor = vscode.window.activeTextEditor; if (editor) { options = editor.options; } } if (options?.insertSpaces) { return ' '.repeat(options.tabSize as number); } return '\t'; } export function lineCount(text: string): number { return (text.endsWith('\n')) ? text.split('\n').length - 1 : text.split('\n').length; } export function endOfLine(document: vscode.TextDocument): string { switch (document.eol) { case vscode.EndOfLine.CRLF: return '\r\n'; case vscode.EndOfLine.LF: default: return '\n'; } } export function positionAfterLastNonEmptyLine(document: vscode.TextDocument): ProposedPosition { for (let i = document.lineCount - 1; i >= 0; --i) { if (!document.lineAt(i).isEmptyOrWhitespace) { return new ProposedPosition(document.lineAt(i).range.end, { after: true }); } } return new ProposedPosition(); } export function sortByRange(a: { range: vscode.Range }, b: { range: vscode.Range }): number { return a.range.end.isAfter(b.range.end) ? 1 : -1; } export type AnySymbol = SourceSymbol | CSymbol | SubSymbol; export type LocationType = vscode.Location | vscode.LocationLink; /** * Finds the most likely definition of symbol and only returns a result with the same base file name. * Returns undefined if the most likely definition found is the same symbol. */ export async function findDefinition(symbol: AnySymbol): Promise<vscode.Location | undefined> { const definitionResults = await vscode.commands.executeCommand<LocationType[]>( 'vscode.executeDefinitionProvider', symbol.uri, symbol.selectionRange.start); return findMostLikelyResult(symbol, definitionResults); } /** * Finds the most likely declaration of symbol and only returns a result with the same base file name. * Returns undefined if the most likely declaration found is the same symbol. */ export async function findDeclaration(symbol: AnySymbol): Promise<vscode.Location | undefined> { const declarationResults = await vscode.commands.executeCommand<LocationType[]>( 'vscode.executeDeclarationProvider', symbol.uri, symbol.selectionRange.start); return findMostLikelyResult(symbol, declarationResults); } function findMostLikelyResult( symbol: AnySymbol, locationResults?: LocationType[] ): vscode.Location | undefined { const thisFileNameBase = fileNameBase(symbol.uri.fsPath); for (const location of makeLocationArray(locationResults)) { if (!containedInWorkspace(location)) { continue; } if (fileNameBase(location.uri.fsPath) === thisFileNameBase && !(location.uri.fsPath === symbol.uri.fsPath && symbol.range.contains(location.range))) { return location; } } } export function makeLocationArray(locationResults?: LocationType[]): vscode.Location[] { if (!locationResults) { return []; } const locations: vscode.Location[] = []; for (const element of locationResults) { const location = (element instanceof vscode.Location) ? element : new vscode.Location(element.targetUri, element.targetRange); locations.push(location); } return locations; } export interface DeclarationDefinitionLink { declaration: CSymbol; definition?: vscode.Location; } export async function makeDeclDefLink(declaration: CSymbol): Promise<DeclarationDefinitionLink> { return { declaration: declaration, definition: await declaration.findDefinition() }; } /** * Indicates that the function requires a definition that is visible to translation unit that declares it. */ export function requiresVisibleDefinition(functionDeclaration: CSymbol): boolean { return functionDeclaration.isInline() || functionDeclaration.isConstexpr() || functionDeclaration.isConsteval() || functionDeclaration.hasUnspecializedTemplate(); } export function formatSignature(symbol: CSymbol): string { if (symbol.isVariable()) { const text = symbol.document.getText(new vscode.Range(symbol.range.start, symbol.declarationEnd())); return parse.removeAttributes(parse.removeComments(text)).replace(/\s+/g, ' '); } else if (activeLanguageServer() === LanguageServer.cpptools) { // cpptools does a good job of providing formatted signatures for DocumentSymbols. return symbol.signature; } if (symbol.isFunction()) { const text = symbol.document.getText(new vscode.Range(symbol.selectionRange.end, symbol.declarationEnd())); return symbol.templatedName(true) + parse.removeAttributes(parse.removeComments(text)).replace(/\s+/g, ' '); } return symbol.templatedName(true); } /** * Test if range contains position, not including the start and end. */ export function containsExclusive(range: vscode.Range, position: vscode.Position): boolean { return !range.end.isBeforeOrEqual(position) && !range.start.isAfterOrEqual(position); } export function firstCharToUpper(str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); } export function firstCharToLower(str: string): string { return str.charAt(0).toLowerCase() + str.slice(1); } export function make_snake_case(text: string): string { return text.replace(/(?<!^|_)[A-Z]/g, match => '_' + match).toLowerCase(); } export function makeCamelCase(text: string): string { return firstCharToLower(text.replace(/_[a-z]/g, match => match.charAt(1).toUpperCase()).replace('_', '')); } export function MakePascalCase(text: string): string { return firstCharToUpper(text.replace(/_[a-z]/g, match => match.charAt(1).toUpperCase()).replace('_', '')); } export function formatPathToDisplay(uri: vscode.Uri): string { const relativePath = vscode.workspace.asRelativePath(uri); // Arbitrary limit, as to not display a path that's running all the way across the screen. if (relativePath.length > 60) { return relativePath.slice(0, 28) + '....' + relativePath.slice(-28); } return relativePath; } export enum AccessLevel { public, protected, private } export function accessSpecifierString(access: AccessLevel): string { switch (access) { case AccessLevel.public: return 'public:'; case AccessLevel.protected: return 'protected:'; case AccessLevel.private: return 'private:'; } } export function accessSpecifierRegexp(access: AccessLevel): RegExp { switch (access) { case AccessLevel.public: return /\bpublic\s*:/; case AccessLevel.protected: return /\bprotected\s*:/; case AccessLevel.private: return /\bprivate\s*:/; } } interface AccessQuickPickItem extends vscode.QuickPickItem { access: AccessLevel; } const accessItems: AccessQuickPickItem[] = [ { label: 'public', access: AccessLevel.public }, { label: 'protected', access: AccessLevel.protected }, { label: 'private', access: AccessLevel.private } ]; export async function getMemberAccessFromUser(): Promise<AccessLevel | undefined> { const accessItem = await showSingleQuickPick<AccessQuickPickItem>(accessItems, { title: 'Select member access level' }); return accessItem?.access; }
the_stack
import { Range, Position } from 'vscode'; import * as path from 'path'; import { DCollection } from '../diagnostic'; import { isNumber } from 'util'; import { Moment } from 'moment'; export enum CheckState { Running = 'R', Success = 'S', Error = 'E', Stopped = 'X' } export enum CheckStatus { NotStarted, Starting, SanyParsing, SanyFinished, InitialStatesComputing, SuccessorStatesComputing, Checkpointing, CheckingLiveness, CheckingLivenessFinal, ServerRunning, WorkersRegistered, Finished } const STATUS_NAMES = new Map<CheckStatus, string>(); STATUS_NAMES.set(CheckStatus.NotStarted, 'Not started'); STATUS_NAMES.set(CheckStatus.Starting, 'Starting'); STATUS_NAMES.set(CheckStatus.SanyParsing, 'SANY parsing'); STATUS_NAMES.set(CheckStatus.SanyFinished, 'SANY finished'); STATUS_NAMES.set(CheckStatus.InitialStatesComputing, 'Computing initial states'); STATUS_NAMES.set(CheckStatus.SuccessorStatesComputing, 'Computing reachable states'); STATUS_NAMES.set(CheckStatus.Checkpointing, 'Checkpointing'); STATUS_NAMES.set(CheckStatus.CheckingLiveness, 'Checking liveness'); STATUS_NAMES.set(CheckStatus.CheckingLivenessFinal, 'Checking final liveness'); STATUS_NAMES.set(CheckStatus.ServerRunning, 'Master waiting for workers'); STATUS_NAMES.set(CheckStatus.WorkersRegistered, 'Workers connected'); STATUS_NAMES.set(CheckStatus.Finished, 'Finished'); const STATE_NAMES = new Map<CheckState, string>(); STATE_NAMES.set(CheckState.Running, 'Running'); STATE_NAMES.set(CheckState.Success, 'Success'); STATE_NAMES.set(CheckState.Error, 'Errors'); STATE_NAMES.set(CheckState.Stopped, 'Stopped'); const VALUE_FORMAT_LENGTH_THRESHOLD = 30; /** * Statistics on initial state generation. */ export class InitialStateStatItem { constructor( readonly timeStamp: string, readonly diameter: number, readonly total: number, readonly distinct: number, readonly queueSize: number ) {} } /** * Statistics on coverage. */ export class CoverageItem { constructor( readonly module: string, readonly action: string, readonly filePath: string | undefined, readonly range: Range, readonly total: number, readonly distinct: number ) {} } enum MessageSpanType { Text = 'T', SourceLink = 'SL' } export class MessageSpan { private constructor( readonly type: MessageSpanType, readonly text: string, readonly filePath?: string | undefined, readonly location?: Position | undefined ) {} static newTextSpan(text: string): MessageSpan { return new MessageSpan(MessageSpanType.Text, text); } static newSourceLinkSpan(text: string, filePath: string, location: Position): MessageSpan { return new MessageSpan(MessageSpanType.SourceLink, text, filePath, location); } } /** * Represents an error or warning line of a message. */ export class MessageLine { constructor( readonly spans: ReadonlyArray<MessageSpan> ) {} static fromText(text: string): MessageLine { return new MessageLine([ MessageSpan.newTextSpan(text) ]); } toString(): string { return this.spans.map((s) => s.text).join(''); } } export type ValueKey = string | number; /** * Type of value change between two consecutive states. */ export enum Change { NOT_CHANGED = 'N', ADDED = 'A', MODIFIED = 'M', DELETED = 'D' } /** * Base class for values. */ export class Value { static idCounter = 0; static idStep = 1; changeType = Change.NOT_CHANGED; readonly id: number; constructor( readonly key: ValueKey, readonly str: string ) { Value.idCounter += Value.idStep; this.id = Value.idCounter; } /** * Switches off ID incrementation. For tests only. */ static switchIdsOff(): void { Value.idStep = 0; } /** * Switches on ID incrementation. For tests only. */ static switchIdsOn(): void { Value.idStep = 1; } setModified(): Value { this.changeType = Change.MODIFIED; return this; } setAdded(): Value { this.changeType = Change.ADDED; return this; } setDeleted(): Value { this.changeType = Change.MODIFIED; return this; } /** * Adds formatted representation of the value to the given array of strings. */ format(indent: string): string { return `${this.str}`; } } /** * A value that is represented by some variable name. */ export class NameValue extends Value { constructor(key: ValueKey, name: string) { super(key, name); } } /** * Value that is a collection of other values. */ export abstract class CollectionValue extends Value { readonly expandSingle = true; deletedItems: Value[] | undefined; constructor( key: ValueKey, readonly items: Value[], readonly prefix: string, readonly postfix: string, toStr?: (v: Value) => string ) { super(key, makeCollectionValueString(items, prefix, postfix, ', ', toStr || (v => v.str))); } addDeletedItems(items: Value[]): void { if (!items || items.length === 0) { return; } if (!this.deletedItems) { this.deletedItems = []; } const delItems = this.deletedItems; items.forEach(delItem => { const newValue = new Value(delItem.key, delItem.str); // No need in deep copy here newValue.changeType = Change.DELETED; delItems.push(newValue); }); } findItem(id: number): Value | undefined { for (const item of this.items) { if (item.changeType === Change.DELETED) { continue; } if (item.id === id) { return item; } if (item instanceof CollectionValue) { const subItem = item.findItem(id); if (subItem) { return subItem; } } } return undefined; } format(indent: string): string { if (this.items.length === 0) { return `${this.prefix}${this.postfix}`; } if (this.str.length <= VALUE_FORMAT_LENGTH_THRESHOLD) { return this.str; } const subIndent = indent + ' '; const fmtFunc = (v: Value) => this.formatKey(subIndent, v) + '' + v.format(subIndent); const body = makeCollectionValueString(this.items, '', '', ',\n', fmtFunc); return `${this.prefix}\n${body}\n${indent}${this.postfix}`; } formatKey(indent: string, value: Value): string { return `${indent}${value.key}: `; } } /** * Represents a set: {1, "b", <<TRUE, 5>>}, {}, etc. */ export class SetValue extends CollectionValue { constructor(key: ValueKey, items: Value[]) { super(key, items, '{', '}'); } setModified(): SetValue { super.setModified(); return this; } formatKey(indent: string, _: Value): string { return indent; } } /** * Represents a sequence/tuple: <<1, "b", TRUE>>, <<>>, etc. */ export class SequenceValue extends CollectionValue { constructor(key: ValueKey, items: Value[]) { super(key, items, '<<', '>>'); } formatKey(indent: string, _: Value): string { return indent; } } /** * Represents a structure: [a |-> 'A', b |-> 34, c |-> <<TRUE, 2>>], [], etc. */ export class StructureValue extends CollectionValue { constructor(key: ValueKey, items: Value[], preserveOrder = false) { if (!preserveOrder) { items.sort(StructureValue.compareItems); } super(key, items, '[', ']', StructureValue.itemToString); } static itemToString(item: Value): string { return `${item.key} |-> ${item.str}`; } static compareItems(a: Value, b: Value): number { if (a.key < b.key) { return -1; } else if (a.key > b.key) { return 1; } return 0; } setModified(): StructureValue { super.setModified(); return this; } formatKey(indent: string, value: Value): string { return `${indent}${value.key} |-> `; } } /** * Represents a simple function: (10 :> TRUE), ("foo" :> "bar"), etc */ export class SimpleFunctionItem extends Value { constructor( key: ValueKey, readonly from: Value, readonly to: Value ) { super(key, `${from.str} :> ${to.str}`); } format(indent: string): string { if (this.str.length <= VALUE_FORMAT_LENGTH_THRESHOLD || !(this.to instanceof CollectionValue)) { return `(${this.str})`; } const body = this.to.format(indent + ' '); return `(${this.from.str} :> ${body}\n${indent})`; } } /** * Represents a collection of merged simple functions: (10 :> TRUE), * ("foo" :> "bar" @@ "baz" => 31), etc */ export class SimpleFunction extends Value { readonly expandSingle = false; constructor( key: ValueKey, readonly items: SimpleFunctionItem[] ) { super(key, makeCollectionValueString(items, '(', ')', ' @@ ', (v => v.str))); } format(indent: string): string { if (this.items.length === 1) { return this.items[0].format(indent); } return super.format(indent); } } /** * A state of a process in a particular moment of time. */ export class ErrorTraceItem { constructor( readonly num: number, readonly title: string, readonly module: string, readonly action: string, readonly filePath: string | undefined, readonly range: Range, readonly variables: StructureValue // Variables are presented as items of a structure ) {} } /** * An output line produced by Print/PrintT along with the number of consecutive occurrences. */ export class OutputLine { count = 1; constructor(readonly text: string) { } increment(): void { this.count += 1; } } /** * A warning, issued by TLC. */ export class WarningInfo { constructor( readonly lines: MessageLine[] ) {} } /** * An error, issued by TLC. */ export class ErrorInfo { constructor( public lines: MessageLine[], readonly errorTrace: ErrorTraceItem[] ) {} } export enum ModelCheckResultSource { Process, // The result comes from an ongoing TLC process OutFile // The result comes from a .out file } export class SpecFiles { readonly tlaFileName: string; readonly cfgFileName: string; constructor( readonly tlaFilePath: string, readonly cfgFilePath: string ) { this.tlaFileName = path.basename(tlaFilePath); this.cfgFileName = path.basename(cfgFilePath); } } /** * Represents the state of a TLA model checking process. */ export class ModelCheckResult { readonly stateName: string; readonly startDateTimeStr: string | undefined; readonly endDateTimeStr: string | undefined; readonly durationStr: string | undefined; readonly statusDetails: string | undefined; constructor( readonly source: ModelCheckResultSource, readonly specFiles: SpecFiles | unknown, readonly showFullOutput: boolean, readonly state: CheckState, readonly status: CheckStatus, readonly processInfo: string | undefined, readonly initialStatesStat: InitialStateStatItem[], readonly coverageStat: CoverageItem[], readonly warnings: WarningInfo[], readonly errors: ErrorInfo[], readonly sanyMessages: DCollection | undefined, readonly startDateTime: Moment | undefined, readonly endDateTime: Moment | undefined, readonly duration: number | undefined, readonly workersCount: number, readonly collisionProbability: string | undefined, readonly outputLines: OutputLine[], ) { this.stateName = getStateName(this.state); this.startDateTimeStr = dateTimeToStr(startDateTime); this.endDateTimeStr = dateTimeToStr(endDateTime); this.durationStr = durationToStr(duration); let statusDetails; switch (state) { case CheckState.Running: statusDetails = getStatusName(status); break; case CheckState.Success: statusDetails = collisionProbability ? `Fingerprint collision probability: ${collisionProbability}` : ''; break; case CheckState.Error: statusDetails = `${errors.length} error(s)`; break; } this.statusDetails = statusDetails; } static createEmpty(source: ModelCheckResultSource): ModelCheckResult { return new ModelCheckResult( source, undefined, false, CheckState.Running, CheckStatus.Starting, undefined, [], [], [], [], undefined, undefined, undefined, undefined, 0, undefined, []); } formatValue(valueId: number): string | undefined { for (const err of this.errors) { for (const items of err.errorTrace) { const value = items.variables.findItem(valueId); if (value) { return value.format(''); } } } return undefined; } } function getStateName(state: CheckState): string { const name = STATE_NAMES.get(state); if (typeof name !== 'undefined') { return name; } throw new Error(`Name not defined for check state ${state}`); } export function getStatusName(status: CheckStatus): string { const name = STATUS_NAMES.get(status); if (name) { return name; } throw new Error(`Name not defined for check status ${status}`); } /** * Recursively finds and marks all the changes between two collections. */ export function findChanges(prev: CollectionValue, state: CollectionValue): boolean { let pi = 0; let si = 0; let modified = false; const deletedItems = []; while (pi < prev.items.length && si < state.items.length) { const prevValue = prev.items[pi]; const stateValue = state.items[si]; if (prevValue.key > stateValue.key) { stateValue.changeType = Change.ADDED; modified = true; si += 1; } else if (prevValue.key < stateValue.key) { deletedItems.push(prevValue); pi += 1; } else { if (prevValue instanceof CollectionValue && stateValue instanceof CollectionValue) { modified = findChanges(prevValue, stateValue) || modified; } else if (prevValue.str !== stateValue.str) { stateValue.changeType = Change.MODIFIED; modified = true; } si += 1; pi += 1; } } for (; si < state.items.length; si++) { state.items[si].changeType = Change.ADDED; modified = true; } for (; pi < prev.items.length; pi++) { deletedItems.push(prev.items[pi]); } state.addDeletedItems(deletedItems); modified = modified || deletedItems.length > 0; if (modified) { state.changeType = Change.MODIFIED; } return modified; } function dateTimeToStr(dateTime: Moment | undefined): string { if (!dateTime) { return 'not yet'; } return dateTime.format('HH:mm:ss (MMM D)'); } function durationToStr(dur: number | undefined): string { if (!isNumber(dur)) { return ''; } return `${dur} msec`; } function makeCollectionValueString( items: Value[], prefix: string, postfix: string, delimiter: string, toStr: (v: Value) => string ) { // TODO: trim to fit into 100 symbols const valuesStr = items .filter(i => i.changeType !== Change.DELETED) .map(i => toStr(i)) .join(delimiter); return prefix + valuesStr + postfix; }
the_stack
import { Node as AcornNode } from 'acorn'; import { isDummy } from 'acorn-loose'; import { traverse, VisitorOption } from 'estraverse'; import { Identifier, MemberExpression, Node, Program } from 'estree'; import { inject, injectable } from 'inversify'; import Cdp from '../cdp/api'; import { ICdpApi } from '../cdp/connection'; import { IPosition } from '../common/positions'; import { getEnd, getStart, getText, parseProgram } from '../common/sourceCodeManipulations'; import { PositionToOffset } from '../common/stringUtils'; import Dap from '../dap/api'; import { IEvaluator, returnValueStr } from './evaluator'; import { StackFrame } from './stackTrace'; import { enumerateProperties, enumeratePropertiesTemplate } from './templates/enumerateProperties'; /** * Context in which a completion is being evaluated. */ export interface ICompletionContext { expression: string; executionContextId: number | undefined; stackFrame: StackFrame | undefined; } /** * A completion expresson to be evaluated. */ export interface ICompletionExpression { expression: string; position: IPosition; } export interface ICompletionWithSort extends Dap.CompletionItem { sortText: string; } /** * Completion kinds known to VS Code. This isn't formally restricted on the DAP. * @see https://github.com/microsoft/vscode/blob/71eb6ad17eaf49a46fd176ca74a083001e17f7de/src/vs/editor/common/modes.ts#L329 */ export const enum CompletionKind { Method = 'method', Function = 'function', Constructor = 'constructor', Field = 'field', Variable = 'variable', Class = 'class', Struct = 'struct', Interface = 'interface', Module = 'module', Property = 'property', Event = 'event', Operator = 'operator', Unit = 'unit', Value = 'value', Constant = 'constant', Enum = 'enum', EnumMember = 'enumMember', Keyword = 'keyword', Snippet = 'snippet', Text = 'text', Color = 'color', File = 'file', Reference = 'reference', Customcolor = 'customcolor', Folder = 'folder', Type = 'type', TypeParameter = 'typeParameter', } /** * Tries to infer the completion kind for the given Acorn node. */ const inferCompletionInfoForDeclaration = (node: Node) => { switch (node.type) { case 'ClassDeclaration': case 'ClassExpression': return { type: CompletionKind.Class, id: node.id }; case 'MethodDefinition': return { type: node.key?.type === 'Identifier' && node.key.name === 'constructor' ? CompletionKind.Constructor : CompletionKind.Method, id: node.key, }; case 'VariableDeclarator': return { type: node.init?.type === 'FunctionExpression' || node.init?.type === 'ArrowFunctionExpression' ? CompletionKind.Function : CompletionKind.Variable, id: node.id, }; } }; function maybeHasSideEffects(node: Node): boolean { let result = false; traverse(node, { enter(node) { if ( node.type === 'CallExpression' || node.type === 'NewExpression' || (node.type === 'UnaryExpression' && node.operator === 'delete') || node.type === 'ClassBody' ) { result = true; return VisitorOption.Break; } }, }); return result; } export const ICompletions = Symbol('ICompletions'); /** * Gets autocompletion results for an expression. */ export interface ICompletions { completions(options: ICompletionContext & ICompletionExpression): Promise<Dap.CompletionItem[]>; } /** * Provides REPL completions for the debug session. */ @injectable() export class Completions { constructor( @inject(IEvaluator) private readonly evaluator: IEvaluator, @inject(ICdpApi) private readonly cdp: Cdp.Api, ) {} public async completions( options: ICompletionContext & ICompletionExpression, ): Promise<Dap.CompletionItem[]> { const source = parseProgram(options.expression); const offset = new PositionToOffset(options.expression).convert(options.position); let candidate: () => Promise<ICompletionWithSort[]> = () => Promise.resolve([]); traverse(source, { enter: node => { const asAcorn = node as AcornNode; if (asAcorn.start < offset && offset <= asAcorn.end) { if (node.type === 'Identifier') { candidate = () => this.identifierCompleter(options, source, node, offset); } else if (node.type === 'MemberExpression') { candidate = node.computed ? () => this.elementAccessCompleter(options, node, offset) : () => this.propertyAccessCompleter(options, node, offset); } } }, }); return candidate().then(v => v.sort((a, b) => (a.sortText > b.sortText ? 1 : -1))); } /** * Completer for a TS element access, via bracket syntax. */ private async elementAccessCompleter( options: ICompletionContext, node: MemberExpression, offset: number, ) { if (node.property.type !== 'Literal' || typeof node.property.value !== 'string') { // If this is not a string literal, either they're typing a number (where // autocompletion would be quite silly) or a complex expression where // trying to complete by property name is inappropriate. return []; } const prefix = options.expression.slice(getStart(node.property) + 1, offset); const completions = await this.defaultCompletions(options, prefix); // Filter out the array access, adjust replacement ranges return completions .filter(c => c.sortText !== '~~[') .map(item => ({ ...item, text: JSON.stringify(item.text ?? item.label) + ']', start: getStart(node.property), length: getEnd(node.property) - getStart(node.property), })); } /** * Completer for an arbitrary identifier. */ private async identifierCompleter( options: ICompletionContext, source: Program, node: Identifier, offset: number, ) { // Walk through the expression and look for any locally-declared variables or identifiers. const localIdentifiers: ICompletionWithSort[] = []; traverse(source, { enter(node) { const completion = inferCompletionInfoForDeclaration(node); if (completion?.id?.type === 'Identifier') { localIdentifiers.push({ label: completion.id.name, type: completion.type, sortText: completion.id.name, }); } }, }); const prefix = options.expression.slice(getStart(node), offset); const completions = [...localIdentifiers, ...(await this.defaultCompletions(options, prefix))]; if ( this.evaluator.hasReturnValue && options.executionContextId !== undefined && returnValueStr.startsWith(prefix) ) { completions.push({ sortText: `~${returnValueStr}`, label: returnValueStr, type: 'variable', }); } return completions; } /** * Completes a property access on an object. */ async propertyAccessCompleter( options: ICompletionContext, node: MemberExpression, offset: number, ): Promise<ICompletionWithSort[]> { const { result, isArray } = await this.completePropertyAccess({ executionContextId: options.executionContextId, stackFrame: options.stackFrame, expression: getText(options.expression, node.object), prefix: isDummy(node.property) ? '' : options.expression.slice(getStart(node.property), offset), // If we see the expression might have a side effect, still try to get // completions, but tell V8 to throw if it sees a side effect. This is a // fairly conservative checker, we don't enable it if not needed. throwOnSideEffect: maybeHasSideEffects(node), }); const start = getStart(node.property) - 1; // For any properties are aren't valid identifiers, (erring on the side of // caution--not checking unicode and such), quote them as foo['bar!'] const validIdentifierRe = /^[$a-z_][0-9a-z_$]*$/i; for (const item of result) { if (!validIdentifierRe.test(item.label)) { item.text = `[${JSON.stringify(item.label)}]`; item.start = start; item.length = 1; } } if (isArray) { const placeholder = 'index'; result.unshift({ label: `[${placeholder}]`, text: `[${placeholder}]`, type: 'property', sortText: '~~[', start, selectionStart: 1, selectionLength: placeholder.length, length: 1, }); } return result; } private async completePropertyAccess({ executionContextId, stackFrame, expression, prefix, isInGlobalScope = false, throwOnSideEffect = false, }: { executionContextId?: number; stackFrame?: StackFrame; expression: string; prefix: string; throwOnSideEffect?: boolean; isInGlobalScope?: boolean; }): Promise<{ result: ICompletionWithSort[]; isArray: boolean }> { const params = { expression: `(${expression})`, objectGroup: 'console', silent: true, throwOnSideEffect, }; const callFrameId = stackFrame && stackFrame.callFrameId(); const objRefResult = await this.evaluator.evaluate( callFrameId ? { ...params, callFrameId } : { ...params, contextId: executionContextId }, { stackFrame }, ); if (!objRefResult || objRefResult.exceptionDetails) { return { result: [], isArray: false }; } // No object ID indicates a primitive. Call enumeration on the value // directly. We don't do this all the time, since our enumeration logic // triggers Chrome's side-effect detect and fails. if (!objRefResult.result.objectId) { const primitiveParams = { ...params, returnByValue: true, throwOnSideEffect: false, expression: enumeratePropertiesTemplate( `(${expression})`, JSON.stringify(prefix), JSON.stringify(isInGlobalScope), ), }; const propsResult = await this.evaluator.evaluate( callFrameId ? { ...primitiveParams, callFrameId } : { ...primitiveParams, contextId: executionContextId }, ); return !propsResult || propsResult.exceptionDetails ? { result: [], isArray: false } : propsResult.result.value; } // Otherwise, invoke the property enumeration on the returned object ID. try { const propsResult = await enumerateProperties({ cdp: this.cdp, args: [undefined, prefix, isInGlobalScope], objectId: objRefResult.result.objectId, returnByValue: true, }); return propsResult.value; } catch { return { result: [], isArray: false }; } finally { this.cdp.Runtime.releaseObject({ objectId: objRefResult.result.objectId }); // no await } } /** * Returns completion for globally scoped variables. Used for a fallback * if we can't find anything more specific to complete. */ private async defaultCompletions( options: ICompletionContext, prefix = '', ): Promise<ICompletionWithSort[]> { for (const global of ['self', 'global', 'this']) { const { result: items } = await this.completePropertyAccess({ executionContextId: options.executionContextId, stackFrame: options.stackFrame, expression: global, prefix, isInGlobalScope: true, }); if (!items.length) { continue; } if (options.stackFrame) { // When evaluating on a call frame, also autocomplete with scope variables. const names = new Set(items.map(item => item.label)); for (const completion of await options.stackFrame.completions()) { if (names.has(completion.label)) continue; names.add(completion.label); items.push(completion as ICompletionWithSort); } } items.push(...this.syntheticCompletions(options, prefix)); return items; } return this.syntheticCompletions(options, prefix); } private syntheticCompletions( _options: ICompletionContext, prefix: string, ): ICompletionWithSort[] { if (this.evaluator.hasReturnValue && returnValueStr.startsWith(prefix)) { return [ { sortText: `~${returnValueStr}`, label: returnValueStr, type: 'variable', }, ]; } return []; } }
the_stack
import { keys, values } from "./Dict"; import { Result } from "./OptionResult"; import { zip } from "./ZipUnzip"; type PendingPayload<A> = { resolveCallbacks?: Array<(value: A) => void>; cancelCallbacks?: Array<() => void>; cancel?: void | (() => void); }; function FutureInit<A>( this: Future<A>, init: (resolver: (value: A) => void) => (() => void) | void, ) { const resolver = (value: A) => { if (this.tag === "Pending") { const pending = this.pending as PendingPayload<A>; const resolveCallbacks = pending.resolveCallbacks; resolveCallbacks?.forEach((func) => func(value)); this.tag = "Resolved"; this.value = value; this.pending = undefined; } }; const pendingPayload: PendingPayload<A> = {}; this.tag = "Pending"; this.pending = pendingPayload; pendingPayload.cancel = init(resolver); } export class Future<A> { /** * Creates a new future from its initializer function (like `new Promise(...)`) */ static make = <A>( init: (resolver: (value: A) => void) => (() => void) | void, ): Future<A> => { const future = Object.create(proto); FutureInit.call(future, init); return future as Future<A>; }; /** * Creates a future resolved to the passed value */ static value = <A>(value: A): Future<A> => { const future = Object.create(proto); FutureInit.call(future, (resolve) => resolve(value)); return future as Future<A>; }; /** * Converts a Promise to a Future\<Result\<Value, unknown>> */ static fromPromise<A>(promise: Promise<A>): Future<Result<A, unknown>> { return Future.make((resolve) => { promise.then( (ok) => resolve(Result.Ok(ok)), (reason) => resolve(Result.Error(reason)), ); }); } /** * Turns an array of futures into a future of array */ static all = <Futures extends readonly Future<any>[] | []>( futures: Futures, propagateCancel = false, ): Future<{ -readonly [P in keyof Futures]: Futures[P] extends Future<infer T> ? T : never; }> => { const length = futures.length; let acc = Future.value<Array<unknown>>([]); let index = 0; while (true) { if (index >= length) { return acc as unknown as Future<{ -readonly [P in keyof Futures]: Futures[P] extends Future<infer T> ? T : never; }>; } const item = futures[index] as Future<unknown>; acc = acc.flatMap((array) => { return item.map((value) => { array.push(value); return array; }, propagateCancel); }, propagateCancel); index++; } }; /** * Turns an dict of futures into a future of dict */ static allFromDict = <Dict extends Record<string, Future<any>>>( dict: Dict, ): Future<{ -readonly [P in keyof Dict]: Dict[P] extends Future<infer T> ? T : never; }> => { const dictKeys = keys(dict); return Future.all(values(dict)).map((values) => Object.fromEntries(zip(dictKeys, values)), ); }; tag: "Pending" | "Cancelled" | "Resolved"; value?: A; pending?: PendingPayload<A>; constructor(_init: (resolver: (value: A) => void) => (() => void) | void) { const pendingPayload: PendingPayload<A> = {}; this.tag = "Pending"; this.pending = pendingPayload; } isPending(): this is Future<A> & { tag: "Pending"; value: PendingPayload<A>; } { return this.tag === "Pending"; } isCancelled(): this is Future<A> & { tag: "Cancelled"; value: undefined; } { return this.tag === "Cancelled"; } isResolved(): this is Future<A> & { tag: "Resolved"; value: A; } { return this.tag === "Resolved"; } /** * Runs the callback with the future value when resolved */ get(func: (value: A) => void) { if (this.isPending()) { const pending = this.pending as PendingPayload<A>; pending.resolveCallbacks = pending.resolveCallbacks ?? []; pending.resolveCallbacks.push(func); } if (this.isResolved()) { func(this.value); } } /** * Runs the callback if and when the future is cancelled */ onCancel(func: () => void) { if (this.isPending()) { const pending = this.pending as PendingPayload<A>; pending.cancelCallbacks = pending.cancelCallbacks ?? []; pending.cancelCallbacks.push(func); } if (this.isCancelled()) { func(); } } /** * Cancels the future */ cancel() { if (this.tag === "Pending") { this.tag = "Cancelled"; this.value = undefined; const pending = this.pending as PendingPayload<A>; const cancelCallbacks = pending.cancelCallbacks; pending.cancel?.(); cancelCallbacks?.forEach((func) => func()); this.pending = undefined; } } /** * Returns the Future containing the value from the callback * * (Future\<A>, A => B) => Future\<B> */ map<B>(func: (value: A) => B, propagateCancel = false): Future<B> { const future = Future.make<B>((resolve) => { this.get((value) => { resolve(func(value)); }); if (propagateCancel) { return () => { this.cancel(); }; } }); this.onCancel(() => { future.cancel(); }); return future as Future<B>; } then(func: (value: A) => void) { this.get(func); return this; } /** * Returns the Future containing the value from the callback * * (Future\<A>, A => Future\<B>) => Future\<B> */ flatMap<B>( func: (value: A) => Future<B>, propagateCancel = false, ): Future<B> { const future = Future.make<B>((resolve) => { this.get((value) => { const returnedFuture = func(value); returnedFuture.get(resolve); returnedFuture.onCancel(() => future.cancel()); }); if (propagateCancel) { return () => { this.cancel(); }; } }); this.onCancel(() => { future.cancel(); }); return future as Future<B>; } /** * Runs the callback and returns `this` */ tap(func: (value: A) => unknown): Future<A> { this.get(func); return this as Future<A>; } /** * For Future<Result<*>>: * * Runs the callback with the value if ok and returns `this` */ tapOk<A, E>( this: Future<Result<A, E>>, func: (value: A) => unknown, ): Future<Result<A, E>> { this.get((value) => { value.match({ Ok: (value) => func(value), Error: () => {}, }); }); return this as Future<Result<A, E>>; } /** * For Future<Result<*>>: * * Runs the callback with the error if in error and returns `this` */ tapError<A, E>( this: Future<Result<A, E>>, func: (value: E) => unknown, ): Future<Result<A, E>> { this.get((value) => { value.match({ Ok: () => {}, Error: (error) => func(error), }); }); return this as Future<Result<A, E>>; } /** * For Future<Result<*>>: * * Takes a callback taking the Ok value and returning a new result and returns a future resolving to this new result */ mapResult<A, E, B, F = E>( this: Future<Result<A, E>>, func: (value: A) => Result<B, F>, propagateCancel = false, ): Future<Result<B, F | E>> { return this.map((value) => { return value.match({ Ok: (value) => func(value), Error: () => value as unknown as Result<B, E | F>, }); }, propagateCancel); } /** * For Future<Result<*>>: * * Takes a callback taking the Ok value and returning a new ok value and returns a future resolving to this new result */ mapOk<A, E, B>( this: Future<Result<A, E>>, func: (value: A) => B, propagateCancel = false, ): Future<Result<B, E>> { return this.map((value) => { return value.match({ Ok: (value) => Result.Ok(func(value)), Error: () => value as unknown as Result<B, E>, }); }, propagateCancel); } /** * For Future<Result<*>>: * * Takes a callback taking the Error value and returning a new error value and returns a future resolving to this new result */ mapError<A, E, B>( this: Future<Result<A, E>>, func: (value: E) => B, propagateCancel = false, ): Future<Result<A, B>> { return this.map((value) => { return value.match({ Ok: () => value as unknown as Result<A, B>, Error: (error) => Result.Error(func(error)), }); }, propagateCancel); } /** * For Future<Result<*>>: * * Takes a callback taking the Ok value and returning a future */ flatMapOk<A, E, B, F = E>( this: Future<Result<A, E>>, func: (value: A) => Future<Result<B, F>>, propagateCancel = false, ): Future<Result<B, F | E>> { return this.flatMap((value) => { return value.match({ Ok: (value) => func(value) as Future<Result<B, F | E>>, Error: () => Future.value(value as unknown as Result<B, F | E>), }); }, propagateCancel); } /** * For Future<Result<*>>: * * Takes a callback taking the Error value and returning a future */ flatMapError<A, E, B, F>( this: Future<Result<A, E>>, func: (value: E) => Future<Result<B, F>>, propagateCancel = false, ): Future<Result<A | B, F>> { return this.flatMap((value) => { return value.match({ Ok: () => Future.value(value as unknown as Result<A | B, F>), Error: (error) => func(error) as Future<Result<A | B, F>>, }); }, propagateCancel); } /** * Converts the future into a promise */ toPromise(): Promise<A> { return new Promise((resolve) => { this.get(resolve); }); } /** * For Future<Result<*>>: * * Converts the future into a promise (rejecting if in Error) */ resultToPromise<A, E>(this: Future<Result<A, E>>): Promise<A> { return new Promise((resolve, reject) => { this.get((value) => { value.match({ Ok: resolve, Error: reject, }); }); }); } } const proto = Object.create( null, Object.getOwnPropertyDescriptors(Future.prototype), );
the_stack
import { Broadphase, GSSolver, NaiveBroadphase, PrismaticConstraint, RevoluteConstraint, SAPBroadphase, vec2, } from 'p2-es' import { KinematicCharacterController, PlatformController } from '../Controllers' import type { CannonMessage } from '../setup' import { addContactMaterial, removeContactMaterial } from './contact-material' import { createMaterialFactory } from './material' import { addBodies, addConstraint, addKinematicCharacterController, addRay, addSpring, addTopDownVehicle, init, step, } from './operations' import { state } from './state' import type { CannonWorkerGlobalScope } from './types' declare const self: CannonWorkerGlobalScope const isPrismaticConstraint = (c: unknown): c is PrismaticConstraint => c instanceof PrismaticConstraint const isRevoluteConstraint = (c: unknown): c is RevoluteConstraint => c instanceof RevoluteConstraint function syncBodies() { state.bodiesNeedSyncing = true state.bodies = state.world.bodies.reduce((bodies, body) => ({ ...bodies, [body.uuid!]: body }), {}) } //const broadphases = { NaiveBroadphase, SAPBroadphase } const createMaterial = createMaterialFactory(state.materials) self.onmessage = ({ data }: { data: CannonMessage }) => { switch (data.op) { case 'init': { init(state, data.props) break } case 'step': { step(state, data) break } case 'addBodies': { addBodies(state, createMaterial, data) syncBodies() break } case 'removeBodies': { for (let i = 0; i < data.uuid.length; i++) state.world.removeBody(state.bodies[data.uuid[i]]) syncBodies() break } case 'subscribe': { const { id, target, type } = data.props state.subscriptions[id] = [data.uuid, type, target] break } case 'unsubscribe': { delete state.subscriptions[data.props] break } case 'setPosition': vec2.set(state.bodies[data.uuid].position, data.props[0], data.props[1]) break case 'setAngle': state.bodies[data.uuid].angle = data.props break case 'setVelocity': state.bodies[data.uuid].velocity = [data.props[0], data.props[1]] break case 'setAngularVelocity': state.bodies[data.uuid].angularVelocity = data.props break case 'setMass': state.bodies[data.uuid].mass = data.props state.bodies[data.uuid].updateMassProperties() break case 'setMaterial': // todo material is per shape not per body //state.bodies[data.uuid].material = data.props ? createMaterial(data.props) : null break case 'setLinearDamping': state.bodies[data.uuid].damping = data.props break case 'setAngularDamping': state.bodies[data.uuid].angularDamping = data.props break case 'setAllowSleep': state.bodies[data.uuid].allowSleep = data.props break case 'setSleepSpeedLimit': state.bodies[data.uuid].sleepSpeedLimit = data.props break case 'setSleepTimeLimit': state.bodies[data.uuid].sleepTimeLimit = data.props break case 'setCollisionFilterGroup': // shapes have this prop //state.bodies[data.uuid].collisionGroup = data.props break case 'setCollisionFilterMask': // shapes have this prop //state.bodies[data.uuid].collisionMask = data.props break case 'setCollisionResponse': state.bodies[data.uuid].collisionResponse = data.props break case 'setFixedRotation': state.bodies[data.uuid].fixedRotation = data.props break case 'setIsTrigger': // shapes have sensor prop //state.bodies[data.uuid].isTrigger = data.props break case 'setGravity': vec2.set(state.world.gravity, data.props[0], data.props[1]) break case 'setTolerance': if (state.world.solver instanceof GSSolver) { state.world.solver.tolerance = data.props } break case 'setIterations': if (state.world.solver instanceof GSSolver) { state.world.solver.iterations = data.props } break case 'setBroadphase': state.world.broadphase = data.props === 'SAP' ? new SAPBroadphase(Broadphase.SAP) : new NaiveBroadphase(Broadphase.NAIVE) //state.world.broadphase = new (broadphases[`${data.props}Broadphase`] || NaiveBroadphase)(state.world) break case 'setAxisIndex': if (state.world.broadphase instanceof SAPBroadphase) { state.world.broadphase.axisIndex = data.props === undefined || data.props === null ? 0 : data.props } break case 'applyForce': state.bodies[data.uuid].applyForce( vec2.fromValues(...data.props[0]), data.props[1] && vec2.fromValues(...data.props[1]), ) break case 'applyImpulse': state.bodies[data.uuid].applyImpulse( vec2.fromValues(...data.props[0]), data.props[1] && vec2.fromValues(...data.props[1]), ) break case 'applyLocalForce': state.bodies[data.uuid].applyForceLocal( vec2.fromValues(...data.props[0]), data.props[1] && vec2.fromValues(...data.props[1]), ) break case 'applyLocalImpulse': state.bodies[data.uuid].applyImpulseLocal( vec2.fromValues(...data.props[0]), data.props[1] && vec2.fromValues(...data.props[1]), ) break case 'applyTorque': //state.bodies[data.uuid].applyTorque(vec2.fromValues(...data.props[0])) break case 'addConstraint': { addConstraint(state, data) break } case 'removeConstraint': state.world.constraints .filter(({ uuid }) => uuid === data.uuid) .map((c) => state.world.removeConstraint(c)) break case 'enableConstraintMotor': state.world.constraints .filter((c) => c.uuid === data.uuid) .filter(isPrismaticConstraint || isRevoluteConstraint) .map((c) => c.enableMotor()) break case 'disableConstraintMotor': state.world.constraints .filter((c) => c.uuid === data.uuid) .filter(isPrismaticConstraint || isRevoluteConstraint) .map((c) => c.disableMotor()) break case 'setConstraintMotorSpeed': state.world.constraints .filter((c) => c.uuid === data.uuid) .filter(isRevoluteConstraint) .map((c) => c.setMotorSpeed(data.props)) break case 'addSpring': { addSpring(state, data) break } case 'setSpringStiffness': { state.springInstances[data.uuid].stiffness = data.props break } case 'setSpringRestLength': { // only LinearSpring //state.springInstances[data.uuid].restLength = data.props break } case 'setSpringDamping': { state.springInstances[data.uuid].damping = data.props break } case 'removeSpring': { // not needed in p2? //state.world.off('postStep', state.springs[data.uuid]) break } case 'addRay': { addRay(state, data) break } case 'removeRay': { state.world.off('preSolve', state.rays[data.uuid]) delete state.rays[data.uuid] break } case 'addContactMaterial': { addContactMaterial(state.world, createMaterial, data.props, data.uuid) break } case 'removeContactMaterial': { removeContactMaterial(state.world, data.uuid) break } case 'addTopDownVehicle': { addTopDownVehicle(state, data) break } case 'removeTopDownVehicle': { state.vehicles[data.uuid].vehicle.removeFromWorld() delete state.vehicles[data.uuid] break } case 'setTopDownVehicleSteeringValue': { const [value, wheelIndex] = data.props state.vehicles[data.uuid].vehicle.wheels[wheelIndex].steerValue = value break } case 'applyTopDownVehicleEngineForce': { const [value, wheelIndex] = data.props state.vehicles[data.uuid].vehicle.wheels[wheelIndex].engineForce = value break } case 'setTopDownVehicleBrake': { const [brake, wheelIndex] = data.props state.vehicles[data.uuid].vehicle.wheels[wheelIndex].setBrakeForce(brake) break } case 'addKinematicCharacterController': { addKinematicCharacterController(state, data) break } case 'removeKinematicCharacterController': { delete state.controllers[data.uuid] break } case 'setKinematicCharacterControllerInput': { if (state.controllers[data.uuid].controller instanceof KinematicCharacterController) { const controller = <KinematicCharacterController>state.controllers[data.uuid].controller controller.input = data.props } break } case 'setKinematicCharacterControllerJump': { if (state.controllers[data.uuid].controller instanceof KinematicCharacterController) { const controller = <KinematicCharacterController>state.controllers[data.uuid].controller controller.setJumpKeyState(data.props) } break } case 'addPlatformController': { const [body, passengerMask, localWaypoints, speed, skinWidth, dstBetweenRays] = data.props const controller = new PlatformController({ body: state.bodies[body], //controllers: Object.fromEntries(Object.entries(state.controllers).filter(([, val]) => val.controller instanceof KinematicCharacterController)) as { [uuid: string]: { controller: KinematicCharacterController } }, controllers: state.controllers as { [uuid: string]: { controller: KinematicCharacterController } }, dstBetweenRays, localWaypoints, passengerMask, skinWidth, speed, world: state.world, }) state.controllers[data.uuid] = { controller } break } case 'removePlatformController': { delete state.controllers[data.uuid] break } case 'wakeUp': { state.bodies[data.uuid].wakeUp() break } case 'sleep': { state.bodies[data.uuid].sleep() break } } }
the_stack
/** * @brief Test two arrays of C-style strings for deep equality. The results * are reported via the testing framework (Check). * @param a First array of strings * @param size_a Size of first array * @param b Second array of strings * @param size_b Size of second array */ static void deep_eq_str_ary(char **a, int size_a, char **b, int size_b) { int i; ck_assert_int_eq(size_a, size_b); for (i = 0; i < size_a; i++) ck_assert_str_eq(a[i], b[i]); return; } /** * @brief Create dot-bracket structures from moves * @param moves list of vrna_move_t * @param length the number of moves. * @param pt_structure the RNA structure on which the moves can be applied. * @param seqLen the length of the RNA sequence. * @return Pointer to an array of structure dot-bracket strings */ static char ** createStructuresFromMoves(vrna_move_t *moves, size_t length, const short *pt_structure, int seqLen) { char *cur = NULL; char **structs = (char **)malloc(3 * seqLen * seqLen * sizeof(char *)); int size = 0; //while( cur = pop()) for (vrna_move_t *m = moves; m->pos_5 != 0; m++) { short *pt_tmp = vrna_ptable_copy(pt_structure); vrna_move_apply(pt_tmp, m); cur = vrna_db_from_ptable(pt_tmp); structs[size++] = cur; free(pt_tmp); } return structs; } /************************************************************ * QuickSort stolen from * http://www.comp.dit.ie/rlawlor/Alg_DS/sorting/quickSort.c * Adapted to sort string arrays, core dumps fixed. ************************************************************/ static int partition(char *a[], int l, int r) { int i, j; char *pivot, *t; pivot = a[l]; i = l; j = r + 1; while (1) { /* FK: first compare i and r to prevent core dumps */ do ++i; while (i <= r && strcmp(a[i], pivot) <= 0); do --j; while (strcmp(a[j], pivot) > 0); if (i >= j) break; t = a[i]; a[i] = a[j]; a[j] = t; } t = a[l]; a[l] = a[j]; a[j] = t; return j; } static void quickSort(char *a[], int l, int r) { int j; if (l < r) { // divide and conquer j = partition(a, l, r); quickSort(a, l, j - 1); quickSort(a, j + 1, r); } } /** * @brief QuickSort an array of zero-terminated strings * @param ary Array of strings (i.e. array of char*) * @param size Number of strings in array */ static void sort_str(char *ary[], int size) { quickSort(ary, 0, size - 1); } /** * @brief Test the function RNA2_move_it by comparing the generated neighbor * to a passed list of structures. The passed structures are sorted, so their * order is irrelevant. Results will be reported by the test framework (Check) * @param vc vrna_fold_compound_t * @param str Structure of which to generate neighbors * @param nb_size Number of passed neighbor structures (cf. '...') * @param ... several structure dot-bracket strings to which the generated * neighbors should be compared to. This list will be sorted, so the order * in which structures are passed is irrelevant. */ static void test_RNA2_move_it(vrna_fold_compound_t *vc, char *str, unsigned int options, int nb_size, ...) { int i; va_list valist; /* Variable args list */ va_start(valist, nb_size); int seqLen = vc->length; char **gen_nb = NULL; /* To store generated neighbors */ int gen_nb_size; /* Number of generated structures */ char **nb = (char **)vrna_alloc(3 * seqLen * seqLen * sizeof(char *)); for (i = 0; i < nb_size; i++) nb[i] = va_arg(valist, char *); sort_str(nb, nb_size); short *pt_structure = vrna_ptable(str); vrna_move_t *neighbors = vrna_neighbors(vc, pt_structure, options); int length = 0; for (vrna_move_t *m = neighbors; m->pos_5 != 0; m++) length++; gen_nb = createStructuresFromMoves(neighbors, length, pt_structure, seqLen); /* Collect neighbors from stapel */ gen_nb_size = length; sort_str(gen_nb, gen_nb_size); /* Sort generated neighbors */ /*fprintf( stderr, "\"%s\" (input)\n", str); */ /* for(i = 0; i<gen_nb_size; i++) /* Output generated neighbors */ /* fprintf( stderr, "\"%s\",\n", gen_nb[i]); */ deep_eq_str_ary(gen_nb, gen_nb_size, nb, nb_size); for (int i = 0; i < length; i++) free(gen_nb[i]); free(gen_nb); free(nb); va_end(valist); free(pt_structure); vrna_move_list_free(neighbors); } #suite Neighbor #test test_vrna_neighbors { char *sequence = "GGGAAACCCAACCUUU"; char *structure = ".(.....)........"; int expectedLength = 8; vrna_move_t expectedNeighbors[8] = { { 1, 9 }, { 3, 7 }, { -2, -8 }, { 10, 16 }, { 10, 15 }, { 10, 14 }, { 11, 16 }, { 11, 15 } }; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_EVAL_ONLY); short *pt = vrna_ptable(structure); vrna_move_t *neighbors = vrna_neighbors(vc, pt, VRNA_MOVESET_DEFAULT); //check if all neighbors are in the set. int neighborsFound = 0; for (int i = 0; i < expectedLength; i++) { for (vrna_move_t *m = neighbors; m->pos_5 != 0; m++) { if (expectedNeighbors[i].pos_5 == m->pos_5 && expectedNeighbors[i].pos_3 == m->pos_3) { neighborsFound++; break; } } } ck_assert_int_eq(neighborsFound, expectedLength); vrna_fold_compound_free(vc); free(pt); free(neighbors); } #test test_vrna_neighbors_with_shifts { char *sequence = "GAAACCAACCU"; char *structure = "(....)....."; // "(....)(...)" after vrna_move_t // "123456789.. int expectedLength = 6; vrna_move_t expectedNeighbors[6] = { { -1, -6 }, { 7, 11 }, { 1, -5 }, { 1, -9 },{ 1, -10 }, { 1, -11 } /* shifts */ }; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_EVAL_ONLY); short *pt = vrna_ptable(structure); vrna_move_t *neighbors = vrna_neighbors(vc, pt, VRNA_MOVESET_DEFAULT | VRNA_MOVESET_SHIFT); //check if all neighbors are in the set. int neighborsFound = 0; for (int i = 0; i < expectedLength; i++) { for (vrna_move_t *m = neighbors; m->pos_5 != 0; m++) { if (expectedNeighbors[i].pos_5 == m->pos_5 && expectedNeighbors[i].pos_3 == m->pos_3) { neighborsFound++; break; } } } ck_assert_int_eq(neighborsFound, expectedLength); vrna_fold_compound_free(vc); free(pt); free(neighbors); } #test test_vrna_perform_move { char *sequence = "GGGAAACCCAACCUUU"; char *structure = "................"; short *pt = vrna_ptable(structure); vrna_move_t m = { 2, 8 }; vrna_move_apply(pt, &m); char *resultInsertion = vrna_db_from_ptable(pt); char *expectedResult = ".(.....)........"; //check if the vrna_move_t was inserted. ck_assert_str_eq(resultInsertion, expectedResult); //check if deletion is possible vrna_move_t m2 = { -2, -8 }; vrna_move_apply(pt, &m2); char *resultDeletion = vrna_db_from_ptable(pt); ck_assert_str_eq(resultDeletion, structure); free(resultInsertion); free(resultDeletion); free(pt); } #test test_update_loop_indices_deletion { char *sequence = "GGGAAACCCAACCUUU"; char *structure = ".(.....)........"; //test deletion vrna_move_t m = { -2, -8 }; int expectedLoopIndices[17] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; short *pt = vrna_ptable(structure); int *loopIndices = vrna_loopidx_from_ptable(pt); vrna_loopidx_update(loopIndices, pt, strlen(structure), &m); int notEqual = 0; for (int i = 0; i < pt[0]; i++) if (loopIndices[i] != expectedLoopIndices[i]) notEqual = 1; ck_assert_int_eq(notEqual, 0); free(loopIndices); free(pt); } #test test_update_loop_indices_insertion { //test insertion // "GGGAAACCCAACCUUU"; char *structure = "................"; int expectedLoopIndices1[17] = { 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }; short *pt = vrna_ptable(structure); int *loopIndices = vrna_loopidx_from_ptable(pt); vrna_move_t m1 = { 2, 8 }; vrna_loopidx_update(loopIndices, pt, strlen(structure), &m1); int notEqual = 0; for (int i = 0; i < pt[0]; i++) if (loopIndices[i] != expectedLoopIndices1[i]) notEqual = 1; ck_assert_int_eq(notEqual, 0); free(loopIndices); free(pt); } #test test_update_loop_indices_insertion_after_insertion { //test insertion after insertion // "GGGAAACCCAACCUUU"; char *structure = ".(.....)........"; // ".(.....)..(...)." after vrna_move_t int expectedLoopIndices2[17] = { 2, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 0 }; short *pt = vrna_ptable(structure); int *loopIndices = vrna_loopidx_from_ptable(pt); vrna_move_t m2 = { 11, 15 }; vrna_loopidx_update(loopIndices, pt, strlen(structure), &m2); int notEqual = 0; for (int i = 0; i < pt[0]; i++) if (loopIndices[i] != expectedLoopIndices2[i]) notEqual = 1; ck_assert_int_eq(notEqual, 0); free(loopIndices); free(pt); } #test test_update_loop_indices_insertion_within_insertion { //test insertion within insertion // "GGGAAACCCAACCUUU"; char *structure = ".(.....)........"; // ".((...))........" after vrna_move_t int expectedLoopIndices3[17] = { 2, 0, 1, 2, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0 }; short *pt = vrna_ptable(structure); int *loopIndices = vrna_loopidx_from_ptable(pt); vrna_move_t m3 = { 3, 7 }; vrna_loopidx_update(loopIndices, pt, strlen(structure), &m3); int notEqual = 0; for (int i = 0; i < pt[0]; i++) if (loopIndices[i] != expectedLoopIndices3[i]) notEqual = 1; ck_assert_int_eq(notEqual, 0); free(loopIndices); free(pt); } //TODO: test all combinations of insertions and deletions #test test_vrna_neighbors_successive { char *sequence = "GGGAAACCCAACCUUU"; char *structure = ".(.....)........"; // ".(.....).(.....)" after vrna_move_t vrna_move_t currentMove = { 10, 16 }; // for the second neighbor generation. int expectedLength = 5; vrna_move_t expectedNeighbors[5] = { { 1, 9 }, { 3, 7 }, { -2, -8 }, { -10, -16 }, { 11, 15 } }; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_EVAL_ONLY); short *previousStructure = vrna_ptable(structure); vrna_move_t *previousMoves = vrna_neighbors(vc, previousStructure, VRNA_MOVESET_DEFAULT); int length = 0; for (vrna_move_t *m = previousMoves; m->pos_5 != 0; m++) length++; int newLength; vrna_move_t *neighbors = vrna_neighbors_successive(vc, &currentMove, previousStructure, previousMoves, length, &newLength, VRNA_MOVESET_DEFAULT); //check if all neighbors are in the set. int neighborsFound = 0; for (int i = 0; i < expectedLength; i++) { for (vrna_move_t *m = neighbors; m->pos_5 != 0; m++) { if (expectedNeighbors[i].pos_5 == m->pos_5 && expectedNeighbors[i].pos_3 == m->pos_3) { neighborsFound++; break; } } } ck_assert_int_eq(neighborsFound, expectedLength); vrna_fold_compound_free(vc); free(previousStructure); free(previousMoves); free(neighbors); } #test test_vrna_neighbors_successive_deletions_only { char *sequence = "GGGAAACCCAACCUUU"; char *structure = ".(.....)........"; // ".(.....).(.....)" after vrna_move_t vrna_move_t currentMove = { 10, 16 }; // for the second neighbor generation. int expectedLength = 2; vrna_move_t expectedNeighbors[2] = { { -2, -8 }, { -10, -16 } }; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_EVAL_ONLY); short *previousStructure = vrna_ptable(structure); vrna_move_t *previousMoves = vrna_neighbors(vc, previousStructure, VRNA_MOVESET_DELETION); int length = 0; for (vrna_move_t *m = previousMoves; m->pos_5 != 0; m++) length++; int newLength; vrna_move_t *neighbors = vrna_neighbors_successive(vc, &currentMove, previousStructure, previousMoves, length, &newLength, VRNA_MOVESET_DELETION); //check if all neighbors are in the set. int neighborsFound = 0; for (int i = 0; i < expectedLength; i++) { for (vrna_move_t *m = neighbors; m->pos_5 != 0; m++) { if (expectedNeighbors[i].pos_5 == m->pos_5 && expectedNeighbors[i].pos_3 == m->pos_3) { neighborsFound++; break; } } } ck_assert_int_eq(neighborsFound, expectedLength); vrna_fold_compound_free(vc); free(previousStructure); free(previousMoves); free(neighbors); } #test test_vrna_neighbors_successive_insertions_only { char *sequence = "GGGAAACCCAACCUUU"; char *structure = ".(.....)........"; // ".(.....).(.....)" after vrna_move_t vrna_move_t currentMove = { 10, 16 }; // for the second neighbor generation. int expectedLength = 3; vrna_move_t expectedNeighbors[3] = { { 1, 9 }, { 3, 7 }, { 11, 15 } }; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_EVAL_ONLY); short *previousStructure = vrna_ptable(structure); vrna_move_t *previousMoves = vrna_neighbors(vc, previousStructure, VRNA_MOVESET_DEFAULT); int length = 0; for (vrna_move_t *m = previousMoves; m->pos_5 != 0; m++) length++; int newLength; vrna_move_t *neighbors = vrna_neighbors_successive(vc, &currentMove, previousStructure, previousMoves, length, &newLength, VRNA_MOVESET_DEFAULT); //check if all neighbors are in the set. int neighborsFound = 0; for (int i = 0; i < expectedLength; i++) { for (vrna_move_t *m = neighbors; m->pos_5 != 0; m++) { if (expectedNeighbors[i].pos_5 == m->pos_5 && expectedNeighbors[i].pos_3 == m->pos_3) { neighborsFound++; break; } } } ck_assert_int_eq(neighborsFound, expectedLength); vrna_fold_compound_free(vc); free(previousStructure); free(previousMoves); free(neighbors); } //TODO: test more shift combinations #test test_vrna_neighbors_successive_with_shifts { char *sequence = "GAAACCAACCU"; char *structure = "(....)....."; // "(....)(...)" after vrna_move_t // "123456789.. vrna_move_t currentMove = { 7, 11 }; // for the second neighbor generation. int expectedLength = 3; vrna_move_t expectedNeighbors[3] = { { -1, -6 }, { -7, -11 }, { 1, -5 } }; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_EVAL_ONLY); short *previousStructure = vrna_ptable(structure); vrna_move_t *previousMoves = vrna_neighbors(vc, previousStructure, VRNA_MOVESET_DEFAULT | VRNA_MOVESET_SHIFT); int length = 0; for (vrna_move_t *m = previousMoves; m->pos_5 != 0; m++) length++; int newLength; vrna_move_t *neighbors = vrna_neighbors_successive(vc, &currentMove, previousStructure, previousMoves, length, &newLength, VRNA_MOVESET_DEFAULT | VRNA_MOVESET_SHIFT); //check if all neighbors are in the set. int neighborsFound = 0; for (int i = 0; i < expectedLength; i++) { for (vrna_move_t *m = neighbors; m->pos_5 != 0; m++) { if (expectedNeighbors[i].pos_5 == m->pos_5 && expectedNeighbors[i].pos_3 == m->pos_3) { neighborsFound++; break; } } } ck_assert_int_eq(neighborsFound, expectedLength); vrna_fold_compound_free(vc); free(previousStructure); free(previousMoves); free(neighbors); } /* Test generation of neighbor structures, without shift moves, with lonely pairs */ #test test_rnamoves_noshift_lp { //int noLP = 0; //int shift = 0; unsigned int options = VRNA_MOVESET_DEFAULT; char *seq = "GGGGUUUCCCC"; char *str = "((((...))))"; int nb_size = 4; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(seq, &md, VRNA_OPTION_EVAL_ONLY); test_RNA2_move_it(vc, str, options, nb_size, "(((.....)))", "((.(...).))", "(.((...)).)", ".(((...)))." ); vrna_fold_compound_free(vc); seq = "GGUUUCC"; str = "......."; nb_size = 5; /* Number of passed neighbors */ vc = vrna_fold_compound(seq, &md, VRNA_OPTION_EVAL_ONLY); test_RNA2_move_it(vc, str, options, nb_size, ".(....)", ".(...).", "(.....)", "(....).", "(...).." ); vrna_fold_compound_free(vc); } /* Test generation of neighbor structures, with shift moves, with lonely pairs */ #test test_rnamoves_shift_lp { //int shift = 1; //int noLP = 0; unsigned int options = VRNA_MOVESET_DEFAULT | VRNA_MOVESET_SHIFT; char *seq = "GGGGGGGGGGGGAAAUUUUUUUGUUUU"; char *str = ".(((....(((.....)))....)))."; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(seq, &md, VRNA_OPTION_EVAL_ONLY); int nb_size = 40; test_RNA2_move_it(vc, str, options, nb_size, ".(((...((((.....))))...))).", ".(((.(..(((.....)))..).))).", "((((....(((.....)))....))))", ".(((....((((...))))....))).", "..((....(((.....)))....))..", ".(((.....((.....)).....))).", ".(((....((.......))....))).", ".(((..(.(((.....))).)..))).", ".((.....(((.....))).....)).", ".(.(....(((.....)))....).).", ".(((....(.(.....).)....))).", ".(((....(((....).))....))).", ".(((.(..(((.....))).)..))).", ".(((..(.(((.....)))..).))).", ".(((....((.(....)))....))).", ".(((..(.(((.....))))...))).", ".(((...((((.....))).)..))).", ".(((....(((.....)))....)).)", ".((.(...(((.....)))....))).", ".(((...(.((.....)))....))).", ".(((....(((.....)).)...))).", "(.((....(((.....)))....))).", ".((((...(((.....)))..).))).", ".((((...(((.....))).)..))).", ".(((.(..(((.....))))...))).", ".(((...((((.....)))..).))).", ".(((....((..(...)))....))).", ".((..(..(((.....)))....))).", ".(((..(..((.....)))....))).", ".(((....(((.....))..)..))).", ".((((...(((.....))))...))).", ".(((....(((.....)))..)..)).", ".((....((((.....)))....))).", ".(((....(((.....))))....)).", ".((((....((.....)))....))).", ".((...(.(((.....)))....))).", ".(((....(((.....))).)...)).", ".(((.(...((.....)))....))).", ".(((....(((.....))...).))).", ".(((.....((.....))(...))))." ); vrna_fold_compound_free(vc); } /* Test generation of neighbor structures, without shift moves, without lonely pairs */ #test test_rnamoves_noshift_nolp { //int shift = 0; //int noLP = 1; unsigned int options = VRNA_MOVESET_DEFAULT | VRNA_MOVESET_NO_LP; char *seq = "GGGGUUUCCCC"; char *str = "((((...))))"; vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(seq, &md, VRNA_OPTION_EVAL_ONLY); int nb_size = 2; test_RNA2_move_it(vc, str, options, nb_size, "(((.....)))", ".(((...)))." ); str = "..........."; nb_size = 12; test_RNA2_move_it(vc, str, options, nb_size, "((......)).", ".((....))..", ".((.....)).", "((.....))..", "..((....)).", ".((......))", "..((...))..", "((.......))", "..((.....))", "((....))...", ".((...))...", "((...))...." ); vrna_fold_compound_free(vc); } /* Test generation of neighbor structures, with shift moves, without lonely pairs */ #test test_rnamoves_shift_nolp { //int shift = 1; //int noLP = 1; unsigned int options = VRNA_MOVESET_DEFAULT | VRNA_MOVESET_SHIFT | VRNA_MOVESET_NO_LP; char *seq = "GGGGGGGGUUUUUUU"; char *str = "((..(((...)))))"; // 01234567890123456789012 // 0 1 2 vrna_md_t md; vrna_md_set_default(&md); vrna_fold_compound_t *vc = vrna_fold_compound(seq, &md, VRNA_OPTION_EVAL_ONLY); int nb_size = 4; test_RNA2_move_it(vc, str, options, nb_size, "....(((...)))..", "((..((.....))))", "(((..((...)))))", "((...((...)).))" ); vrna_fold_compound_free(vc); seq = "AAGUGAUACCAGCAUCGUCUUGAUGCCCUUGGCAGCACUUCAU"; str = "(((((((......)))).)))((((((...)))).....)).."; nb_size = 9; vc = vrna_fold_compound(seq, &md, VRNA_OPTION_EVAL_ONLY); test_RNA2_move_it(vc, str, options, nb_size, "(((((((......))))).))((((((...)))).....))..", "(((((((......)))).)))(((((.....))).....))..", "(((((((......)))).)))((.(((...)))......))..", "(((((((......)))).)))..((((...)))).........", "((((((........))).)))((((((...)))).....))..", "(((.(((......)))..)))((((((...)))).....))..", "((.((((......))))..))((((((...)))).....))..", ".((((((......)))).))(((((((...)))).....))).", ".((((((......)))).)).((((((...)))).....)).." ); vrna_fold_compound_free(vc); }
the_stack
declare module 'vscode' { /** * Represents an item that can be selected from * a list of items. */ export interface QuickPickItem { /** * A human readable string which is rendered prominent. */ label: string; /** * A human readable string which is rendered less prominent. */ description?: string; /** * A human readable string which is rendered less prominent. */ detail?: string; /** * Optional flag indicating if this item is picked initially. * (Only honored when the picker allows multiple selections.) * * @see [QuickPickOptions.canPickMany](#QuickPickOptions.canPickMany) * not implemented yet */ picked?: boolean; /** * Always show this item. * not implemented yet */ alwaysShow?: boolean; /** * Optional buttons that will be rendered on this particular item. These buttons will trigger * an {@link QuickPickItemButtonEvent} when clicked. Buttons are only rendered when using a quickpick * created by the {@link window.createQuickPick()} API. Buttons are not rendered when using * the {@link window.showQuickPick()} API. */ buttons?: QuickInputButton[]; } /** * A concrete [QuickInput](#QuickInput) to let the user pick an item from a * list of items of type T. The items can be filtered through a filter text field and * there is an option [canSelectMany](#QuickPick.canSelectMany) to allow for * selecting multiple items. * * Note that in many cases the more convenient [window.showQuickPick](#window.showQuickPick) * is easier to use. [window.createQuickPick](#window.createQuickPick) should be used * when [window.showQuickPick](#window.showQuickPick) does not offer the required flexibility. */ export interface QuickPick<T extends QuickPickItem> extends QuickInput { /** * Current value of the filter text. */ value: string; /** * Optional placeholder in the filter text. */ placeholder: string | undefined; /** * An event signaling when the value of the filter text has changed. */ readonly onDidChangeValue: Event<string>; /** * An event signaling when the user indicated acceptance of the selected item(s). */ readonly onDidAccept: Event<void>; /** * Buttons for actions in the UI. * not implemented yet */ buttons: ReadonlyArray<QuickInputButton>; /** * An event signaling when a button was triggered. */ readonly onDidTriggerButton: Event<QuickInputButton>; /** * An event signaling when a button in a particular {@link QuickPickItem} was triggered. * This event does not fire for buttons in the title bar. */ readonly onDidTriggerItemButton: Event<QuickPickItemButtonEvent<T>>; /** * Items to pick from. */ items: ReadonlyArray<T>; /** * If multiple items can be selected at the same time. Defaults to false. * not implemented yet */ canSelectMany: boolean; /** * If the filter text should also be matched against the description of the items. Defaults to false. */ matchOnDescription: boolean; /** * If the filter text should also be matched against the detail of the items. Defaults to false. */ matchOnDetail: boolean; /* * An optional flag to maintain the scroll position of the quick pick when the quick pick items are updated. Defaults to false. */ keepScrollPosition?: boolean; /** * Active items. This can be read and updated by the extension. * not implemented yet */ activeItems: ReadonlyArray<T>; /** * An event signaling when the active items have changed. */ readonly onDidChangeActive: Event<T[]>; /** * Selected items. This can be read and updated by the extension. * not implemented yet */ selectedItems: ReadonlyArray<T>; /** * An event signaling when the selected items have changed. */ readonly onDidChangeSelection: Event<T[]>; } /** * Options to configure the behavior of the quick pick UI. */ export interface QuickPickOptions { /** * An optional string that represents the title of the quick pick. */ title?: string; /** * An optional flag to include the description when filtering the picks. */ matchOnDescription?: boolean; /** * An optional flag to include the detail when filtering the picks. */ matchOnDetail?: boolean; /* * An optional flag to maintain the scroll position of the quick pick when the quick pick items are updated. Defaults to false. */ keepScrollPosition?: boolean; /** * An optional string to show as place holder in the input box to guide the user what to pick on. */ placeHolder?: string; /** * Set to `true` to keep the picker open when focus moves to another part of the editor or to another window. */ ignoreFocusOut?: boolean; /** * An optional flag to make the picker accept multiple selections, if true the result is an array of picks. * not implemented yet */ canPickMany?: boolean; /** * An optional function that is invoked whenever an item is selected. */ onDidSelectItem?(item: QuickPickItem | string): any; } /** * A light-weight user input UI that is initially not visible. After * configuring it through its properties the extension can make it * visible by calling [QuickInput.show](#QuickInput.show). * * There are several reasons why this UI might have to be hidden and * the extension will be notified through [QuickInput.onDidHide](#QuickInput.onDidHide). * (Examples include: an explicit call to [QuickInput.hide](#QuickInput.hide), * the user pressing Esc, some other input UI opening, etc.) * * A user pressing Enter or some other gesture implying acceptance * of the current state does not automatically hide this UI component. * It is up to the extension to decide whether to accept the user's input * and if the UI should indeed be hidden through a call to [QuickInput.hide](#QuickInput.hide). * * When the extension no longer needs this input UI, it should * [QuickInput.dispose](#QuickInput.dispose) it to allow for freeing up * any resources associated with it. * * See [QuickPick](#QuickPick) and [InputBox](#InputBox) for concrete UIs. */ export interface QuickInput { /** * An optional title. */ title: string | undefined; /** * An optional current step count. */ step: number | undefined; /** * An optional total step count. */ totalSteps: number | undefined; /** * If the UI should allow for user input. Defaults to true. * * Change this to false, e.g., while validating user input or * loading data for the next step in user input. */ enabled: boolean; /** * If the UI should show a progress indicator. Defaults to false. * * Change this to true, e.g., while loading more data or validating * user input. */ busy: boolean; /** * If the UI should stay open even when loosing UI focus. Defaults to false. */ ignoreFocusOut: boolean; /** * Makes the input UI visible in its current configuration. Any other input * UI will first fire an [QuickInput.onDidHide](#QuickInput.onDidHide) event. */ show(): void; /** * Hides this input UI. This will also fire an [QuickInput.onDidHide](#QuickInput.onDidHide) * event. */ hide(): void; /** * An event signaling when this input UI is hidden. * * There are several reasons why this UI might have to be hidden and * the extension will be notified through [QuickInput.onDidHide](#QuickInput.onDidHide). * (Examples include: an explicit call to [QuickInput.hide](#QuickInput.hide), * the user pressing Esc, some other input UI opening, etc.) */ onDidHide: Event<void>; /** * Dispose of this input UI and any associated resources. If it is still * visible, it is first hidden. After this call the input UI is no longer * functional and no additional methods or properties on it should be * accessed. Instead a new input UI should be created. */ dispose(): void; } /** * Options to configure the behavior of the input box UI. */ export interface InputBoxOptions { /** * An optional string that represents the title of the input box. */ title?: string; /** * The value to prefill in the input box. */ value?: string; /** * Selection of the prefilled [`value`](#InputBoxOptions.value). Defined as tuple of two number where the * first is the inclusive start index and the second the exclusive end index. When `undefined` the whole * word will be selected, when empty (start equals end) only the cursor will be set, * otherwise the defined range will be selected. */ valueSelection?: [number, number]; /** * The text to display underneath the input box. */ prompt?: string; /** * An optional string to show as place holder in the input box to guide the user what to type. */ placeHolder?: string; /** * Set to `true` to show a password prompt that will not show the typed value. */ password?: boolean; /** * Set to `true` to keep the input box open when focus moves to another part of the editor or to another window. */ ignoreFocusOut?: boolean; /** * An optional function that will be called to validate input and to give a hint * to the user. * * @param value The current value of the input box. * @return A human readable string which is presented as diagnostic message. * Return `undefined`, `null`, or the empty string when 'value' is valid. */ validateInput?(value: string): string | undefined | null | Thenable<string | undefined | null>; } /** * A concrete [QuickInput](#QuickInput) to let the user input a text value. * * Note that in many cases the more convenient [window.showInputBox](#window.showInputBox) * is easier to use. [window.createInputBox](#window.createInputBox) should be used * when [window.showInputBox](#window.showInputBox) does not offer the required flexibility. */ export interface InputBox extends QuickInput { /** * Current input value. */ value: string; /** * Optional placeholder in the filter text. */ placeholder: string | undefined; /** * If the input value should be hidden. Defaults to false. */ password: boolean; /** * An event signaling when the value has changed. */ readonly onDidChangeValue: Event<string>; /** * An event signaling when the user indicated acceptance of the input value. */ readonly onDidAccept: Event<void>; /** * Buttons for actions in the UI. */ buttons: ReadonlyArray<QuickInputButton>; /** * An event signaling when a button was triggered. */ readonly onDidTriggerButton: Event<QuickInputButton>; /** * An optional prompt text providing some ask or explanation to the user. */ prompt: string | undefined; /** * An optional validation message indicating a problem with the current input value. */ validationMessage: string | undefined; } export namespace window { /** * Creates a [QuickPick](#QuickPick) to let the user pick an item from a list * of items of type T. * * Note that in many cases the more convenient [window.showQuickPick](#window.showQuickPick) * is easier to use. [window.createQuickPick](#window.createQuickPick) should be used * when [window.showQuickPick](#window.showQuickPick) does not offer the required flexibility. * * @return A new [QuickPick](#QuickPick). */ export function createQuickPick<T extends QuickPickItem>(): QuickPick<T>; /** * Shows a selection list allowing multiple selections. * * @param items An array of strings, or a promise that resolves to an array of strings. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. * @return A promise that resolves to the selected items or `undefined`. */ export function showQuickPick(items: string[] | Thenable<string[]>, options: QuickPickOptions & { canPickMany: true; }, token?: CancellationToken): Thenable<string[] | undefined>; /** * Shows a selection list. * * @param items An array of strings, or a promise that resolves to an array of strings. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. * @return A promise that resolves to the selection or `undefined`. */ export function showQuickPick(items: string[] | Thenable<string[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<string | undefined>; /** * Shows a selection list allowing multiple selections. * * @param items An array of items, or a promise that resolves to an array of items. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. * @return A promise that resolves to the selected items or `undefined`. */ export function showQuickPick<T extends QuickPickItem>(items: T[] | Thenable<T[]>, options: QuickPickOptions & { canPickMany: true; }, token?: CancellationToken): Thenable<T[] | undefined>; /** * Shows a selection list. * * @param items An array of items, or a promise that resolves to an array of items. * @param options Configures the behavior of the selection list. * @param token A token that can be used to signal cancellation. * @return A promise that resolves to the selected item or `undefined`. */ export function showQuickPick<T extends QuickPickItem>(items: T[] | Thenable<T[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<T | undefined>; /** * Opens an input box to ask the user for input. * * The returned value will be `undefined` if the input box was canceled (e.g. pressing ESC). Otherwise the * returned value will be the string typed by the user or an empty string if the user did not type * anything but dismissed the input box with OK. * * @param options Configures the behavior of the input box. * @param token A token that can be used to signal cancellation. * @return A promise that resolves to a string the user provided or to `undefined` in case of dismissal. */ export function showInputBox(options?: InputBoxOptions, token?: CancellationToken): Thenable<string | undefined>; /** * Creates a [InputBox](#InputBox) to let the user enter some text input. * * Note that in many cases the more convenient [window.showInputBox](#window.showInputBox) * is easier to use. [window.createInputBox](#window.createInputBox) should be used * when [window.showInputBox](#window.showInputBox) does not offer the required flexibility. * * @return A new [InputBox](#InputBox). */ export function createInputBox(): InputBox; } /** * Button for an action in a [QuickPick](#QuickPick) or [InputBox](#InputBox). */ export interface QuickInputButton { /** * Icon for the button. */ readonly iconPath: Uri | { light: Uri; dark: Uri } | ThemeIcon; /** * An optional tooltip. */ readonly tooltip?: string | undefined; } /** * Predefined buttons for [QuickPick](#QuickPick) and [InputBox](#InputBox). */ export class QuickInputButtons { /** * A back button for [QuickPick](#QuickPick) and [InputBox](#InputBox). * * When a navigation 'back' button is needed this one should be used for consistency. * It comes with a predefined icon, tooltip and location. */ static readonly Back: QuickInputButton; /** * @hidden */ private constructor(); } /** * An event signaling when a button in a particular {@link QuickPickItem} was triggered. * This event does not fire for buttons in the title bar. */ export interface QuickPickItemButtonEvent<T extends QuickPickItem> { /** * The button that was clicked. */ readonly button: QuickInputButton; /** * The item that the button belongs to. */ readonly item: T; } }
the_stack
import CodeMirror from 'codemirror'; import 'codemirror/mode/clike/clike.js'; import 'codemirror-addon-infotip'; import 'codemirror-addon-lint-fix'; import type { Message, ChangeData, DiagnosticData, SlowUpdateMessage, DiagnosticSeverity, ServerOptions, SpanData, Language } from '../interfaces/protocol'; import type { Connection } from './connection'; import type { SelfDebug } from './self-debug'; import { renderInfotip } from './render-infotip'; import { Hinter } from './hinter'; import { SignatureTip } from './signature-tip'; import { addEvents } from '../helpers/add-events'; const indexKey = '$mirrorsharp-index'; interface PositionWithIndex extends CodeMirror.Position { [indexKey]: number; } interface DiagnosticAnnotation extends CodeMirror.Annotation { readonly diagnostic: DiagnosticData; } interface AnnotationFixWithId extends CodeMirror.AnnotationFix { readonly id: number; } interface EditorOptions<TExtensionServerOptions, TSlowUpdateExtensionData> { language?: Language; on?: { slowUpdateWait?: () => void; slowUpdateResult?: (args: { diagnostics: ReadonlyArray<DiagnosticData>; x: TSlowUpdateExtensionData }) => void; textChange?: (getText: () => string) => void; connectionChange?: { (event: 'open', e: Event): void; (event: 'error', e: ErrorEvent): void; (event: 'close', e: CloseEvent): void; }; serverError?: (message: string) => void; }; forCodeMirror?: CodeMirror.EditorConfiguration; initialServerOptions?: TExtensionServerOptions; } const languageModes = { 'C#': 'text/x-csharp', 'Visual Basic': 'text/x-vb', 'F#': 'text/x-fsharp', 'IL': 'text/x-cil', 'PHP': 'application/x-httpd-php' } as const; const defaultLanguage = 'C#'; const lineSeparator = '\r\n'; export class Editor<TExtensionServerOptions, TSlowUpdateExtensionData> { readonly #connection: Connection<TExtensionServerOptions, TSlowUpdateExtensionData>; readonly #selfDebug: SelfDebug|null; readonly #options: EditorOptions<TExtensionServerOptions, TSlowUpdateExtensionData>; readonly #cm: CodeMirror.EditorFromTextArea; readonly #hinter: Hinter<TExtensionServerOptions, TSlowUpdateExtensionData>; readonly #signatureTip: InstanceType<typeof SignatureTip>; readonly #keyMap: CodeMirror.KeyMap; readonly #removeCodeMirrorEvents: () => void; readonly #removeConnectionEvents: () => void; #language: Language; #serverOptions: ServerOptions & TExtensionServerOptions; #pendingServerOptions: (ServerOptions & TExtensionServerOptions) | null | undefined; #lintingSuspended = true; #hadChangesSinceLastLinting = false; #capturedUpdateLinting: CodeMirror.UpdateLintingCallback | null | undefined; #changePending = false; #changeReason: string|null = null; #changesAreFromServer = false; constructor( textarea: HTMLTextAreaElement, connection: Connection<TExtensionServerOptions, TSlowUpdateExtensionData>, selfDebug: SelfDebug|null, options: EditorOptions<TExtensionServerOptions, TSlowUpdateExtensionData> ) { this.#connection = connection; this.#selfDebug = selfDebug; options = { language: defaultLanguage, ...options }; options.on = { slowUpdateWait: () => ({}), slowUpdateResult: () => ({}), textChange: () => ({}), connectionChange: () => ({}), serverError: (message: string) => { throw new Error(message); }, ...options.on }; this.#options = options; const cmOptions = { gutters: [], indentUnit: 4, ...options.forCodeMirror, lineSeparator, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion mode: languageModes[options.language!], lint: { async: true, getAnnotations: this.#lintGetAnnotations, hasGutters: true }, lintFix: { getFixes: this.#getLintFixes }, infotip: { async: true, delay: 500, getInfo: this.#infotipGetInfo, render: renderInfotip } } as CodeMirror.EditorConfiguration & { lineSeparator: string }; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion cmOptions.gutters!.push('CodeMirror-lint-markers'); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#language = options.language!; this.#serverOptions = { ...(options.initialServerOptions ?? {}), language: this.#language } as ServerOptions&TExtensionServerOptions; const cmSource = (function getCodeMirror() { const next = textarea.nextSibling as { CodeMirror?: CodeMirror.EditorFromTextArea }; if (next?.CodeMirror) { const existing = next.CodeMirror; for (const key in cmOptions) { // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call existing.setOption(key as any, cmOptions[key as keyof typeof cmOptions]); } return { cm: existing, existing: true }; } return { cm: CodeMirror.fromTextArea(textarea, cmOptions) }; })(); this.#cm = cmSource.cm; this.#keyMap = { /* eslint-disable object-shorthand */ 'Tab': () => { if (this.#cm.somethingSelected()) { this.#cm.execCommand('indentMore'); return; } this.#cm.replaceSelection(' ', 'end'); }, 'Shift-Tab': 'indentLess', // eslint-disable-next-line @typescript-eslint/no-floating-promises 'Ctrl-Space': () => { connection.sendCompletionState('force'); }, // eslint-disable-next-line @typescript-eslint/no-floating-promises 'Shift-Ctrl-Space': () => { connection.sendSignatureHelpState('force'); }, 'Ctrl-.': 'lintFixShow', 'Shift-Ctrl-Y': selfDebug ? () => { // eslint-disable-next-line @typescript-eslint/no-floating-promises selfDebug.requestData(connection); } : false /* eslint-enable object-shorthand */ }; this.#cm.addKeyMap(this.#keyMap); // see https://github.com/codemirror/CodeMirror/blob/dbaf6a94f1ae50d387fa77893cf6b886988c2147/addon/lint/lint.js#L133 // ensures that next 'id' will be -1 whether a change happened or not // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access this.#cm.state.lint.waitingFor = -2; if (!cmSource.existing) this.setText(textarea.value); const getText = this.#cm.getValue.bind(this.#cm); if (selfDebug) selfDebug.watchEditor(getText, this.#getCursorIndex); const cmWrapper = this.#cm.getWrapperElement(); cmWrapper.classList.add('mirrorsharp', 'mirrorsharp-theme'); this.#hinter = new Hinter(this.#cm, connection); this.#signatureTip = new SignatureTip(this.#cm); this.#removeConnectionEvents = addEvents(connection, { open: this.#onConnectionOpen, message: this.#onConnectionMessage, error: this.#onConnectionCloseOrError, close: this.#onConnectionCloseOrError }); this.#removeCodeMirrorEvents = addEvents(this.#cm, { beforeChange: this.#onCodeMirrorBeforeChange, cursorActivity: this.#onCodeMirrorCursorActivity, changes: this.#onCodeMirrorChanges }); } #onConnectionOpen = (e: Event) => { this.#hideConnectionLoss(); if (!this.#hasDefaultServerOptions()) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendSetOptions(this.#pendingServerOptions ?? this.#serverOptions); } const text = this.#cm.getValue(); if (text === '' || text == null) { this.#lintingSuspended = false; return; } // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendReplaceText(0, 0, text, this.#getCursorIndex()); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#options.on!.connectionChange!('open', e); this.#lintingSuspended = false; this.#hadChangesSinceLastLinting = true; if (this.#capturedUpdateLinting) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#requestSlowUpdate(); } }; #onConnectionMessage = (message: Message<TExtensionServerOptions, TSlowUpdateExtensionData>) => { switch (message.type) { case 'changes': this.#receiveServerChanges(message.changes, message.reason); break; case 'completions': this.#hinter.start(message.completions, message.span, { commitChars: message.commitChars, suggestion: message.suggestion }); break; case 'completionInfo': this.#hinter.showTip(message.index, message.parts); break; case 'signatures': this.#signatureTip.update(message); break; case 'infotip': if (!message.sections) { this.#cm.infotipUpdate(null); return; } this.#cm.infotipUpdate({ data: message, range: this.#spanToRange(message.span) }); break; case 'slowUpdate': this.#showSlowUpdate(message); break; case 'optionsEcho': this.#receiveServerOptions(message.options); break; case 'self:debug': // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#selfDebug!.displayData(message); break; case 'error': // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#options.on!.serverError!(message.message); break; default: throw new Error('Unknown message type "' + message.type); } }; #onConnectionCloseOrError = (e: CloseEvent|ErrorEvent) => { this.#lintingSuspended = true; this.#showConnectionLoss(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const connectionChange = this.#options.on!.connectionChange!; if (e instanceof CloseEvent) { connectionChange('close', e); } else { connectionChange('error', e); } }; #onCodeMirrorBeforeChange = (_: CodeMirror.Editor, change: CodeMirror.EditorChange) => { (change.from as PositionWithIndex)[indexKey] = this.#cm.indexFromPos(change.from); (change.to as PositionWithIndex)[indexKey] = this.#cm.indexFromPos(change.to); this.#changePending = true; }; #onCodeMirrorCursorActivity = () => { if (this.#changePending) return; // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendMoveCursor(this.#getCursorIndex()); }; #onCodeMirrorChanges = (_: CodeMirror.Editor, changes: ReadonlyArray<CodeMirror.EditorChange>) => { this.#hadChangesSinceLastLinting = true; this.#changePending = false; const cursorIndex = this.#getCursorIndex(); changes = this.#mergeChanges(changes); for (let i = 0; i < changes.length; i++) { const change = changes[i]; const start = (change.from as PositionWithIndex)[indexKey]; const length = (change.to as PositionWithIndex)[indexKey] - start; const text = change.text.join(lineSeparator); if (cursorIndex === start + 1 && text.length === 1 && !this.#changesAreFromServer) { if (length > 0) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendReplaceText(start, length, '', cursorIndex - 1); } // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendTypeChar(text); } else { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendReplaceText(start, length, text, cursorIndex, this.#changeReason); } } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#options.on!.textChange!(this.#getText); }; #mergeChanges = (changes: ReadonlyArray<CodeMirror.EditorChange>) => { if (changes.length < 2) return changes; const canBeMerged = (first: CodeMirror.EditorChange|null, second: CodeMirror.EditorChange|null) => { return first && second && first.origin === 'undo' && second.origin === 'undo' && first.to.line === second.from.line && first.text.length === 1 && second.text.length === 1 && second.from.ch === second.to.ch && (first.to.ch + first.text[0].length) === second.from.ch; }; const results = []; let before: CodeMirror.EditorChange|null = null; for (const change of changes) { if (canBeMerged(before, change)) { before = { /* eslint-disable @typescript-eslint/no-non-null-assertion */ from: before!.from, to: before!.to, text: [before!.text[0] + change.text[0]], origin: change.origin /* eslint-enable @typescript-eslint/no-non-null-assertion */ }; } else { if (before) results.push(before); before = change; } } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion results.push(before!); return results; }; #lintGetAnnotations = (_: string, updateLinting: CodeMirror.UpdateLintingCallback) => { if (!this.#capturedUpdateLinting) { this.#capturedUpdateLinting = function(this: ThisParameterType<CodeMirror.UpdateLintingCallback>, ...args: Parameters<CodeMirror.UpdateLintingCallback>) { const [cm] = args; // see https://github.com/codemirror/CodeMirror/blob/dbaf6a94f1ae50d387fa77893cf6b886988c2147/addon/lint/lint.js#L133 // ensures that next 'id' will always match 'waitingFor' (cm.state as { lint: { waitingFor: number } }).lint.waitingFor = -1; updateLinting.apply(this, args); }; } // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#requestSlowUpdate(); }; #getText = () => this.#cm.getValue(); #getCursorIndex = () => this.#cm.indexFromPos(this.#cm.getCursor()); #receiveServerChanges = (changes: ReadonlyArray<ChangeData>, reason: string|null) => { this.#changesAreFromServer = true; this.#changeReason = reason ?? 'server'; this.#cm.operation(() => { let offset = 0; for (const change of changes) { const from = this.#cm.posFromIndex(change.start + offset); const to = change.length > 0 ? this.#cm.posFromIndex(change.start + offset + change.length) : from; this.#cm.replaceRange(change.text, from, to, '+server'); offset += change.text.length - change.length; } }); this.#changeReason = null; this.#changesAreFromServer = false; }; #getLintFixes = (cm: CodeMirror.Editor, line: number, annotations: ReadonlyArray<CodeMirror.Annotation>) => { const requestApplyFix = (cm: CodeMirror.Editor, line: number, fix: AnnotationFixWithId) => { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendApplyDiagnosticAction(fix.id); }; const fixes: Array<CodeMirror.AnnotationFix> = []; for (const annotation of annotations) { const diagnostic = (annotation as DiagnosticAnnotation).diagnostic; if (!diagnostic.actions) continue; for (const action of diagnostic.actions) { fixes.push({ text: action.title, apply: requestApplyFix, id: action.id } as AnnotationFixWithId); } } return fixes; }; #infotipGetInfo = (cm: CodeMirror.Editor, position: CodeMirror.Position) => { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#connection.sendRequestInfoTip(cm.indexFromPos(position)); }; #requestSlowUpdate = (force?: boolean) => { if (this.#lintingSuspended || !(this.#hadChangesSinceLastLinting || force)) return null; this.#hadChangesSinceLastLinting = false; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#options.on!.slowUpdateWait!(); return this.#connection.sendSlowUpdate(); }; #showSlowUpdate = (update: SlowUpdateMessage<TSlowUpdateExtensionData>) => { const annotations: Array<DiagnosticAnnotation> = []; // Higher severities must go last -- CodeMirror uses last one for the icon. // Unless one is error, in which case it's always error -- but still makes // sense to handle this consistently. const priorityBySeverity = { hidden: 0, info: 1, warning: 2, error: 3 }; const diagnostics = update.diagnostics.slice(0); diagnostics.sort((a, b) => { const aOrder = priorityBySeverity[a.severity]; const bOrder = priorityBySeverity[b.severity]; return aOrder !== bOrder ? (aOrder > bOrder ? 1 : -1) : 0; }); for (const diagnostic of diagnostics) { let severity: DiagnosticSeverity|'unnecessary' = diagnostic.severity; const isUnnecessary = diagnostic.tags.includes('unnecessary'); if (severity === 'hidden' && !isUnnecessary) continue; if (isUnnecessary && (severity === 'hidden' || severity === 'info')) severity = 'unnecessary'; const range = this.#spanToRange(diagnostic.span); annotations.push({ severity, message: diagnostic.message, from: range.from, to: range.to, diagnostic }); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#capturedUpdateLinting!(this.#cm, annotations); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#options.on!.slowUpdateResult!({ diagnostics: update.diagnostics, x: update.x }); }; #connectionLossElement: HTMLDivElement|undefined; #showConnectionLoss = () => { const wrapper = this.#cm.getWrapperElement(); if (!this.#connectionLossElement) { const connectionLossElement = document.createElement('div'); connectionLossElement.setAttribute('class', 'mirrorsharp-connection-issue'); connectionLossElement.innerText = 'Server connection lost, reconnecting…'; wrapper.appendChild(connectionLossElement); this.#connectionLossElement = connectionLossElement; } wrapper.classList.add('mirrorsharp-connection-has-issue'); }; #hideConnectionLoss = () => { this.#cm.getWrapperElement().classList.remove('mirrorsharp-connection-has-issue'); }; #hasDefaultServerOptions = () => { const keys = Object.keys(this.#pendingServerOptions ?? this.#serverOptions); return keys.length === 1 && keys[0] === 'language' && this.#serverOptions.language === defaultLanguage; }; #sendServerOptions = async (value: ServerOptions | Partial<ServerOptions & TExtensionServerOptions>) => { this.#pendingServerOptions = { ...this.#serverOptions, ...value }; await this.#connection.sendSetOptions(value); await this.#requestSlowUpdate(true); }; #receiveServerOptions = (value: ServerOptions&TExtensionServerOptions) => { this.#pendingServerOptions = null; this.#serverOptions = { ...this.#serverOptions, ...value }; // TODO: understand later // eslint-disable-next-line no-undefined if (value.language !== undefined && value.language !== this.#language) { this.#language = value.language; this.#cm.setOption('mode', languageModes[this.#language]); } }; #spanToRange = (span: SpanData) => { return { from: this.#cm.posFromIndex(span.start), to: this.#cm.posFromIndex(span.start + span.length) }; }; getCodeMirror() { return this.#cm; } setText(text: string) { this.#cm.setValue(text.replace(/(\r\n|\r|\n)/g, '\r\n')); } getLanguage() { return this.#language; } setLanguage(value: Language) { return this.#sendServerOptions({ language: value }); } setServerOptions(value: ServerOptions) { return this.#sendServerOptions(value); } destroy(destroyOptions: { readonly keepCodeMirror?: boolean } = {}) { this.#cm.save(); this.#removeConnectionEvents(); if (!destroyOptions.keepCodeMirror) { this.#cm.toTextArea(); return; } this.#cm.removeKeyMap(this.#keyMap); this.#removeCodeMirrorEvents(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#cm.setOption('lint', null!); this.#cm.setOption('lintFix', null); // TODO: fix in infotip // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.#cm.setOption('infotip', null!); } }
the_stack
import { DocgeniContext } from '../docgeni.interface'; import { ApiDeclaration, ComponentDocItem, ExampleSourceFile, Library, LiveExample, Locale, NgDefaultExportInfo } from '../interfaces'; import { toolkit } from '@docgeni/toolkit'; import { createNgSourceFile, NgModuleInfo, NgSourceFile } from '@docgeni/ngdoc'; import { ASSETS_API_DOCS_RELATIVE_PATH, ASSETS_EXAMPLES_HIGHLIGHTED_RELATIVE_PATH, ASSETS_EXAMPLES_SOURCE_BUNDLE_RELATIVE_PATH, ASSETS_OVERVIEWS_RELATIVE_PATH, EXAMPLE_META_FILE_NAME, SITE_ASSETS_RELATIVE_PATH } from '../constants'; import { highlight } from '../utils'; import { DocType } from '../enums'; import { Markdown } from '../markdown'; import { cosmiconfig } from 'cosmiconfig'; import fm from 'front-matter'; import { DocSourceFile } from './doc-file'; import { ComponentDocMeta, EmitFiles, LibraryComponent } from '../types'; import { getSystemPath, resolve } from '../fs'; import { FileEmitter } from './emitter'; import { generateComponentExamplesModule } from './examples-module'; export class LibraryComponentImpl extends FileEmitter implements LibraryComponent { public name: string; /** Component Path */ public absPath: string; public meta?: ComponentDocMeta; public absExamplesPath: string; public absDocPath: string; public absApiPath: string; private get absDestSiteContentComponentsPath() { return resolve(this.docgeni.paths.absSiteContentPath, `components/${this.lib.name}/${this.name}`); } private get absDestAssetsExamplesHighlightedPath() { return resolve(this.docgeni.paths.absSitePath, `${ASSETS_EXAMPLES_HIGHLIGHTED_RELATIVE_PATH}/${this.lib.name}/${this.name}`); } private get absDestAssetsOverviewsPath() { return resolve(this.docgeni.paths.absSitePath, `${ASSETS_OVERVIEWS_RELATIVE_PATH}/${this.lib.name}/${this.name}`); } private get absDestAssetsApiDocsPath() { return resolve(this.docgeni.paths.absSitePath, `${ASSETS_API_DOCS_RELATIVE_PATH}/${this.lib.name}/${this.name}`); } private get absExamplesSourceBundleDir() { return resolve(this.docgeni.paths.absSitePath, `${ASSETS_EXAMPLES_SOURCE_BUNDLE_RELATIVE_PATH}/${this.lib.name}/${this.name}`); } public examples: LiveExample[]; private localeOverviewsMap: Record<string, DocSourceFile> = {}; private localeApiDocsMap: Record<string, ApiDeclaration[]> = {}; private localeDocItemsMap: Record<string, ComponentDocItem> = {}; // entry file index.ts private examplesEntrySource: string; private examplesModuleSource: string; constructor(private docgeni: DocgeniContext, public lib: Library, name: string, absPath: string) { super(); this.name = name; this.absPath = absPath; this.meta = {}; this.absExamplesPath = resolve(this.absPath, this.lib.examplesDir); this.absDocPath = resolve(this.absPath, this.lib.docDir); this.absApiPath = resolve(this.absPath, this.lib.apiDir); } public async build(): Promise<void> { this.resetEmitted(); await this.buildOverviews(); await this.buildApiDocs(); await this.buildExamples(); await this.buildDocItems(); } public async onEmit(): Promise<void> { await this.emitOverviews(); await this.emitApiDocs(); await this.emitExamples(); } public getApiDocs(locale: string): ApiDeclaration[] { return this.localeApiDocsMap[locale]; } public getDocItem(locale: string): ComponentDocItem { return this.localeDocItemsMap[locale]; } /** * Get module key, `{libName}/{name}` * example alib/button */ public getModuleKey() { return `${this.lib.name}/${this.name}`; } private async buildOverviews(): Promise<void> { const docSourceFiles: DocSourceFile[] = []; for (const locale of this.docgeni.config.locales) { const absDocPath = resolve(this.absDocPath, `${locale.key}.md`); if (await this.docgeni.host.pathExists(absDocPath)) { const docSourceFile = new DocSourceFile( { cwd: this.docgeni.paths.cwd, base: this.docgeni.paths.cwd, path: absDocPath, type: DocType.component, locale: locale.key }, this.docgeni.host ); docSourceFiles.push(docSourceFile); this.localeOverviewsMap[locale.key] = docSourceFile; await this.buildOverview(docSourceFile); } } const defaultLocaleDoc = this.localeOverviewsMap[this.docgeni.config.defaultLocale]; if (defaultLocaleDoc) { this.meta = defaultLocaleDoc.meta; this.name = defaultLocaleDoc.meta.name || this.name; } } private async buildOverview(docSourceFile: DocSourceFile) { // this.hooks.buildDoc.call(docSourceFile); await docSourceFile.build(); // this.hooks.buildDocSucceed.call(docSourceFile); } private async tryGetApiDocsByManual(): Promise<Record<string, ApiDeclaration[]>> { const result: Record<string, ApiDeclaration[]> = {}; for (const locale of this.docgeni.config.locales) { const localeKey = locale.key; const realAbsApiPath = getSystemPath(this.absApiPath); const explorer = cosmiconfig.call(cosmiconfig, localeKey, { searchPlaces: [ localeKey, `${localeKey}.json`, `${localeKey}.yaml`, `${localeKey}.yml`, `${localeKey}.js`, `${localeKey}.config.js` ], stopDir: realAbsApiPath }); const localeResult: { config: ApiDeclaration[]; filepath: string } = await explorer.search(realAbsApiPath); result[localeKey] = localeResult && localeResult.config && toolkit.utils.isArray(localeResult.config) ? localeResult.config : undefined; } return result; } private async buildApiDocs(): Promise<void> { if (this.lib.apiMode === 'automatic') { const apiDocs = this.lib.ngDocParser.parse(resolve(this.absPath, '*.ts')) as ApiDeclaration[]; this.docgeni.config.locales.forEach(locale => { this.localeApiDocsMap[locale.key] = apiDocs; }); } else if (this.lib.apiMode === 'compatible') { const apiDocs = await this.tryGetApiDocsByManual(); this.docgeni.config.locales.forEach(locale => { if (!apiDocs[locale.key]) { apiDocs[locale.key] = this.lib.ngDocParser.parse(resolve(this.absPath, '*.ts')) as ApiDeclaration[]; } }); this.localeApiDocsMap = apiDocs; } else { this.localeApiDocsMap = await this.tryGetApiDocsByManual(); } this.docgeni.config.locales.forEach(locale => { const apiDocs = this.localeApiDocsMap[locale.key]; (apiDocs || []).forEach(item => { item.description = item.description ? Markdown.toHTML(item.description) : ''; (item.properties || []).forEach(property => { property.default = !toolkit.utils.isEmpty(property.default) ? property.default : undefined; property.description = property.description ? Markdown.toHTML(property.description) : ''; }); }); }); } private async buildExamples(): Promise<void> { this.examples = []; if (!(await this.docgeni.host.pathExists(this.absExamplesPath))) { return; } let examplesModuleName = toolkit.strings.pascalCase(`${this.getLibAbbrName(this.lib)}-${this.name}-examples-module`); const dirs = await this.docgeni.host.getDirs(this.absExamplesPath); const exampleOrderMap: WeakMap<LiveExample, number> = new WeakMap(); for (const exampleName of dirs) { const { order, liveExample } = await this.buildExample(exampleName, examplesModuleName); exampleOrderMap.set(liveExample, order); this.examples.push(liveExample); } this.examples = toolkit.utils.sortByOrderMap(this.examples, exampleOrderMap); const moduleFilePath = resolve(this.absExamplesPath, 'module.ts'); let exportedExamplesModule: NgModuleInfo; let exampleModuleSourceFile: NgSourceFile; if (await this.docgeni.host.pathExists(moduleFilePath)) { const moduleSourceText = await this.docgeni.host.readFile(moduleFilePath); exampleModuleSourceFile = createNgSourceFile(moduleFilePath, moduleSourceText); exportedExamplesModule = exampleModuleSourceFile.getExportedNgModule(); this.examplesModuleSource = moduleSourceText; } else { exampleModuleSourceFile = createNgSourceFile(moduleFilePath, ''); } if (exportedExamplesModule) { examplesModuleName = exportedExamplesModule.name; } else { this.examplesModuleSource = await generateComponentExamplesModule( exampleModuleSourceFile, examplesModuleName, this.examples.map(item => { return { name: item.componentName, moduleSpecifier: `./${item.name}/${item.name}.component` }; }) ); } this.examplesEntrySource = toolkit.template.compile('component-examples-entry.hbs', { examples: this.examples, examplesModule: examplesModuleName }); } private async buildExample(exampleName: string, moduleName: string) { const libAbbrName = this.getLibAbbrName(this.lib); const componentKey = `${libAbbrName}-${this.name}-${exampleName}-example`; const defaultComponentName = toolkit.strings.pascalCase(`${libAbbrName}-${this.name}-${exampleName}-example-component`); const absComponentExamplePath = resolve(this.absExamplesPath, exampleName); const absComponentExampleDocPath = resolve(absComponentExamplePath, EXAMPLE_META_FILE_NAME); const liveExample: LiveExample = { key: componentKey, name: exampleName, title: toolkit.strings.headerCase(exampleName, { delimiter: ' ' }), componentName: defaultComponentName, module: { name: moduleName, importSpecifier: `${this.lib.name}/${this.name}` }, sourceFiles: [], additionalFiles: [], additionalComponents: [] }; // build example source files const exampleSourceFiles = await this.buildExampleSourceFiles(absComponentExamplePath); liveExample.sourceFiles = exampleSourceFiles; // try extract component name from example entry ts file const entrySourceFile = exampleSourceFiles.find(sourceFile => { return sourceFile.name === `${exampleName}.component.ts`; }); if (entrySourceFile) { const component = createNgSourceFile(entrySourceFile.name, entrySourceFile.content).getExpectExportedComponent(exampleName); if (component) { liveExample.componentName = component.name; } } // build order, title from FrontMatter let exampleOrder = Number.MAX_SAFE_INTEGER; if (await this.docgeni.host.pathExists(absComponentExampleDocPath)) { const content = await this.docgeni.host.readFile(absComponentExampleDocPath); const exampleFmResult = fm<{ title: string; order: number }>(content); if (exampleFmResult.attributes.title) { liveExample.title = exampleFmResult.attributes.title; } if (toolkit.utils.isNumber(exampleFmResult.attributes.order)) { exampleOrder = exampleFmResult.attributes.order; } } return { order: exampleOrder, liveExample }; } private async buildExampleSourceFiles(absComponentExamplePath: string): Promise<ExampleSourceFile[]> { const files = await this.docgeni.host.getFiles(absComponentExamplePath, { exclude: EXAMPLE_META_FILE_NAME }); const exampleSourceFiles: ExampleSourceFile[] = []; for (const fileName of files) { const ext = toolkit.utils.extractExtname(fileName, true); const sourceCode = await this.docgeni.host.readFile(resolve(absComponentExamplePath, fileName)); const highlightedSourceCode = highlight(sourceCode, ext); const destFileName = `${toolkit.strings.paramCase(fileName)}.html`; exampleSourceFiles.push({ name: fileName, highlightedPath: destFileName, highlightedContent: highlightedSourceCode, content: sourceCode }); } return exampleSourceFiles; } private async buildDocItems() { this.docgeni.config.locales.forEach(locale => { let overviewSourceFile = this.localeOverviewsMap[locale.key]; // Use default locale's data when locale is not found if (!overviewSourceFile) { overviewSourceFile = this.localeOverviewsMap[this.docgeni.config.defaultLocale]; } // Use default locale's data when api locale is not found let apiDocs = this.localeApiDocsMap[locale.key]; if (!apiDocs) { apiDocs = this.localeApiDocsMap[this.docgeni.config.defaultLocale]; } const title = this.getMetaProperty(overviewSourceFile, 'title') || toolkit.strings.titleCase(this.name); const subtitle = this.getMetaProperty(overviewSourceFile, 'subtitle') || ''; const order = this.getMetaProperty(overviewSourceFile, 'order'); if (overviewSourceFile || !toolkit.utils.isEmpty(this.examples) || (apiDocs && apiDocs.length > 0)) { const componentNav: ComponentDocItem = { id: this.name, title, subtitle, path: this.name, importSpecifier: `${this.lib.name}/${this.name}`, examples: this.examples.map(example => example.key), overview: overviewSourceFile && overviewSourceFile.output ? true : false, api: apiDocs && apiDocs.length > 0 ? true : false, order: toolkit.utils.isNumber(order) ? order : Number.MAX_SAFE_INTEGER, category: this.meta.category, hidden: this.meta.hidden, label: this.meta.label ? this.lib.labels[this.meta.label] : undefined, originPath: overviewSourceFile && overviewSourceFile.relative, toc: toolkit.utils.isUndefinedOrNull(this.meta.toc) ? 'content' : this.meta.toc }; this.localeDocItemsMap[locale.key] = componentNav; } }); } private async emitOverviews() { const defaultSourceFile = this.localeOverviewsMap[this.docgeni.config.defaultLocale]; for (const locale of this.docgeni.config.locales) { const sourceFile = this.localeOverviewsMap[locale.key] || defaultSourceFile; if (sourceFile) { const filePath = resolve(this.absDestAssetsOverviewsPath, `${locale.key}.html`); this.addEmitFile(filePath, sourceFile.output); await this.docgeni.host.writeFile(filePath, sourceFile.output); } } } private async emitApiDocs() { const defaultApiDoc = this.localeApiDocsMap[this.docgeni.config.defaultLocale]; for (const locale of this.docgeni.config.locales) { const apiDocs = this.localeApiDocsMap[locale.key] || defaultApiDoc; if (apiDocs) { const componentApiDocDistPath = resolve(this.absDestAssetsApiDocsPath, `${locale.key}.html`); const componentApiJsonDistPath = resolve(this.absDestAssetsApiDocsPath, `${locale.key}.json`); const apiDocContent = toolkit.template.compile('api-doc.hbs', { declarations: apiDocs }); this.addEmitFile(componentApiJsonDistPath, JSON.stringify(apiDocs)); await this.docgeni.host.writeFile(componentApiDocDistPath, apiDocContent); await this.docgeni.host.writeFile(componentApiJsonDistPath, JSON.stringify(apiDocs)); } } } private async emitExamples() { if (!(await this.docgeni.host.pathExists(this.absExamplesPath))) { return; } const examplesEntryPath = resolve(this.absDestSiteContentComponentsPath, 'index.ts'); await this.docgeni.host.copy(this.absExamplesPath, this.absDestSiteContentComponentsPath); await this.docgeni.host.writeFile(resolve(this.absDestSiteContentComponentsPath, 'module.ts'), this.examplesModuleSource); this.addEmitFile(examplesEntryPath, this.examplesEntrySource); await this.docgeni.host.writeFile(examplesEntryPath, this.examplesEntrySource); const allExampleSources: { path: string; content: string }[] = []; for (const example of this.examples) { for (const sourceFile of example.sourceFiles) { const absExampleHighlightPath = resolve(this.absDestAssetsExamplesHighlightedPath, `${example.name}`); const destHighlightedSourceFilePath = `${absExampleHighlightPath}/${sourceFile.highlightedPath}`; allExampleSources.push({ path: `${example.name}/${sourceFile.name}`, content: sourceFile.content }); this.addEmitFile(destHighlightedSourceFilePath, sourceFile.highlightedContent); await this.docgeni.host.writeFile(destHighlightedSourceFilePath, sourceFile.highlightedContent); } } // for online example e.g. StackBlitz allExampleSources.push({ path: 'examples.module.ts', content: this.examplesModuleSource }); const bundlePath = resolve(this.absExamplesSourceBundleDir, 'bundle.json'); const content = JSON.stringify(allExampleSources); await this.addEmitFile(bundlePath, content); await this.docgeni.host.writeFile(bundlePath, content); } private getLibAbbrName(lib: Library): string { return lib.abbrName || lib.name; } private getMetaProperty<TPropertyKey extends keyof ComponentDocMeta>( docSourceFile: DocSourceFile, propertyName: TPropertyKey ): ComponentDocMeta[TPropertyKey] { return docSourceFile && docSourceFile.meta && docSourceFile.meta[propertyName]; } }
the_stack
import {Type} from "../Types"; import {UriComponent} from "./UriComponent"; import {Scheme} from "./Scheme"; import {SchemeValue} from "./SchemeValue"; import {QueryParam} from "./QueryParam"; import {encode, parseToMap, Separator} from "./QueryParams"; import {trim} from "../Text/Utility"; import {Exception} from "../Exception"; import {ArgumentException} from "../Exceptions/ArgumentException"; import {ArgumentOutOfRangeException} from "../Exceptions/ArgumentOutOfRangeException"; import {IUri} from "./IUri"; import {IMap} from "../../IMap"; import {Primitive} from "../Primitive"; import {StringKeyValuePair} from "../KeyValuePair"; import {IEquatable} from "../IEquatable"; import {Action} from "../FunctionTypes"; const VOID0:undefined = void 0; /** * Provides an read-only model representation of a uniform resource identifier (URI) and easy access to the parts of the URI. * * The read-only model (frozen) is easier for debugging than exposing accessors for each property. * ICloneable&lt;Uri&gt; is not used to prevent unnecessary copying of values that won't change. */ export class Uri implements IUri, IEquatable<IUri> { readonly scheme:SchemeValue.Any | null; readonly userInfo:string | null; readonly host:string | null; readonly port:number | null; readonly path:string | null; readonly query:string | null; readonly fragment:string | null; readonly queryParams:IMap<Primitive|Primitive[]>;//Readonly<IMap<Primitive|Primitive[]>>; /** * @param scheme The user name, password, or other user-specific information associated with the specified URI. * @param userInfo The host component of this instance. * @param host The port number of this URI. * @param port The absolute path of the URI. * @param path The absolute path of the URI. * @param query Any query information included in the specified URI. * @param fragment The escaped URI fragment. */ constructor( scheme:SchemeValue.Any|null, userInfo:string|null, host:string|null, port:number|null, path:string|null, query?:QueryParam.Convertible, fragment?:string) { const _ = this; this.scheme = getScheme(scheme) || null; this.userInfo = userInfo || null; this.host = host || null; this.port = getPort(port); this.authority = _.getAuthority() || null; this.path = path || null; if(!Type.isString(query)) query = encode(<UriComponent.Map|StringKeyValuePair<Primitive>[]>query); this.query = formatQuery(<string>query) || null; Object.freeze(this.queryParams = _.query ? parseToMap(_.query) : {}); this.pathAndQuery = _.getPathAndQuery() || null; this.fragment = formatFragment(fragment) || null; // This should validate the uri... this.absoluteUri = _.getAbsoluteUri(); this.baseUri = _.absoluteUri.replace(/[?#].*/, ''); // Intended to be read-only. Call .toMap() to get a writable copy. Object.freeze(this); } /** * Compares the values of another IUri via toString comparison. * @param other * @returns {boolean} */ equals(other:IUri):boolean { return this===other || this.absoluteUri==Uri.toString(other); } /** * Parses or clones values from existing Uri values. * @param uri * @param defaults * @returns {Uri} */ static from(uri:string|IUri|null|undefined, defaults?:IUri):Uri { const u = Type.isString(uri) ? Uri.parse(<string>uri) // Parsing a string should throw errors. Null or undefined simply means empty. : <IUri>uri; return new Uri( u && u.scheme || defaults && <any>defaults.scheme, u && u.userInfo || defaults && <any>defaults.userInfo, u && u.host || defaults && <any>defaults.host, u && Type.isNumber(u.port,true) ? u.port : defaults && <any>defaults.port, u && u.path || defaults && <any>defaults.path, u && u.query || defaults && <any>defaults.query, u && u.fragment || defaults && <any>defaults.fragment ); } /** * Parses a URL into it's components. * @param url The url to parse. * @returns {IUri} Will throw an exception if not able to parse. */ static parse(url:string):IUri static parse(url:string, throwIfInvalid:true):IUri /** * Parses a URL into it's components. * @param url The url to parse. * @param throwIfInvalid Defaults to true. * @returns {IUri} Returns a map of the values or *null* if invalid and *throwIfInvalid* is <b>false</b>. */ static parse(url:string, throwIfInvalid:boolean):IUri|null static parse(url:string, throwIfInvalid:boolean = true):IUri|null { let result:IUri|null = null; const ex = tryParse(url, (out) => {result = out;}); if(throwIfInvalid && ex) throw ex; return result; } /** * Parses a URL into it's components. * @param url The url to parse. * @param out A delegate to capture the value. * @returns {boolean} True if valid. False if invalid. */ static tryParse(url:string, out:(result:IUri)=>void):boolean { return !tryParse(url, out); // return type is Exception. } static copyOf(map:IUri):IUri { return copyUri(map); } copyTo(map:IUri):IUri { return copyUri(this, map); } updateQuery(query:QueryParam.Convertible):Uri { const map = this.toMap(); map.query = <any>query; return Uri.from(map); } /** * Is provided for sub classes to override this value. */ protected getAbsoluteUri():string { return uriToString(this); } /** * Is provided for sub classes to override this value. */ protected getAuthority():string { return getAuthority(this); } /** * Is provided for sub classes to override this value. */ protected getPathAndQuery():string { return getPathAndQuery(this); } /** * The absolute URI. */ absoluteUri:string; /** * Gets the Domain Name System (DNS) host name or IP address and the port number for a server. */ readonly authority:string | null; /** * Gets the path and Query properties separated by a question mark (?). */ readonly pathAndQuery:string | null; /** * Gets the full path without the query or fragment. */ readonly baseUri:string; /** * The segments that represent a path.<br/> * https://msdn.microsoft.com/en-us/library/system.uri.segments%28v=vs.110%29.aspx * * <h5><b>Example:</b></h5> * If the path value equals: ```/tree/node/index.html```<br/> * The result will be: ```['/','tree/','node/','index.html']``` * @returns {string[]} */ get pathSegments():string[] { return this.path && this.path.match(/^[/]|[^/]*[/]|[^/]+$/g) || []; } /** * Creates a writable copy. * @returns {IUri} */ toMap():IUri { return this.copyTo({}); } /** * @returns {string} The full absolute uri. */ toString():string { return this.absoluteUri; } /** * Properly converts an existing URI to a string. * @param uri * @returns {string} */ static toString(uri:IUri):string { return uri instanceof <any>Uri ? (<Uri>uri).absoluteUri : uriToString(uri); } /** * Returns the authority segment of an URI. * @param uri * @returns {string} */ static getAuthority(uri:IUri):string { return getAuthority(uri); } } export enum Fields { scheme, userInfo, host, port, path, query, fragment } Object.freeze(Fields); function copyUri(from:IUri, to?:IUri) { let i = 0, field:string; if(!to) to = {}; while(field = Fields[i++]) { const value = (<any>from)[field]; if(value) (<any>to)[field] = value; } return to; } const SLASH = '/', SLASH2 = '//', QM = Separator.Query, HASH = '#', EMPTY = '', AT = '@'; function getScheme(scheme:SchemeValue.Any|string|null|undefined):SchemeValue.Any|null { let s:any = scheme; if(Type.isString(s)) { if(!s) return null; s = trim(s) .toLowerCase() .replace(/[^a-z0-9+.-]+$/g, EMPTY); if(!s) return null; if(Scheme.isValid(s)) return s; } else { if(s==null) return s; } throw new ArgumentOutOfRangeException('scheme', scheme, 'Invalid scheme.'); } function getPort(port:number|string|null|undefined):number|null { if(port===0) return <number>port; if(!port) return null; let p:number; if(Type.isNumber(port)) { p = <number>port; if(p>=0 && isFinite(p)) return p; } else if(Type.isString(port) && (p = parseInt(<string>port)) && !isNaN(p)) { return getPort(p); } throw new ArgumentException("port", "invalid value"); } function getAuthority(uri:IUri):string { if(!uri.host) { if(uri.userInfo) throw new ArgumentException('host', 'Cannot include user info when there is no host.'); if(Type.isNumber(uri.port, true)) throw new ArgumentException('host', 'Cannot include a port when there is no host.'); } /* * [//[user:password@]host[:port]] */ let result = uri.host || EMPTY; if(result) { if(uri.userInfo) result = uri.userInfo + AT + result; if(!isNaN(<any>(uri.port))) result += ':' + uri.port; result = SLASH2 + result; } return result; } function formatQuery(query:string|null|undefined):string|null|undefined { return query && ((query.indexOf(QM)!==0 ? QM : EMPTY) + query); } function formatFragment(fragment:string|null|undefined):string|null|undefined { return fragment && ((fragment.indexOf(HASH)!==0 ? HASH : EMPTY) + fragment); } function getPathAndQuery(uri:IUri):string { const path = uri.path, query = uri.query; return EMPTY + (path || EMPTY) + (formatQuery(query) || EMPTY); } function uriToString(uri:IUri):string { // scheme:[//[user:password@]domain[:port]][/]path[?query][#fragment] // {scheme}{authority}{path}{query}{fragment} const scheme = getScheme(uri.scheme); let authority = getAuthority(uri); const pathAndQuery = getPathAndQuery(uri), fragment = formatFragment(uri.fragment); const part1 = EMPTY + ((scheme && (scheme + ':')) || EMPTY) + (authority || EMPTY); let part2 = EMPTY + (pathAndQuery || EMPTY) + (fragment || EMPTY); if(part1 && part2 && scheme && !authority) throw new ArgumentException('authority', "Cannot format schemed Uri with missing authority."); if(part1 && pathAndQuery && pathAndQuery.indexOf(SLASH)!==0) part2 = SLASH + part2; return part1 + part2; } function tryParse(url:string, out:Action<IUri>):null|Exception { if(!url) return new ArgumentException('url', 'Nothing to parse.'); // Could use a regex here, but well follow some rules instead. // The intention is to 'gather' the pieces. This isn't validation (yet). // scheme:[//[user:password@]domain[:port]][/]path[?query][#fragment] let i:number; const result:IUri = {}; // Anything after the first # is the fragment. i = url.indexOf(HASH); if(i!= -1) { result.fragment = url.substring(i + 1) || VOID0; url = url.substring(0, i); } // Anything after the first ? is the query. i = url.indexOf(QM); if(i!= -1) { result.query = url.substring(i + 1) || VOID0; url = url.substring(0, i); } // Guarantees a separation. i = url.indexOf(SLASH2); if(i!= -1) { let scheme = trim(url.substring(0, i)); const c = /:$/; if(!c.test(scheme)) return new ArgumentException('url', 'Scheme was improperly formatted'); scheme = trim(scheme.replace(c, EMPTY)); try { result.scheme = getScheme(scheme) || VOID0; } catch(ex) { return ex; } url = url.substring(i + 2); } // Find any path information. i = url.indexOf(SLASH); if(i!= -1) { result.path = url.substring(i); url = url.substring(0, i); } // Separate user info. i = url.indexOf(AT); if(i!= -1) { result.userInfo = url.substring(0, i) || VOID0; url = url.substring(i + 1); } // Remaining is host and port. i = url.indexOf(':'); if(i!= -1) { const port = parseInt(trim(url.substring(i + 1))); if(isNaN(port)) return new ArgumentException('url', 'Port was invalid.'); result.port = port; url = url.substring(0, i); } url = trim(url); if(url) result.host = url; out(copyUri(result)); // null is good! (here) return null; } export default Uri;
the_stack
import React, { useState } from 'react' import FullscreenIcon from '@material-ui/icons/Fullscreen' import FullscreenExitIcon from '@material-ui/icons/FullscreenExit'; import Tooltip from '@material-ui/core/Tooltip'; import PhotoCameraIcon from '@material-ui/icons/PhotoCamera'; import { Network as NetworkType, IdType } from 'vis/index' import { EditOptionsDialog, SearchDialog, FilterDialog, TuneDialog, SettingDialog } from './ViewDialogs' import { Network, Node, Edge } from 'react-vis-network' import { ItemInfo, NodeType, EdgeType, CatType, Pos2d } from './datatypes' import InfoBoard from './InfoBoard' import CircularProgress from './CircularProgressWithLabel' const getCanvas = () => document.getElementsByTagName("canvas")[0] const DefaultNetStyle = { NodeColor: "#66bbff", NodeBorderWidth: 3, } const createNode = (n: NodeType, catgories: Record<string, CatType>) => { let cat = catgories[n.categorie] let color; if (cat) { color = cat.color } else { color = DefaultNetStyle.NodeColor } return ( <Node key={n.id} id={n.id} label={n.label} shape="circularImage" image={n.image} color={color} borderWidth={DefaultNetStyle.NodeBorderWidth} /> ) } const createEdge = (e: EdgeType) => { let arrows = "" if (('direction' in e) && (e['direction'] === true)) { arrows = "to" } return ( <Edge key={e.id} id={e.id} arrows={arrows} from={e.from} to={e.to} label={e.label} /> ) } type ViewControlProps = { setOpt: (opt: any) => void, getOpt: () => any, captureImg: () => void, queryAndFocus: (q: string) => void, queryAndFilter: (q: string, reverse: boolean) => void, reset: () => void, inforBoardSwitch: boolean, setInforBoardSwitch: (on: boolean) => void, hiddenUnselectedSwitch: boolean, setHiddenUnselectedSwitch: (on: boolean) => void, } const ViewControl = (props: ViewControlProps) => { const [fullScreenMode, setFullScreenMode] = useState(false) let oriHeight = 300 const enterFullScreen = () => { let canvas = getCanvas() let fullRegion = document.getElementById("full-screen-region") fullRegion?.requestFullscreen() oriHeight = canvas.clientHeight canvas.style.height = window.screen.height + "px"; setFullScreenMode(true) document.addEventListener('fullscreenchange', (event) => { if (!(document.fullscreenElement)) { turnBackSize() setFullScreenMode(false) } }); } const turnBackSize = () => { let canvas = getCanvas() canvas.style.height = oriHeight + "px" } const exitFullScreen = () => { document.exitFullscreen() turnBackSize() setFullScreenMode(false) } return ( <div className="viewControl"> <SearchDialog queryAndFocus={props.queryAndFocus}/> <FilterDialog queryAndFilter={props.queryAndFilter} reset={props.reset}/> <Tooltip title="截图" placement="top"><PhotoCameraIcon onClick={() => props.captureImg()}/></Tooltip> <TuneDialog setOpt={props.setOpt} getOpt={props.getOpt}/> <EditOptionsDialog setOpt={props.setOpt} getOpt={props.getOpt}/> <SettingDialog inforBoardSwitch={props.inforBoardSwitch} setInforBoardSwitch={props.setInforBoardSwitch} hiddenUnselectedSwitch={props.hiddenUnselectedSwitch} setHiddenUnselectedSwitch={props.setHiddenUnselectedSwitch} /> {fullScreenMode ? <Tooltip title="退出全屏" placement="top"><FullscreenExitIcon onClick={exitFullScreen}/></Tooltip> : <Tooltip title="全屏" placement="top"><FullscreenIcon onClick={enterFullScreen}/></Tooltip> } </div> ) } const DEFAULT_NETWORK_OPTIONS = { autoResize: false, nodes: { shape: "dot", }, physics: { enabled: true, stabilization: false, solver: 'forceAtlas2Based', forceAtlas2Based: { gravitationalConstant: -20, centralGravity: 0.002, springLength: 100, springConstant: 0.01 }, }, edges: { width: 0.3, color: { inherit: "to" } }, interaction: { hideEdgesOnDrag: false, hover: true, multiselect: true, } } type NetViewProps = { info: ItemInfo, setNodes: (nodes: Array<NodeType>) => void, queryNodes: (q: string, reverse: boolean) => Array<NodeType>, } type NetworkRef = { network: NetworkType } type NetViewState = { infoBoard: JSX.Element | null, loadingRatio: number, inforBoardSwitch: boolean, netRef: React.RefObject<NetworkRef>, netOptions: any, oldNodes: Array<NodeType>, hiddenUnselectedSwitch: boolean, } export default class NetView extends React.Component<NetViewProps, NetViewState> { constructor(props: NetViewProps) { super(props) this.state = { infoBoard: null, loadingRatio: 0, inforBoardSwitch: true, netRef: React.createRef(), netOptions: null, oldNodes: props.info.data.nodes, hiddenUnselectedSwitch: false } } setHiddenUnselectedSwitch(on: boolean) { const oldState = this.state.hiddenUnselectedSwitch if ((oldState === true) && (on === false)) { this.resetNodes() } else if((oldState === false) && (on === true)) { this.hiddenNonSelected() } this.setState({ hiddenUnselectedSwitch: on }) } handlePopup (params: any) { const network = (this.state.netRef.current as NetworkRef).network const node_id = network.getNodeAt(params.pointer.DOM) const select_node = (typeof node_id !== "undefined") const pos: Pos2d = {x: 20, y: 20} const create_board = () => { let node = this.props.info.data.nodes.find((n) => (n.id === node_id)) return <InfoBoard pos={pos} node={node as NodeType} cats={this.props.info.categories} close={() => (this.setState({infoBoard: null}))}/> } let board = this.state.infoBoard if (select_node && (board === null) && this.state.inforBoardSwitch) { this.setState({infoBoard: create_board()}) } else if (select_node && (board !== null) && this.state.inforBoardSwitch) { this.setState({infoBoard: create_board()}) } else if (board !== null ) { this.setState({infoBoard: null}) } } handleHidden(params: any) { if (!(this.state.hiddenUnselectedSwitch)) {return} const select_node = (params.nodes.length > 0) if (select_node) { this.hiddenNonSelected() } else { this.resetNodes() } } handleClick(params: any) { this.handlePopup(params) this.handleHidden(params) } setInforBoardSwitch(on: boolean) { this.setState({ inforBoardSwitch: on }) } setNetOptions(options: any) { let network = (this.state.netRef.current as NetworkRef).network network.setOptions(options) this.setState({netOptions: options}) } getNetOptions() { return this.state.netOptions } componentDidMount() { this.setNetOptions(DEFAULT_NETWORK_OPTIONS) this.registerLoading() } createNetwork() { let info = this.props.info const network = ( <> {this.createLoadindBar()} <Network ref={this.state.netRef} onClick={(params: any) => {this.handleClick(params)}} > {info.data.nodes.map(n => createNode(n, info.categories))} {info.data.edges.map((e) => createEdge(e))} </Network> </> ) return network } createLoadindBar() { return ( <div id="progressBar"> <CircularProgress variant="determinate" value={this.state.loadingRatio * 100}/> </div> ) } registerLoading() { // https://jsfiddle.net/api/post/library/pure/ const self = this const ref = (this.state.netRef.current as NetworkRef).network ref.on("stabilizationProgress", function (params: any) { const ratio = params.iterations / params.total; self.setState({loadingRatio: ratio}) }) ref.once("stabilizationIterationsDone", function () { self.setState({loadingRatio: 1}) }) } captureImg() { const canvas = getCanvas() // Fill the canvas background, see: // https://stackoverflow.com/questions/50104437/set-background-color-to-save-canvas-chart const context = canvas.getContext('2d') if (context !== null) { context.save() context.globalCompositeOperation = 'destination-over' context.fillStyle = "#ffffff" context.fillRect(0, 0, canvas.width, canvas.height) context.restore() } const img = canvas.toDataURL("image/png", 1.0) const url = img.replace(/^data:image\/[^;]/, 'data:application/octet-stream') let a = document.createElement('a'); a.download = "network.png"; a.href = url a.target = '_blank'; document.body.appendChild(a); a.click(); document.body.removeChild(a); } queryNodesAndFocus(q:string) { const nodes = this.props.queryNodes(q, false) if (nodes.length <= 0) {return} const network = (this.state.netRef.current as NetworkRef).network network.selectNodes([]) const nodes_id = nodes.map(n => String(n.id)) if (nodes.length > 1) { network.fit({nodes: nodes_id, animation: true}) } else { network.focus(nodes_id[0], {scale: 1, animation: true}) } network.selectNodes(nodes_id) } queryNodesAndFilter(q:string, reverse:boolean) { const nodes = this.props.queryNodes(q, reverse) this.props.setNodes(nodes) } resetNodes() { this.props.setNodes(this.state.oldNodes) } getSelectedClosure() { const network = (this.state.netRef.current as NetworkRef).network const selected = network.getSelectedNodes() let closure: Set<IdType> = new Set(); for (const nid of selected) { closure.add( parseInt(String(nid)) ) const connected = network.getConnectedNodes(nid) for (const nid2 of (connected as IdType[])) { closure.add( parseInt(String(nid2)) ) } } return closure } hiddenNonSelected() { this.resetNodes() const closure = this.getSelectedClosure() let nodes = [] for (const n of this.state.oldNodes) { if (closure.has(n.id)) { nodes.push(n) } } this.props.setNodes(nodes) } render() { return ( <div className="netView"> <div className="canvas-wrap" id="full-screen-region"> {this.createNetwork()} {this.state.infoBoard} <ViewControl setOpt={this.setNetOptions.bind(this)} getOpt={this.getNetOptions.bind(this)} captureImg={this.captureImg.bind(this)} queryAndFocus={this.queryNodesAndFocus.bind(this)} queryAndFilter={this.queryNodesAndFilter.bind(this)} reset={this.resetNodes.bind(this)} inforBoardSwitch={this.state.inforBoardSwitch} setInforBoardSwitch={this.setInforBoardSwitch.bind(this)} hiddenUnselectedSwitch={this.state.hiddenUnselectedSwitch} setHiddenUnselectedSwitch={this.setHiddenUnselectedSwitch.bind(this)} /> </div> </div> ) } }
the_stack
import { Button } from "@components/button"; import { Keys } from "@components/shared"; import { Overlay, UsePopupOptions, usePopup } from "@components/overlay"; import { Transition } from "@components/transition"; import { act, fireEvent, waitFor } from "@testing-library/react"; import { renderWithTheme } from "@jest-utils"; import userEvent from "@testing-library/user-event"; type PopupProps = UsePopupOptions & { "data-triggertestid"?: string; "data-overlaytestid"?: string; }; function Popup({ id, open, defaultOpen, onOpenChange, hideOnEscape = true, hideOnLeave = true, hideOnOutsideClick = true, restoreFocus = false, trigger, disabled, "data-triggertestid": triggerTestId, "data-overlaytestid": overlayTestId }: PopupProps) { const { triggerProps, overlayProps } = usePopup("dialog", { id, open, defaultOpen, onOpenChange, hideOnEscape, hideOnLeave, hideOnOutsideClick, restoreFocus, trigger, disabled }); return ( <> <Button {...triggerProps} data-testid={triggerTestId}>Trigger</Button> <Overlay {...overlayProps} tabIndex={-1} data-testid={overlayTestId} > Overlay </Overlay> </> ); } // Using "beforeEach" instead of "beforeAll" because the restore focus tests currently need the fade out animation to works properly. beforeEach(() => { // @ts-ignore Transition.disableAnimation = true; }); // ***** Behaviors ***** describe("\"click\" trigger", () => { test("when closed, open on trigger click", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); }); test("when closed, open on trigger space keypress", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.space }); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); }); test("when closed, open on trigger enter keypress", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.enter }); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); }); test("when closed and disabled, do not open on trigger click", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup disabled trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when closed and disabled, do not open on trigger space keypress", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup disabled trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.space }); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when closed and disabled, do not open on trigger enter keypress", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup disabled trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.enter }); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when opened, close on trigger click", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when opened, close on esc keypress", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); act(() => { getByTestId("overlay").focus(); }); act(() => { fireEvent.keyDown(getByTestId("overlay"), { key: Keys.esc }); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when opened and hideOnEscape is false, do not close on esc keypress", async () => { const { getByTestId } = renderWithTheme( <Popup hideOnEscape={false} trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); act(() => { getByTestId("overlay").focus(); }); act(() => { fireEvent.keyDown(getByTestId("overlay"), { key: Keys.esc }); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); }); test("when opened, close on blur", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <> <button type="button" data-testid="focusable-element">Focusable element</button> <Popup trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> </> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); act(() => { getByTestId("overlay").focus(); }); act(() => { getByTestId("focusable-element").focus(); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when opened and hideOnLeave is false, do not close on blur", async () => { const { getByTestId } = renderWithTheme( <> <button type="button" data-testid="focusable-element">Focusable element</button> <Popup hideOnLeave={false} trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> </> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); act(() => { getByTestId("overlay").focus(); }); act(() => { getByTestId("focusable-element").focus(); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); }); test("when opened, close on outside click", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); act(() => { getByTestId("overlay").focus(); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when opened and hideOnOutsideClick is false, do not close on outside click", async () => { const { getByTestId } = renderWithTheme( <Popup hideOnOutsideClick={false} trigger="click" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); act(() => { getByTestId("overlay").focus(); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("overlay")).toBeInTheDocument()); }); }); describe("\"none\" trigger", () => { test("when closed, do not open on trigger click", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="none" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when closed, do not open on trigger hover", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="none" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { fireEvent.focus(getByTestId("trigger")); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when closed, do not open on trigger space keypress", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="none" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.space }); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); test("when closed, do not open on trigger enter keypress", async () => { const { getByTestId, queryByTestId } = renderWithTheme( <Popup trigger="none" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { fireEvent.keyDown(getByTestId("trigger"), { key: Keys.enter }); }); await waitFor(() => expect(queryByTestId("overlay")).not.toBeInTheDocument()); }); }); test("when restoreFocus is true, closing the popup with esc keypress return the focus to the trigger", async () => { // @ts-ignore Transition.disableAnimation = false; const { getByTestId } = renderWithTheme( <Popup restoreFocus data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); act(() => { getByTestId("overlay").focus(); }); await waitFor(() => expect(getByTestId("trigger")).not.toHaveFocus()); act(() => { fireEvent.keyDown(getByTestId("overlay"), { key: Keys.esc }); }); await waitFor(() => expect(getByTestId("trigger")).toHaveFocus()); }); // ***** Aria ***** test("a popup trigger have an aria-haspopup attribute", async () => { const { getByTestId } = renderWithTheme( <Popup data-triggertestid="trigger" data-overlaytestid="overlay" /> ); await waitFor(() => expect(getByTestId("trigger")).toHaveAttribute("aria-haspopup", "dialog")); }); test("when the popup is open, the popup trigger aria-expanded is \"true\"", async () => { const { getByTestId } = renderWithTheme( <Popup data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("trigger")).toHaveAttribute("aria-expanded", "true")); }); test("when the popup is open, the popup trigger aria-controls match the overlay id", async () => { const { getByTestId } = renderWithTheme( <Popup data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("trigger")).toHaveAttribute("aria-controls", getByTestId("overlay").getAttribute("id"))); }); test("when an id is provided for the overlay, it is used as the overlay id", async () => { const { getByTestId } = renderWithTheme( <Popup id="overlay-custom-id" data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toHaveAttribute("id", "overlay-custom-id")); }); test("when no overlay id is provided, an overlay id is autogenerated", async () => { const { getByTestId } = renderWithTheme( <Popup data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(getByTestId("overlay")).toHaveAttribute("id")); }); // ***** Api ***** test("call onOpenChange when the popup open", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <Popup onOpenChange={handler} data-triggertestid="trigger" data-overlaytestid="overlay" /> ); act(() => { userEvent.click(getByTestId("trigger")); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), true)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("call onOpenChange when the popup close", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <Popup onOpenChange={handler} defaultOpen data-overlaytestid="overlay" /> ); act(() => { getByTestId("overlay").focus(); }); act(() => { fireEvent.keyDown(getByTestId("overlay"), { key: Keys.esc }); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), false)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); });
the_stack
import { AuthenticateRequestWithCredentials as RequestWithCredentials, AuthenticateRequestWithToken as RequestWithToken } from "common" import { post } from "handlers/authenticate" import { mockAuthenticationClientAuthenticateWithCredentialsWithError, mockAuthenticationClientAuthenticateWithCredentialsWithResult, mockAuthenticationClientAuthenticateWithTokenWithError, mockAuthenticationClientAuthenticateWithTokenWithResult } from "_/mocks/clients" import { mockAuthenticateRequestWithCredentials, mockAuthenticateRequestWithToken, mockSession } from "_/mocks/common" import { mockAPIGatewayProxyEvent } from "_/mocks/vendor/aws-lambda" /* ---------------------------------------------------------------------------- * Tests * ------------------------------------------------------------------------- */ /* Authentication */ describe("handlers/authenticate", () => { /* POST /authenticate */ describe("post", () => { /* Session */ const session = mockSession(true) /* with credentials */ describe("with credentials", () => { /* Credentials and event */ const { username, password } = mockAuthenticateRequestWithCredentials() const event = mockAPIGatewayProxyEvent<RequestWithCredentials>({ body: { username, password } }) /* Test: should resolve with identity token */ it("should resolve with identity token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ id: jasmine.objectContaining({ token: session.id.token }) })) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve with access token */ it("should resolve with access token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ access: jasmine.objectContaining({ token: session.access.token }) })) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve without refresh token (body) */ it("should resolve without refresh token (body)", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body).refresh).toBeUndefined() expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve without refresh token (cookie) */ it("should resolve without refresh token (cookie)", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, headers } = await post(event) expect(statusCode).toEqual(200) expect(headers).toEqual({}) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve with authentication client error */ it("should resolve with authentication client error", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithError() const { statusCode, body } = await post(event) expect(statusCode).toEqual(400) expect(body).toEqual(JSON.stringify({ type: "Error", message: "authenticateWithCredentials" })) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) }) /* with credentials and remember me */ describe("with credentials and remember me", () => { /* Credentials and event */ const { username, password } = mockAuthenticateRequestWithCredentials() const event = mockAPIGatewayProxyEvent<RequestWithCredentials>({ body: { username, password, remember: true } }) /* Test: should resolve with identity token */ it("should resolve with identity token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ id: jasmine.objectContaining({ token: session.id.token }) })) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve with access token */ it("should resolve with access token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ access: jasmine.objectContaining({ token: session.access.token }) })) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve with refresh token (body) */ it("should resolve with refresh token (body)", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ refresh: jasmine.objectContaining({ token: session.refresh!.token }) })) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve with refresh token (cookie) */ it("should resolve with refresh token (cookie)", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithResult(session) const { statusCode, headers } = await post(event) expect(statusCode).toEqual(200) expect(headers).toEqual({ "Set-Cookie": `__Secure-token=${ encodeURIComponent(session.refresh!.token) }; Domain=${ process.env.COGNITO_IDENTITY_POOL_PROVIDER! }; Path=/${ process.env.API_BASE_PATH! }/authenticate; Expires=${ session.refresh!.expires.toUTCString() }; HttpOnly; Secure; SameSite=Strict` }) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) /* Test: should resolve with authentication client error */ it("should resolve with authentication client error", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithCredentialsWithError() const { statusCode, body } = await post(event) expect(statusCode).toEqual(400) expect(body).toEqual(JSON.stringify({ type: "Error", message: "authenticateWithCredentials" })) expect(authenticateMock) .toHaveBeenCalledWith(username, password) }) }) /* with refresh token (body) */ describe("with refresh token (body)", () => { /* Token and event */ const { token } = mockAuthenticateRequestWithToken() const event = mockAPIGatewayProxyEvent<RequestWithToken>({ body: { token } }) /* Test: should resolve with identity token */ it("should resolve with identity token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ id: jasmine.objectContaining({ token: session.id.token }) })) expect(authenticateMock).toHaveBeenCalledWith(token) }) /* Test: should resolve with access token */ it("should resolve with access token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ access: jasmine.objectContaining({ token: session.access.token }) })) expect(authenticateMock).toHaveBeenCalledWith(token) }) /* Test: should resolve with error for missing token */ it("should resolve with error for missing token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithResult() const { statusCode, body } = await post(mockAPIGatewayProxyEvent<RequestWithToken>()) expect(statusCode).toEqual(400) expect(body).toEqual(JSON.stringify({ type: "TypeError", message: "Invalid request" })) expect(authenticateMock).not.toHaveBeenCalled() }) /* Test: should resolve with authentication client error */ it("should resolve with authentication client error", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithError() const { statusCode, body } = await post(event) expect(statusCode).toEqual(400) expect(body).toEqual(JSON.stringify({ type: "Error", message: "authenticateWithToken" })) expect(authenticateMock).toHaveBeenCalledWith(token) }) }) /* with refresh token (cookie) */ describe("with refresh token (cookie)", () => { /* Token and event */ const { token } = mockAuthenticateRequestWithToken() const event = mockAPIGatewayProxyEvent<RequestWithToken>({ headers: { Cookie: `__Secure-token=${token}` } }) /* Test: should resolve with identity token */ it("should resolve with identity token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ id: jasmine.objectContaining({ token: session.id.token }) })) expect(authenticateMock).toHaveBeenCalledWith(token) }) /* Test: should resolve with access token */ it("should resolve with access token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithResult(session) const { statusCode, body } = await post(event) expect(statusCode).toEqual(200) expect(JSON.parse(body)).toEqual(jasmine.objectContaining({ access: jasmine.objectContaining({ token: session.access.token }) })) expect(authenticateMock).toHaveBeenCalledWith(token) }) /* Test: should resolve with error for missing token */ it("should resolve with error for missing token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithResult() const { statusCode, body } = await post(mockAPIGatewayProxyEvent<RequestWithToken>()) expect(statusCode).toEqual(400) expect(body).toEqual(JSON.stringify({ type: "TypeError", message: "Invalid request" })) expect(authenticateMock).not.toHaveBeenCalled() }) /* Test: should resolve with authentication client error */ it("should resolve with authentication client error", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithError() const { statusCode, body } = await post(event) expect(statusCode).toEqual(400) expect(body).toEqual(JSON.stringify({ type: "Error", message: "authenticateWithToken" })) expect(authenticateMock).toHaveBeenCalledWith(token) }) /* Test: should invalidate cookie for invalid token */ it("should invalidate cookie for invalid token", async () => { const authenticateMock = mockAuthenticationClientAuthenticateWithTokenWithError() const { statusCode, headers, body } = await post(event) expect(statusCode).toEqual(400) expect(headers).toEqual({ "Set-Cookie": `__Secure-token=; Domain=${ process.env.COGNITO_IDENTITY_POOL_PROVIDER! }; Path=/${ process.env.API_BASE_PATH! }/authenticate; Expires=${ new Date(0).toUTCString() }; HttpOnly; Secure; SameSite=Strict` }) expect(body).toEqual(JSON.stringify({ type: "Error", message: "authenticateWithToken" })) expect(authenticateMock).toHaveBeenCalledWith(token) }) }) }) })
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Terms properties. */ export interface DatadogAgreementProperties { /** * Publisher identifier string. */ publisher?: string; /** * Product identifier string. */ product?: string; /** * Plan identifier string. */ plan?: string; /** * Link to HTML with Microsoft and Publisher terms. */ licenseTextLink?: string; /** * Link to the privacy policy of the publisher. */ privacyPolicyLink?: string; /** * Date and time in UTC of when the terms were accepted. This is empty if Accepted is false. */ retrieveDatetime?: Date; /** * Terms signature. */ signature?: string; /** * If any version of the terms have been accepted, otherwise false. */ accepted?: boolean; } /** * Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** * The identity that created the resource. */ createdBy?: string; /** * The type of identity that created the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ createdByType?: CreatedByType; /** * The timestamp of resource creation (UTC). */ createdAt?: Date; /** * The identity that last modified the resource. */ lastModifiedBy?: string; /** * The type of identity that last modified the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ lastModifiedByType?: CreatedByType; /** * The timestamp of resource last modification (UTC) */ lastModifiedAt?: Date; } /** * An interface representing DatadogAgreementResource. */ export interface DatadogAgreementResource extends BaseResource { /** * ARM id of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Name of the agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Represents the properties of the resource. */ properties?: DatadogAgreementProperties; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; } /** * An interface representing DatadogApiKey. */ export interface DatadogApiKey { /** * The user that created the API key. */ createdBy?: string; /** * The name of the API key. */ name?: string; /** * The value of the API key. */ key: string; /** * The time of creation of the API key. */ created?: string; } /** * An interface representing DatadogInstallMethod. */ export interface DatadogInstallMethod { /** * The tool. */ tool?: string; /** * The tool version. */ toolVersion?: string; /** * The installer version. */ installerVersion?: string; } /** * An interface representing DatadogLogsAgent. */ export interface DatadogLogsAgent { /** * The transport. */ transport?: string; } /** * An interface representing DatadogHostMetadata. */ export interface DatadogHostMetadata { /** * The agent version. */ agentVersion?: string; installMethod?: DatadogInstallMethod; logsAgent?: DatadogLogsAgent; } /** * An interface representing DatadogHost. */ export interface DatadogHost { /** * The name of the host. */ name?: string; /** * The aliases for the host. */ aliases?: string[]; /** * The Datadog integrations reporting metrics for the host. */ apps?: string[]; meta?: DatadogHostMetadata; } /** * The definition of a linked resource. */ export interface LinkedResource { /** * The ARM id of the linked resource. */ id?: string; } /** * The properties of a resource currently being monitored by the Datadog monitor resource. */ export interface MonitoredResource { /** * The ARM id of the resource. */ id?: string; /** * Flag indicating if resource is sending metrics to Datadog. */ sendingMetrics?: boolean; /** * Reason for why the resource is sending metrics (or why it is not sending). */ reasonForMetricsStatus?: string; /** * Flag indicating if resource is sending logs to Datadog. */ sendingLogs?: boolean; /** * Reason for why the resource is sending logs (or why it is not sending). */ reasonForLogsStatus?: string; } /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider, i.e., Microsoft.Datadog. */ provider?: string; /** * Type on which the operation is performed, e.g., 'monitors'. */ resource?: string; /** * Operation type, e.g., read, write, delete, etc. */ operation?: string; /** * Description of the operation, e.g., 'Write monitors'. */ description?: string; } /** * A Microsoft.Datadog REST API operation. */ export interface OperationResult { /** * Operation name, i.e., {provider}/{resource}/{operation}. */ name?: string; display?: OperationDisplay; /** * Indicates whether the operation is a data action */ isDataAction?: boolean; } /** * An interface representing ResourceSku. */ export interface ResourceSku { /** * Name of the SKU. */ name: string; } /** * Datadog organization properties */ export interface DatadogOrganizationProperties { /** * Name of the Datadog organization. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Id of the Datadog organization. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The auth code used to linking to an existing datadog organization. */ linkingAuthCode?: string; /** * The client_id from an existing in exchange for an auth token to link organization. */ linkingClientId?: string; /** * The redirect uri for linking. */ redirectUri?: string; /** * Api key associated to the Datadog organization. */ apiKey?: string; /** * Application key associated to the Datadog organization. */ applicationKey?: string; /** * The Id of the Enterprise App used for Single sign on. */ enterpriseAppId?: string; } /** * User info */ export interface UserInfo { /** * Name of the user */ name?: string; /** * Email of the user used by Datadog for contacting them if needed */ emailAddress?: string; /** * Phone number of the user used by Datadog for contacting them if needed */ phoneNumber?: string; } /** * Properties specific to the monitor resource. */ export interface MonitorProperties { /** * Possible values include: 'Accepted', 'Creating', 'Updating', 'Deleting', 'Succeeded', * 'Failed', 'Canceled', 'Deleted', 'NotSpecified' */ provisioningState?: ProvisioningState; /** * Possible values include: 'Enabled', 'Disabled'. Default value: 'Enabled'. */ monitoringStatus?: MonitoringStatus; /** * Possible values include: 'Provisioning', 'Active', 'Suspended', 'Unsubscribed' */ marketplaceSubscriptionStatus?: MarketplaceSubscriptionStatus; datadogOrganizationProperties?: DatadogOrganizationProperties; userInfo?: UserInfo; /** * Possible values include: 'Unknown', 'MonitorLogs' */ liftrResourceCategory?: LiftrResourceCategories; /** * The priority of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly liftrResourcePreference?: number; } /** * An interface representing IdentityProperties. */ export interface IdentityProperties { /** * The identity ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly principalId?: string; /** * The tenant ID of resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tenantId?: string; /** * Possible values include: 'SystemAssigned', 'UserAssigned' */ type?: ManagedIdentityTypes; } /** * An interface representing DatadogMonitorResource. */ export interface DatadogMonitorResource extends BaseResource { /** * ARM id of the monitor resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Name of the monitor resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the monitor resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; sku?: ResourceSku; properties?: MonitorProperties; identity?: IdentityProperties; tags?: { [propertyName: string]: string }; location: string; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; } /** * The set of properties that can be update in a PATCH request to a monitor resource. */ export interface MonitorUpdateProperties { /** * Possible values include: 'Enabled', 'Disabled'. Default value: 'Enabled'. */ monitoringStatus?: MonitoringStatus; } /** * The parameters for a PATCH request to a monitor resource. */ export interface DatadogMonitorResourceUpdateParameters { properties?: MonitorUpdateProperties; /** * The new tags of the monitor resource. */ tags?: { [propertyName: string]: string }; sku?: ResourceSku; } /** * An interface representing DatadogSetPasswordLink. */ export interface DatadogSetPasswordLink { setPasswordLink?: string; } /** * The definition of a filtering tag. Filtering tags are used for capturing resources and * include/exclude them from being monitored. */ export interface FilteringTag { /** * The name (also known as the key) of the tag. */ name?: string; /** * The value of the tag. */ value?: string; /** * Possible values include: 'Include', 'Exclude' */ action?: TagAction; } /** * Set of rules for sending logs for the Monitor resource. */ export interface LogRules { /** * Flag specifying if AAD logs should be sent for the Monitor resource. */ sendAadLogs?: boolean; /** * Flag specifying if Azure subscription logs should be sent for the Monitor resource. */ sendSubscriptionLogs?: boolean; /** * Flag specifying if Azure resource logs should be sent for the Monitor resource. */ sendResourceLogs?: boolean; /** * List of filtering tags to be used for capturing logs. This only takes effect if * SendResourceLogs flag is enabled. If empty, all resources will be captured. If only Exclude * action is specified, the rules will apply to the list of all available resources. If Include * actions are specified, the rules will only include resources with the associated tags. */ filteringTags?: FilteringTag[]; } /** * Set of rules for sending metrics for the Monitor resource. */ export interface MetricRules { /** * List of filtering tags to be used for capturing metrics. If empty, all resources will be * captured. If only Exclude action is specified, the rules will apply to the list of all * available resources. If Include actions are specified, the rules will only include resources * with the associated tags. */ filteringTags?: FilteringTag[]; } /** * Definition of the properties for a TagRules resource. */ export interface MonitoringTagRulesProperties { /** * Possible values include: 'Accepted', 'Creating', 'Updating', 'Deleting', 'Succeeded', * 'Failed', 'Canceled', 'Deleted', 'NotSpecified' */ provisioningState?: ProvisioningState; logRules?: LogRules; metricRules?: MetricRules; } /** * Capture logs and metrics of Azure resources based on ARM tags. */ export interface MonitoringTagRules extends BaseResource { /** * Name of the rule set. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The id of the rule set. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The type of the rule set. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; properties?: MonitoringTagRulesProperties; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; } /** * An interface representing DatadogSingleSignOnProperties. */ export interface DatadogSingleSignOnProperties { /** * Possible values include: 'Accepted', 'Creating', 'Updating', 'Deleting', 'Succeeded', * 'Failed', 'Canceled', 'Deleted', 'NotSpecified' */ provisioningState?: ProvisioningState; /** * Possible values include: 'Initial', 'Enable', 'Disable', 'Existing' */ singleSignOnState?: SingleSignOnStates; /** * The Id of the Enterprise App used for Single sign-on. */ enterpriseAppId?: string; /** * The login URL specific to this Datadog Organization. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly singleSignOnUrl?: string; } /** * An interface representing DatadogSingleSignOnResource. */ export interface DatadogSingleSignOnResource extends BaseResource { /** * ARM id of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Name of the configuration. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; properties?: DatadogSingleSignOnProperties; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; } /** * 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?: any; } /** * 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[]; } /** * Common error response for all Azure Resource Manager APIs to return error details for failed * operations. (This also follows the OData error response format.). * @summary Error response */ export interface ErrorResponse { /** * The error object. */ error?: ErrorDetail; } /** * Optional Parameters. */ export interface MarketplaceAgreementsCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { body?: DatadogAgreementResource; } /** * Optional Parameters. */ export interface MonitorsSetDefaultKeyOptionalParams extends msRest.RequestOptionsBase { body?: DatadogApiKey; } /** * Optional Parameters. */ export interface MonitorsCreateOptionalParams extends msRest.RequestOptionsBase { body?: DatadogMonitorResource; } /** * Optional Parameters. */ export interface MonitorsUpdateOptionalParams extends msRest.RequestOptionsBase { body?: DatadogMonitorResourceUpdateParameters; } /** * Optional Parameters. */ export interface MonitorsBeginCreateOptionalParams extends msRest.RequestOptionsBase { body?: DatadogMonitorResource; } /** * Optional Parameters. */ export interface MonitorsBeginUpdateOptionalParams extends msRest.RequestOptionsBase { body?: DatadogMonitorResourceUpdateParameters; } /** * Optional Parameters. */ export interface TagRulesCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { body?: MonitoringTagRules; } /** * Optional Parameters. */ export interface SingleSignOnConfigurationsCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { body?: DatadogSingleSignOnResource; } /** * Optional Parameters. */ export interface SingleSignOnConfigurationsBeginCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { body?: DatadogSingleSignOnResource; } /** * An interface representing MicrosoftDatadogClientOptions. */ export interface MicrosoftDatadogClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Response of a list operation. * @extends Array<DatadogAgreementResource> */ export interface DatadogAgreementResourceListResponse extends Array<DatadogAgreementResource> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * @interface * Response of a list operation. * @extends Array<DatadogApiKey> */ export interface DatadogApiKeyListResponse extends Array<DatadogApiKey> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * @interface * Response of a list operation. * @extends Array<DatadogHost> */ export interface DatadogHostListResponse extends Array<DatadogHost> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * @interface * Response of a list operation. * @extends Array<LinkedResource> */ export interface LinkedResourceListResponse extends Array<LinkedResource> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * @interface * Response of a list operation. * @extends Array<MonitoredResource> */ export interface MonitoredResourceListResponse extends Array<MonitoredResource> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * @interface * Response of a list operation. * @extends Array<DatadogMonitorResource> */ export interface DatadogMonitorResourceListResponse extends Array<DatadogMonitorResource> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * @interface * Result of GET request to list the Microsoft.Datadog operations. * @extends Array<OperationResult> */ export interface OperationListResult extends Array<OperationResult> { /** * URL to get the next set of operation list results if there are any. */ nextLink?: string; } /** * @interface * Response of a list operation. * @extends Array<MonitoringTagRules> */ export interface MonitoringTagRulesListResponse extends Array<MonitoringTagRules> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * @interface * Response of a list operation. * @extends Array<DatadogSingleSignOnResource> */ export interface DatadogSingleSignOnResourceListResponse extends Array<DatadogSingleSignOnResource> { /** * Link to the next set of results, if any. */ nextLink?: string; } /** * Defines values for CreatedByType. * Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' * @readonly * @enum {string} */ export type CreatedByType = "User" | "Application" | "ManagedIdentity" | "Key"; /** * Defines values for ProvisioningState. * Possible values include: 'Accepted', 'Creating', 'Updating', 'Deleting', 'Succeeded', 'Failed', * 'Canceled', 'Deleted', 'NotSpecified' * @readonly * @enum {string} */ export type ProvisioningState = | "Accepted" | "Creating" | "Updating" | "Deleting" | "Succeeded" | "Failed" | "Canceled" | "Deleted" | "NotSpecified"; /** * Defines values for MonitoringStatus. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type MonitoringStatus = "Enabled" | "Disabled"; /** * Defines values for MarketplaceSubscriptionStatus. * Possible values include: 'Provisioning', 'Active', 'Suspended', 'Unsubscribed' * @readonly * @enum {string} */ export type MarketplaceSubscriptionStatus = | "Provisioning" | "Active" | "Suspended" | "Unsubscribed"; /** * Defines values for LiftrResourceCategories. * Possible values include: 'Unknown', 'MonitorLogs' * @readonly * @enum {string} */ export type LiftrResourceCategories = "Unknown" | "MonitorLogs"; /** * Defines values for ManagedIdentityTypes. * Possible values include: 'SystemAssigned', 'UserAssigned' * @readonly * @enum {string} */ export type ManagedIdentityTypes = "SystemAssigned" | "UserAssigned"; /** * Defines values for TagAction. * Possible values include: 'Include', 'Exclude' * @readonly * @enum {string} */ export type TagAction = "Include" | "Exclude"; /** * Defines values for SingleSignOnStates. * Possible values include: 'Initial', 'Enable', 'Disable', 'Existing' * @readonly * @enum {string} */ export type SingleSignOnStates = "Initial" | "Enable" | "Disable" | "Existing"; /** * Contains response data for the list operation. */ export type MarketplaceAgreementsListResponse = DatadogAgreementResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogAgreementResourceListResponse; }; }; /** * Contains response data for the createOrUpdate operation. */ export type MarketplaceAgreementsCreateOrUpdateResponse = DatadogAgreementResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogAgreementResource; }; }; /** * Contains response data for the listNext operation. */ export type MarketplaceAgreementsListNextResponse = DatadogAgreementResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogAgreementResourceListResponse; }; }; /** * Contains response data for the listApiKeys operation. */ export type MonitorsListApiKeysResponse = DatadogApiKeyListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogApiKeyListResponse; }; }; /** * Contains response data for the getDefaultKey operation. */ export type MonitorsGetDefaultKeyResponse = DatadogApiKey & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogApiKey; }; }; /** * Contains response data for the listHosts operation. */ export type MonitorsListHostsResponse = DatadogHostListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogHostListResponse; }; }; /** * Contains response data for the listLinkedResources operation. */ export type MonitorsListLinkedResourcesResponse = LinkedResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: LinkedResourceListResponse; }; }; /** * Contains response data for the listMonitoredResources operation. */ export type MonitorsListMonitoredResourcesResponse = MonitoredResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MonitoredResourceListResponse; }; }; /** * Contains response data for the list operation. */ export type MonitorsListResponse = DatadogMonitorResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResourceListResponse; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type MonitorsListByResourceGroupResponse = DatadogMonitorResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResourceListResponse; }; }; /** * Contains response data for the get operation. */ export type MonitorsGetResponse = DatadogMonitorResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResource; }; }; /** * Contains response data for the create operation. */ export type MonitorsCreateResponse = DatadogMonitorResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResource; }; }; /** * Contains response data for the update operation. */ export type MonitorsUpdateResponse = DatadogMonitorResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResource; }; }; /** * Contains response data for the refreshSetPasswordLink operation. */ export type MonitorsRefreshSetPasswordLinkResponse = DatadogSetPasswordLink & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogSetPasswordLink; }; }; /** * Contains response data for the beginCreate operation. */ export type MonitorsBeginCreateResponse = DatadogMonitorResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResource; }; }; /** * Contains response data for the beginUpdate operation. */ export type MonitorsBeginUpdateResponse = DatadogMonitorResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResource; }; }; /** * Contains response data for the listApiKeysNext operation. */ export type MonitorsListApiKeysNextResponse = DatadogApiKeyListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogApiKeyListResponse; }; }; /** * Contains response data for the listHostsNext operation. */ export type MonitorsListHostsNextResponse = DatadogHostListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogHostListResponse; }; }; /** * Contains response data for the listLinkedResourcesNext operation. */ export type MonitorsListLinkedResourcesNextResponse = LinkedResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: LinkedResourceListResponse; }; }; /** * Contains response data for the listMonitoredResourcesNext operation. */ export type MonitorsListMonitoredResourcesNextResponse = MonitoredResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MonitoredResourceListResponse; }; }; /** * Contains response data for the listNext operation. */ export type MonitorsListNextResponse = DatadogMonitorResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResourceListResponse; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type MonitorsListByResourceGroupNextResponse = DatadogMonitorResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogMonitorResourceListResponse; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the list operation. */ export type TagRulesListResponse = MonitoringTagRulesListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MonitoringTagRulesListResponse; }; }; /** * Contains response data for the createOrUpdate operation. */ export type TagRulesCreateOrUpdateResponse = MonitoringTagRules & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MonitoringTagRules; }; }; /** * Contains response data for the get operation. */ export type TagRulesGetResponse = MonitoringTagRules & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MonitoringTagRules; }; }; /** * Contains response data for the listNext operation. */ export type TagRulesListNextResponse = MonitoringTagRulesListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MonitoringTagRulesListResponse; }; }; /** * Contains response data for the list operation. */ export type SingleSignOnConfigurationsListResponse = DatadogSingleSignOnResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogSingleSignOnResourceListResponse; }; }; /** * Contains response data for the createOrUpdate operation. */ export type SingleSignOnConfigurationsCreateOrUpdateResponse = DatadogSingleSignOnResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogSingleSignOnResource; }; }; /** * Contains response data for the get operation. */ export type SingleSignOnConfigurationsGetResponse = DatadogSingleSignOnResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogSingleSignOnResource; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type SingleSignOnConfigurationsBeginCreateOrUpdateResponse = DatadogSingleSignOnResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogSingleSignOnResource; }; }; /** * Contains response data for the listNext operation. */ export type SingleSignOnConfigurationsListNextResponse = DatadogSingleSignOnResourceListResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DatadogSingleSignOnResourceListResponse; }; };
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [ses](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonses.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Ses extends PolicyStatement { public servicePrefix = 'ses'; /** * Statement provider for service [ses](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonses.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to create a receipt rule set by cloning an existing one * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CloneReceiptRuleSet.html */ public toCloneReceiptRuleSet() { return this.to('CloneReceiptRuleSet'); } /** * Grants permission to create a new configuration set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateConfigurationSet.html */ public toCreateConfigurationSet() { return this.to('CreateConfigurationSet'); } /** * Grants permission to create a configuration set event destination * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateConfigurationSetEventDestination.html */ public toCreateConfigurationSetEventDestination() { return this.to('CreateConfigurationSetEventDestination'); } /** * Grants permission to creates an association between a configuration set and a custom domain for open and click event tracking * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateConfigurationSetTrackingOptions.html */ public toCreateConfigurationSetTrackingOptions() { return this.to('CreateConfigurationSetTrackingOptions'); } /** * Grants permission to create a new custom verification email template * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateCustomVerificationEmailTemplate.html */ public toCreateCustomVerificationEmailTemplate() { return this.to('CreateCustomVerificationEmailTemplate'); } /** * Grants permission to create a new IP address filter * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateReceiptFilter.html */ public toCreateReceiptFilter() { return this.to('CreateReceiptFilter'); } /** * Grants permission to create a receipt rule * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateReceiptRule.html */ public toCreateReceiptRule() { return this.to('CreateReceiptRule'); } /** * Grants permission to create an empty receipt rule set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateReceiptRuleSet.html */ public toCreateReceiptRuleSet() { return this.to('CreateReceiptRuleSet'); } /** * Grants permission to creates an email template * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateTemplate.html */ public toCreateTemplate() { return this.to('CreateTemplate'); } /** * Grants permission to delete an existing configuration set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteConfigurationSet.html */ public toDeleteConfigurationSet() { return this.to('DeleteConfigurationSet'); } /** * Grants permission to delete an event destination * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteConfigurationSetEventDestination.html */ public toDeleteConfigurationSetEventDestination() { return this.to('DeleteConfigurationSetEventDestination'); } /** * Grants permission to delete an association between a configuration set and a custom domain for open and click event tracking * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteConfigurationSetTrackingOptions.html */ public toDeleteConfigurationSetTrackingOptions() { return this.to('DeleteConfigurationSetTrackingOptions'); } /** * Grants permission to delete an existing custom verification email template * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteCustomVerificationEmailTemplate.html */ public toDeleteCustomVerificationEmailTemplate() { return this.to('DeleteCustomVerificationEmailTemplate'); } /** * Grants permission to delete the specified identity * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteIdentity.html */ public toDeleteIdentity() { return this.to('DeleteIdentity'); } /** * Grants permission to delete the specified sending authorization policy for the given identity (an email address or a domain) * * Access Level: Permissions management * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteIdentityPolicy.html */ public toDeleteIdentityPolicy() { return this.to('DeleteIdentityPolicy'); } /** * Grants permission to delete the specified IP address filter * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteReceiptFilter.html */ public toDeleteReceiptFilter() { return this.to('DeleteReceiptFilter'); } /** * Grants permission to delete the specified receipt rule * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteReceiptRule.html */ public toDeleteReceiptRule() { return this.to('DeleteReceiptRule'); } /** * Grants permission to delete the specified receipt rule set and all of the receipt rules it contains * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteReceiptRuleSet.html */ public toDeleteReceiptRuleSet() { return this.to('DeleteReceiptRuleSet'); } /** * Grants permission to delete an email template * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteTemplate.html */ public toDeleteTemplate() { return this.to('DeleteTemplate'); } /** * Grants permission to delete the specified email address from the list of verified addresses * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteVerifiedEmailAddress.html */ public toDeleteVerifiedEmailAddress() { return this.to('DeleteVerifiedEmailAddress'); } /** * Grants permission to return the metadata and receipt rules for the receipt rule set that is currently active * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DescribeActiveReceiptRuleSet.html */ public toDescribeActiveReceiptRuleSet() { return this.to('DescribeActiveReceiptRuleSet'); } /** * Grants permission to return the details of the specified configuration set * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DescribeConfigurationSet.html */ public toDescribeConfigurationSet() { return this.to('DescribeConfigurationSet'); } /** * Grants permission to return the details of the specified receipt rule * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DescribeReceiptRule.html */ public toDescribeReceiptRule() { return this.to('DescribeReceiptRule'); } /** * Grants permission to return the details of the specified receipt rule set * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_DescribeReceiptRuleSet.html */ public toDescribeReceiptRuleSet() { return this.to('DescribeReceiptRuleSet'); } /** * Grants permission to return the email sending status of your account * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetAccountSendingEnabled.html */ public toGetAccountSendingEnabled() { return this.to('GetAccountSendingEnabled'); } /** * Grants permission to return the custom email verification template for the template name you specify * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetCustomVerificationEmailTemplate.html */ public toGetCustomVerificationEmailTemplate() { return this.to('GetCustomVerificationEmailTemplate'); } /** * Grants permission to return the current status of Easy DKIM signing for an entity * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetIdentityDkimAttributes.html */ public toGetIdentityDkimAttributes() { return this.to('GetIdentityDkimAttributes'); } /** * Grants permission to return the custom MAIL FROM attributes for a list of identities (email addresses and/or domains) * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetIdentityMailFromDomainAttributes.html */ public toGetIdentityMailFromDomainAttributes() { return this.to('GetIdentityMailFromDomainAttributes'); } /** * Grants permission to return a structure describing identity notification attributes for a list of verified identities (email addresses and/or domains), * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetIdentityNotificationAttributes.html */ public toGetIdentityNotificationAttributes() { return this.to('GetIdentityNotificationAttributes'); } /** * Grants permission to return the requested sending authorization policies for the given identity (an email address or a domain) * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetIdentityPolicies.html */ public toGetIdentityPolicies() { return this.to('GetIdentityPolicies'); } /** * Grants permission to return the verification status and (for domain identities) the verification token for a list of identities * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetIdentityVerificationAttributes.html */ public toGetIdentityVerificationAttributes() { return this.to('GetIdentityVerificationAttributes'); } /** * Grants permission to return the user's current sending limits * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetSendQuota.html */ public toGetSendQuota() { return this.to('GetSendQuota'); } /** * Grants permission to returns the user's sending statistics * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetSendStatistics.html */ public toGetSendStatistics() { return this.to('GetSendStatistics'); } /** * Grants permission to return the template object, which includes the subject line, HTML par, and text part for the template you specify * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_GetTemplate.html */ public toGetTemplate() { return this.to('GetTemplate'); } /** * Grants permission to list all of the configuration sets for your account * * Access Level: List * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListConfigurationSets.html */ public toListConfigurationSets() { return this.to('ListConfigurationSets'); } /** * Grants permission to list all of the existing custom verification email templates for your account * * Access Level: List * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListCustomVerificationEmailTemplates.html */ public toListCustomVerificationEmailTemplates() { return this.to('ListCustomVerificationEmailTemplates'); } /** * Grants permission to list the email identities for your account * * Access Level: List * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListIdentities.html */ public toListIdentities() { return this.to('ListIdentities'); } /** * Grants permission to list all of the email templates for your account * * Access Level: List * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListIdentityPolicies.html */ public toListIdentityPolicies() { return this.to('ListIdentityPolicies'); } /** * Grants permission to list the IP address filters associated with your account * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListReceiptFilters.html */ public toListReceiptFilters() { return this.to('ListReceiptFilters'); } /** * Grants permission to list the receipt rule sets that exist under your account * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListReceiptRuleSets.html */ public toListReceiptRuleSets() { return this.to('ListReceiptRuleSets'); } /** * Grants permission to list the email templates present in your account * * Access Level: List * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListTemplates.html */ public toListTemplates() { return this.to('ListTemplates'); } /** * Grants permission to list all of the email addresses that have been verified in your account * * Access Level: Read * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ListVerifiedEmailAddresses.html */ public toListVerifiedEmailAddresses() { return this.to('ListVerifiedEmailAddresses'); } /** * Grants permission to add or update the delivery options for a configuration set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_PutConfigurationSetDeliveryOptions.html */ public toPutConfigurationSetDeliveryOptions() { return this.to('PutConfigurationSetDeliveryOptions'); } /** * Grants permission to add or update a sending authorization policy for the specified identity (an email address or a domain) * * Access Level: Permissions management * * https://docs.aws.amazon.com/ses/latest/APIReference/API_PutIdentityPolicy.html */ public toPutIdentityPolicy() { return this.to('PutIdentityPolicy'); } /** * Grants permission to reorder the receipt rules within a receipt rule set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ReorderReceiptRuleSet.html */ public toReorderReceiptRuleSet() { return this.to('ReorderReceiptRuleSet'); } /** * Grants permission to generate and send a bounce message to the sender of an email you received through Amazon SES * * Access Level: Write * * Possible conditions: * - .ifFromAddress() * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SendBounce.html */ public toSendBounce() { return this.to('SendBounce'); } /** * Grants permission to compose an email message to multiple destinations * * Access Level: Write * * Possible conditions: * - .ifFeedbackAddress() * - .ifFromAddress() * - .ifFromDisplayName() * - .ifRecipients() * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SendBulkTemplatedEmail.html */ public toSendBulkTemplatedEmail() { return this.to('SendBulkTemplatedEmail'); } /** * Grants permission to add an email address to the list of identities and attempts to verify it for your account * * Access Level: Write * * Possible conditions: * - .ifFeedbackAddress() * - .ifFromAddress() * - .ifFromDisplayName() * - .ifRecipients() * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SendCustomVerificationEmail.html */ public toSendCustomVerificationEmail() { return this.to('SendCustomVerificationEmail'); } /** * Grants permission to send an email message * * Access Level: Write * * Possible conditions: * - .ifFeedbackAddress() * - .ifFromAddress() * - .ifFromDisplayName() * - .ifRecipients() * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SendEmail.html */ public toSendEmail() { return this.to('SendEmail'); } /** * Grants permission to send an email message, with header and content specified by the client * * Access Level: Write * * Possible conditions: * - .ifFeedbackAddress() * - .ifFromAddress() * - .ifFromDisplayName() * - .ifRecipients() * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SendRawEmail.html */ public toSendRawEmail() { return this.to('SendRawEmail'); } /** * Grants permission to compose an email message using an email template * * Access Level: Write * * Possible conditions: * - .ifFeedbackAddress() * - .ifFromAddress() * - .ifFromDisplayName() * - .ifRecipients() * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SendTemplatedEmail.html */ public toSendTemplatedEmail() { return this.to('SendTemplatedEmail'); } /** * Grants permission to set the specified receipt rule set as the active receipt rule set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SetActiveReceiptRuleSet.html */ public toSetActiveReceiptRuleSet() { return this.to('SetActiveReceiptRuleSet'); } /** * Grants permission to enable or disable Easy DKIM signing of email sent from an identity * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SetIdentityDkimEnabled.html */ public toSetIdentityDkimEnabled() { return this.to('SetIdentityDkimEnabled'); } /** * Grants permission to enable or disable whether Amazon SES forwards bounce and complaint notifications for an identity (an email address or a domain) * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SetIdentityFeedbackForwardingEnabled.html */ public toSetIdentityFeedbackForwardingEnabled() { return this.to('SetIdentityFeedbackForwardingEnabled'); } /** * Grants permission to set whether Amazon SES includes the original email headers in the Amazon Simple Notification Service (Amazon SNS) notifications of a specified type for a given identity (an email address or a domain) * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SetIdentityHeadersInNotificationsEnabled.html */ public toSetIdentityHeadersInNotificationsEnabled() { return this.to('SetIdentityHeadersInNotificationsEnabled'); } /** * Grants permission to enable or disable the custom MAIL FROM domain setup for a verified identity * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SetIdentityMailFromDomain.html */ public toSetIdentityMailFromDomain() { return this.to('SetIdentityMailFromDomain'); } /** * Grants permission to set an Amazon Simple Notification Service (Amazon SNS) topic to use when delivering notifications for a verified identity * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SetIdentityNotificationTopic.html */ public toSetIdentityNotificationTopic() { return this.to('SetIdentityNotificationTopic'); } /** * Grants permission to set the position of the specified receipt rule in the receipt rule set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_SetReceiptRulePosition.html */ public toSetReceiptRulePosition() { return this.to('SetReceiptRulePosition'); } /** * Grants permission to create a preview of the MIME content of an email when provided with a template and a set of replacement data * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_TestRenderTemplate.html */ public toTestRenderTemplate() { return this.to('TestRenderTemplate'); } /** * Grants permission to enable or disable email sending for your account * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateAccountSendingEnabled.html */ public toUpdateAccountSendingEnabled() { return this.to('UpdateAccountSendingEnabled'); } /** * Grants permission to update the event destination of a configuration set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateConfigurationSetEventDestination.html */ public toUpdateConfigurationSetEventDestination() { return this.to('UpdateConfigurationSetEventDestination'); } /** * Grants permission to enable or disable the publishing of reputation metrics for emails sent using a specific configuration set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateConfigurationSetReputationMetricsEnabled.html */ public toUpdateConfigurationSetReputationMetricsEnabled() { return this.to('UpdateConfigurationSetReputationMetricsEnabled'); } /** * Grants permission to enable or disable email sending for messages sent using a specific configuration set * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateConfigurationSetSendingEnabled.html */ public toUpdateConfigurationSetSendingEnabled() { return this.to('UpdateConfigurationSetSendingEnabled'); } /** * Grants permission to modify an association between a configuration set and a custom domain for open and click event tracking * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateConfigurationSetTrackingOptions.html */ public toUpdateConfigurationSetTrackingOptions() { return this.to('UpdateConfigurationSetTrackingOptions'); } /** * Grants permission to update an existing custom verification email template * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateCustomVerificationEmailTemplate.html */ public toUpdateCustomVerificationEmailTemplate() { return this.to('UpdateCustomVerificationEmailTemplate'); } /** * Grants permission to update a receipt rule * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateReceiptRule.html */ public toUpdateReceiptRule() { return this.to('UpdateReceiptRule'); } /** * Grants permission to update an email template * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateTemplate.html */ public toUpdateTemplate() { return this.to('UpdateTemplate'); } /** * Grants permission to return a set of DKIM tokens for a domain * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyDomainDkim.html */ public toVerifyDomainDkim() { return this.to('VerifyDomainDkim'); } /** * Grants permission to verify a domain * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyDomainIdentity.html */ public toVerifyDomainIdentity() { return this.to('VerifyDomainIdentity'); } /** * Grants permission to verify an email address * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyEmailAddress.html */ public toVerifyEmailAddress() { return this.to('VerifyEmailAddress'); } /** * Grants permission to verify an email identity * * Access Level: Write * * https://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyEmailIdentity.html */ public toVerifyEmailIdentity() { return this.to('VerifyEmailIdentity'); } protected accessLevelList: AccessLevelList = { "Write": [ "CloneReceiptRuleSet", "CreateConfigurationSet", "CreateConfigurationSetEventDestination", "CreateConfigurationSetTrackingOptions", "CreateCustomVerificationEmailTemplate", "CreateReceiptFilter", "CreateReceiptRule", "CreateReceiptRuleSet", "CreateTemplate", "DeleteConfigurationSet", "DeleteConfigurationSetEventDestination", "DeleteConfigurationSetTrackingOptions", "DeleteCustomVerificationEmailTemplate", "DeleteIdentity", "DeleteReceiptFilter", "DeleteReceiptRule", "DeleteReceiptRuleSet", "DeleteTemplate", "DeleteVerifiedEmailAddress", "PutConfigurationSetDeliveryOptions", "ReorderReceiptRuleSet", "SendBounce", "SendBulkTemplatedEmail", "SendCustomVerificationEmail", "SendEmail", "SendRawEmail", "SendTemplatedEmail", "SetActiveReceiptRuleSet", "SetIdentityDkimEnabled", "SetIdentityFeedbackForwardingEnabled", "SetIdentityHeadersInNotificationsEnabled", "SetIdentityMailFromDomain", "SetIdentityNotificationTopic", "SetReceiptRulePosition", "TestRenderTemplate", "UpdateAccountSendingEnabled", "UpdateConfigurationSetEventDestination", "UpdateConfigurationSetReputationMetricsEnabled", "UpdateConfigurationSetSendingEnabled", "UpdateConfigurationSetTrackingOptions", "UpdateCustomVerificationEmailTemplate", "UpdateReceiptRule", "UpdateTemplate", "VerifyDomainDkim", "VerifyDomainIdentity", "VerifyEmailAddress", "VerifyEmailIdentity" ], "Permissions management": [ "DeleteIdentityPolicy", "PutIdentityPolicy" ], "Read": [ "DescribeActiveReceiptRuleSet", "DescribeConfigurationSet", "DescribeReceiptRule", "DescribeReceiptRuleSet", "GetAccountSendingEnabled", "GetCustomVerificationEmailTemplate", "GetIdentityDkimAttributes", "GetIdentityMailFromDomainAttributes", "GetIdentityNotificationAttributes", "GetIdentityPolicies", "GetIdentityVerificationAttributes", "GetSendQuota", "GetSendStatistics", "GetTemplate", "ListReceiptFilters", "ListReceiptRuleSets", "ListVerifiedEmailAddresses" ], "List": [ "ListConfigurationSets", "ListCustomVerificationEmailTemplates", "ListIdentities", "ListIdentityPolicies", "ListTemplates" ] }; /** * Adds a resource of type configuration-set to the statement * * https://docs.aws.amazon.com/ses/latest/APIReference/API_ConfigurationSet.html * * @param configurationSetName - Identifier for the configurationSetName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onConfigurationSet(configurationSetName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:configuration-set/${ConfigurationSetName}'; arn = arn.replace('${ConfigurationSetName}', configurationSetName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type custom-verification-email-template to the statement * * https://docs.aws.amazon.com/ses/latest/APIReference/API_CustomVerificationEmailTemplate.html * * @param templateName - Identifier for the templateName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onCustomVerificationEmailTemplate(templateName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:custom-verification-email-template/${TemplateName}'; arn = arn.replace('${TemplateName}', templateName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type identity to the statement * * https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_IdentityInfo.html * * @param identityName - Identifier for the identityName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onIdentity(identityName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:identity/${IdentityName}'; arn = arn.replace('${IdentityName}', identityName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type template to the statement * * https://docs.aws.amazon.com/ses/latest/APIReference/API_Template.html * * @param templateName - Identifier for the templateName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onTemplate(templateName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:template/${TemplateName}'; arn = arn.replace('${TemplateName}', templateName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters actions based on the "Return-Path" address, which specifies where bounces and complaints are sent by email feedback forwarding * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendBulkTemplatedEmail() * - .toSendCustomVerificationEmail() * - .toSendEmail() * - .toSendRawEmail() * - .toSendTemplatedEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFeedbackAddress(value: string | string[], operator?: Operator | string) { return this.if(`FeedbackAddress`, value, operator || 'StringLike'); } /** * Filters actions based on the "From" address of a message * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendBounce() * - .toSendBulkTemplatedEmail() * - .toSendCustomVerificationEmail() * - .toSendEmail() * - .toSendRawEmail() * - .toSendTemplatedEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFromAddress(value: string | string[], operator?: Operator | string) { return this.if(`FromAddress`, value, operator || 'StringLike'); } /** * Filters actions based on the "From" address that is used as the display name of a message * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendBulkTemplatedEmail() * - .toSendCustomVerificationEmail() * - .toSendEmail() * - .toSendRawEmail() * - .toSendTemplatedEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFromDisplayName(value: string | string[], operator?: Operator | string) { return this.if(`FromDisplayName`, value, operator || 'StringLike'); } /** * Filters actions based on the recipient addresses of a message, which include the "To", "CC", and "BCC" addresses * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendBulkTemplatedEmail() * - .toSendCustomVerificationEmail() * - .toSendEmail() * - .toSendRawEmail() * - .toSendTemplatedEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifRecipients(value: string | string[], operator?: Operator | string) { return this.if(`Recipients`, value, operator || 'StringLike'); } }
the_stack
import axios from "axios"; import { getDateBefore, RKIError } from "../utils"; import { ResponseData } from "./response-data"; function parseDate(dateString: string): Date { const parts = dateString.split(","); const dateParts = parts[0].split("."); const timeParts = parts[1].replace("Uhr", "").split(":"); return new Date( parseInt(dateParts[2]), parseInt(dateParts[1]) - 1, parseInt(dateParts[0]), parseInt(timeParts[0]), parseInt(timeParts[1]) ); } export interface IDistrictData { ags: string; name: string; county: string; state: string; population: number; cases: number; deaths: number; casesPerWeek: number; deathsPerWeek: number; lastUpdated: number; } export async function getDistrictsData(): Promise< ResponseData<IDistrictData[]> > { const response = await axios.get( `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=1%3D1&outFields=RS,GEN,EWZ,cases,deaths,county,last_update,cases7_lk,death7_lk,BL&returnGeometry=false&outSR=4326&f=json` ); const data = response.data; if (data.error) { throw new RKIError(data.error, response.config.url); } const districts = data.features.map((feature) => { return { ags: feature.attributes.RS, name: feature.attributes.GEN, county: feature.attributes.county, state: feature.attributes.BL, population: feature.attributes.EWZ, cases: feature.attributes.cases, deaths: feature.attributes.deaths, casesPerWeek: feature.attributes.cases7_lk, deathsPerWeek: feature.attributes.death7_lk, }; }); return { data: districts, lastUpdate: parseDate(data.features[0].attributes.last_update), }; } export async function getDistrictsRecoveredData(): Promise< ResponseData<{ ags: string; recovered: number }[]> > { const response = await axios.get( `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_COVID19/FeatureServer/0/query?where=NeuGenesen IN(1,0)&objectIds=&time=&resultType=standard&outFields=AnzahlGenesen,MeldeDatum,IdLandkreis&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=IdLandkreis&groupByFieldsForStatistics=IdLandkreis&outStatistics=[{"statisticType":"sum","onStatisticField":"AnzahlGenesen","outStatisticFieldName":"recovered"},{"statisticType":"max","onStatisticField":"MeldeDatum","outStatisticFieldName":"date"}]&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=` ); const data = response.data; if (data.error) { throw new RKIError(data.error, response.config.url); } const districts = data.features.map((feature) => { return { ags: feature.attributes.IdLandkreis, recovered: feature.attributes.recovered, }; }); return { data: districts, lastUpdate: new Date(data.features[0].attributes.date), }; } export async function getNewDistrictCases(): Promise< ResponseData<{ ags: string; cases: number }[]> > { const response = await axios.get( `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_COVID19/FeatureServer/0/query?where=NeuerFall IN(1,-1)&objectIds=&time=&resultType=standard&outFields=AnzahlFall,MeldeDatum,IdLandkreis&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=IdLandkreis&groupByFieldsForStatistics=IdLandkreis&outStatistics=[{"statisticType":"sum","onStatisticField":"AnzahlFall","outStatisticFieldName":"cases"},{"statisticType":"max","onStatisticField":"MeldeDatum","outStatisticFieldName":"date"}]&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=` ); const data = response.data; const districts = data.features.map((feature) => { return { ags: feature.attributes.IdLandkreis, cases: feature.attributes.cases, }; }); return { data: districts, lastUpdate: new Date(data.features[0].attributes.date), }; } export async function getNewDistrictDeaths(): Promise< ResponseData<{ ags: string; deaths: number }[]> > { const response = await axios.get( `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_COVID19/FeatureServer/0/query?where=NeuerTodesfall IN(1,-1)&objectIds=&time=&resultType=standard&outFields=AnzahlTodesfall,MeldeDatum,IdLandkreis&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=IdLandkreis&groupByFieldsForStatistics=IdLandkreis&outStatistics=[{"statisticType":"sum","onStatisticField":"AnzahlTodesfall","outStatisticFieldName":"deaths"},{"statisticType":"max","onStatisticField":"MeldeDatum","outStatisticFieldName":"date"}]&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=` ); const data = response.data; const districts = data.features.map((feature) => { return { ags: feature.attributes.IdLandkreis, deaths: feature.attributes.deaths, }; }); return { data: districts, lastUpdate: new Date(data.features[0].attributes.date), }; } export async function getNewDistrictRecovered(): Promise< ResponseData<{ ags: string; recovered: number }[]> > { const response = await axios.get( `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_COVID19/FeatureServer/0/query?where=NeuGenesen IN(1,-1)&objectIds=&time=&resultType=standard&outFields=AnzahlGenesen,MeldeDatum,IdLandkreis&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=IdLandkreis&groupByFieldsForStatistics=IdLandkreis&outStatistics=[{"statisticType":"sum","onStatisticField":"AnzahlGenesen","outStatisticFieldName":"recovered"},{"statisticType":"max","onStatisticField":"MeldeDatum","outStatisticFieldName":"date"}]&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=` ); const data = response.data; if (data.error) { throw new RKIError(data.error, response.config.url); } const districts = data.features.map((feature) => { return { ags: feature.attributes.IdLandkreis, recovered: feature.attributes.recovered, }; }); return { data: districts, lastUpdate: new Date(data.features[0].attributes.date), }; } export async function getLastDistrictCasesHistory( days?: number, ags?: string ): Promise< ResponseData<{ ags: string; name: string; cases: number; date: Date }[]> > { const whereParams = [`NeuerFall IN(1,0)`]; if (ags != null) { whereParams.push(`IdLandkreis = '${ags}'`); } else { // if ags is not defined restrict days to 36 if (days != null) { days = Math.min(days, 36); } else { days = 36; } } if (days != null) { const dateString = getDateBefore(days); whereParams.push(`MeldeDatum >= TIMESTAMP '${dateString}'`); } const url = `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_COVID19/FeatureServer/0/query?where=${whereParams.join( " AND " )}&objectIds=&time=&resultType=standard&outFields=AnzahlFall,MeldeDatum,Landkreis,IdLandkreis&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=IdLandkreis,MeldeDatum&groupByFieldsForStatistics=IdLandkreis,MeldeDatum,Landkreis&outStatistics=[{"statisticType":"sum","onStatisticField":"AnzahlFall","outStatisticFieldName":"cases"}]&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=`; const response = await axios.get(url); const data = response.data; if (data.error) { throw new RKIError(data.error, response.config.url); } const history: { ags: string; name: string; cases: number; date: Date; }[] = data.features.map((feature) => { return { ags: feature.attributes.IdLandkreis, name: feature.attributes.Landkreis, cases: feature.attributes.cases, date: new Date(feature.attributes.MeldeDatum), }; }); return { data: history, lastUpdate: history[history.length - 1] ? history[history.length - 1].date : new Date(), }; } export async function getLastDistrictDeathsHistory( days?: number, ags?: string ): Promise< ResponseData<{ ags: string; name: string; deaths: number; date: Date }[]> > { const whereParams = [`NeuerTodesfall IN(1,0,-9)`]; if (ags != null) { whereParams.push(`IdLandkreis = '${ags}'`); } else { // if ags is not defined restrict days to 30 if (days != null) { days = Math.min(days, 30); } else { days = 30; } } if (days != null) { const dateString = getDateBefore(days); whereParams.push(`MeldeDatum >= TIMESTAMP '${dateString}'`); } const url = `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_COVID19/FeatureServer/0/query?where=${whereParams.join( " AND " )}&objectIds=&time=&resultType=standard&outFields=AnzahlTodesfall,MeldeDatum,Landkreis,IdLandkreis&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=IdLandkreis,MeldeDatum&groupByFieldsForStatistics=IdLandkreis,MeldeDatum,Landkreis&outStatistics=[{"statisticType":"sum","onStatisticField":"AnzahlTodesfall","outStatisticFieldName":"deaths"}]&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=`; const response = await axios.get(url); const data = response.data; if (data.error) { throw new RKIError(data.error, response.config.url); } const history: { ags: string; name: string; deaths: number; date: Date; }[] = data.features.map((feature) => { return { ags: feature.attributes.IdLandkreis, name: feature.attributes.Landkreis, deaths: feature.attributes.deaths, date: new Date(feature.attributes.MeldeDatum), }; }); return { data: history, lastUpdate: history[history.length - 1] ? history[history.length - 1].date : new Date(), }; } export async function getLastDistrictRecoveredHistory( days?: number, ags?: string ): Promise< ResponseData<{ ags: string; name: string; recovered: number; date: Date }[]> > { const whereParams = [`NeuGenesen IN(1,0,-9)`]; if (ags != null) { whereParams.push(`IdLandkreis = '${ags}'`); } else { // if ags is not defined restrict days to 30 if (days != null) { days = Math.min(days, 30); } else { days = 30; } } if (days != null) { const dateString = getDateBefore(days); whereParams.push(`MeldeDatum >= TIMESTAMP '${dateString}'`); } const url = `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_COVID19/FeatureServer/0/query?where=${whereParams.join( " AND " )}&objectIds=&time=&resultType=standard&outFields=AnzahlGenesen,MeldeDatum,Landkreis,IdLandkreis&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=IdLandkreis,MeldeDatum&groupByFieldsForStatistics=IdLandkreis,MeldeDatum,Landkreis&outStatistics=[{"statisticType":"sum","onStatisticField":"AnzahlGenesen","outStatisticFieldName":"recovered"}]&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=`; const response = await axios.get(url); const data = response.data; if (data.error) { throw new RKIError(data.error, response.config.url); } const history: { ags: string; name: string; recovered: number; date: Date; }[] = data.features.map((feature) => { return { ags: feature.attributes.IdLandkreis, name: feature.attributes.Landkreis, recovered: feature.attributes.recovered, date: new Date(feature.attributes.MeldeDatum), }; }); return { data: history, lastUpdate: history[history.length - 1] ? history[history.length - 1].date : new Date(), }; }
the_stack
import * as React from 'react'; import { IPropertyFieldAlignPickerPropsInternal } from './PropertyFieldAlignPicker'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import GuidHelper from './GuidHelper'; import styles from './PropertyFields.module.scss'; /** * @interface * PropertyFieldAlignPickerHost properties interface * */ export interface IPropertyFieldAlignPickerHostProps extends IPropertyFieldAlignPickerPropsInternal { } export interface IPropertyFieldAlignPickerHostState { mode?: string; overList?: boolean; overTiles?: boolean; overRight?: boolean; errorMessage?: string; } /** * @class * Renders the controls for PropertyFieldAlignPicker component */ export default class PropertyFieldAlignPickerHost extends React.Component<IPropertyFieldAlignPickerHostProps, IPropertyFieldAlignPickerHostState> { private latestValidateValue: string; private async: Async; private delayedValidate: (value: string) => void; private _key: string; /** * @function * Constructor */ constructor(props: IPropertyFieldAlignPickerHostProps) { super(props); //Bind the current object to the external called onSelectDate method this.onValueChanged = this.onValueChanged.bind(this); this.onClickBullets = this.onClickBullets.bind(this); this.onClickTiles = this.onClickTiles.bind(this); this.onClickRight = this.onClickRight.bind(this); this.mouseListEnterDropDown = this.mouseListEnterDropDown.bind(this); this.mouseListLeaveDropDown = this.mouseListLeaveDropDown.bind(this); this.mouseTilesEnterDropDown = this.mouseTilesEnterDropDown.bind(this); this.mouseTilesLeaveDropDown = this.mouseTilesLeaveDropDown.bind(this); this.mouseRightEnterDropDown = this.mouseRightEnterDropDown.bind(this); this.mouseRightLeaveDropDown = this.mouseRightLeaveDropDown.bind(this); this._key = GuidHelper.getGuid(); this.state = { mode: this.props.initialValue != null && this.props.initialValue != '' ? this.props.initialValue : '', overList: false, overTiles: false, overRight: false, errorMessage: '' }; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } /** * @function * Function called when the component selected value changed */ private onValueChanged(element: any, previous: string, value: string): void { this.delayedValidate(value); } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.initialValue, value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.props.initialValue, value); this.state.errorMessage = result; this.setState(this.state); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.props.initialValue, value); this.state.errorMessage = errorMessage; this.setState(this.state); }); } } else { this.notifyAfterValidate(this.props.initialValue, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: string, newValue: string) { if (this.props.onPropertyChanged && newValue != null) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChanged(this.props.targetProperty, oldValue, newValue); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } } /** * @function * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } private onClickBullets(element?: any) { var previous = this.state.mode; this.state.mode = 'left'; this.setState(this.state); this.onValueChanged(this, previous, this.state.mode); } private onClickTiles(element?: any) { var previous = this.state.mode; this.state.mode = 'center'; this.setState(this.state); this.onValueChanged(this, previous, this.state.mode); } private onClickRight(element?: any) { var previous = this.state.mode; this.state.mode = 'right'; this.setState(this.state); this.onValueChanged(this, previous, this.state.mode); } private mouseListEnterDropDown() { if (this.props.disabled === true) return; this.state.overList = true; this.setState(this.state); } private mouseListLeaveDropDown() { if (this.props.disabled === true) return; this.state.overList = false; this.setState(this.state); } private mouseTilesEnterDropDown() { if (this.props.disabled === true) return; this.state.overTiles = true; this.setState(this.state); } private mouseTilesLeaveDropDown() { if (this.props.disabled === true) return; this.state.overTiles = false; this.setState(this.state); } private mouseRightEnterDropDown() { if (this.props.disabled === true) return; this.state.overRight = true; this.setState(this.state); } private mouseRightLeaveDropDown() { if (this.props.disabled === true) return; this.state.overRight = false; this.setState(this.state); } /** * @function * Renders the controls */ public render(): JSX.Element { var backgroundTiles = this.state.overTiles ? '#DFDFDF': ''; var backgroundLists = this.state.overList ? '#DFDFDF': ''; var backgroundRight = this.state.overRight ? '#DFDFDF': ''; if (this.state.mode == 'left') backgroundLists = '#EEEEEE'; if (this.state.mode == 'center') backgroundTiles = '#EEEEEE'; if (this.state.mode == 'right') backgroundRight = '#EEEEEE'; var styleLeft = styles['spcfChoiceFieldField']; var styleCenter = styles['spcfChoiceFieldField']; var styleRight = styles['spcfChoiceFieldField']; if (this.state.mode === 'left') styleLeft += ' is-checked'; else if (this.state.mode === 'center') styleCenter += ' is-checked'; else if (this.state.mode === 'right') styleRight += ' is-checked'; if (this.props.disabled === true) { styleLeft += ' is-disabled'; styleCenter += ' is-disabled'; styleRight += ' is-disabled'; } //Renders content return ( <div style={{ marginBottom: '8px'}}> <Label>{this.props.label}</Label> <div style={{display: 'inline-flex'}}> <div style={{cursor: this.props.disabled === false ? 'pointer' : 'default', width: '70px', marginRight: '30px', backgroundColor: backgroundLists}} onMouseEnter={this.mouseListEnterDropDown} onMouseLeave={this.mouseListLeaveDropDown}> <div style={{float: 'left'}} className={styles['spcfChoiceField']}> <input id={"leftRadio-" + this._key} className={styles['spcfChoiceFieldInput']} disabled={this.props.disabled} onChange={this.onClickBullets} type="radio" role="radio" name={"align-picker-" + this._key} defaultChecked={this.state.mode == "left" ? true : false} aria-checked={this.state.mode == "left" ? true : false} value="left" style={{cursor: this.props.disabled === false ? 'pointer' : 'default', width: '18px', height: '18px', opacity: 0}}/> <label htmlFor={"leftRadio-" + this._key} className={styleLeft}> <div className={styles['spcfChoiceFieldInnerField']}> <div className={styles['spcfChoiceFieldIconWrapper']}> <i className='ms-Icon ms-Icon--AlignLeft' aria-hidden="true" style={{cursor: this.props.disabled === false ? 'pointer' : 'default',fontSize:'32px', paddingLeft: '30px', color: this.props.disabled === false ? '#808080' : '#A6A6A6'}}></i> </div> </div> </label> </div> </div> <div style={{cursor: this.props.disabled === false ? 'pointer' : 'default', width: '70px', marginRight: '30px', backgroundColor: backgroundTiles}} onMouseEnter={this.mouseTilesEnterDropDown} onMouseLeave={this.mouseTilesLeaveDropDown}> <div style={{float: 'left'}} className={styles['spcfChoiceField']}> <input id={"centerRadio-" + this._key } className={styles['spcfChoiceFieldInput']} onChange={this.onClickTiles} type="radio" name={"align-picker-" + this._key} role="radio" disabled={this.props.disabled} defaultChecked={this.state.mode == "center" ? true : false} aria-checked={this.state.mode == "center" ? true : false} value="center" style={{cursor: this.props.disabled === false ? 'pointer' : 'default', width: '18px', height: '18px', opacity: 0}}/> <label htmlFor={"centerRadio-" + this._key } className={styleCenter}> <div className={styles['spcfChoiceFieldInnerField']}> <div className={styles['spcfChoiceFieldIconWrapper']}> <i className='ms-Icon ms-Icon--AlignCenter' aria-hidden="true" style={{cursor: this.props.disabled === false ? 'pointer' : 'default',fontSize:'32px', paddingLeft: '30px', color: this.props.disabled === false ? '#808080' : '#A6A6A6'}}></i> </div> </div> </label> </div> </div> <div style={{cursor: this.props.disabled === false ? 'pointer' : 'default', width: '70px', marginRight: '30px', backgroundColor: backgroundRight}} onMouseEnter={this.mouseRightEnterDropDown} onMouseLeave={this.mouseRightLeaveDropDown}> <div style={{float: 'left'}} className={styles['spcfChoiceField']}> <input id={"rightRadio-" + this._key } className={styles['spcfChoiceFieldInput']} onChange={this.onClickRight} type="radio" name={"align-picker-" + this._key} role="radio" disabled={this.props.disabled} defaultChecked={this.state.mode == "right" ? true : false} aria-checked={this.state.mode == "right" ? true : false} value="right" style={{cursor: this.props.disabled === false ? 'pointer' : 'default', width: '18px', height: '18px', opacity: 0}}/> <label htmlFor={"rightRadio-" + this._key } className={styleRight} > <div className={styles['spcfChoiceFieldInnerField']}> <div className={styles['spcfChoiceFieldIconWrapper']}> <i className='ms-Icon ms-Icon--AlignRight' aria-hidden="true" style={{cursor: this.props.disabled === false ? 'pointer' : 'default',fontSize:'32px', paddingLeft: '30px', color: this.props.disabled === false ? '#808080' : '#A6A6A6'}}></i> </div> </div> </label> </div> </div> </div> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } }
the_stack